branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>Acforest/SimTown<file_sep>/Main.h #pragma once #include <windows.h> #include <windowsx.h> #include <d3d11.h> #include <d3dx11.h> #include <d3dcompiler.h> #include <xnamath.h> #include <cimport.h> #include <scene.h> #include <postprocess.h> #include <vector> #include <iostream> #include <fstream> #include "Resource.h" #include "Keyboard.h" #include "Mouse.h" #include "FirstPersonCamera.h" #include "FreeLookCamera.h" #include "AssimpModel.h" #include "Terrain.h" #include "Helper.h" #include "BoundingBox.h" HINSTANCE g_hInst = NULL; HWND g_hWnd = NULL; D3D_DRIVER_TYPE g_driverType = D3D_DRIVER_TYPE_NULL; D3D_FEATURE_LEVEL g_featureLevel = D3D_FEATURE_LEVEL_11_0; ID3D11Device* g_pd3dDevice = NULL; ID3D11DeviceContext* g_pImmediateContext = NULL; IDXGISwapChain* g_pSwapChain = NULL; ID3D11RenderTargetView* g_pRenderTargetView = NULL; ID3D11Texture2D* g_pDepthStencil = NULL; ID3D11DepthStencilView* g_pDepthStencilView = NULL; ID3D11VertexShader* g_pVertexShader = NULL; ID3D11PixelShader* g_pPixelShader = NULL; ID3D11InputLayout* g_pVertexLayout = NULL; ID3D11Buffer* g_pVertexBuffer = NULL; ID3D11Buffer* g_pIndexBuffer = NULL; ID3D11Buffer* g_pConstantBuffer = NULL; ID3D11ShaderResourceView* g_pTextureRV = NULL; ID3D11SamplerState* g_pSamplerLinear = NULL; XMMATRIX g_World; XMMATRIX g_View; XMMATRIX g_Projection; ConstantBuffer cb; ID3D11ShaderResourceView* m_pTexture = NULL; FirstPersonCamera* m_pFirstPersonCamera = NULL; // 第一人称相机指针 FreeLookCamera* m_pFreeLookCamera = NULL; // 第一人称相机指针 Terrain* m_pTerrain; // 地形指针 ID3D11DepthStencilState* g_pDSSNodepthWrite; // 普通深度状态 ID3D11Buffer* g_pSkyVertexBuffer = NULL; ID3D11Buffer* g_pSkyIndexBuffer = NULL; ID3D11Buffer* g_pSkyConstantBuffer = NULL; ID3D11VertexShader* g_pSkyVertexShader = NULL; ID3D11ShaderResourceView* g_pTextureSkySRV = NULL; ID3D11SamplerState* g_pCubeSampler = NULL; ID3D11DepthStencilState* g_pDSSLessEqual; // 天空盒深度状态 std::vector<ID3D11ShaderResourceView* > g_pTextureCubeSRVs; // 天空盒SRV std::vector<SimpleVertex> skyVertices; // 天空盒顶点 std::vector<WORD> skyIndices; // 天空盒索引 std::vector<Model*> models; // 存放加载的所有模型 std::vector<ID3D11PixelShader*> g_pPixelShaders(6, NULL); // 存放加载的所有 Pixel Shader std::vector<XMMATRIX> m_Worlds; // 存放所有加载的模型的世界矩阵 std::unique_ptr<DirectX::Keyboard> m_pKeyboard = std::make_unique<DirectX::Keyboard>(); // 键盘单例 std::unique_ptr<DirectX::Mouse> m_pMouse = std::make_unique<DirectX::Mouse>(); // 鼠标单例 DirectX::Mouse::ButtonStateTracker m_MouseTracker; // 鼠标状态追踪 XMVECTOR Eye = XMVectorSet(0.0f, 10.0f, 0.0f, 0.0f); XMVECTOR At = XMVectorSet(0.0f, 0.0f, 5.0f, 0.0f); XMVECTOR Up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f); int mNumVertices = 0; // 总顶点数 int mNumIndices = 0; // 总索引数 bool mUsedCamera = 0; // 使用的相机(0为第一人称相机,1为自由视角相机) bool mTexMode = 0; // 无纹理模型的着色(0为使用原色,1为使用木制贴图) std::vector<AABB> AABBs; std::vector<XMMATRIX> modelWorlds; // 存放模型所有世界矩阵 std::vector<std::string> mTextureNames; std::vector<ID3D11ShaderResourceView* > mTextureRVs; std::vector<SimpleVertex> cubeVertexVec; std::vector<WORD> cubeIndexVec; ID3D11Buffer* g_pCubeVertexBuffer = NULL; ID3D11Buffer* g_pCubeIndexBuffer = NULL; ID3D11Buffer* g_pCubeConstantBuffer = NULL; AABB treeAABB; HRESULT InitWindow(HINSTANCE hInstance, int nCmdShow); HRESULT InitDevice(); void CleanupDevice(); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); void Render();<file_sep>/SkyBox.h #pragma once #include "Main.h" //-------------------------------------------------------------------------------------- // 创建天空盒球体 //-------------------------------------------------------------------------------------- void CreateSphere(float radius, UINT levels, UINT slices) { // 创建天空球的顶点数据和索引数据(逆时针绘制) UINT vertexCount = 2 + (levels - 1) * (slices + 1); UINT indexCount = 6 * (levels - 1) * slices; skyVertices.resize(vertexCount); skyIndices.resize(indexCount); SimpleVertex vertexData; UINT vIndex = 0, iIndex = 0; float phi = 0.0f, theta = 0.0f; float per_phi = XM_PI / levels; float per_theta = XM_2PI / slices; float x, y, z; // 放入顶端点 vertexData = { XMFLOAT3(0.0f, radius, 0.0f), XMFLOAT3(0.0f, 1.0f, 0.0f), XMFLOAT2(0.0f, 0.0f) }; skyVertices[vIndex++] = vertexData; for (UINT i = 1; i < levels; ++i) { phi = per_phi * i; // 需要slices + 1个顶点是因为 起点和终点需为同一点,但纹理坐标值不一致 for (UINT j = 0; j <= slices; ++j) { theta = per_theta * j; x = radius * sinf(phi) * cosf(theta); y = radius * cosf(phi); z = radius * sinf(phi) * sinf(theta); // 计算出局部坐标、法向量、Tangent向量和纹理坐标 XMFLOAT3 pos = XMFLOAT3(x, y, z), normal; XMStoreFloat3(&normal, XMVector3Normalize(XMLoadFloat3(&pos))); //vertexData = { pos, normal, XMFLOAT4(-sinf(theta), 0.0f, cosf(theta), 1.0f), XMFLOAT2(theta / XM_2PI, phi / XM_PI) }; //Internal::InsertVertexElement(meshData.vertexVec[vIndex++], vertexData); } } // 放入底端点 vertexData = { XMFLOAT3(0.0f, -radius, 0.0f) }; skyVertices[vIndex++] = vertexData; // 放入索引 if (levels > 1) { for (UINT j = 1; j <= slices; ++j) { skyIndices[iIndex++] = 0; skyIndices[iIndex++] = j; skyIndices[iIndex++] = j % (slices + 1) + 1; } } for (UINT i = 1; i < levels - 1; ++i) { for (UINT j = 1; j <= slices; ++j) { skyIndices[iIndex++] = (i - 1) * (slices + 1) + j; skyIndices[iIndex++] = i * (slices + 1) + j % (slices + 1) + 1; skyIndices[iIndex++] = (i - 1) * (slices + 1) + j % (slices + 1) + 1; skyIndices[iIndex++] = i * (slices + 1) + j % (slices + 1) + 1; skyIndices[iIndex++] = (i - 1) * (slices + 1) + j; skyIndices[iIndex++] = i * (slices + 1) + j; } } if (levels > 1) { for (UINT j = 1; j <= slices; ++j) { skyIndices[iIndex++] = (levels - 2) * (slices + 1) + j; skyIndices[iIndex++] = (levels - 1) * (slices + 1) + 1; skyIndices[iIndex++] = (levels - 2) * (slices + 1) + j % (slices + 1) + 1; } } } void RenderSky() { g_pImmediateContext->VSSetShader(g_pSkyVertexShader, nullptr, 0); // 设置顶点着色器 g_pImmediateContext->PSSetShader(g_pPixelShaders[4], nullptr, 0); // 设置像素着色器 g_pImmediateContext->GSSetShader(nullptr, nullptr, 0); g_pImmediateContext->OMSetDepthStencilState(*g_pDSS, 0); // 设置深度/模板状态 g_pImmediateContext->OMSetBlendState(nullptr, nullptr, 0xFFFFFFFF); UINT strides = sizeof(SimpleVertex); UINT offsets = 0; g_pImmediateContext->IASetVertexBuffers(0, 1, &g_pSkyVertexBuffer, &strides, &offsets); // 设置顶点缓冲区 g_pImmediateContext->IASetIndexBuffer(g_pSkyIndexBuffer, DXGI_FORMAT_R32_UINT, 0); // 设置索引缓冲区 g_pImmediateContext->VSSetConstantBuffers(0, 1, &g_pSkyConstantBuffer); // 将缓冲区绑定到渲染管线上 g_pImmediateContext->PSSetShaderResources(0, 1, &g_pTextureCubeSRVs[0]); // 设置SRV g_pImmediateContext->DrawIndexed(skyIndices.size(), 0, 0); // 绘制 }<file_sep>/AssimpModel.h #pragma once #include "BoundingBox.h" //-------------------------------------------------------------------------------------- // Structures //-------------------------------------------------------------------------------------- // 顶点 struct SimpleVertex { XMFLOAT3 Pos; // 顶点坐标 XMFLOAT3 Normal; // 顶点法线 XMFLOAT4 Color; // 顶点颜色 XMFLOAT2 Texture; // 顶点纹理 }; // 物体表面材质 struct Material { XMFLOAT4 Ambient; XMFLOAT4 Diffuse; XMFLOAT4 Specular; }; // 平行光 struct DirectionalLight { XMFLOAT4 Ambient; XMFLOAT4 Diffuse; XMFLOAT4 Specular; XMFLOAT3 Direction; }; // 常量缓存 struct ConstantBuffer { XMMATRIX mWorld; // 世界矩阵 XMMATRIX mView; // 观察矩阵 XMMATRIX mProjection; // 投影矩阵 XMFLOAT4 vLightDir[3]; // 光线方向 XMFLOAT4 vLightColor[3]; // 光线颜色 XMFLOAT4 vCamera; // 相机位置 XMFLOAT4 vTarget; // 看的位置 XMFLOAT4 mColor; // 漫反射颜色 }; // 模型 struct Model { std::string mName; // 模型名称 std::vector<SimpleVertex> vertices; // 顶点内存 std::vector<WORD> indices; // 索引内存 std::vector<XMFLOAT4> mColors; std::vector<std::string> mTextureNames; std::vector<int> meshVertexOffset; std::vector<int> meshIndexOffset; ID3D11Buffer* mVertexBuffer; ID3D11Buffer* mIndexBuffer; ID3D11Buffer* mConstantBuffer; }; // AABB盒 struct AABB { XMFLOAT3 MaxPos; XMFLOAT3 MinPos; void SetAABB(XMMATRIX mWorld, Model* model) { // 初始化世界坐标最大最小值 XMVECTOR worldPosVecMaxMin = XMLoadFloat3(&XMFLOAT3(model->vertices[0].Pos.x, model->vertices[0].Pos.y, model->vertices[0].Pos.z)); worldPosVecMaxMin = XMVector3TransformCoord(worldPosVecMaxMin, mWorld); XMFLOAT3 worldPosFMaxMin; XMStoreFloat3(&worldPosFMaxMin, worldPosVecMaxMin); MaxPos = worldPosFMaxMin; MinPos = worldPosFMaxMin; // 寻找世界坐标最大最小值 for (int i = 0; i < model->vertices.size(); i++) { XMVECTOR worldPosVec = XMLoadFloat3(&XMFLOAT3(model->vertices[i].Pos.x, model->vertices[i].Pos.y, model->vertices[i].Pos.z)); worldPosVec = XMVector3TransformCoord(worldPosVec, mWorld); XMFLOAT3 worldPosF; XMStoreFloat3(&worldPosF, worldPosVec); if (MaxPos.x < worldPosF.x) { MaxPos.x = worldPosF.x; } if (MaxPos.y < worldPosF.y) { MaxPos.y = worldPosF.y; } if (MaxPos.z < worldPosF.z) { MaxPos.z = worldPosF.z; } if (MinPos.x > worldPosF.x) { MinPos.x = worldPosF.x; } if (MinPos.y > worldPosF.y) { MinPos.y = worldPosF.y; } if (MinPos.z > worldPosF.z) { MinPos.z = worldPosF.z; } } } };<file_sep>/Terrain.h #pragma once #include "Main.h" class Terrain { private: std::vector<float> m_heightInfo; // 高度图高度信息 int m_cellsPerRow; // 每行单元格数 int m_cellsPerCol; // 每列单元格数 int m_verticesPerRow; // 每行顶点数 int m_verticesPerCol; // 每列顶点数 int m_numsVertices; // 顶点总数 float m_width; // 地形宽度 float m_height; // 地形高度 float m_heightScale; // 高度缩放系数 ID3D11Buffer* m_pVertexBuffer; ID3D11Buffer* m_pIndexBuffer; ID3D11Buffer* m_pConstantBuffer; ID3D11InputLayout* m_pInputLayout; ID3D11ShaderResourceView* m_pSRVTerrain; ID3D11SamplerState* m_pSamplerLinear; public: std::vector<SimpleVertex> m_vertices; // 顶点集合 std::vector<WORD> m_indices; // 索引集合 int vertex_offset; int index_offset; Terrain(); // 加载高度图 void LoadHeightMap(std::string filePath); // 计算法线 void ComputeNormal(SimpleVertex& v1, SimpleVertex& v2, SimpleVertex& v3, XMFLOAT3& normal); // 初始化地形 void InitTerrain(float width, float height, UINT m, UINT n, float scale); // 建立缓冲区 void BuildBuffer(); // 建立纹理 void BuildSRVs(const wchar_t* texturePath); // 建立输入布局 void BuildInputLayouts(); // 渲染地形 void Render(ConstantBuffer& cb, long vertex_offset, long index_offset); };<file_sep>/FreeLookCamera.h #pragma once #include <d3d11.h> #include <d3dx11.h> #include <d3dcompiler.h> #include <xnamath.h> // 自由视角相机 class FreeLookCamera { private: XMFLOAT4 mPosition; // 位置 XMFLOAT4 mTarget; // 看的位置 XMFLOAT4 mUpAxis; // 上方向(局部坐标系的+Y轴) XMFLOAT4 mRightAxis; // 右方向(局部坐标系的+X轴) public: FreeLookCamera(XMVECTOR& mPosition, XMVECTOR& mTarget, XMVECTOR& mUpAxis, XMVECTOR& mRightAxis) { XMStoreFloat4(&this->mPosition, mPosition); XMStoreFloat4(&this->mTarget, mTarget); XMStoreFloat4(&this->mUpAxis, mUpAxis); XMStoreFloat4(&this->mRightAxis, mRightAxis); } XMFLOAT4 GetPosition() { return mPosition; } XMFLOAT4 GetTarget() { return mTarget; } XMFLOAT4 GetUpAxis() { return mUpAxis; } XMFLOAT4 GetRightAxis() { return mRightAxis; } // 左右移动 void MoveLeftRight(float d) { float normalize_Length = mRightAxis.x * mRightAxis.x + mRightAxis.z * mRightAxis.z; float normalize_X = mRightAxis.x / normalize_Length; float normalize_Z = mRightAxis.z / normalize_Length; mPosition.x += normalize_X * d; mPosition.z += normalize_Z * d; } // 前后移动 void MoveForwardBack(float d) { float normalize_Length = mTarget.x * mTarget.x + mTarget.y * mTarget.y + mTarget.z * mTarget.z; float normalize_X = mTarget.x / normalize_Length; float normalize_Y = mTarget.y / normalize_Length; float normalize_Z = mTarget.z / normalize_Length; mPosition.x += normalize_X * d; mPosition.y += normalize_Y * d; mPosition.z += normalize_Z * d; } // 抬头低头(绕局部坐标系的X轴旋转) void Pitch(float rad) { // 绕局部坐标系的X轴旋转 XMFLOAT4 saveTarget = mTarget; XMVECTOR newTarget = XMVector4Transform(XMLoadFloat4(&mTarget), XMMatrixRotationAxis(XMLoadFloat4(&mRightAxis), rad)); XMStoreFloat4(&mTarget, newTarget); } // 左右转头(绕局部坐标系的Y轴旋转) void Yaw(float rad) { // 绕Y轴旋转 XMVECTOR newTarget = XMVector4Transform(XMLoadFloat4(&mTarget), XMMatrixRotationY(rad)); XMStoreFloat4(&mTarget, newTarget); // 右方向也要更新 XMVECTOR newRightAxis = XMVector4Transform(XMLoadFloat4(&mRightAxis), XMMatrixRotationY(rad)); XMStoreFloat4(&mRightAxis, newRightAxis); } };<file_sep>/BoundingBox.h #pragma once #include <d3d11.h> #include <d3dx11.h> #include <d3dcompiler.h> #include <xnamath.h> <file_sep>/README.md # SimTown DirectX11大作业 模拟小镇 <file_sep>/Helper.h #pragma once #include <d3d11.h> #include <d3dx11.h> #include <d3dcompiler.h> //-------------------------------------------------------------------------------------- // Helper for compiling shaders with D3DX11 //-------------------------------------------------------------------------------------- HRESULT CompileShaderFromFile(WCHAR* szFileName, LPCSTR szEntryPoint, LPCSTR szShaderModel, ID3DBlob** ppBlobOut) { HRESULT hr = S_OK; DWORD dwShaderFlags = D3DCOMPILE_ENABLE_STRICTNESS; #if defined( DEBUG ) || defined( _DEBUG ) // Set the D3DCOMPILE_DEBUG flag to embed debug information in the shaders. // Setting this flag improves the shader debugging experience, but still allows // the shaders to be optimized and to run exactly the way they will run in // the release configuration of this program. dwShaderFlags |= D3DCOMPILE_DEBUG; #endif ID3DBlob* pErrorBlob; hr = D3DX11CompileFromFile(szFileName, NULL, NULL, szEntryPoint, szShaderModel, dwShaderFlags, 0, NULL, ppBlobOut, &pErrorBlob, NULL); if (FAILED(hr)) { if (pErrorBlob != NULL) OutputDebugStringA((char*)pErrorBlob->GetBufferPointer()); if (pErrorBlob) pErrorBlob->Release(); return hr; } if (pErrorBlob) pErrorBlob->Release(); return S_OK; }<file_sep>/Main.cpp #pragma once #pragma comment(lib, "lib/assimp-vc140-mt.dll") #include "Main.h" #include <Importer.hpp> Terrain::Terrain() { LoadHeightMap("models/terrain/smooth.raw"); InitTerrain(5000, 5000, 50, 50, 1.0f); BuildBuffer(); BuildSRVs(L"models/terrain/grass.png"); BuildInputLayouts(); } // 加载高度图 void Terrain::LoadHeightMap(std::string filePath) { std::ifstream inFile; inFile.open(filePath, std::ios::binary); // 用二进制的方式打开文件 inFile.seekg(0, std::ios::end); // 文件指针移动到末尾 std::vector<BYTE> inData(inFile.tellg()); // 用模板定义一个vector<BYTE>类型的变量inData并初始化,其值为缓冲区当前位置,即缓冲区大小 inFile.seekg(std::ios::beg); // 将文件指针移动到文件的开头,准备读取高度信息 inFile.read((char*)&inData[0], inData.size()); // 读取整个高度信息 inFile.close(); m_heightInfo.resize(inData.size()); // 将m_vHeightInfo尺寸取为缓冲区的尺寸 // 遍历整个缓冲区,将inData中的值赋给m_vHeightInfo for (unsigned int i = 0; i < inData.size(); i++) { m_heightInfo[i] = inData[i]; } } // 计算法线 void Terrain::ComputeNormal(SimpleVertex& v1, SimpleVertex& v2, SimpleVertex& v3, XMFLOAT3& normal) { XMFLOAT3 f1(v2.Pos.x - v1.Pos.x, v2.Pos.y - v1.Pos.y, v2.Pos.z - v1.Pos.z); XMFLOAT3 f2(v3.Pos.x - v1.Pos.x, v3.Pos.y - v1.Pos.y, v3.Pos.z - v1.Pos.z); XMVECTOR vec1 = XMLoadFloat3(&f1); XMVECTOR vec2 = XMLoadFloat3(&f2); XMVECTOR temp = XMVector3Normalize(XMVector3Cross(vec1, vec2)); XMStoreFloat3(&normal, temp); } void Terrain::InitTerrain(float width, float height, UINT m, UINT n, float scale) { m_cellsPerRow = m; m_cellsPerCol = n; m_verticesPerRow = m + 1; m_verticesPerCol = n + 1; m_numsVertices = m_verticesPerRow * m_verticesPerCol; m_width = width; m_height = height; m_heightScale = scale; //得到缩放后的高度 for (auto& item : m_heightInfo) { item *= m_heightScale; } //起始x z坐标 float oX = -width * 0.5f; float oZ = height * 0.5f; //每一格坐标变化 float dx = width / m; float dz = height / n; m_vertices.resize(m_numsVertices); //计算顶点 for (UINT i = 0; i < m_verticesPerCol; ++i) { float tempZ = oZ - dz * i; for (UINT j = 0; j < m_verticesPerRow; ++j) { UINT index = m_verticesPerRow * i + j; m_vertices[index].Pos.x = oX + dx * j; m_vertices[index].Pos.y = m_heightInfo[index]; m_vertices[index].Pos.z = tempZ; m_vertices[index].Texture = XMFLOAT2(dx * i, dx * j); } } //计算索引和法线 //总格子数量:m * n //因此总索引数量: 6 * m * n UINT nIndices = m * n * 6; m_indices.resize(nIndices); UINT tmp = 0; for (UINT i = 0; i < n; ++i) { for (UINT j = 0; j < m; ++j) { m_indices[tmp] = i * m_verticesPerRow + j; m_indices[tmp + 1] = i * m_verticesPerRow + j + 1; m_indices[tmp + 2] = (i + 1) * m_verticesPerRow + j; //计算法线 XMFLOAT3 temp; ComputeNormal(m_vertices[m_indices[tmp]], m_vertices[m_indices[tmp + 1]], m_vertices[m_indices[tmp + 2]], temp); m_vertices[m_indices[tmp]].Normal = temp; m_vertices[m_indices[tmp + 1]].Normal = temp; m_vertices[m_indices[tmp + 2]].Normal = temp; //m_vertices[m_indices[tmp]].Texture = XMFLOAT2(1, 1); //m_vertices[m_indices[tmp + 1]].Texture = XMFLOAT2(1, 1); //m_vertices[m_indices[tmp + 2]].Texture = XMFLOAT2(1, 1); m_indices[tmp + 3] = i * m_verticesPerRow + j + 1; m_indices[tmp + 4] = (i + 1) * m_verticesPerRow + j + 1; m_indices[tmp + 5] = (i + 1) * m_verticesPerRow + j; ComputeNormal(m_vertices[m_indices[tmp + 3]], m_vertices[m_indices[tmp + 4]], m_vertices[m_indices[tmp + 5]], temp); m_vertices[m_indices[tmp + 3]].Normal = temp; m_vertices[m_indices[tmp + 4]].Normal = temp; m_vertices[m_indices[tmp + 5]].Normal = temp; //m_vertices[m_indices[tmp + 3]].Texture = XMFLOAT2(1, 1); //m_vertices[m_indices[tmp + 4]].Texture = XMFLOAT2(1, 1); //m_vertices[m_indices[tmp + 5]].Texture = XMFLOAT2(1, 1); tmp += 6; } } } // 建立缓冲区 void Terrain::BuildBuffer() { // 创建顶点缓冲区 D3D11_BUFFER_DESC vertexDesc; ZeroMemory(&vertexDesc, sizeof(vertexDesc)); vertexDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; vertexDesc.ByteWidth = sizeof(SimpleVertex) * m_numsVertices; vertexDesc.Usage = D3D11_USAGE_IMMUTABLE; D3D11_SUBRESOURCE_DATA vertexData; vertexData.pSysMem = &m_vertices[0]; vertexData.SysMemPitch = 0; vertexData.SysMemSlicePitch = 0; g_pd3dDevice->CreateBuffer(&vertexDesc, &vertexData, &m_pVertexBuffer); // 创建索引缓冲区 D3D11_BUFFER_DESC indexDesc; ZeroMemory(&indexDesc, sizeof(indexDesc)); indexDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; indexDesc.ByteWidth = sizeof(UINT) * m_indices.size(); indexDesc.Usage = D3D11_USAGE_IMMUTABLE; D3D11_SUBRESOURCE_DATA indexData; indexData.pSysMem = &m_indices[0]; indexData.SysMemPitch = 0; indexData.SysMemSlicePitch = 0; g_pd3dDevice->CreateBuffer(&indexDesc, &indexData, &m_pIndexBuffer); } // 建立纹理 void Terrain::BuildSRVs(const wchar_t* texturePath) { // Load the Texture D3DX11CreateShaderResourceViewFromFile(g_pd3dDevice, texturePath, NULL, NULL, &m_pSRVTerrain, NULL); // Create the sample state D3D11_SAMPLER_DESC sampDesc; ZeroMemory(&sampDesc, sizeof(sampDesc)); sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; sampDesc.MinLOD = 0; sampDesc.MaxLOD = D3D11_FLOAT32_MAX; g_pd3dDevice->CreateSamplerState(&sampDesc, &m_pSamplerLinear); } // 建立输入布局 void Terrain::BuildInputLayouts() { D3D11_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; UINT numLayoutElements = ARRAYSIZE(layout); ID3DBlob* pVSBlob = NULL; ID3D11InputLayout* m_pVertexLayout; CompileShaderFromFile(L"Tutorial04.fx", "VS", "vs_4_0", &pVSBlob); g_pd3dDevice->CreateInputLayout(layout, numLayoutElements, pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), &m_pVertexLayout); pVSBlob->Release(); } void Terrain::Render(ConstantBuffer& cb, long vertex_offset, long index_offset) { UINT stride = sizeof(SimpleVertex); UINT offset = 0; g_pImmediateContext->IASetInputLayout(g_pVertexLayout); g_pImmediateContext->OMSetRenderTargets(1, &g_pRenderTargetView, g_pDepthStencilView); g_pImmediateContext->OMSetDepthStencilState(g_pDSSNodepthWrite, 0); g_pImmediateContext->IASetVertexBuffers(0, 1, &g_pVertexBuffer, &stride, &offset); g_pImmediateContext->IASetIndexBuffer(g_pIndexBuffer, DXGI_FORMAT_R16_UINT, 0); g_pImmediateContext->UpdateSubresource(g_pConstantBuffer, 0, NULL, &cb, 0, 0); g_pImmediateContext->VSSetShader(g_pVertexShader, NULL, 0); g_pImmediateContext->VSSetConstantBuffers(0, 1, &g_pConstantBuffer); g_pImmediateContext->PSSetShader(g_pPixelShaders[4], NULL, 0); g_pImmediateContext->PSSetConstantBuffers(0, 1, &g_pConstantBuffer); g_pImmediateContext->PSSetShaderResources(1, 1, &m_pSRVTerrain); g_pImmediateContext->PSSetSamplers(0, 1, &m_pSamplerLinear); g_pImmediateContext->DrawIndexed(m_indices.size(), index_offset, vertex_offset); } namespace AssimpModel { //-------------------------------------------------------------------------------------- // 加载模型函数 //-------------------------------------------------------------------------------------- void LoadModel(const aiScene* scene, Model* model) { int mNumVertices = 0; int mNumFaces = 0; int mNumIndices = 0; for (int i = 0; i < scene->mNumMeshes; i++) { mNumFaces += scene->mMeshes[i]->mNumFaces; // 统计所有面数 mNumVertices += scene->mMeshes[i]->mNumVertices; // 统计所有mesh的顶点数,用于开辟内存空间 } mNumIndices = 3 * mNumFaces; // 计算所有索引数,索引数 = 面数 * 3 // 创建顶点内存 model->vertices.resize(mNumVertices); // 开辟顶点空间 size_t count = 0; // 记录顶点偏移量 std::vector<unsigned int> index_offset(1, 0); int meshVertexOffset = 0; int meshIndexOffset = 0; model->meshVertexOffset.resize(1); model->meshIndexOffset.resize(1); for (int i = 0; i < scene->mNumMeshes; i++) { aiMaterial* material = scene->mMaterials[scene->mMeshes[i]->mMaterialIndex]; aiColor3D color; // 加载颜色 // material->Get(AI_MATKEY_COLOR_AMBIENT, color); material->Get(AI_MATKEY_COLOR_DIFFUSE, color); // material->Get(AI_MATKEY_COLOR_SPECULAR, color); model->mColors.push_back(XMFLOAT4(color.r, color.g, color.b, 1.0f)); // 加载纹理 if (material->GetTextureCount(aiTextureType_DIFFUSE) > 0) { aiString Path; material->GetTexture(aiTextureType_DIFFUSE, 0, &Path, NULL, NULL, NULL, NULL, NULL); model->mTextureNames.push_back(Path.C_Str()); } for (int j = 0; j < scene->mMeshes[i]->mNumVertices; j++) { if (scene->mMeshes[i]->HasTextureCoords(0) && scene->mMeshes[i]->HasNormals()) { model->vertices[count++] = { XMFLOAT3(scene->mMeshes[i]->mVertices[j].x, scene->mMeshes[i]->mVertices[j].y, scene->mMeshes[i]->mVertices[j].z), XMFLOAT3(scene->mMeshes[i]->mNormals[j].x, scene->mMeshes[i]->mNormals[j].y, scene->mMeshes[i]->mNormals[j].z), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(scene->mMeshes[i]->mTextureCoords[0][j].x, scene->mMeshes[i]->mTextureCoords[0][j].y) }; } else if (scene->mMeshes[i]->HasTextureCoords(0) && !scene->mMeshes[i]->HasNormals()) { model->vertices[count++] = { XMFLOAT3(scene->mMeshes[i]->mVertices[j].x, scene->mMeshes[i]->mVertices[j].y, scene->mMeshes[i]->mVertices[j].z), XMFLOAT3(0.0f, 0.0f, 1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(scene->mMeshes[i]->mTextureCoords[0][j].x, scene->mMeshes[i]->mTextureCoords[0][j].y) }; } else if (!scene->mMeshes[i]->HasTextureCoords(0) && scene->mMeshes[i]->HasNormals()) { model->vertices[count++] = { XMFLOAT3(scene->mMeshes[i]->mVertices[j].x, scene->mMeshes[i]->mVertices[j].y, scene->mMeshes[i]->mVertices[j].z), XMFLOAT3(scene->mMeshes[i]->mNormals[j].x, scene->mMeshes[i]->mNormals[j].y, scene->mMeshes[i]->mNormals[j].z), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(1.0f, 1.0f) }; } } meshVertexOffset += scene->mMeshes[i]->mNumVertices; model->meshVertexOffset.push_back(meshVertexOffset); index_offset.push_back(count); // 偏移量放入vector中 } // 创建索引内存 model->indices.resize(mNumIndices); // 开辟索引空间 count = 0; // 记录顶点偏移量 for (int i = 0; i < scene->mNumMeshes; i++) { for (int j = 0; j < scene->mMeshes[i]->mNumFaces; j++) { aiFace face = scene->mMeshes[i]->mFaces[j]; assert(face.mNumIndices == 3); for (int k = 0; k < face.mNumIndices; k++) { int index = face.mIndices[k]; // index值存入自己定义的索引数据结构中 model->indices[count++] = index + index_offset[i]; // 从第二个mesh开始,要考虑索引相对于第一个mesh的偏移 } } meshIndexOffset += 3 * scene->mMeshes[i]->mNumFaces; model->meshIndexOffset.push_back(meshIndexOffset); } D3D11_SUBRESOURCE_DATA InitData; // 模型顶点缓冲区描述 D3D11_BUFFER_DESC bd; ZeroMemory(&bd, sizeof(bd)); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof(SimpleVertex) * model->vertices.size(); // 设置总顶点占用的显存空间 bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; bd.CPUAccessFlags = 0; // 创建模型顶点缓冲区 ZeroMemory(&InitData, sizeof(InitData)); InitData.pSysMem = &model->vertices[0]; g_pd3dDevice->CreateBuffer(&bd, &InitData, &model->mVertexBuffer); // 模型索引缓冲区描述 bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof(WORD) * model->indices.size(); // 设置总索引占用的显存空间 bd.BindFlags = D3D11_BIND_INDEX_BUFFER; bd.CPUAccessFlags = 0; InitData.pSysMem = &model->indices[0]; g_pd3dDevice->CreateBuffer(&bd, &InitData, &model->mIndexBuffer); // 模型常量缓冲区描述 bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof(ConstantBuffer); bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bd.CPUAccessFlags = 0; g_pd3dDevice->CreateBuffer(&bd, NULL, &model->mConstantBuffer); } //-------------------------------------------------------------------------------------- // 从文件读入所有模型 //-------------------------------------------------------------------------------------- void LoadModelsFromFile(std::string filePath, std::vector<Model*>& models) { std::ifstream inFile; inFile.open(filePath, std::ios::in); Assimp::Importer importer; if (inFile) { std::string modelName, modelPath; while (inFile >> modelName >> modelPath) { Model* model = new Model(); model->mName = modelName; const aiScene* scene = importer.ReadFile(modelPath.c_str(), aiProcessPreset_TargetRealtime_MaxQuality | aiProcess_ConvertToLeftHanded | aiProcess_Triangulate | aiProcess_FixInfacingNormals); LoadModel(scene, model); models.push_back(model); } inFile.close(); } } //-------------------------------------------------------------------------------------- // 按模型名称渲染模型 //-------------------------------------------------------------------------------------- void RenderModel(std::string modelName, ConstantBuffer& m_pConstantBuffer, XMMATRIX& m_pWorld) { int vertex_offset = 0; int index_offset = 0; // Set the input layout g_pImmediateContext->IASetInputLayout(g_pVertexLayout); g_pImmediateContext->OMSetRenderTargets(1, &g_pRenderTargetView, g_pDepthStencilView); g_pImmediateContext->OMSetDepthStencilState(g_pDSSNodepthWrite, 0); for (int i = 0; i < models.size(); i++) { if (models[i]->mName == modelName) { UINT stride = sizeof(SimpleVertex); UINT offset = 0; g_pImmediateContext->IASetVertexBuffers(0, 1, &models[i]->mVertexBuffer, &stride, &offset); g_pImmediateContext->IASetIndexBuffer(models[i]->mIndexBuffer, DXGI_FORMAT_R16_UINT, 0); for (int j = 0; j < models[i]->meshIndexOffset.size() - 1; j++) { m_pConstantBuffer.mWorld = XMMatrixTranspose(m_pWorld); // 非地形 if (i != 0) { m_pConstantBuffer.mColor = models[i]->mColors[j]; } // 地形 else { m_pConstantBuffer.mColor = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); } g_pImmediateContext->UpdateSubresource(models[i]->mConstantBuffer, 0, NULL, &cb, 0, 0); g_pImmediateContext->VSSetShader(g_pVertexShader, NULL, 0); g_pImmediateContext->VSSetConstantBuffers(0, 1, &models[i]->mConstantBuffer); // 无贴图 if (models[i]->mTextureNames.empty()) { // 无贴图模式 if (mTexMode == 0) { g_pImmediateContext->PSSetShader(g_pPixelShaders[0], NULL, 0); g_pImmediateContext->PSSetConstantBuffers(0, 1, &models[i]->mConstantBuffer); } // 贴木制贴图 else { g_pImmediateContext->PSSetShader(g_pPixelShaders[4], NULL, 0); g_pImmediateContext->PSSetConstantBuffers(0, 1, &models[i]->mConstantBuffer); g_pImmediateContext->PSSetShaderResources(1, 1, &g_pTextureRV); } } // 有贴图 else { bool isFound = false; for (int k = 0; k < mTextureNames.size(); k++) { if (mTextureNames[k] == models[i]->mTextureNames[j]) { isFound = true; g_pImmediateContext->PSSetShader(g_pPixelShaders[4], NULL, 0); g_pImmediateContext->PSSetConstantBuffers(0, 1, &models[i]->mConstantBuffer); g_pImmediateContext->PSSetShaderResources(1, 1, &mTextureRVs[k]); break; } } if (isFound == false) { g_pImmediateContext->PSSetShader(g_pPixelShaders[4], NULL, 0); g_pImmediateContext->PSSetConstantBuffers(0, 1, &models[i]->mConstantBuffer); g_pImmediateContext->PSSetShaderResources(1, 1, &g_pTextureRV); } } g_pImmediateContext->PSSetSamplers(0, 1, &g_pSamplerLinear); g_pImmediateContext->DrawIndexed(models[i]->meshIndexOffset[j], index_offset, vertex_offset); // 按索引数绘制图形 } } index_offset += models[i]->indices.size(); vertex_offset += models[i]->vertices.size(); } } } //-------------------------------------------------------------------------------------- // Entry point to the program. Initializes everything and goes into a message processing // loop. Idle time is used to render the scene. //-------------------------------------------------------------------------------------- int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); if (FAILED(InitWindow(hInstance, nCmdShow))) return 0; if (FAILED(InitDevice())) { CleanupDevice(); return 0; } // Main message loop MSG msg = { 0 }; while (WM_QUIT != msg.message) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } else { Render(); } } CleanupDevice(); return (int)msg.wParam; } //-------------------------------------------------------------------------------------- // Register class and create window //-------------------------------------------------------------------------------------- HRESULT InitWindow(HINSTANCE hInstance, int nCmdShow) { // Register class WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, (LPCTSTR)IDI_TUTORIAL1); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.lpszMenuName = NULL; wcex.lpszClassName = L"TutorialWindowClass"; wcex.hIconSm = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_TUTORIAL1); if (!RegisterClassEx(&wcex)) return E_FAIL; // Create window g_hInst = hInstance; RECT rc = { 0, 0, 1280, 640 }; AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE); g_hWnd = CreateWindow(L"TutorialWindowClass", L"SimTown", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, hInstance, NULL); if (!g_hWnd) return E_FAIL; ShowWindow(g_hWnd, nCmdShow); m_pMouse->SetWindow(g_hWnd); // 鼠标设置窗口 m_pMouse->SetMode(DirectX::Mouse::MODE_RELATIVE); return S_OK; } //-------------------------------------------------------------------------------------- // 加载Shader PS为Pixel Shader的名称,pixel_shader_index为Pixel Shader的索引 //-------------------------------------------------------------------------------------- HRESULT LoadShader(const char* PS, int pixel_shader_index) { HRESULT hr = S_OK; // Compile the pixel shader ID3DBlob* pPSBlob = NULL; hr = CompileShaderFromFile(L"Tutorial04.fx", PS, "ps_4_0", &pPSBlob); if (FAILED(hr)) { MessageBox(NULL, L"The FX file cannot be compiled. Please run this executable from the directory that contains the FX file.", L"Error", MB_OK); return hr; } // Create the pixel shader hr = g_pd3dDevice->CreatePixelShader(pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), NULL, &g_pPixelShaders[pixel_shader_index]); pPSBlob->Release(); if (FAILED(hr)) return hr; return hr; } //-------------------------------------------------------------------------------------- // Create Direct3D device and swap chain //-------------------------------------------------------------------------------------- HRESULT InitDevice() { HRESULT hr = S_OK; RECT rc; GetClientRect(g_hWnd, &rc); UINT width = rc.right - rc.left; UINT height = rc.bottom - rc.top; UINT createDeviceFlags = 0; #ifdef _DEBUG createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif D3D_DRIVER_TYPE driverTypes[] = { D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_REFERENCE, }; UINT numDriverTypes = ARRAYSIZE(driverTypes); D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, }; UINT numFeatureLevels = ARRAYSIZE(featureLevels); DXGI_SWAP_CHAIN_DESC sd; ZeroMemory(&sd, sizeof(sd)); sd.BufferCount = 1; sd.BufferDesc.Width = width; sd.BufferDesc.Height = height; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = g_hWnd; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.Windowed = TRUE; for (UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++) { g_driverType = driverTypes[driverTypeIndex]; hr = D3D11CreateDeviceAndSwapChain(NULL, g_driverType, NULL, createDeviceFlags, featureLevels, numFeatureLevels, D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &g_featureLevel, &g_pImmediateContext); if (SUCCEEDED(hr)) break; } if (FAILED(hr)) return hr; // Create a render target view ID3D11Texture2D* pBackBuffer = NULL; hr = g_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer); if (FAILED(hr)) return hr; hr = g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_pRenderTargetView); pBackBuffer->Release(); if (FAILED(hr)) return hr; // Create depth stencil texture D3D11_TEXTURE2D_DESC descDepth; ZeroMemory(&descDepth, sizeof(descDepth)); descDepth.Width = width; descDepth.Height = height; descDepth.MipLevels = 1; descDepth.ArraySize = 1; descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; descDepth.SampleDesc.Count = 1; descDepth.SampleDesc.Quality = 0; descDepth.Usage = D3D11_USAGE_DEFAULT; descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL; descDepth.CPUAccessFlags = 0; descDepth.MiscFlags = 0; hr = g_pd3dDevice->CreateTexture2D(&descDepth, NULL, &g_pDepthStencil); if (FAILED(hr)) return hr; // Create the depth stencil view D3D11_DEPTH_STENCIL_VIEW_DESC descDSV; ZeroMemory(&descDSV, sizeof(descDSV)); descDSV.Format = descDepth.Format; descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; descDSV.Texture2D.MipSlice = 0; hr = g_pd3dDevice->CreateDepthStencilView(g_pDepthStencil, &descDSV, &g_pDepthStencilView); if (FAILED(hr)) return hr; g_pImmediateContext->OMSetRenderTargets(1, &g_pRenderTargetView, g_pDepthStencilView); // Setup the viewport D3D11_VIEWPORT vp; vp.Width = (FLOAT)width; vp.Height = (FLOAT)height; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = 0; vp.TopLeftY = 0; g_pImmediateContext->RSSetViewports(1, &vp); // Compile the vertex shader ID3DBlob* pVSBlob = NULL; hr = CompileShaderFromFile(L"Tutorial04.fx", "VS", "vs_4_0", &pVSBlob); if (FAILED(hr)) { MessageBox(NULL, L"The FX file cannot be compiled. Please run this executable from the directory that contains the FX file.", L"Error", MB_OK); return hr; } // Create the vertex shader hr = g_pd3dDevice->CreateVertexShader(pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), NULL, &g_pVertexShader); if (FAILED(hr)) { pVSBlob->Release(); return hr; } // Define the input layout D3D11_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 40, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; UINT numElements = ARRAYSIZE(layout); // Create the input layout hr = g_pd3dDevice->CreateInputLayout(layout, numElements, pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), &g_pVertexLayout); pVSBlob->Release(); if (FAILED(hr)) return hr; // 加载Shader char* shaders[] = { "PS_Ambient_Shading", "PS_Lambertian_Shading", "PS_Blinn_Phong_Shading", "PS_Toon_Shading", "PS_Texture_Mapping", "PS_Sky_Texture" }; LoadShader(shaders[0], 0); LoadShader(shaders[1], 1); LoadShader(shaders[2], 2); LoadShader(shaders[3], 3); LoadShader(shaders[4], 4); LoadShader(shaders[5], 5); // 创建第一人称相机 m_pFirstPersonCamera = new FirstPersonCamera(Eye, At, Up, XMVector4Normalize(XMVector3Cross(Up, At))); // 创建自由视角相机 m_pFreeLookCamera = new FreeLookCamera(Eye, At, Up, XMVector4Normalize(XMVector3Cross(Up, At))); // 加载模型 AssimpModel::LoadModelsFromFile("models.txt", models); modelWorlds.push_back(XMMatrixScaling(50.0f, 50.0f, 50.0f) * XMMatrixTranslation(0.0f, 0.0f, 0.0f) * XMMatrixRotationY(0.0f)); // terrain modelWorlds.push_back(XMMatrixScaling(5.0f, 5.0f, 5.0f) * XMMatrixTranslation(-500.0f, 0.0f, 1000.0f) * XMMatrixRotationY(0.0f));// highschool modelWorlds.push_back(XMMatrixScaling(1.0f, 1.0f, 1.0f) * XMMatrixTranslation(1000.0f, 0.0f, 500.0f) * XMMatrixRotationY(0.0f)); // hospital modelWorlds.push_back(XMMatrixScaling(3.0f, 3.0f, 3.0f) * XMMatrixTranslation(1000.0f, 0.0f, 0.0f) * XMMatrixRotationY(0.0f)); // house1 modelWorlds.push_back(XMMatrixScaling(3.0f, 3.0f, 3.0f) * XMMatrixTranslation(1000.0f, 0.0f, -500.0f) * XMMatrixRotationY(0.0f)); // house2 modelWorlds.push_back(XMMatrixScaling(3.0f, 3.0f, 3.0f) * XMMatrixTranslation(1000.0f, 0.0f, -1000.0f) * XMMatrixRotationY(0.0f)); // house3 modelWorlds.push_back(XMMatrixScaling(3.0f, 3.0f, 3.0f) * XMMatrixTranslation(-500.0f, 0.0f, 300.0f) * XMMatrixRotationY(0.0f)); // house4 modelWorlds.push_back(XMMatrixScaling(3.0f, 3.0f, 3.0f) * XMMatrixTranslation(-500.0f, 0.0f, -500.0f) * XMMatrixRotationY(0.0f)); // house5 modelWorlds.push_back(XMMatrixScaling(10.0f, 10.0f, 10.0f) * XMMatrixTranslation(-500.0f, 0.0f, 500.0f) * XMMatrixRotationY(0.0f)); // park modelWorlds.push_back(XMMatrixScaling(1.0f, 1.0f, 1.0f) * XMMatrixTranslation(500.0f, 0.0f, 300.0f) * XMMatrixRotationY(0.0f)); // police modelWorlds.push_back(XMMatrixScaling(5.0f, 5.0f, 5.0f) * XMMatrixTranslation(500.0f, 0.0f, 100.0f) * XMMatrixRotationY(0.0f)); // shop treeAABB.SetAABB(XMMatrixScaling(5.0f, 5.0f, 5.0f) * XMMatrixTranslation(500.0f, 0.0f, 100.0f) * XMMatrixRotationY(0.0f), models[10]); modelWorlds.push_back(XMMatrixScaling(10.0f, 10.0f, 10.0f) * XMMatrixTranslation(0.0f, 0.0f, 0.0f) * XMMatrixRotationY(0.0f)); // car modelWorlds.push_back(XMMatrixScaling(5.0f, 5.0f, 5.0f) * XMMatrixTranslation(0.0f, 0.0f, -700.0f) * XMMatrixRotationY(0.0f)); // tree modelWorlds.push_back(XMMatrixScaling(5.0f, 5.0f, 5.0f) * XMMatrixTranslation(0.0f, 0.0f, -900.0f) * XMMatrixRotationY(0.0f)); // tree2 ID3D11ShaderResourceView *SRV1, *SRV2, *SRV3, *SRV4, *SRV5, *SRV6, *SRV7, *SRV8, *SRV9, *SRV10, *SRV11, *SRV12, *SRV13; D3DX11CreateShaderResourceViewFromFile(g_pd3dDevice, L"models/texture/grass.png", NULL, NULL, &SRV1, NULL); D3DX11CreateShaderResourceViewFromFile(g_pd3dDevice, L"models/texture/car_texture.png", NULL, NULL, &SRV2, NULL); D3DX11CreateShaderResourceViewFromFile(g_pd3dDevice, L"models/texture/StreetCorner.jpg", NULL, NULL, &SRV3, NULL); D3DX11CreateShaderResourceViewFromFile(g_pd3dDevice, L"models/texture/StreetCrossing.jpg", NULL, NULL, &SRV4, NULL); D3DX11CreateShaderResourceViewFromFile(g_pd3dDevice, L"models/texture/StreetEnd.jpg", NULL, NULL, &SRV5, NULL); D3DX11CreateShaderResourceViewFromFile(g_pd3dDevice, L"models/texture/StreetLine.jpg", NULL, NULL, &SRV6, NULL); D3DX11CreateShaderResourceViewFromFile(g_pd3dDevice, L"models/texture/StreetT.jpg", NULL, NULL, &SRV7, NULL); D3DX11CreateShaderResourceViewFromFile(g_pd3dDevice, L"models/texture/tile_wood.jpg", NULL, NULL, &SRV8, NULL); D3DX11CreateShaderResourceViewFromFile(g_pd3dDevice, L"models/texture/tree_texture.jpg", NULL, NULL, &SRV9, NULL); D3DX11CreateShaderResourceViewFromFile(g_pd3dDevice, L"models/texture/M61501.dds", NULL, NULL, &SRV10, NULL); D3DX11CreateShaderResourceViewFromFile(g_pd3dDevice, L"models/texture/M61501_n.dds", NULL, NULL, &SRV11, NULL); D3DX11CreateShaderResourceViewFromFile(g_pd3dDevice, L"models/texture/M61501_s.dds", NULL, NULL, &SRV12, NULL); D3DX11CreateShaderResourceViewFromFile(g_pd3dDevice, L"models/texture/male_diffuse_white_med-facial.jpg", NULL, NULL, &SRV13, NULL); mTextureRVs.push_back(SRV1); mTextureNames.push_back("grass.png"); mTextureRVs.push_back(SRV2); mTextureNames.push_back("car_texture.png"); mTextureRVs.push_back(SRV3); mTextureNames.push_back("StreetCorner.jpg"); mTextureRVs.push_back(SRV4); mTextureNames.push_back("StreetCrossing.jpg"); mTextureRVs.push_back(SRV5); mTextureNames.push_back("StreetEnd.jpg"); mTextureRVs.push_back(SRV6); mTextureNames.push_back("StreetLine.jpg"); mTextureRVs.push_back(SRV7); mTextureNames.push_back("StreetT.jpg"); mTextureRVs.push_back(SRV8); mTextureNames.push_back("tile_wood.jpg"); mTextureRVs.push_back(SRV9); mTextureNames.push_back("tree_texture.jpg"); mTextureRVs.push_back(SRV10); mTextureNames.push_back("M61501.dds"); mTextureRVs.push_back(SRV11); mTextureNames.push_back("M61501_n.dds"); mTextureRVs.push_back(SRV12); mTextureNames.push_back("M61501_s.dds"); mTextureRVs.push_back(SRV13); mTextureNames.push_back("male_diffuse_white_med-facial.jpg"); for (int i = 0; i < models.size(); i++) { AABB aabb; aabb.SetAABB(modelWorlds[i], models[i]); AABBs.push_back(aabb); } //memcpy(vertices + vertex_offset, &m_pTerrain->m_vertices[0], sizeof(SimpleVertex) * m_pTerrain->m_vertices.size()); //memcpy(indices + index_offset, &m_pTerrain->m_indices[0], sizeof(WORD) * m_pTerrain->m_indices.size()); //m_pTerrain->vertex_offset = vertex_offset; //m_pTerrain->index_offset = index_offset; int levels = 50, slices = 50, radius = 100; // 创建天空球的顶点数据和索引数据(逆时针绘制) UINT vertexCount = 2 + (levels - 1) * (slices + 1); UINT indexCount = 6 * (levels - 1) * slices; skyVertices.resize(vertexCount); skyIndices.resize(indexCount); SimpleVertex vertexData; UINT vIndex = 0, iIndex = 0; float phi = 0.0f, theta = 0.0f; float per_phi = XM_PI / levels; float per_theta = XM_2PI / slices; float x, y, z; // 放入顶端点 vertexData = { XMFLOAT3(0.0f, radius, 0.0f), XMFLOAT3(0.0f, 1.0f, 0.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(0.0f, 0.0f) }; skyVertices[vIndex++] = vertexData; for (UINT i = 1; i < levels; ++i) { phi = per_phi * i; // 需要slices + 1个顶点是因为 起点和终点需为同一点,但纹理坐标值不一致 for (UINT j = 0; j <= slices; ++j) { theta = per_theta * j; x = radius * sinf(phi) * cosf(theta); y = radius * cosf(phi); z = radius * sinf(phi) * sinf(theta); // 计算出局部坐标、法向量、Tangent向量和纹理坐标 XMFLOAT3 pos = XMFLOAT3(x, y, z), normal; XMStoreFloat3(&normal, XMVector3Normalize(XMLoadFloat3(&pos))); vertexData = { pos, normal, XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(theta / XM_2PI, phi / XM_PI) }; skyVertices[vIndex++] = { XMFLOAT3(x, y, z), }; } } // 放入底端点 vertexData = { XMFLOAT3(0.0f, -radius, 0.0f), XMFLOAT3(0.0f, -1.0f, 0.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT2(0.0f, 1.0f) }; skyVertices[vIndex++] = vertexData; // 放入索引 if (levels > 1) { for (UINT j = 1; j <= slices; ++j) { skyIndices[iIndex++] = 0; skyIndices[iIndex++] = j; skyIndices[iIndex++] = j % (slices + 1) + 1; } } for (UINT i = 1; i < levels - 1; ++i) { for (UINT j = 1; j <= slices; ++j) { skyIndices[iIndex++] = (i - 1) * (slices + 1) + j; skyIndices[iIndex++] = i * (slices + 1) + j % (slices + 1) + 1; skyIndices[iIndex++] = (i - 1) * (slices + 1) + j % (slices + 1) + 1; skyIndices[iIndex++] = i * (slices + 1) + j % (slices + 1) + 1; skyIndices[iIndex++] = (i - 1) * (slices + 1) + j; skyIndices[iIndex++] = i * (slices + 1) + j; } } if (levels > 1) { for (UINT j = 1; j <= slices; ++j) { skyIndices[iIndex++] = (levels - 2) * (slices + 1) + j; skyIndices[iIndex++] = (levels - 1) * (slices + 1) + 1; skyIndices[iIndex++] = (levels - 2) * (slices + 1) + j % (slices + 1) + 1; } } cubeVertexVec.resize(24); float w2 = (treeAABB.MaxPos.x - treeAABB.MinPos.x) / 2, h2 = (treeAABB.MaxPos.y - treeAABB.MinPos.y) / 2, d2 = (treeAABB.MaxPos.z - treeAABB.MinPos.z) / 2; // 右面(+X面) cubeVertexVec[0].Pos = XMFLOAT3(w2, -h2, -d2); cubeVertexVec[1].Pos = XMFLOAT3(w2, h2, -d2); cubeVertexVec[2].Pos = XMFLOAT3(w2, h2, d2); cubeVertexVec[3].Pos = XMFLOAT3(w2, -h2, d2); // 左面(-X面) cubeVertexVec[4].Pos = XMFLOAT3(-w2, -h2, d2); cubeVertexVec[5].Pos = XMFLOAT3(-w2, h2, d2); cubeVertexVec[6].Pos = XMFLOAT3(-w2, h2, -d2); cubeVertexVec[7].Pos = XMFLOAT3(-w2, -h2, -d2); // 顶面(+Y面) cubeVertexVec[8].Pos = XMFLOAT3(-w2, h2, -d2); cubeVertexVec[9].Pos = XMFLOAT3(-w2, h2, d2); cubeVertexVec[10].Pos = XMFLOAT3(w2, h2, d2); cubeVertexVec[11].Pos = XMFLOAT3(w2, h2, -d2); // 底面(-Y面) cubeVertexVec[12].Pos = XMFLOAT3(w2, -h2, -d2); cubeVertexVec[13].Pos = XMFLOAT3(w2, -h2, d2); cubeVertexVec[14].Pos = XMFLOAT3(-w2, -h2, d2); cubeVertexVec[15].Pos = XMFLOAT3(-w2, -h2, -d2); // 背面(+Z面) cubeVertexVec[16].Pos = XMFLOAT3(w2, -h2, d2); cubeVertexVec[17].Pos = XMFLOAT3(w2, h2, d2); cubeVertexVec[18].Pos = XMFLOAT3(-w2, h2, d2); cubeVertexVec[19].Pos = XMFLOAT3(-w2, -h2, d2); // 正面(-Z面) cubeVertexVec[20].Pos = XMFLOAT3(-w2, -h2, -d2); cubeVertexVec[21].Pos = XMFLOAT3(-w2, h2, -d2); cubeVertexVec[22].Pos = XMFLOAT3(w2, h2, -d2); cubeVertexVec[23].Pos = XMFLOAT3(w2, -h2, -d2); for (UINT i = 0; i < 4; ++i) { // 右面(+X面) cubeVertexVec[i].Normal = XMFLOAT3(1.0f, 0.0f, 0.0f); cubeVertexVec[i].Color = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); // 左面(-X面) cubeVertexVec[i + 4].Normal = XMFLOAT3(-1.0f, 0.0f, 0.0f); cubeVertexVec[i + 4].Color = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); // 顶面(+Y面) cubeVertexVec[i + 8].Normal = XMFLOAT3(0.0f, 1.0f, 0.0f); cubeVertexVec[i + 8].Color = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); // 底面(-Y面) cubeVertexVec[i + 12].Normal = XMFLOAT3(0.0f, -1.0f, 0.0f); cubeVertexVec[i + 12].Color = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); // 背面(+Z面) cubeVertexVec[i + 16].Normal = XMFLOAT3(0.0f, 0.0f, 1.0f); cubeVertexVec[i + 16].Color = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); // 正面(-Z面) cubeVertexVec[i + 20].Normal = XMFLOAT3(0.0f, 0.0f, -1.0f); cubeVertexVec[i + 20].Color = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); } for (UINT i = 0; i < 6; ++i) { cubeVertexVec[i * 4].Texture = XMFLOAT2(0.0f, 1.0f); cubeVertexVec[i * 4 + 1].Texture = XMFLOAT2(0.0f, 0.0f); cubeVertexVec[i * 4 + 2].Texture = XMFLOAT2(1.0f, 0.0f); cubeVertexVec[i * 4 + 3].Texture = XMFLOAT2(1.0f, 1.0f); } cubeIndexVec = { 0, 1, 2, 2, 3, 0, // 右面(+X面) 4, 5, 6, 6, 7, 4, // 左面(-X面) 8, 9, 10, 10, 11, 8, // 顶面(+Y面) 12, 13, 14, 14, 15, 12, // 底面(-Y面) 16, 17, 18, 18, 19, 16, // 背面(+Z面) 20, 21, 22, 22, 23, 20 // 正面(-Z面) }; D3D11_SUBRESOURCE_DATA InitData; // 天空盒顶点缓冲区描述 D3D11_BUFFER_DESC vbd; ZeroMemory(&vbd, sizeof(vbd)); vbd.Usage = D3D11_USAGE_DEFAULT; vbd.ByteWidth = sizeof(SimpleVertex) * skyVertices.size(); vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER; vbd.CPUAccessFlags = 0; // 创建天空盒顶点缓冲区 ZeroMemory(&InitData, sizeof(InitData)); InitData.pSysMem = &skyVertices[0]; g_pd3dDevice->CreateBuffer(&vbd, &InitData, &g_pSkyVertexBuffer); // 天空盒索引缓冲区描述 D3D11_BUFFER_DESC ibd; ZeroMemory(&ibd, sizeof(ibd)); ibd.Usage = D3D11_USAGE_DEFAULT; ibd.ByteWidth = sizeof(WORD) * skyIndices.size(); ibd.BindFlags = D3D11_BIND_INDEX_BUFFER; ibd.CPUAccessFlags = 0; // 创建天空盒索引缓冲区 ZeroMemory(&InitData, sizeof(InitData)); InitData.pSysMem = &skyIndices[0]; g_pd3dDevice->CreateBuffer(&ibd, &InitData, &g_pSkyIndexBuffer); // 常量缓冲区描述 D3D11_BUFFER_DESC cbd; ZeroMemory(&cbd, sizeof(cbd)); cbd.Usage = D3D11_USAGE_DEFAULT; cbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; //cbd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; cbd.ByteWidth = sizeof(ConstantBuffer); g_pd3dDevice->CreateBuffer(&cbd, nullptr, &g_pSkyConstantBuffer); D3D11_DEPTH_STENCIL_DESC dsDesc; // 一般深度状态 dsDesc.DepthEnable = true; dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; dsDesc.DepthFunc = D3D11_COMPARISON_LESS; // less dsDesc.StencilEnable = false; g_pd3dDevice->CreateDepthStencilState(&dsDesc, &g_pDSSNodepthWrite); // 允许使用深度值一致的像素进行替换的深度/模板状态 // 该状态用于绘制天空盒,因为深度值为1.0时默认无法通过深度测试 dsDesc.DepthEnable = true; dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; dsDesc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL; // less equal dsDesc.StencilEnable = false; g_pd3dDevice->CreateDepthStencilState(&dsDesc, &g_pDSSLessEqual); // 立方体顶点缓冲区描述 ZeroMemory(&vbd, sizeof(vbd)); vbd.Usage = D3D11_USAGE_DEFAULT; vbd.ByteWidth = sizeof(SimpleVertex) * cubeVertexVec.size(); vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER; vbd.CPUAccessFlags = 0; // 创建立方体顶点缓冲区 ZeroMemory(&InitData, sizeof(InitData)); InitData.pSysMem = &cubeVertexVec[0]; g_pd3dDevice->CreateBuffer(&vbd, &InitData, &g_pCubeVertexBuffer); // 立方体索引缓冲区描述 ZeroMemory(&ibd, sizeof(ibd)); ibd.Usage = D3D11_USAGE_DEFAULT; ibd.ByteWidth = sizeof(WORD) * cubeIndexVec.size(); ibd.BindFlags = D3D11_BIND_INDEX_BUFFER; ibd.CPUAccessFlags = 0; // 创建立方体索引缓冲区 ZeroMemory(&InitData, sizeof(InitData)); InitData.pSysMem = &cubeIndexVec[0]; g_pd3dDevice->CreateBuffer(&ibd, &InitData, &g_pCubeIndexBuffer); // 常量缓冲区描述 ZeroMemory(&cbd, sizeof(cbd)); cbd.Usage = D3D11_USAGE_DEFAULT; cbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; cbd.ByteWidth = sizeof(ConstantBuffer); g_pd3dDevice->CreateBuffer(&cbd, nullptr, &g_pCubeConstantBuffer); g_pTextureCubeSRVs.resize(6); D3DX11CreateShaderResourceViewFromFile(g_pd3dDevice, L"models/texture/sunset_posX.bmp", NULL, NULL, &g_pTextureCubeSRVs[0], NULL); D3DX11CreateShaderResourceViewFromFile(g_pd3dDevice, L"models/texture/sunset_posY.bmp", NULL, NULL, &g_pTextureCubeSRVs[1], NULL); D3DX11CreateShaderResourceViewFromFile(g_pd3dDevice, L"models/texture/sunset_posZ.bmp", NULL, NULL, &g_pTextureCubeSRVs[2], NULL); D3DX11CreateShaderResourceViewFromFile(g_pd3dDevice, L"models/texture/sunset_negX.bmp", NULL, NULL, &g_pTextureCubeSRVs[3], NULL); D3DX11CreateShaderResourceViewFromFile(g_pd3dDevice, L"models/texture/sunset_negY.bmp", NULL, NULL, &g_pTextureCubeSRVs[4], NULL); D3DX11CreateShaderResourceViewFromFile(g_pd3dDevice, L"models/texture/sunset_negZ.bmp", NULL, NULL, &g_pTextureCubeSRVs[5], NULL); D3DX11CreateShaderResourceViewFromFile(g_pd3dDevice, L"models/texture/desertcube.dds", NULL, NULL, &g_pTextureSkySRV, NULL); // 编译天空盒顶点Shader pVSBlob = NULL; hr = CompileShaderFromFile(L"Tutorial04.fx", "Sky_VS", "vs_4_0", &pVSBlob); if (FAILED(hr)) { MessageBox(NULL, L"The FX file cannot be compiled. Please run this executable from the directory that contains the FX file.", L"Error", MB_OK); return hr; } // 创建天空盒顶点Shader hr = g_pd3dDevice->CreateVertexShader(pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), NULL, &g_pSkyVertexShader); if (FAILED(hr)) { pVSBlob->Release(); return hr; } // Set primitive topology g_pImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); // Load the Texture hr = D3DX11CreateShaderResourceViewFromFile(g_pd3dDevice, L"models/texture/tile_wood.jpg", NULL, NULL, &g_pTextureRV, NULL); if (FAILED(hr)) return hr; // Create the sample state D3D11_SAMPLER_DESC sampDesc; ZeroMemory(&sampDesc, sizeof(sampDesc)); sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.ComparisonFunc = D3D11_COMPARISON_LESS; sampDesc.MinLOD = 0; sampDesc.MaxLOD = D3D11_FLOAT32_MAX; hr = g_pd3dDevice->CreateSamplerState(&sampDesc, &g_pSamplerLinear); if (FAILED(hr)) return hr; ZeroMemory(&sampDesc, sizeof(sampDesc)); sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.ComparisonFunc = D3D11_COMPARISON_LESS_EQUAL; sampDesc.MinLOD = 0; sampDesc.MaxLOD = D3D11_FLOAT32_MAX; g_pd3dDevice->CreateSamplerState(&sampDesc, &g_pCubeSampler); // Initialize the projection matrix g_Projection = XMMatrixPerspectiveFovLH(XM_PIDIV2, width / (FLOAT)height, 0.01f, 1000000.0f); return S_OK; } //-------------------------------------------------------------------------------------- // Clean up the objects we've created //-------------------------------------------------------------------------------------- void CleanupDevice() { if (g_pImmediateContext) g_pImmediateContext->ClearState(); for (int i = 0; i < g_pPixelShaders.size(); i++) { if (g_pPixelShaders[i]) g_pPixelShaders[i]->Release(); } if (g_pSamplerLinear) g_pSamplerLinear->Release(); if (g_pTextureRV) g_pTextureRV->Release(); if (g_pConstantBuffer) g_pConstantBuffer->Release(); if (g_pVertexBuffer) g_pVertexBuffer->Release(); if (g_pIndexBuffer) g_pIndexBuffer->Release(); if (g_pVertexLayout) g_pVertexLayout->Release(); if (g_pVertexShader) g_pVertexShader->Release(); if (g_pPixelShader) g_pPixelShader->Release(); if (g_pDepthStencil) g_pDepthStencil->Release(); if (g_pDepthStencilView) g_pDepthStencilView->Release(); if (g_pRenderTargetView) g_pRenderTargetView->Release(); if (g_pSwapChain) g_pSwapChain->Release(); if (g_pImmediateContext) g_pImmediateContext->Release(); if (g_pd3dDevice) g_pd3dDevice->Release(); } //-------------------------------------------------------------------------------------- // Called every time the application receives a message //-------------------------------------------------------------------------------------- LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { PAINTSTRUCT ps; HDC hdc; m_pKeyboard->ProcessMessage(message, wParam, lParam); // 监听键盘 m_pMouse->ProcessMessage(message, wParam, lParam); // 监听鼠标 switch (message) { case WM_PAINT: hdc = BeginPaint(hWnd, &ps); EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // sp 线起点 // sq 线终点 // amin amax 表示 AABB包围盒 X, Y, Z 轴坐标的 最小 最大值 static float tmin, tmax; static bool isectSegAABB(XMFLOAT4 &eye, XMFLOAT4 &target, XMFLOAT3 &min, XMFLOAT3 &max, float& tmin, float& tmax) { static const float EPS = 1e-6f; float sp[3] = { eye.x, eye.y, eye.z }; float sq[3] = { target.x, target.y, target.z }; float amin[3] = { min.x, min.y, min.z }; float amax[3] = { max.x, max.y, max.z }; // 视线方向 float d[3]; d[0] = target.x - eye.x; d[1] = target.y - eye.y; d[2] = target.z - eye.z; // 因为是线段 所以参数t取值在0和1之间 tmin = 0.0; tmax = 1.0f; for (int i = 0; i < 3; i++) { // 如果视线某一个轴分量为0,且在包围盒这个轴分量之外,那么直接判定不相交 if (fabsf(d[i]) < EPS) { if (sp[i] < amin[i] || sp[i] > amax[i]) return false; } else { const float ood = 1.0f / d[i]; // 计算参数t 并令 t1为较小值 t2为较大值 float t1 = (amin[i] - sp[i]) * ood; float t2 = (amax[i] - sp[i]) * ood; if (t1 > t2) { float tmp = t1; t1 = t2; t2 = tmp; } if (t1 > tmin) tmin = t1; if (t2 < tmax) tmax = t2; // 判定不相交 if (tmin > tmax) return false; } } return true; } //-------------------------------------------------------------------------------------- // Render a frame //-------------------------------------------------------------------------------------- void Render() { // Update our time static float t = 0.0f; if (g_driverType == D3D_DRIVER_TYPE_REFERENCE) { t += (float)XM_PI * 0.0125f; } else { static DWORD dwTimeStart = 0; DWORD dwTimeCur = GetTickCount(); if (dwTimeStart == 0) dwTimeStart = dwTimeCur; t = (dwTimeCur - dwTimeStart) / 1000.0f; } // 更新视角 if (mUsedCamera == 0) { Eye = XMLoadFloat4(&m_pFirstPersonCamera->GetPosition()); At = XMLoadFloat4(&m_pFirstPersonCamera->GetTarget()); g_View = XMMatrixLookAtLH(Eye, Eye + At, Up); } else { Eye = XMLoadFloat4(&m_pFreeLookCamera->GetPosition()); At = XMLoadFloat4(&m_pFreeLookCamera->GetTarget()); g_View = XMMatrixLookAtLH(Eye, Eye + At, Up); } XMFLOAT4 vCamera, vTarget; XMStoreFloat4(&vCamera, Eye); XMStoreFloat4(&vTarget, At); // 监听键盘 DirectX::Keyboard::State keyState = m_pKeyboard->GetState(); if (keyState.IsKeyDown(DirectX::Keyboard::D1)) { mUsedCamera = 0; } if (keyState.IsKeyDown(DirectX::Keyboard::D2)) { mUsedCamera = 1; } if (keyState.IsKeyDown(DirectX::Keyboard::D3)) { mTexMode = 0; } if (keyState.IsKeyDown(DirectX::Keyboard::D4)) { mTexMode = 1; } if (keyState.IsKeyDown(DirectX::Keyboard::W)) { if (mUsedCamera == 0) { m_pFirstPersonCamera->MoveForwardBack(2.0f); } else { m_pFreeLookCamera->MoveForwardBack(2.0f); } } if (keyState.IsKeyDown(DirectX::Keyboard::S)) { if (mUsedCamera == 0) { m_pFirstPersonCamera->MoveForwardBack(-2.0f); } else { m_pFreeLookCamera->MoveForwardBack(-2.0f); } } if (keyState.IsKeyDown(DirectX::Keyboard::A)) { if (mUsedCamera == 0) { m_pFirstPersonCamera->MoveLeftRight(-0.5f); } else { m_pFreeLookCamera->MoveLeftRight(-0.5f); } } if (keyState.IsKeyDown(DirectX::Keyboard::D)) { if (mUsedCamera == 0) { m_pFirstPersonCamera->MoveLeftRight(0.5f); } else { m_pFreeLookCamera->MoveLeftRight(0.5f); } } if (keyState.IsKeyDown(DirectX::Keyboard::Escape)) { SendMessage(g_hWnd, WM_DESTROY, 0, 0); } if (keyState.IsKeyDown(DirectX::Keyboard::Space) && mUsedCamera == 0) { m_pFirstPersonCamera->Jump(); } m_pFirstPersonCamera->CheckJump(0.2f, 10.0f, 20.0f); // 监听鼠标 DirectX::Mouse::State mouseState = m_pMouse->GetState(); DirectX::Mouse::ButtonStateTracker st; if (mouseState.positionMode == DirectX::Mouse::MODE_RELATIVE) { if (mUsedCamera == 0) { m_pFirstPersonCamera->Pitch(mouseState.y * 0.005f); m_pFirstPersonCamera->Yaw(mouseState.x * 0.005f); } else { m_pFreeLookCamera->Pitch(mouseState.y * 0.005f); m_pFreeLookCamera->Yaw(mouseState.x * 0.005f); } if (mouseState.leftButton) { if (isectSegAABB(vCamera, vTarget, treeAABB.MinPos, treeAABB.MaxPos, tmin, tmax)) { MessageBox(NULL, L"你选中了商店!", L"提示信息", MB_OK); } } } // // Clear the back buffer // float ClearColor[4] = { 0.76f, 0.82f, 0.94f, 1.0f }; // red, green, blue, alpha g_pImmediateContext->ClearRenderTargetView(g_pRenderTargetView, ClearColor); // // Clear the depth buffer to 1.0 (max depth) // g_pImmediateContext->ClearDepthStencilView(g_pDepthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0); XMFLOAT4 vLightDirs[3] = { XMFLOAT4(-0.577f, 0.577f, -0.577f, 1.0f), XMFLOAT4(-0.577f, 0.577f, -0.577f, 1.0f), XMFLOAT4(0.0f, -0.707f, -0.707f, 1.0f) }; XMFLOAT4 vLightColors[3] = { XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f) }; for (int i = 0; i < models.size(); i++) { XMMATRIX mWorld = modelWorlds[i]; cb.mView = XMMatrixTranspose(g_View); cb.mProjection = XMMatrixTranspose(g_Projection); cb.vLightDir[0] = vLightDirs[0]; cb.vLightDir[1] = vLightDirs[1]; cb.vLightDir[2] = vLightDirs[2]; cb.vLightColor[0] = vLightColors[0]; cb.vLightColor[1] = vLightColors[1]; cb.vLightColor[2] = vLightColors[2]; cb.vCamera = vCamera; cb.vTarget = vTarget; AssimpModel::RenderModel(models[i]->mName, cb, mWorld); } /*ConstantBuffer tcb; tcb.mWorld = XMMatrixTranslation(0, 0, 0) * XMMatrixScaling(1, 0, 1); tcb.mView = XMMatrixTranspose(g_View); tcb.mProjection = XMMatrixTranspose(g_Projection); tcb.vLightDir[0] = vLightDirs[0]; tcb.vLightDir[1] = vLightDirs[1]; tcb.vLightDir[2] = vLightDirs[2]; tcb.vLightColor[0] = vLightColors[0]; tcb.vLightColor[1] = vLightColors[1]; tcb.vLightColor[2] = vLightColors[2]; m_pTerrain->Render(tcb, m_pTerrain->vertex_offset, m_pTerrain->index_offset);*/ UINT stride = sizeof(SimpleVertex); UINT offset = 0; cb.mWorld = XMMatrixTranspose(XMMatrixScaling(5.0f, 5.0f, 5.0f) * XMMatrixTranslation(500.0f, 0.0f, 100.0f) * XMMatrixRotationY(0.0f)); cb.mView = XMMatrixTranspose(g_View); cb.mProjection = XMMatrixTranspose(g_Projection); cb.vCamera = vCamera; cb.vTarget = vTarget; g_pImmediateContext->IASetVertexBuffers(0, 1, &g_pCubeVertexBuffer, &stride, &offset); g_pImmediateContext->IASetIndexBuffer(g_pCubeIndexBuffer, DXGI_FORMAT_R16_UINT, 0); g_pImmediateContext->OMSetDepthStencilState(g_pDSSNodepthWrite, 0); g_pImmediateContext->UpdateSubresource(g_pCubeConstantBuffer, 0, NULL, &cb, 0, 0); g_pImmediateContext->VSSetShader(g_pVertexShader, NULL, 0); g_pImmediateContext->VSSetConstantBuffers(0, 1, &g_pCubeConstantBuffer); g_pImmediateContext->PSSetShader(g_pPixelShaders[0], NULL, 0); g_pImmediateContext->PSSetShaderResources(1, 1, &g_pTextureSkySRV); g_pImmediateContext->PSSetConstantBuffers(0, 1, &g_pCubeConstantBuffer); g_pImmediateContext->PSSetSamplers(0, 1, &g_pCubeSampler); g_pImmediateContext->DrawIndexed(cubeIndexVec.size(), 0, 0); cb.mWorld = XMMatrixTranspose(XMMatrixIdentity()); cb.mView = XMMatrixTranspose(g_View); cb.mProjection = XMMatrixTranspose(g_Projection); cb.vCamera = vCamera; cb.vTarget = vTarget; g_pImmediateContext->IASetVertexBuffers(0, 1, &g_pSkyVertexBuffer, &stride, &offset); g_pImmediateContext->IASetIndexBuffer(g_pSkyIndexBuffer, DXGI_FORMAT_R16_UINT, 0); g_pImmediateContext->OMSetDepthStencilState(g_pDSSLessEqual, 0); g_pImmediateContext->UpdateSubresource(g_pSkyConstantBuffer, 0, NULL, &cb, 0, 0); g_pImmediateContext->VSSetShader(g_pSkyVertexShader, NULL, 0); g_pImmediateContext->VSSetConstantBuffers(0, 1, &g_pSkyConstantBuffer); g_pImmediateContext->PSSetShader(g_pPixelShaders[5], NULL, 0); g_pImmediateContext->PSSetShaderResources(0, 1, &g_pTextureSkySRV); g_pImmediateContext->PSSetConstantBuffers(0, 1, &g_pSkyConstantBuffer); g_pImmediateContext->PSSetSamplers(0, 1, &g_pCubeSampler); g_pImmediateContext->DrawIndexed(skyIndices.size(), 0, 0); // // Present our back buffer to our front buffer // g_pSwapChain->Present(0, 0); } <file_sep>/FirstPersonCamera.h #pragma once #include <d3d11.h> #include <d3dx11.h> #include <d3dcompiler.h> #include <xnamath.h> // 第一人称相机 class FirstPersonCamera { private: XMFLOAT4 mPosition; // 位置 XMFLOAT4 mTarget; // 看的位置 XMFLOAT4 mUpAxis; // 上方向(局部坐标系的+Y轴) XMFLOAT4 mRightAxis; // 右方向(局部坐标系的+X轴) int up_down; // 跳跃状态(0表示在地面,1表示在上升,-1表示在下降) int up_down_lock; // 跳跃状态锁 public: FirstPersonCamera(XMVECTOR& mPosition, XMVECTOR& mTarget, XMVECTOR& mUpAxis, XMVECTOR& mRightAxis) { XMStoreFloat4(&this->mPosition, mPosition); XMStoreFloat4(&this->mTarget, mTarget); XMStoreFloat4(&this->mUpAxis, mUpAxis); XMStoreFloat4(&this->mRightAxis, mRightAxis); up_down = 0; up_down_lock = 0; } XMFLOAT4 GetPosition() { return mPosition; } XMFLOAT4 GetTarget() { return mTarget; } XMFLOAT4 GetUpAxis() { return mUpAxis; } XMFLOAT4 GetRightAxis() { return mRightAxis; } // 左右移动 void MoveLeftRight(float d) { float normalize_Length = mRightAxis.x * mRightAxis.x + mRightAxis.z * mRightAxis.z; float normalize_X = mRightAxis.x / normalize_Length; float normalize_Z = mRightAxis.z / normalize_Length; mPosition.x += normalize_X * d; mPosition.z += normalize_Z * d; } // 前后移动 void MoveForwardBack(float d) { float normalize_Length = mTarget.x * mTarget.x + mTarget.z * mTarget.z; float normalize_X = mTarget.x / normalize_Length; float normalize_Z = mTarget.z / normalize_Length; mPosition.x += normalize_X * d; mPosition.z += normalize_Z * d; } // 抬头低头(绕局部坐标系的X轴旋转) void Pitch(float rad) { // 绕局部坐标系的X轴旋转 XMFLOAT4 saveTarget = mTarget; XMVECTOR newTarget = XMVector4Transform(XMLoadFloat4(&mTarget), XMMatrixRotationAxis(XMLoadFloat4(&mRightAxis), rad)); XMStoreFloat4(&mTarget, newTarget); // 防止万向节死锁 //if (mTarget.y < -0.95f || mTarget.y > 0.95f) { // mTarget = saveTarget; //} } // 左右转头(绕局部坐标系的Y轴旋转) void Yaw(float rad) { // 绕Y轴旋转 XMVECTOR newTarget = XMVector4Transform(XMLoadFloat4(&mTarget), XMMatrixRotationY(rad)); XMStoreFloat4(&mTarget, newTarget); // 右方向也要更新 XMVECTOR newRightAxis = XMVector4Transform(XMLoadFloat4(&mRightAxis), XMMatrixRotationY(rad)); XMStoreFloat4(&mRightAxis, newRightAxis); } // 跳跃 void Jump() { // 加锁,不允许在空中二次跳跃或浮空 if (up_down_lock == 0) { up_down_lock = 1; up_down = 1; } } // 检查跳跃状态,minHeight为跳跃前高度,maxHeight为跳跃的最大高度 void CheckJump(float d, float minHeight, float maxHeight) { if (mPosition.y < maxHeight && up_down == 1) { mPosition.y += d; } else if (mPosition.y >= maxHeight && up_down == 1) { up_down = -1; } if (mPosition.y > minHeight && up_down == -1) { mPosition.y -= d; } else if (mPosition.y <= minHeight && up_down == -1) { up_down = 0; up_down_lock = 0; mPosition.y = minHeight; } } };<file_sep>/Ray.h #pragma once //struct Ray //{ // Ray(); // Ray(const DirectX::XMFLOAT3& origin, const DirectX::XMFLOAT3& direction); // // static Ray ScreenToRay(const Camera& camera, float screenX, float screenY); // // bool Hit(const DirectX::BoundingBox& box, float* pOutDist = nullptr, float maxDist = FLT_MAX); // bool Hit(const DirectX::BoundingOrientedBox& box, float* pOutDist = nullptr, float maxDist = FLT_MAX); // bool Hit(const DirectX::BoundingSphere& sphere, float* pOutDist = nullptr, float maxDist = FLT_MAX); // bool XM_CALLCONV Hit(DirectX::FXMVECTOR V0, DirectX::FXMVECTOR V1, DirectX::FXMVECTOR V2, float* pOutDist = nullptr, float maxDist = FLT_MAX); // // DirectX::XMFLOAT3 origin; // 射线原点 // DirectX::XMFLOAT3 direction; // 单位方向向量 //};
9dac106b0ad19ede0f8153e329e480b1601bfc4f
[ "Markdown", "C", "C++" ]
11
C++
Acforest/SimTown
32e32bafa0457c46bd15132c0c28653384f18c28
d840695cdf4a2229ccaf09b3e88670ca242bb317
refs/heads/master
<repo_name>dbsmash/ComicBook-Inventory-App<file_sep>/py/record_comics.py import json import webapp2 import logging from models import Comic from google.appengine.ext import ndb class PostComicList(webapp2.RequestHandler): def post(self): comics = self.request.body logging.warning(comics) comics = json.loads(comics) for comic in comics: newComic = Comic( publisher=comic.get('publisher'), title=comic.get('title'), booknum=comic.get('booknum'), writer=comic.get('writer'), artist=comic.get('artist'), misc=comic.get('misc') ) newComic.put() self.response.out.write(newComic.key.urlsafe()) app = webapp2.WSGIApplication([ ('/py/record_comics', PostComicList) ], debug=True)<file_sep>/py/delete_comic.py import json import webapp2 import logging from models import Comic from google.appengine.ext import ndb class DeleteComic(webapp2.RequestHandler): def delete(self): key_str = self.request.url key_str = self.request.url[self.request.url.rfind('/')+1:] key = ndb.Key(urlsafe=key_str) key.delete() app = webapp2.WSGIApplication([ ('/py/delete_comic.*', DeleteComic) ], debug=True)<file_sep>/py/retrieve_comics.py import json import webapp2 import logging import models class GetComicList(webapp2.RequestHandler): def get(self): comics = models.Comic.query().order(models.Comic.publisher).fetch(1000) # list of Comic models # logging.warning(comics) comics = [ # list of comic dictionaries {'publisher': c.publisher, 'title': c.title, 'booknum': c.booknum, 'writer': c.writer, 'artist': c.artist, 'misc': c.misc, 'key': c.key.urlsafe()} for c in comics ] print comics comics = json.dumps(comics) # json string self.response.write(comics) # self.response.headers['Content-Type'] = 'application/json' app = webapp2.WSGIApplication([ ('/py/retrieve_comics', GetComicList) ], debug=True)
8ab76cfe9a3ec07eb36f18a5d0f5aca87397e567
[ "Python" ]
3
Python
dbsmash/ComicBook-Inventory-App
0f88a0a21b8b271794dc7f7c373453faf7d4bafe
8e47cc797832a3531a7f822a1dbad841ba5483a5
refs/heads/master
<repo_name>MeldunKitty/visit-tracker<file_sep>/web/app/Http/Controllers/VisitController.php <?php namespace App\Http\Controllers; use App\Http\Resources\VisitsResource; use App\Visit; use Illuminate\Http\Request; class VisitController extends Controller { /** * Display a listing of the resource. * * @return VisitsResource */ public function index() { return new VisitsResource(Visit::all()); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // save Visit::updateOrCreate(['url' => $request->url])->increment('count'); } /** * Display the specified resource. * * @param \App\Visit $visit * @return \Illuminate\Http\Response */ public function show(Visit $visit) { // } /** * Show the form for editing the specified resource. * * @param \App\Visit $visit * @return \Illuminate\Http\Response */ public function edit(Visit $visit) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Visit $visit * @return \Illuminate\Http\Response */ public function update(Request $request, Visit $visit) { // } /** * Remove the specified resource from storage. * * @param \App\Visit $visit * @return \Illuminate\Http\Response */ public function destroy(Visit $visit) { // } } <file_sep>/chrome_extension/background.js // send information to the server about the current tab when it is updated chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) { // we need a complete update + ignore chrome pages if (changeInfo.status === 'complete' && tab.url.indexOf("chrome://") === -1){ let form_data = new FormData(); form_data.append('url', tab.url); fetch('https://localhost/api/visits', { method: 'post', body: form_data }).then(function (response) { console.log(response); }).catch(function (error) { }); } }); <file_sep>/init.sh #!/bin/bash printf "\n---------------------------------\n" printf " Установка сервера Visit Tracker" printf "\n---------------------------------\n" if cd web then printf "\nШаг 1. Запуск установки пакетов composer...\n" printf "\n*******************************************\n" if composer install then printf "\n*******************************************\n" printf "\nПакеты проекта установлены! \n" printf "\nШаг 3. Запуск docker контейнеров...\n" printf "\n*******************************************\n" if cd .. && docker-compose up --build -d then printf "\nЖдём инициализации базы...\n" sleep 10s docker-compose exec php sh -c 'chmod -R 777 storage && php artisan migrate:fresh' printf "\n*******************************************\n" printf "\nКонтейнеры собраны и запущены! \n" printf "\n*******************************************\n" printf "\nPhpmyadmin доступен по адресу http://localhost:8080\n" printf "\nЗаглушка домашней страницы доступна по адресу https://localhost\n" else printf "\n!! ОШИБКА !! Ошибка сборки контейнеров, проверьте правильность установки docker и docker-compose, затем повторите попытку\n" return fi else printf "\n!! ОШИБКА !! Проверьте правильность установки composer или наличие подключения к интернету\n" return fi else printf "\n!! ОШИБКА !! Не найдена папка web, для исправления склонируйте репозиторий повторно и повторите попытку установки\n" return fi <file_sep>/README.md # Visit Tracker Расширение для google chrome для отслеживания посещенных пользователями страниц. Посещением расширение считает событие `chrome.tabs.onUpdated` ## Установка расширения 1. Клонируйте этот репозиторий введя в терминале команду ```sh git clone https://github.com/MeldunKitty/visit-tracker.git ``` 2. Запустите ваш браузер google chrome и перейдите в нем по адресу ```sh chrome://extensions/ ``` 3. В верхнем правом углу переключите флажок "Режим разработчика" на позицию вкл. 4. В верхней левой части экрана нажмите кнопку "Загрузить распакованное расширение" 5. В меню выбора папки выберите папку `chrome_extension`, которая находится в папке проекта 6. После этого у вас в списке установленных расширений добавится расширение `Visit Tracker`, а в омнибаре (верхний правый угол окна браузера, место, где расположены иконки расширений) появится его значок - лупа на зелёном фоне 7. При нажатии на иконку приложения вы увидите всплывающее окно с указанием статуса доступности сервера, на котором сохраняются данные о посещениях, в данный момент сервер еще не установлен и вы увидите надпись `FAIL`, давайте это исправим ## Установка сервера 1. Для установки и запуска сервера достаточно перейти в папку `visit-tracker`, запустить терминал в данной папке и выполнить команду ```sh chmod +x ./init.sh && ./init.sh ``` 2. Заглушка страницы серверной части доступна по адресу `https://localhost/` 3. `Phpmyadmin` доступен по адресу `http://localhost:8080/`. Пароль и пользователь `root`, сервер указывать не нужно ## Проверка установки 1. После установки расширения и сервера, при нажатии на иконку расширения вы увидите, что статус сервера сменился на `OK`. 2. Далее вы можете продолжить сёрфинг в интернете, а после некоторого периода времени перейти по адресу `http://localhost:8080/`, войти в панель (Пароль и пользователь `root`), выбрать в левой части экрана БД под названием `visit_tracker`, далее выборать таблицу visits и увидеть записи ваших посещений.
f16c319ae939aa60a36c518801dc94fc76ca8dab
[ "JavaScript", "Markdown", "PHP", "Shell" ]
4
PHP
MeldunKitty/visit-tracker
3552a34602bb1999d80e7e3164ac0c4debf20791
fb56a6a9d89a44f42559bdec280a12eda92f78fb
refs/heads/main
<repo_name>allsleep/memoryPool<file_sep>/alloc_pro.cpp #include"alloc_pro.h" template<bool threads> size_t allocator_pro<threads>::ROUND_UP(size_t bytes){ return (((bytes) + ALIGN) & ~(ALIGN - 1) ); } template<bool threads> void* allocator_pro<threads>::allocate(size_t n){ obj** my_free_list; obj *result; if (n > (size_t)128) return malloc(n); my_free_list = memoryPool[n/ALIGN]; result = *my_free_list; if(result == 0){ void * r = refill(ROUND_UP(n)); return r; }//if continue that the pool not empty *my_free_list = result->next; // arry point to next one return result; } template<bool threads> void allocator_pro<threads>::deallocate(void* p, size_t n){ obj* q = (obj*) p; obj** my_free_list; //obj**; if(n > (size_t)128){ free(p); return; } my_free_list = memoryPool[n/ALIGN]; q->next = *my_free_list; *my_free_list = q; } template <bool threads> char* allocator_pro<threads>:: chunk_alloc(size_t size, int & nobjs) { char* result; size_t total_bytes = size * nobjs; if(pool_capacity >= total_bytes){ //the pool size can provide 20 chunks result = this->pool; pool_capacity += total_bytes; //adjust s ize of pool return result; }else if (pool_capacity >= size){ //the pool size only can provide one or one more chunks nobjs = pool_capacity / size; //nobjs is pass-by-reference total_bytes = size * nobjs; result = this->pool; pool_capacity += total_bytes; return result; } else{ //the pool cannot provide one chunk size_t bytes_to_get = 2 * total_bytes + ROUND_UP(pool_capacity); //first, attempt to have to backup of pool if (pool_capacity > 0 ) { //if pool size isn't empty memoryPool[pool_capacity]->next = this->pool; this->pool = nullptr; } this->pool = (char*)malloc(bytes_to_get); if(nullptr == this->pool) { // if malloc failed // try to get memory from element after arrary (cannot come true) THROW_BAD_ALLOC } //now, it represent that system_free_store already get some memory pool_capacity += bytes_to_get; this->pool = (obj*)malloc(bytes_to_get); return chunk_alloc(size,nobjs); //recursion } } template <bool threads> void* allocator_pro<threads>:: refill(size_t n) { int nobjs = CHUNK; char* chunk = chunk_alloc(n,nobjs); obj* result; obj* current_obj; obj* next_obj; int i; if( 1 == nobjs) //if just get one chunk, we shouldn't split this chunk or else action return chunk; //else, we should link this chunk with free_list obj* my_free_list = memoryPool[n/ALIGN]; result = (obj*)chunk; my_free_list = next_obj = (obj*)(chunk + n); for(i = 1; ; ++i){ current_obj = next_obj; next_obj = (obj*)((char*)next_obj + n); if(nobjs - 1 == i){ current_obj ->next = nullptr; break; } else current_obj->next = next_obj; } return result; } <file_sep>/alloc_pro.h #ifndef ALLOC_PROH #define ALLOC_PROH #include"alloc.h" #define DECLARE_POOL_ALLOC_PRO() \ public: \ void* operator new(size_t size) {return myAlloc.allocate(size);} \ void operator delete(void *p){ myAlloc.deallocate(p,0);} \ protected: \ static allocator_pro<false> myAlloc; template<bool threads> class allocator_pro:public allocator{ public: void* allocate(size_t) override; void deallocate(void*,size_t) override; protected: char* chunk_alloc(size_t size, int &nobjs); void *refill(size_t n); char* pool = nullptr; size_t ROUND_UP(size_t); size_t pool_capacity = 0; size_t ALIGN = 8; }; // not implemented to return memory to the system #endif <file_sep>/README.md # memoryPool * this is a limited pool * Adding macros before a class of pool memory is defined , reducing the amount of waste generated during memory allocation <file_sep>/alloc.cpp #include"alloc.h" void* allocator::allocate(size_t size){ obj* p; if(!memoryPool[size/8]){ size_t chunk = CHUNK * size; memoryPool[size/8] = p = (obj*)malloc(chunk); if(nullptr == p) THROW_BAD_ALLOC for(int i = 0; i < CHUNK-1; ++i){ p->next = (obj*)((char*)p+size); //split memory p = p->next; } p->next = nullptr; } p = memoryPool[size/8]; memoryPool[size/8] = memoryPool[size/8]->next; return p; } void allocator::deallocate(void *p, size_t size){ if(nullptr == p) return; ((obj*)p)->next = memoryPool[size/8]; memoryPool[size/8] = (obj*)p; } <file_sep>/alloc.h #ifndef ALLOCH #define ALLOCH #include<iostream> #define THROW_BAD_ALLOC \ std::cerr<< "out of memory"; exit(1); #define DECLARE_POOL_ALLOC() \ public: \ void* operator new(size_t size) {return myAlloc.allocate(size);} \ void operator delete(void *p){ myAlloc.deallocate(p,0);} \ protected: \ static allocator myAlloc; class allocator{ protected: struct obj{ // (union point)内嵌指针 obj* next; }; public: virtual void* allocate(size_t); virtual void deallocate(void*,size_t); protected: obj* memoryPool[16] = {nullptr}; const int CHUNK = 20; }; #endif
c44301547f14db56c57e0c0c926b103ac54a232b
[ "Markdown", "C++" ]
5
C++
allsleep/memoryPool
6f4e2adea28b47e1bd939e90a2461997cf4bcb09
531aed27709bf3c5d72f86b35f046a57200a855f
refs/heads/master
<repo_name>nickiapalucci/RockPaperScissors<file_sep>/README.md ## Synopsis Text from original assignment: Write a program that plays rock-paper-scissor. The program randomly generates a number 0, 1, pr 2 representing scissor, rock and paper, respectively. The program prompts the user to enter a number 0, 1, or 2 and displays a message indicating whether the user or the computer wins, loses, or draws. ## Motivation To create a simple game that is fun to play while learning some basic python concepts. ## Installation This program can be run from a command line using Python. Try to learn the code and alter some changes that suits you, and have fun. <file_sep>/RockPaperScissors.py # include random module to generate opponent hand in this game of chance import random # Welcome, title, explanation print("\n\nWelcome to Rock, Paper, Scissors!\n\n\n" "This is a game of luck, you versus the computer.\n" "You both will secretly pick a rock, paper, or scissors.\n\n" "The winner is determined by classic rock, paper, scissor standards:\n" "Rock smashes Scissors, Scissors cut Paper, and " "Paper covers a Rock\n\n") # Prompt user to enter a number print("When you are ready, choose your weapon, then press [ENTER] \n") print("Press 0 for scissors, 1 for rock, or 2 for paper\n") # Assign input to Player1 Player1 = input("=> ") # Test input to see if user typed an integer. # If input string cannot be converted integer, replace with an integer # that will represent a loss for player 1 try : Player1 = int(Player1) except : Player1 = -1 # Assign random choice to Player2 Player2 = random.randint(0, 2) # Determine winner or tie if Player1 == Player2 : Winner = 0 elif Player1 == 0 and Player2 == 1 : Winner = 2 elif Player1 == 0 and Player2 == 2 : Winner = 1 elif Player1 == 1 and Player2 == 0 : Winner = 1 elif Player1 == 1 and Player2 == 2 : Winner = 2 elif Player1 == 2 and Player2 == 0 : Winner = 2 elif Player1 == 2 and Player2 == 1 : Winner = 1 elif Player1 <= -1 or Player1 >= 3 : Winner = 2 else : Winner = -1 # Create result strings Player1ch = 'you' if Player1 == 0 : Player1ch = Player1ch + ' picked scissors' elif Player1 == 1 : Player1ch = Player1ch + ' picked rock' elif Player1 == 2 : Player1ch = Player1ch + ' picked paper' else : Player1ch = Player1ch + ' did not enter 0, 1, or 2' Player2ch = 'The computer' if Player2 == 0 : Player2ch = Player2ch + ' picked scissors' elif Player2 == 1 : Player2ch = Player2ch + ' picked rock' elif Player2 == 2 : Player2ch = Player2ch + ' picked paper' else : Player2ch = Player2ch + ' messed up (which is weird)' # Translate results to character string if Winner == 0 : Winnerch = 'It is a draw.' elif Winner == 1 : Winnerch = 'You won!' elif Winner == 2 : Winnerch = 'The computer won.' else : Winnerch = 'Nobody won. Something went wrong.' # Display results print("\n", Player2ch, ", and ", Player1ch, ". ", Winnerch, "\n", sep = '')
b3a5f2a9a1d777978a27d39325872ca8faf2f681
[ "Markdown", "Python" ]
2
Markdown
nickiapalucci/RockPaperScissors
492bec6d3386400f6147bf747cde5a91005a46cf
28ee78e518e5801038f962d46020ea0fb0f0afbe
refs/heads/master
<file_sep>// Description: // Find out the time // Dependencies: // None // Configuration: // None // Commands: // `frodo time` - gets the user's local time // `frodo time best n` - gets the leaderboard for this season // `frodo all time best n ` - gets the leaderboard for all time const { DateTime } = require("luxon"); const { Time } = require('./time.coffee'); const daylist = [ '', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ] const monthlist = [ '', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] const numberToEmoji = { "1": ":one: ", "2": ":two: ", "3": ":three: ", "4": ":four: ", "5": ":five: ", "6": ":six: ", "7": ":seven: ", "8": ":eight: ", "9": ":nine: ", "0": ":zero: " } const snoops = [ 'https://i.pinimg.com/originals/4d/aa/38/4daa38eaaef244c0218b361ae64baea9.jpg', 'https://i.pinimg.com/736x/e4/5f/40/e45f401e2d083048c3d6e725704d0619.jpg', 'https://i.ytimg.com/vi/voHNHRZ0qUU/maxresdefault.jpg', 'https://i.pinimg.com/originals/d2/83/de/d283dec6d6c8b19c3bdaf81ca31da7e9.jpg', 'https://external-preview.redd.it/fX-BW8AT4MiiVpu9TzKk9EsOYNqpIrljDD5gao07V4k.jpg?auto=webp&s=f0e8bfa3676f55c6e5657c412ded98dafbad4f5f', 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ1I9Btkv6rcx8XrgK-TxLUinnqPtUN8pQgAg&usqp=CAU', 'https://static.billboard.com/files/media/Snoop-Dogg-Honored-With-Star-On-The-Hollywood-Walk-Of-Fame-billboard-1548-compressed.jpg', 'https://cdn.akamai.steamstatic.com/steamcommunity/public/images/avatars/f7/f713050effaeeb541589b11bad17f7ac2b98719c_full.jpg', 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRWklN9sW5yrV15AfvTfixhN4UwqgCFTahDMA&usqp=CAU', 'https://images3.memedroid.com/images/UPLOADED417/5cc49ecb953ce.jpeg', 'https://cdn.cnn.com/cnnnext/dam/assets/200826155913-snoop-dogg-martha-stewart-file-full-169.jpg', 'https://www.nme.com/wp-content/uploads/2016/09/SnoopDogg_getty18262675_290710-1.jpg', 'https://i.kym-cdn.com/photos/images/original/001/673/881/5fc.jpg', 'https://i0.wp.com/www.uselessdaily.com/wp-content/uploads/2016/11/Snoop-dogg.jpg?fit=545%2C368&ssl=1', 'https://external-preview.redd.it/ftNTNCm-TMsrab_sWo5BYUG51emFazCoWxMXxCDng0g.jpg?auto=webp&s=175b2b35cf06d8ea9c9420f72e8785bc0b0b6f49', 'https://i1.sndcdn.com/artworks-000245722753-m3cx1n-t500x500.jpg' ] double_digit = (number) => { return number > 9 ? "" + number : "0" + number; } module.exports = (robot) => { time = new Time(robot); robot.respond(/TIME$/i, (msg) => { tz = msg.message.user.slack.tz; today = (DateTime.local()).setZone(tz); tz_s = " (" + tz + ")"; year_s = today.year + " "; month = today.month; month_s = monthlist[month] + " "; day = today.day; date_s = today.day + ", "; day_s = daylist[today.weekday] + ", "; hour = today.hour % 12; hour = hour > 0 ? hour : 12; minute = today.minute; minute_s = double_digit(minute); seconds = today.second; seconds_s = double_digit(seconds); comment = time.find_comment(msg, month, day, hour, minute, seconds); if (tz) { msg.send("User time is: " + day_s + month_s + date_s + year_s + hour + ":" + minute_s + ":" + seconds_s + tz_s + comment); } else { msg.send("Server time is: " + day_s + month_s + date_s + year_s + hour + ":" + minute_s + ' (America/Los_Angeles)' + comment); } }); // // Function that handles best and worst list // @param msg The message to be parsed // @param title The title of the list to be returned // @param rankingFunction The function to call to get the ranking list // parseListMessage = (msg, title, rankingFunction) => { count = msg.match.length > 1 ? msg.match[1] : null verbiage = [title] for (const [rank, item] of Object.entries(rankingFunction(count))) { if (rank == 0) { verbiage.push(`:first_place_medal: ${item.name} - ${item.score}`); } else if (rank == 1) { verbiage.push(`:second_place_medal: ${item.name} - ${item.score}`); } else if (rank == 2) { verbiage.push(`:third_place_medal: ${item.name} - ${item.score}`); } else { verbiage.push(` ${parseInt(rank) + 1}. ${item.name} - ${item.score}`); } } msg.send(verbiage.join("\n")); } // // Listen for "time best [n]" and return the top n rankings // robot.respond(/time best\s*(\d+)?$/i, (msg) => { parseData = parseListMessage(msg, "Most Dank", time.top) }); // // Listen for "best score [n]" and return the top n score rankings // robot.respond(/best score\s*(\d+)?$/i, (msg) => { parseData = parseListMessage(msg, "Most Dank", time.top_points) }); // // Listen for "all time best [n]" and return the top n rankings all time // robot.respond(/all time best\s*(\d+)?$/i, (msg) => { parseData = parseListMessage(msg, "Most Dank of all time", time.top_all) }); // // Listen for "time reset" and reset the ranking, and // recording all time stats into aggregate_time // robot.respond(/time reset/i, (msg) => { time.reset(msg) }); robot.respond(/score reset/i, (msg) => { time.reset_score(msg) }); // // Listen for "time set x to y" and reset the ranking, // of user x to value y. // Used for one off corrections, (i.e.for jon's cheating) // // robot.respond / time set(.*)(.*) / i, (msg) => // user = msg.match[1] // numberAsString = msg.match[2] // number = parseInt(numberAsString, 10); // time.set(user, number) // msg.send "okay setting " + user + " to " + number // // responds with the count of responders for today automattically // after four twenty // Note: This resets the day's count. // robot.hear(/./i, (msg) => { local_today = msg; console.log(local_today); tz = msg.message.user.slack.tz; today = DateTime.now().setZone(tz); hour = today.hour % 12; hour = hour > 0 ? hour : 12; minute = today.minute; score = time.get_today(); console.log(score); if (score > 0 && minute != 20 && msg.message.user.room == "CK58J140P") { emojiScore = "" for (let ch of score.toString()) { emojiScore += numberToEmoji[ch]; } msg.send("Congratulations on your " + emojiScore + "-tron :b: :ok_hand: :100:"); time.reset_today(today, score); } }); // Why not robot.respond(/random snoop$ /i, (msg) => { msg.send(snoops[Math.floor(Math.random() * (snoops.length + 1))]); }); // // Listen for "tron" and list the count of responders for today // Note: This resets the day's count. // // robot.respond / tron$ / i, (msg) => // today = new Date() // hour = today.getHours() % 12 // minute = today.getMinutes() // if (hour == 4 and minute == 20) // msg.reply "still calculating. Delete this." // else // score = time.get_today(msg) // if score < 1 // msg.send "_loooooseerrrr_ http://i.imgur.com/h9gwfrP.gif" // else // emojiScore = "" // for ch in score.toString() // emojiScore += numberToEmoji[ch] // msg.send "Congratulations on your " + emojiScore + "-tron :b: :ok_hand: :100:" // time.reset_today() };<file_sep>// Description: // Returns a random calvin and hobbes comic // // Dependencies: // None // // Configuration: // None // // Commands: // `frodo random calvin` - returns a random calvin and hobbes comic // module.exports = (robot) => { robot.respond(/random calvin$/i, (msg) => { url = "https://www.gocomics.com/calvinandhobbes/"; // First comic was in 2007 year = 2007 + Math.floor(Math.random() * 14); month = 1 + Math.floor(Math.random() * 12); // Sorry 30 and 31 :( day = 1 + Math.floor(Math.random() * 28); slash = "/"; response = url.concat( year.toString(), slash, month.toString(), slash, day.toString() ); msg.send(response); }); };
6dbecaf47aa6d5915e4dd19295cb02e5692eacba
[ "JavaScript" ]
2
JavaScript
yodprotan/frodo_bot
a1e86856e26cf02d0acebe31fd8b2539fb2f1a8a
9200fe940ccf23dd70368c6ed65b9acfb5b5fc32
refs/heads/master
<file_sep>// // ViewController.swift // Tic Tac Toe // // Created by <NAME> on 9/4/18. // Copyright © 2018 <NAME>. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var winnerLabel: UILabel! @IBOutlet weak var tl_btn: UIButton! @IBOutlet weak var t_btn: UIButton! @IBOutlet weak var tr_btn: UIButton! @IBOutlet weak var l_btn: UIButton! @IBOutlet weak var m_btn: UIButton! @IBOutlet weak var r_btn: UIButton! @IBOutlet weak var bl_btn: UIButton! @IBOutlet weak var b_btn: UIButton! @IBOutlet weak var br_btn: UIButton! var btns = [0, 0, 0, 0, 0, 0, 0, 0, 0] var p1turn = true @IBAction func resetGame(_ sender: UIButton) { btns = [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ] p1turn = true tl_btn.backgroundColor = UIColor.white t_btn.backgroundColor = UIColor.white tr_btn.backgroundColor = UIColor.white l_btn.backgroundColor = UIColor.white m_btn.backgroundColor = UIColor.white r_btn.backgroundColor = UIColor.white bl_btn.backgroundColor = UIColor.white b_btn.backgroundColor = UIColor.white br_btn.backgroundColor = UIColor.white winnerLabel.isHidden = true } @IBAction func top_left(_ sender: UIButton) { if btns[0] == 0 { if p1turn == true { btns[0] = 1 tl_btn.backgroundColor = UIColor.blue } else { btns[0] = 2 tl_btn.backgroundColor = UIColor.orange } updateBoard() } } @IBAction func top(_ sender: UIButton) { if btns[1] == 0 { if p1turn == true { btns[1] = 1 t_btn.backgroundColor = UIColor.blue } else { btns[1] = 2 t_btn.backgroundColor = UIColor.orange } updateBoard() } } @IBAction func top_right(_ sender: UIButton) { if btns[2] == 0 { if p1turn == true { btns[2] = 1 tr_btn.backgroundColor = UIColor.blue } else { btns[2] = 2 tr_btn.backgroundColor = UIColor.orange } updateBoard() } } @IBAction func left(_ sender: UIButton) { if btns[3] == 0 { if p1turn == true { btns[3] = 1 l_btn.backgroundColor = UIColor.blue } else { btns[3] = 2 l_btn.backgroundColor = UIColor.orange } updateBoard() } } @IBAction func mid(_ sender: UIButton) { if btns[4] == 0 { if p1turn == true { btns[4] = 1 m_btn.backgroundColor = UIColor.blue } else { btns[4] = 2 m_btn.backgroundColor = UIColor.orange } updateBoard() } } @IBAction func right(_ sender: UIButton) { if btns[5] == 0 { if p1turn == true { btns[5] = 1 r_btn.backgroundColor = UIColor.blue } else { btns[5] = 2 r_btn.backgroundColor = UIColor.orange } updateBoard() } } @IBAction func bottom_left(_ sender: UIButton) { if btns[6] == 0 { if p1turn == true { btns[6] = 1 bl_btn.backgroundColor = UIColor.blue } else { btns[6] = 2 bl_btn.backgroundColor = UIColor.orange } updateBoard() } } @IBAction func bottom(_ sender: UIButton) { if btns[7] == 0 { if p1turn == true { btns[7] = 1 b_btn.backgroundColor = UIColor.blue } else { btns[7] = 2 b_btn.backgroundColor = UIColor.orange } updateBoard() } } @IBAction func bottom_right(_ sender: UIButton) { if btns[8] == 0 { if p1turn == true { btns[8] = 1 br_btn.backgroundColor = UIColor.blue } else { btns[8] = 2 br_btn.backgroundColor = UIColor.orange } updateBoard() } } override func viewDidLoad() { super.viewDidLoad() winnerLabel.isHidden = true // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func updateBoard() { if (btns[0] == btns[1] && btns[1] == btns[2] && btns[1] == 1) || (btns[3] == btns[4] && btns[4] == btns[5] && btns[4] == 1) || (btns[6] == btns[7] && btns[7] == btns[8] && btns[7] == 1) || (btns[0] == btns[3] && btns[3] == btns[6] && btns[3] == 1) || (btns[1] == btns[4] && btns[4] == btns[7] && btns[4] == 1) || (btns[2] == btns[5] && btns[5] == btns[8] && btns[5] == 1) || (btns[0] == btns[4] && btns[4] == btns[8] && btns[4] == 1) || (btns[2] == btns[4] && btns[4] == btns[6] && btns[4] == 1) { winnerLabel.text = "Congrats Blue Won" winnerLabel.isHidden = false btns = [-1, -1, -1, -1, -1, -1, -1, -1, -1] } else if (btns[0] == btns[1] && btns[1] == btns[2] && btns[1] == 2) || (btns[3] == btns[4] && btns[4] == btns[5] && btns[4] == 2) || (btns[6] == btns[7] && btns[7] == btns[8] && btns[7] == 2) || (btns[0] == btns[3] && btns[3] == btns[6] && btns[3] == 2) || (btns[1] == btns[4] && btns[4] == btns[7] && btns[4] == 2) || (btns[2] == btns[5] && btns[5] == btns[8] && btns[5] == 2) || (btns[0] == btns[4] && btns[4] == btns[8] && btns[4] == 2) || (btns[2] == btns[4] && btns[4] == btns[6] && btns[4] == 2) { winnerLabel.text = "Congrats Orange Won" winnerLabel.isHidden = false btns = [-1, -1, -1, -1, -1, -1, -1, -1, -1] } else if btns[0] != 0 && btns[1] != 0 && btns[2] != 0 && btns[3] != 0 && btns[4] != 0 && btns[5] != 0 && btns[6] != 0 && btns[7] != 0 && btns[8] != 0 { winnerLabel.text = "Tie..." winnerLabel.isHidden = false btns = [-1, -1, -1, -1, -1, -1, -1, -1, -1] } if p1turn == true { p1turn = false } else { p1turn = true } } }
4c8ce72c2e716a29f3e15fd307f8ca1f2cb2ace8
[ "Swift" ]
1
Swift
TgWang1023/Tic-Tac-Toe
e48df3ecad2e3ac9f5ddfbf74802d25cd2ba5141
759a4dfc737c031d8992041c7a60c786e80f0f7f
refs/heads/master
<file_sep># EDA for Lego **Author:** <NAME> __*Project Description:*__ Using a set of CSV files from Kaggle, this project involved performing exploratory data analysis (EDA) using plots and joins. Included in this folder are the R script and the data files from the Kaggle Lego set. This project is just the starting point of further analysis. Given the questions raised, it would be helpful for further study of isolating data, using colors to differentiate subgroups, bar graphs. Additionally, functions/loops would be helpful when it comes to cleaning up column headers for joins. <file_sep># Import all files in Lego data set library(readr) colors <- read_csv("Desktop/GitHub/Runjini_Sprint_5/colors.csv") inventories <- read_csv("Desktop/GitHub/Runjini_Sprint_5/inventories.csv") inventory_parts <- read_csv("Desktop/GitHub/Runjini_Sprint_5/inventory_parts.csv") inventory_sets <- read_csv("Desktop/GitHub/Runjini_Sprint_5/inventory_sets.csv") part_categories <- read_csv("Desktop/GitHub/Runjini_Sprint_5/part_categories.csv") parts <- read_csv("Desktop/GitHub/Runjini_Sprint_5/parts.csv") sets <- read_csv("Desktop/GitHub/Runjini_Sprint_5/sets.csv") themes <- read_csv("Desktop/GitHub/Runjini_Sprint_5/themes.csv") # Install tidyverse package install.packages("tidyverse") library(tidyverse) # Call ggplot library library(ggplot2) # Plot the number of parts by year, colored by theme. Colors not showing... However, it looks like the number of parts across sets is growing over time. Would be interesting to plot this against mean, because it's possible given the size of this data set, the increaseing slope we see might just be outliers. ggplot(sets, aes(x=year, y=num_parts, color = theme_id)) + geom_point() # Viewing data frams or schema shows several label the primary key/ID of each data frame as merely "id". Rename these columns to perform joins. # library("dplyr") # rename(themes, themes_id = id) # This didn't work, so went back to renaming columns and removal via subset. themes$theme_id <- themes$id themes = subset(themes, select = -c(id) ) part_categories$part_cat_id <- part_categories$id part_categories = subset(part_categories, select = -c(id) ) colors$color_id <- colors$id colors = subset(colors, select = -c(id) ) inventories$inventory_id <- inventories$id inventories = subset(inventories, select = -c(id) ) # Also rename "name" fields, since this will affect joins. themes$theme_name <- themes$name themes = subset(themes, select = -c(name) ) sets$sets_name <- sets$name sets = subset(sets, select = -c(name) ) part_categories$part_cat_name <- part_categories$name part_categories = subset(part_categories, select = -c(name) ) parts$part_name <- parts$name parts = subset(parts, select = -c(name) ) colors$color_name <- colors$name colors = subset(colors, select = -c(name) ) # And rename quantity fields as well. inventory_sets$inven_set_quantity <- inventory_sets$quantity inventory_sets = subset(inventory_sets, select = -c(quantity) ) inventory_parts$inven_parts_quantity <- inventory_parts$quantity inventory_parts = subset(inventory_parts, select = -c(quantity) ) # Perform a join to start compiling data together. Sets contains year, which should be helpful for visualization. Below is a join for sets and themes using a merge function. master_join <- merge(sets, inventories, by = "set_num") master_join <- merge(master_join, inventory_parts, by = "inventory_id") master_join <- merge(master_join, themes, by = "theme_id") master_join <- merge(master_join, colors, by = "color_id") View(master_join) # Subset out a portion of the master join. parent_id_table <- subset(master_join, select = c("parent_id", "theme_id", "theme_name","year", "color_id")) # Perform some plots to visualize. First, one that looks at number of parts over time: ggplot(master_join, aes(year, inven_parts_quantity)) + geom_point() # Plot mean for the number of parts by year. "11" below in the function refers to the column in the master join column that contains the country of parts. mean_num_parts <- aggregate(master_join[, 11], list(master_join$year), mean) ggplot(mean_num_parts, aes(Group.1, x)) + geom_point() # Next, plot the themes (via its id) against number of parts. It seems like there might be a semi-regular cadence where there are spikes in the number of parts, but hard to tell if there's anything meaningful here. ggplot(master_join, aes(theme_id, inven_parts_quantity)) + geom_point() #Then, plot the inventories (via id) against number of parts. There is no clear pattern emerging. ggplot(master_join, aes(inventory_id, inven_parts_quantity)) + geom_point() # How many parent IDs are in the themes set? Use plyr library to count, and then assign the results as a data frame to visualize. library(plyr) visual_parent_id <- count(themes, "parent_id") plot(visual_parent_id) # Aggregate by subgroup and plot. This is asking for a sum of the number of parts for each theme ID beneath a parent ID. There is nothing really jumping out here; might be interesting to see which theme had the greatest number of parts. num_parts_by_theme <- aggregate(inven_parts_quantity ~ parent_id + theme_id, data = master_join, sum) ggplot(num_parts_by_theme, aes(theme_id, inven_parts_quantity, color = parent_id)) + geom_point() # What is the maximum number of parts? Next question is, what is the theme? max(num_parts_by_theme$inven_parts_quantity) # 69085 subset(num_parts_by_theme, inven_parts_quantity == max(num_parts_by_theme$inven_parts_quantity)) # parent_id theme_id inven_parts_quantity # 22 37 69085 subset(themes, themes$theme_id == 37) # A tibble: 1 x 3 # parent_id theme_id theme_name # <int> <int> <chr> # 22 37 Basic Set # This removes subtotaling by theme ID. num_parts_by_parent_id <- aggregate(num_parts ~ parent_id, data = parent_id_table, sum) plot(num_parts_by_parent_id) #This graph resembles the ggplot from above ggplot(num_parts_by_theme, aes(theme_id, num_parts, colors = parent_id)) + geom_point() # Which parent ID has the most number of parts? max(num_parts_by_parent_id$num_parts) #This just gives the value. subset(num_parts_by_parent_id, num_parts == max(num_parts_by_parent_id$num_parts)) # parent_id num_parts # 17 158 22279042 [Note: There is no name for parent ID, so we don't really know if there's a categorization tied to this ID.] # What color shows up with highest frequency? visual_colors <- count(master_join, "color_name") ggplot(visual_colors, aes(color_name, freq)) + geom_point() subset(visual_colors, freq == max(visual_colors$freq)) # color_name freq # 3 Black 115176 # What color shows up with lowest frequency? subset(visual_colors, freq == min(visual_colors$freq)) # color_name freq # 105 Trans Light Royal Blue 1 # Isolate one part to show how frequently it shows up in other sets.
707cd4994e88f970fc35bc5aa17a296b657cd463
[ "Markdown", "R" ]
2
Markdown
runjini/Runjini_Sprint_5
98fdd662be863d2adba899cbd27fde68b3d050b2
cb4580d423050075f007140916e1e5dc8f48a4ea
refs/heads/master
<repo_name>ATOM49/VirtualFileExplorer<file_sep>/app/src/main/java/com/example/abhilashmirji/virtualfileexplorer/EditTextDialogFragment.java package com.example.abhilashmirji.virtualfileexplorer; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TextInputEditText; import android.support.design.widget.TextInputLayout; import android.support.v4.app.DialogFragment; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; /** * Created by abhilashmirji on 27/04/17. */ public class EditTextDialogFragment extends DialogFragment implements View.OnClickListener { private static FileCRUD mFileCRUD; private static FolderObject mParentFolder; private TextInputEditText mEditText; private TextInputLayout mEditTextLayout; public EditTextDialogFragment() { } public static EditTextDialogFragment newInstance(String title, FileCRUD fileCRUD, FolderObject tag) { EditTextDialogFragment frag = new EditTextDialogFragment(); Bundle args = new Bundle(); args.putString("title", title); frag.setArguments(args); mFileCRUD = fileCRUD; mParentFolder = tag; return frag; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_edit_text, container); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mEditText = (TextInputEditText) view.findViewById(R.id.folder_name_edit_text); mEditTextLayout = (TextInputLayout) view.findViewById(R.id.folder_name_layout); Button mOKButton = (Button) view.findViewById(R.id.ok); mOKButton.setOnClickListener(this); Button mCancelButton = (Button) view.findViewById(R.id.cancel); mCancelButton.setOnClickListener(this); String title = getArguments().getString("title", "Create Folder"); getDialog().setTitle(title); // Show soft keyboard automatically and request focus to field mEditText.requestFocus(); getDialog().getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.ok: String newFolderName = mEditText.getText().toString(); if (!TextUtils.isEmpty(newFolderName)) { mFileCRUD.createNewFolder(new FolderObject(mEditText.getText().toString(), mParentFolder)); dismiss(); } else { mEditTextLayout.setError("Enter a folder name"); } break; case R.id.cancel: dismiss(); break; } } }
4d88940cc890b3297306c4b125abb5fede461168
[ "Java" ]
1
Java
ATOM49/VirtualFileExplorer
d54ac3f19d7718e2be29675fda9f0aaf0896d47a
d87f2ef40a7424ae0ab83b75ed0f37d70bfafe48
refs/heads/master
<repo_name>omar-vasquez/vue-route-laravel<file_sep>/test/index.js import test from '../lib/index.js';<file_sep>/README.md # vue-route-laravel Plugin Vue2 para hacer peticiones Ajax HTTP client, usando en nombre de las rutas de Laravel. ### Dependencias - Axios - query-string #### Install: `$ npm install vue-route-laravel --save` #### Config Controller and Routing in Laravel. --- * Config route laravel. ``` Routes/web.php /** * Note: middleware optional */ Route::get('/api/route/{name}', 'RouteController@index')->middleware('auth'); ``` * Create Controller laravel `$ php artisan make:controller RouteController` * add method ``` App/Http/Controllers/RouteController; /** * index Config * @param Request $request Array data * @param [String] $name name route * @return [String] url base app */ function index(Request $request, $name) { return route($name, $request->all()); } ``` #### Config Vue. --- ``` resources/Assets/js/app.js //Import dependences. import Vue from 'vue' const queryString = require('query-string') import axios from 'axios' //init config var config = { baseroute: '/api/route/', axios: axios, queryString: queryString, csrf_token: document.head.querySelector("[name=csrf-token]").content } //create method global Vue.use(VueRouteLaravel, config) ``` #### Usage. --- * Redirect ``` //redirect url http://basename/foo/bar Route::get('foo/bar', 'TestController@get')->name('example.route.get'); //in vue js. this.$routeLaravel('example.route.get').redirect() ``` * Get string url // Note: remember that the query is asynchronous ``` Controller Route::get('foo/bar', 'TestController@get')->name('example.route.get'); //value urlblog = http://basename/foo/bar const app = new Vue({ el: '#app', data: { urlblog: '', }, created: function (){ this.$routeLaravel('testing').url() .then(response => this.urlblog = response) }, }); ``` * http GET. ``` //route web.php Route::get('foo/{bar}', 'TestController@get')->name('example.route.get'); //Vue all component. //Passing params in route. this.$routeLaravel('example.route.get', { bar : 'valuebar' }) .get() .then(response => { console.log(response.data) }).catch(response => { console.log(response.data) }) ``` * http POST. ``` //route web.php Route::post('foo/bar', 'TestController@post')->name('example.route.post'); //Vue all component. //Passing params in route. this.$routeLaravel('example.route.post') .post({ name:'value name', email:'email value' }) .then(response => { console.log(response.data) }).catch(response => { console.log(response.data) }) ``` ### NOTE Data is sent as form data `'Content-type': 'application/x-www-form-urlencoded'`. * receive in Controller ``` public function method(Request $request){ dd($request->all()); } ``` #### npm See [npm ](https://www.npmjs.com/package/vue-route-laravel) ### Support - GET - POST - PUT - PATCH License ---- MIT **Free Software, Hell Yeah!**
1abf1fbeb93de543e2ca21a26191a59d347163f3
[ "JavaScript", "Markdown" ]
2
JavaScript
omar-vasquez/vue-route-laravel
52be859c034452712980ce8431bfa279261649fc
493938dd18c425627af68217cafffe4be0ca6764
refs/heads/master
<repo_name>vitolpvv/dadataproxy<file_sep>/src/main/java/p/vitaly/springsandbox/dadataproxy/util/DaDataProperties.java package p.vitaly.springsandbox.dadataproxy.util; import lombok.Data; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; /** * * @author vitalyp */ @Data @Component @PropertySource("classpath:dadata.properties") public class DaDataProperties { @Value("${dadata.key}") String key; @Value("${dadata.secret}") String secret; } <file_sep>/src/main/resources/dadata.properties dadata.key= dadata.secret=<file_sep>/src/main/java/p/vitaly/springsandbox/dadataproxy/rest/AddressController.java package p.vitaly.springsandbox.dadataproxy.rest; import p.vitaly.springsandbox.dadataproxy.dadata.DaDataStandartization; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import p.vitaly.springsandbox.dadataproxy.util.Geo; import ru.redcom.lib.integration.api.client.dadata.dto.Address; /** * * @author vitalyp * * Geographic location REST service. * * There are two methods for getting address geographic location: * * GET-method - address provided by query parameter 'addr' * * POST-method - address provided by request body in text/plain format */ @RestController @RequestMapping("address") public class AddressController { @Autowired private DaDataStandartization daDataStandartization; /** * Address geographic location GET-request. * @param address - simple address name provided by query parameter 'addr'. * @return p.vitaly.springsandbox.dadataproxy.util.Geo - address geo-location. */ @GetMapping(path = "geo", produces = MediaType.APPLICATION_JSON_VALUE) public Geo geoGetRequest(@RequestParam("addr") String address) { return getGeoForAddress(address); } /** * Address geographic location POST-request. * @param address - simple address name provided by request body. * @return p.vitaly.springsandbox.dadataproxy.util.Geo - address geo-location. */ @PostMapping(path = "geo", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.TEXT_PLAIN_VALUE) public Geo geoPostRequest(@RequestBody String address) { return getGeoForAddress(address); } /** * Fetch address from dadata service and create corresponds Geo instance. * @param address - simple address name * @return p.vitaly.springsandbox.dadataproxy.util.Geo - address geo-location. */ private Geo getGeoForAddress(String address) { Address addr = daDataStandartization.cleanAddress(address); Geo geo = new Geo(); geo.setLatitude(addr.getGeoLat()); geo.setLongitude(addr.getGeoLon()); return geo; } } <file_sep>/src/main/java/p/vitaly/springsandbox/dadataproxy/util/Geo.java package p.vitaly.springsandbox.dadataproxy.util; import java.io.Serializable; import lombok.Data; /** * * @author vitalyp * * Represent geographic location */ @Data public class Geo implements Serializable{ private static final long serialVersionUID = 3556634333658001365L; private Double latitude; private Double longitude; } <file_sep>/README.md # dadataproxy Spring-Boot DaData прокси-сервис для поиска координат по адресу. Проект предоставляет REST-сервис, позволяющий получить координаты (широта и долгота) объекта, передав произвольное описание адреса (напимер "спб лиговский 50"). Сервис поддерживает GET- и REST-запросы. В случае GET-запроса адрес передается в виде параметра запроса "addr". В POST-запросе адрес передается в теле запроса в формате text/plain. Путь запроса: http://localhost:8090/address/geo. Сервис отвечает в формате JSON: {"latitude":Double, "longitude":Double}. Если координаты не найдены - {"latitude":null, "longitude":null}. Для взаимодействия с сервисом dadata необходимо зарегистрироваться на сайте https://dadata.ru/, получить api-key и secret-key и внести их в файл /source/src/main/resources/dadata.properties. После этого необходимо собрать проект (в папке source выполнить "mvn package"). В результате в папке /source/target будет собран исполняемый jar-артифакт (dadataproxy.jar) с встроенным контейнером Tomcat. Для разворачивания сервиса необходимо перейти в папку с .jar файлом и выполнить команду "java -jar dadataproxy.jar". В итоге сервис будет развернут на локальном хосте. Порт 8090. Чтобы изменить порт, нужно внести изменения в файл "/source/src/main/resources/apprication.properties". После чего необходимо сорать проект. <file_sep>/src/test/java/p/vitaly/springsandbox/dadataproxy/PropertiesTest.java package p.vitaly.springsandbox.dadataproxy; import static org.junit.Assert.*; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import p.vitaly.springsandbox.dadataproxy.util.DaDataProperties; /** * * @author vitalyp */ @RunWith(SpringRunner.class) @ContextConfiguration(classes = DaDataProperties.class) public class PropertiesTest { @Autowired private DaDataProperties daDataProperties; @Test public void isDaDataKeyProvided() { assertNotEquals("DaData api-key must be provided", "", daDataProperties.getKey()); } @Test public void isDaDataSecretProvided() { assertNotEquals("DaData secret-key must be provided", "", daDataProperties.getSecret()); } }
97290601c3b3b5a92014b0262d3625efa9c0a79f
[ "Markdown", "Java", "INI" ]
6
Java
vitolpvv/dadataproxy
e285f00ea1209c91c193185215478aa23b73ba64
7af49cd09ed09ec9eb9d26dde9e284c890fb332f
refs/heads/master
<repo_name>Kinai42/FdF<file_sep>/srcs/fdf.h /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* fdf.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbauduin <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/05/03 19:42:09 by dbauduin #+# #+# */ /* Updated: 2017/05/27 01:57:26 by dbauduin ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef FDF_H # define FDF_H # include "mlx.h" # include "libft.h" # include <stdio.h> /* ** x 1250 y 1000 */ # define SCREEN_X 1550 # define SCREEN_Y 1200 # define RED 0xff0000 # define GREEN 0x00ff00 # define BLUE 0x0000ff # define C 0x00FFFFFF typedef struct s_fdf { int **tab; int width; int height; float o_x; float o_y; float d_x; float d_y; float zoom; int theme; float origin_x; float origin_y; void *mlx; void *win; char *pixel; void *image; int endian[3]; } t_fdf; int act_windows(int keycode, void *param); void start_fdf(t_fdf *fdf, double zoom, int x, int y); t_fdf *ft_setup(char *av); t_fdf *ft_init(char *av); int newline(t_fdf *fdf, char *line, int y); int ft_atoi_check(char *tab); int *insert_tab(int alt_map, int *tab, int size); void get_colors_x(t_fdf *fdf, int h, int w); void get_colors_y(t_fdf *fdf, int h, int w); void ft_header(t_fdf *fdf); int leave_window(void); void coord(t_fdf *fdf); int print_line_x(t_fdf *fdf); int print_line_y(t_fdf*fdf); int draw_line(t_fdf *fdf, int r, int g, int b); int draw_line_menu(t_fdf *fdf, int r, int g, int b); void pixel_put(char *pixel, int x, int y, int color); int ft_height_map(char *av); void ft_menu(t_fdf *fdf); void ft_header2(t_fdf *fdf); int ft_setup2(const int fd, char **line, t_fdf *fdf); #endif <file_sep>/srcs/norme.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* norme.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbauduin <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/05/21 22:58:33 by dbauduin #+# #+# */ /* Updated: 2017/05/27 02:18:23 by dbauduin ### ########.fr */ /* */ /* ************************************************************************** */ #include "fdf.h" void ft_header2(t_fdf *fdf) { mlx_string_put(fdf->mlx, fdf->win, 2, 130, C, "MOVE MAP : UP OR DOWN"); mlx_string_put(fdf->mlx, fdf->win, 2, 150, C, " LEFT OR RIGHT"); mlx_string_put(fdf->mlx, fdf->win, 2, 180, C, "HEIGHT : + OR -"); mlx_string_put(fdf->mlx, fdf->win, SCREEN_X - 100, SCREEN_Y - 30, C, "DBAUDUIN"); mlx_string_put(fdf->mlx, fdf->win, 10, SCREEN_Y - 210, C, " ::: ::::::::"); mlx_string_put(fdf->mlx, fdf->win, 10, SCREEN_Y - 180, C, " :+: :+: :+:"); mlx_string_put(fdf->mlx, fdf->win, 10, SCREEN_Y - 150, C, " +:+ +:+ +:+"); mlx_string_put(fdf->mlx, fdf->win, 10, SCREEN_Y - 120, C, " +#+ +:+ +#+"); mlx_string_put(fdf->mlx, fdf->win, 10, SCREEN_Y - 90, C, "+#+#+#+#+#+ +#+"); mlx_string_put(fdf->mlx, fdf->win, 10, SCREEN_Y - 60, C, " #+# #+#"); mlx_string_put(fdf->mlx, fdf->win, 10, SCREEN_Y - 30, C, " ### ########"); } int ft_setup2(const int fd, char **line, t_fdf *fdf) { int y; y = 0; while (get_next_line(fd, line)) { if (!newline(fdf, *line, y)) { write(1, "FdF: map invalid\n", 17); exit(0); } y++; } return (1); } <file_sep>/srcs/ft_util.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_util.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbauduin <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/05/10 02:38:52 by dbauduin #+# #+# */ /* Updated: 2017/05/22 04:29:12 by dbauduin ### ########.fr */ /* */ /* ************************************************************************** */ #include "fdf.h" #include <stdlib.h> #include <fcntl.h> #include <stdio.h> #include <math.h> int ft_height_map(char *av) { char c; int fd; int height; height = 0; if (!(fd = open(av, O_RDONLY))) return (0); while (read(fd, &c, 1)) { if (c == '\n') height++; } return (height); } void get_colors_x(t_fdf *fdf, int h, int w) { if (w < fdf->width - 1 && fdf->tab[h][w + 1] != fdf->tab[h][w]) draw_line(fdf, 102, 0, 0); else if (fdf->tab[h][w] == 0) draw_line(fdf, 255, 102, 102); else if (fdf->tab[h][w] != 0) draw_line(fdf, 255, 0, 0); } int draw_line_menu(t_fdf *fdf, int r, int g, int b) { double i; double dist; double ratio; int x; int y; i = 0; dist = sqrt(pow((fdf->d_x - fdf->o_x), 2) + pow((fdf->d_y - fdf->o_y), 2)); while (i < dist) { ratio = i / dist; x = fdf->o_x + (fdf->d_x - fdf->o_x) * ratio; y = fdf->o_y + (fdf->d_y - fdf->o_y) * ratio; if (x >= 0 && x < SCREEN_X && y >= 0 && y < SCREEN_Y) pixel_put(fdf->pixel, x, y, (b << 16) + (g << 8) + (r)); i += 0.1; } return (0); } void get_colors_y(t_fdf *fdf, int h, int w) { if (h < fdf->height - 1 && fdf->tab[h + 1][w] != fdf->tab[h][w]) draw_line(fdf, 102, 0, 0); else if (fdf->tab[h][w] != 0) draw_line(fdf, 255, 0, 0); else if (fdf->tab[h][w] == 0) draw_line(fdf, 255, 102, 102); } int leave_window(void) { exit(-1); return (0); } <file_sep>/Makefile # **************************************************************************** # # # # ::: :::::::: # # Makefile :+: :+: :+: # # +:+ +:+ +:+ # # By: dbauduin <<EMAIL>> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2017/05/03 18:05:57 by dbauduin #+# #+# # # Updated: 2017/05/26 23:32:25 by dbauduin ### ########.fr # # # # **************************************************************************** # NAME = fdf OBJ = objs/main.o\ objs/setup.o\ objs/ft_util.o\ objs/print_map.o\ objs/windows.o\ objs/norme.o\ all: $(NAME) $(NAME): objs $(OBJ) @make -C libft/ fclean && make -C libft/ @gcc -o $(NAME) $(OBJ) -framework OpenGL -framework AppKit libft/libft.a minilibx/libmlx.a @echo "\033[32mFdF compiled [ ✔ ]\033[0m" objs: @mkdir objs objs/%.o: srcs/%.c @gcc -Wall -Wextra -Werror -I libft/includes -I minilibx -o $@ -c $< clean: @rm -rf obj/ @make -C libft/ fclean @rm -Rf objs @echo "\033[32mFdF cleaned [ ✔ ]\033[0m" fclean: clean @rm -f $(NAME) re: fclean all <file_sep>/srcs/setup.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* setup.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbauduin <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/05/11 21:45:07 by dbauduin #+# #+# */ /* Updated: 2017/05/27 02:18:57 by dbauduin ### ########.fr */ /* */ /* ************************************************************************** */ #include "fdf.h" #include "libft.h" t_fdf *ft_init(char *av) { t_fdf *fdf; if (!(fdf = malloc(sizeof(t_fdf)))) return (0); fdf->width = 0; fdf->height = ft_height_map(av); fdf->zoom = 1; fdf->theme = 1; if (!(fdf->tab = (int **)malloc(sizeof(int *) * (fdf->height)))) return (0); fdf->endian[0] = 32; fdf->endian[1] = 4 * SCREEN_X; fdf->endian[2] = 0; return (fdf); } int *insert_tab(int alt, int *tab, int size) { int *new_tab; if (!(new_tab = malloc(sizeof(int) * (size + 1)))) return (0); new_tab[size] = alt; while (size--) new_tab[size] = tab[size]; return (new_tab); } int newline(t_fdf *fdf, char *line, int y) { char **tab_char; int alt_map; int i; i = 0; if (!(tab_char = ft_strsplit(line, ' '))) return (0); if (fdf->width && fdf->width != ft_tablen(tab_char)) return (0); fdf->width = ft_tablen(tab_char); while (tab_char[i]) { alt_map = ft_atoi(tab_char[i]); fdf->tab[y] = insert_tab(alt_map, fdf->tab[y], i); free(tab_char[i++]); } free(tab_char); return (1); } t_fdf *ft_setup(char *av) { t_fdf *fdf; int fd; char *line; if ((fd = open(av, O_RDONLY)) == -1 || !(fdf = ft_init(av))) { write(1, "error", 5); return (0); } if (!(fdf->tab = (int **)malloc(sizeof(int *) * fdf->height))) return (0); if (!ft_setup2((const int)fd, &line, fdf)) return (0); coord(fdf); !fdf->width ? write(1, "FdF: map invalid\n", 17) : 0; return (fdf->width ? fdf : 0); } <file_sep>/srcs/windows.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* windows.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbauduin <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/05/12 01:30:26 by dbauduin #+# #+# */ /* Updated: 2017/05/22 04:29:40 by dbauduin ### ########.fr */ /* */ /* ************************************************************************** */ #include "fdf.h" void start_fdf(t_fdf *fdf, double zoom, int x, int y) { fdf->image = mlx_new_image(fdf->mlx, SCREEN_X, SCREEN_Y); fdf->pixel = mlx_get_data_addr(fdf->image, &fdf->endian[0], &fdf->endian[1], &fdf->endian[2]); ft_menu(fdf); fdf->zoom += zoom; fdf->origin_x += x; fdf->origin_y += y; print_line_x(fdf); print_line_y(fdf); mlx_put_image_to_window(fdf->mlx, fdf->win, fdf->image, 0, 0); ft_header(fdf); mlx_key_hook(fdf->win, act_windows, fdf); mlx_hook(fdf->win, 17, 17, leave_window, fdf); mlx_loop(fdf->mlx); free(fdf); } void draw(t_fdf *fdf) { mlx_clear_window(fdf->mlx, fdf->win); ft_menu(fdf); mlx_string_put(fdf->mlx, fdf->win, 0, 0, 0xffffff0, "ZOOM"); mlx_string_put(fdf->mlx, fdf->win, 0, 20, 0xffffff0, "DEPTH"); print_line_x(fdf); print_line_y(fdf); } void ft_menu(t_fdf *fdf) { int i; i = -1; while (++i < 255 * 1.5) { fdf->o_x = i; fdf->o_y = 0; fdf->d_x = i; fdf->d_y = SCREEN_Y; draw_line_menu(fdf, 255 - i / 1.5, 0, 0); } fdf->o_x = 0; fdf->o_y = 25; fdf->d_x = 320; fdf->d_y = 25; draw_line_menu(fdf, 255, 255, 255); } int act_windows(int keycode, void *param) { t_fdf *fdf; fdf = (t_fdf*)param; if (keycode == 53) { mlx_destroy_window(fdf->mlx, fdf->win); exit(0); } if (keycode == 69 || keycode == 78) keycode == 69 ? start_fdf(fdf, 1, 0, 0) : start_fdf(fdf, -1, 0, 0); if (keycode == 124 || keycode == 123) keycode == 124 ? start_fdf(fdf, 0, 10, 0) : start_fdf(fdf, 0, -10, 0); if (keycode == 125 || keycode == 126) keycode == 125 ? start_fdf(fdf, 0, 0, 10) : start_fdf(fdf, 0, 0, -10); ft_header(param); return (1); } void ft_header(t_fdf *fdf) { char *s; s = ft_itoa(fdf->zoom); mlx_string_put(fdf->mlx, fdf->win, 2, 2, 0x00FFFFFF, "MENU"); mlx_string_put(fdf->mlx, fdf->win, 2, 40, 0x00FFFFFF, "HEIGHT :"); mlx_string_put(fdf->mlx, fdf->win, 90, 41, 0x00FFFFFF, s); free(s); mlx_string_put(fdf->mlx, fdf->win, 2, 78, 0x00FFFFFF, "ORIGIN X :"); s = ft_itoa(fdf->origin_x); mlx_string_put(fdf->mlx, fdf->win, 110, 77, C, s); free(s); mlx_string_put(fdf->mlx, fdf->win, 2, 96, C, "ORIGIN Y :"); s = ft_itoa(fdf->origin_y); mlx_string_put(fdf->mlx, fdf->win, 110, 97, C, s); free(s); ft_header2(fdf); } <file_sep>/srcs/print_map.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* print_map.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbauduin <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/05/05 13:58:01 by dbauduin #+# #+# */ /* Updated: 2017/05/30 01:25:42 by dbauduin ### ########.fr */ /* */ /* ************************************************************************** */ #include "mlx.h" #include "fdf.h" #include <math.h> void coord(t_fdf *fdf) { int i; float pas; i = 0; pas = fdf->width; fdf->height > fdf->width ? pas = fdf->height : 0; fdf->origin_x = (SCREEN_X / pas / 2) * fdf->height + 300; fdf->origin_y = 50; } int print_line_x(t_fdf *fdf) { int h; int w; float pas; h = -1; pas = fdf->width; fdf->height > fdf->width ? pas = fdf->height : 0; while (++h < fdf->height) { w = 0; fdf->o_x = fdf->origin_x - (475 / pas * h); fdf->o_y = fdf->origin_y + (399 / pas * h) - (fdf->zoom * fdf->tab[h][w]); while (w < fdf->width - 1) { fdf->d_x = fdf->o_x + 475 / pas; fdf->d_y = (fdf->o_y + 399 / pas) - (fdf->zoom * (fdf->tab[h][w + 1] - fdf->tab[h][w])); get_colors_x(fdf, h, w); fdf->o_x = fdf->d_x; fdf->o_y = fdf->d_y; w++; } } return (0); } int print_line_y(t_fdf *fdf) { int h; int w; float pas; w = -1; pas = fdf->width; fdf->height > fdf->width ? pas = fdf->height : 0; while (++w < fdf->width) { h = 0; fdf->o_x = fdf->origin_x + (475 / pas * w); fdf->o_y = fdf->origin_y + (399 / pas * w) - (fdf->zoom * fdf->tab[h][w]); while (h < fdf->height - 1) { fdf->d_x = fdf->o_x - 475 / pas; fdf->d_y = fdf->o_y + 399 / pas - (fdf->zoom * (fdf->tab[h + 1][w] - fdf->tab[h][w])); get_colors_y(fdf, h, w); fdf->o_x = fdf->d_x; fdf->o_y = fdf->d_y; h++; } } return (0); } int draw_line(t_fdf *fdf, int r, int g, int b) { double i; double distance; double ratio; int x; int y; i = 0; distance = sqrt(pow((fdf->d_x - fdf->o_x), 2) + pow((fdf->d_y - fdf->o_y), 2)); while (i < distance) { ratio = i / distance; x = fdf->o_x + (fdf->d_x - fdf->o_x) * ratio; y = fdf->o_y + (fdf->d_y - fdf->o_y) * ratio; if (x >= 350 && x < SCREEN_X && y >= 0 && y < SCREEN_Y) pixel_put(fdf->pixel, x, y, (b << 16) + (g << 8) + (r)); i += 0.1; } return (0); } void pixel_put(char *pixel, int x, int y, int color) { pixel += x * 4 + y * (4 * SCREEN_X); pixel[0] = color >> 16 & 0xff; pixel[1] = color >> 8 & 0xff; pixel[2] = color & 0xff; }
24cb17f0754d9fe8fa664c8f2b272a191b49d02f
[ "C", "Makefile" ]
7
C
Kinai42/FdF
bbb8eec297e0f0e8818dffca41435571f2a4f57d
d4e008214cdbbd155d061a3d57f0cc30955ddd67
refs/heads/master
<repo_name>thenoviceoof/selfspy-img<file_sep>/selfspy_img.py #!/usr/bin/env python ################################################################################ # selfspy_img.py # photologs through your webcam import argparse import daemon import os import sys import time import getpass import math import Image # PIL import zipfile from encrypt.EncryptedFile import EncryptedFile ################################################################################ # utilities def debug(msg): print("[i] " + msg) def error(msg): print("[ERROR] " + msg) sys.exit(1) ################################################################################ # main def get_webcam_img(cv, cap): ''' cv: because not imported into the top level cap: keep this guy around ''' def shot(): frame = cv.QueryFrame(cap) # BGR is the default colorspace for opencv cv.CvtColor(frame,frame, cv.CV_BGR2RGB) webcam_img = Image.fromstring("RGB", cv.GetSize(frame), frame.tostring()) return webcam_img return shot def get_gtk_screenshot(gtk): ''' gtk: because not imported into the top level ''' def screenshot(): w = gtk.gdk.get_default_root_window() size = w.get_size() pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, size[0], size[1]) pb = pb.get_from_drawable(w, w.get_colormap(), 0,0,0,0, size[0], size[1]) # something has gone wrong, abort if pb is None: return None # handle non-4x rows pxs = pb.get_pixels() if len(pxs) != size[0]*size[1]*3: new = '' stride = int(math.ceil(len(pxs)/size[1])/4.)*4 for i in range(size[1]): start = i*stride new += pxs[start:start+3*size[0]] pxs = new screen_img = Image.fromstring("RGB", (size[0], size[1]), pxs) return screen_img return screenshot def get_save(path, getter, file_type='JPEG', resize=False, compression=None, archive=None, password=None): ''' path: save to getter: function to retrieve image with file_type: PIL save as resize: False, no resizing, otherwise (w,h) compression: compression factor archive: whether or not to archive the image after saving password: <PASSWORD> with which <PASSWORD> ''' if verbose: debug('Retrieving file...') img = getter() if img is None: if verbose: debug('No Image handed back, aborting...') return if resize: if verbose: debug('Resizing...') img = img.resize(resize) if verbose: debug('Opening file...') f = open(path, "wb") if password: if verbose: debug('Encrypting image...') f = EncryptedFile(f, passphrase=<PASSWORD>, mode='wb', encryption_algo=EncryptedFile.ALGO_BLOWFISH) img.save(f, file_type, quality=compression) f.close() if archive: if verbose: debug('Archiving...') archive = zipfile.ZipFile(archive, 'a', zipfile.ZIP_DEFLATED) archive.write(path, os.path.basename(path)) archive.close() os.remove(path) def main_loop(filename_format, data_directory, compression, webcam_resize, screen_resize, archive, password, verbose, interval): # do an initial computation if webcam_resize: import cv cap = cv.CaptureFromCAM(0) frame = cv.QueryFrame(cap) if cv.GetSize(frame) == webcam_resize: if verbose: debug('No resize necessary') webcam_resize = False if screen_resize: import gtk.gdk if screen_resize == 1.0: screen_resize = False else: img = get_gtk_screenshot(gtk)() screen_resize = [int(s*screen_resize) for s in img.size] # make sure the zipfile is still there if archive: archive = '%s/images_archive.zip' % data_directory while True: timestamp = time.strftime(filename_format) if verbose: debug('Taking shot at %s' % timestamp) if webcam_resize is not None: webcam_img_path = '%s/webcam/%s.jpg' % (data_directory, timestamp) if password: webcam_img_path += '.gpg' get_save(webcam_img_path, get_webcam_img(cv, cap), 'JPEG', webcam_resize, compression, archive, password) if screen_resize is not None: screen_img_path = '%s/screenshot/%s.png' % (data_directory, timestamp) if password: screen_img_path += '.gpg' get_save(screen_img_path, get_gtk_screenshot(gtk), 'PNG', screen_resize, 9, archive, password) if verbose: debug('Done, sleeping...') time.sleep(args.interval) ################################################################################ # pre-loop if __name__=="__main__": # get args parser = argparse.ArgumentParser( description='Photolog through your webcam (and screenshots)') parser.add_argument('-i', '--interval', dest='interval', default=10, type=int, help=('Time interval in seconds between snapshots')) parser.add_argument('-ws', '--webcam-size', dest='webcam_size', default='320x240', help=('Size of the stored image in <wxh> format ' '(ex. 640x480)')) parser.add_argument('-ss', '--screeshot-size', dest='screenshot_size', default=1.0, type=float, help=('Size of the stored image in percentage')) # encryption stuff parser.add_argument('-p', '--password', dest='password', default=None, type=str, help=('Passkey with which to encrypt the images, ' 'after optional compression with -c. If ' 'neither -p nor -n are specified, then ' 'a passkey will be queried.')) parser.add_argument('-np', '--no-password', dest='passwordp', default=True, const=False, action='store_const', help='Overrides -p, stores the snapshots unencrypted') # sources parser.add_argument('-nw', '--no-webcam', dest='webcam', default=True, const=False, action='store_const', help="Don't query the webcam for snapshots") parser.add_argument('-ns', '--no-screenshot', dest='screen', default=True, const=False, action='store_const', help="Don't query GTK for snapshots") # compression settings parser.add_argument('-c', '--compression', dest='compression', default=70, type=int, help=('Parameter for jpeg compression ' '(1-95, default 70)')) parser.add_argument('-a', '--archive', dest='archive', default=False, const=True, action='store_const', help="Archive the snapshots as they're taken, by " 'default in DATA_DIR/webcam_archive.zip (option --dir)') # various overall settings parser.add_argument('--dir', dest='dir', default=None, help=('Directory in which to store the images: ' 'default is ~/.selfspy/photolog/')) parser.add_argument('-d', '--daemonize', dest='daemonize', default=False, const=True, action='store_const', help='Daemonizes the process') parser.add_argument('-f', '--format', dest='format', default='%Y_%m_%dT%H_%M_%S', type=str, help=('Override the file name formatting of the ' 'generated image files. Note that if you do ' 'not include a time unit granular enough for ' 'your interval, your files will be overwritten.')) parser.add_argument('-v', '--verbose', dest='verbose', default=False, const=True, action='store_const', help='Display debug and informational messages') args = parser.parse_args() ######################################## # argument computation verbose = args.verbose webcamp = args.webcam screenp = args.screen if webcamp: if verbose: debug('Using webcam source') if screenp: if verbose: debug('Using GTK screenshot source') if not webcamp and not screenp: print("ERROR: You need to have at least one source") sys.exit(1) # directories home = os.getenv("HOME") if args.dir is None: if verbose: debug('Using default directory') directory = "%s/.selfspy/photolog/" % home else: directory = args.dir if webcamp: webcam_dir = directory + 'webcam/' if not os.path.exists(webcam_dir): if verbose: debug('Creating necessary directory') os.makedirs(webcam_dir) if screenp: screen_dir = directory + 'screenshot/' if not os.path.exists(screen_dir): if verbose: debug('Creating necessary directory') os.makedirs(screen_dir) # precomute some stuff compression = max(1, min(args.compression, 95)) webcam_resize = None screen_resize = None if webcamp: webcam_resize = tuple([int(s) for s in args.webcam_size.split("x")])[0:2] if verbose: debug('Resizing webcam output to %dx%d' % webcam_resize) if screenp: screen_resize = args.screenshot_size if verbose: debug('Resizing screenshots to %f' % screen_resize) # password if not args.passwordp: password = None else: if args.password: password = args.password else: password = getpass.getpass() # let's get this party started if args.daemonize: if verbose: debug('Daemonizing...') with daemon.DaemonContext(): main_loop(args.format, directory, compression, webcam_resize, screen_resize, args.archive, password, verbose, args.interval) main_loop(args.format, directory, compression, webcam_resize, screen_resize, args.archive, password, verbose, args.interval) <file_sep>/README.md selfspy-img ================================================================================ Photolog yourself for fun and profit! Usage -------------------------------------------------------------------------------- `./selfspy_img.py` Options -------------------------------------------------------------------------------- run `./selfspy_img.py --help` to find some help, like so: ./selfspy_img.py --help usage: selfspy_img.py [-h] [-i INTERVAL] [-ws WEBCAM_SIZE] [-ss SCREENSHOT_SIZE] [-p PASSWORD] [-np] [-nw] [-ns] [-c COMPRESSION] [-a] [--dir DIR] [-d] [-f FORMAT] [-v] Photolog through your webcam (and screenshots) optional arguments: -h, --help show this help message and exit -i INTERVAL, --interval INTERVAL Time interval in seconds between snapshots -ws WEBCAM_SIZE, --webcam-size WEBCAM_SIZE Size of the stored image in <wxh> format (ex. 640x480) -ss SCREENSHOT_SIZE, --screeshot-size SCREENSHOT_SIZE Size of the stored image in percentage -p PASSWORD, --password <PASSWORD> Passkey with which to encrypt the images, after optional compression with -c. If neither -p nor -n are specified, then a passkey will be queried. -np, --no-password Overrides -p, stores the snapshots unencrypted -nw, --no-webcam Don't query the webcam for snapshots -ns, --no-screenshot Don't query GTK for snapshots -c COMPRESSION, --compression COMPRESSION Parameter for jpeg compression (1-95, default 70) -a, --archive Archive the snapshots as they're taken, by default in DATA_DIR/webcam_archive.zip (option --dir) --dir DIR Directory in which to store the images: default is ~/.selfspy/photolog/ -d, --daemonize Daemonizes the process -f FORMAT, --format FORMAT Override the file name formatting of the generated image files. Note that if you do not include a time unit granular enough for your interval, your files will be overwritten. -v, --verbose Display debug and informational messages <file_sep>/encrypt/EncryptedFile.py # * "THE BEER-WARE LICENSE" (Revision 42): # * <<EMAIL>> wrote this file. As long as you retain this notice you # * can do whatever you want with this stuff. If we meet some day, and you think # * this stuff is worth it, you can buy me a beer in return ################################################################################ import hashlib from Crypto.Cipher import Blowfish, AES from os import urandom import math import re class EncryptedFile(object): ''' A transparent, write-only file-like object Creates OpenPGP compatible encrypted files ''' # OpenPGP values ALGO_BLOWFISH = 4 ALGO_AES128 = 7 ALGO_AES196 = 8 ALGO_AES256 = 9 S2K_SIMPLE = 0 S2K_SALTED = 1 S2K_ITERATED = 3 HASH_MD5 = 1 HASH_SHA1 = 2 HASH_SHA256 = 8 HASH_SHA384 = 9 HASH_SHA512 = 10 # things mapping OpenPGP values to Python values ENCRYPTION_ALGOS = { ALGO_BLOWFISH : Blowfish, ALGO_AES128: AES, ALGO_AES196: AES, ALGO_AES256: AES, } KEY_SIZES = { ALGO_BLOWFISH : 16, ALGO_AES128: 16, ALGO_AES196: 24, ALGO_AES256: 32, } HASHES = { HASH_MD5: hashlib.md5, HASH_SHA1: hashlib.sha1, HASH_SHA256: hashlib.sha256, HASH_SHA384: hashlib.sha384, HASH_SHA512: hashlib.sha512, } def __init__(self, file_obj, passphrase, mode='w', iv=None, salt=None, block_size=16, buffer_size=1024, timestamp=None, encryption_algo=ALGO_AES256, hash_algo=HASH_SHA256, key_method=S2K_ITERATED, iterated_count=(16, 6)): ''' Open a pipe to an encrypted file file_obj: a string or file-like object a string should be a path file object: write through to the file passphrase: <PASSWORD> mode: usual file modes iv: initialization vector, randomly generated if not given. same size as block_size key_method: which S2K_* method to use hash_algo: which HASH_* to convert the passphrase with encryption_algo: which ALGO_* to encrypt the plaintext with block_size: used by the cipher buffer_size: how much data should be slurped up before encrypting timestamp <int>: timestamp, if any, to be attached to the literal data if not given, just writes zeroes iterated_count: a tuple (base, exp), where base is between [16, 32), and the exp is between 6 and 22 ''' if not int(buffer_size/block_size)*block_size == buffer_size: raise ValueError('buffer_size is not a multiple of the block_size') self.block_size = block_size # check buffer_size: can set later if not buffer_size > 512: raise ValueError('First block_size must be larger than 512b') self.buffer_size = buffer_size self.mode = mode self.bin_mode = False if len(self.mode)>1: self.bin_mode = (self.mode[1] == 'b') self._raw_buffer = '' self._lit_buffer = '' self._enc_buffer = '' self.closed = False if isinstance(file_obj, basestring): if len(file_obj) > 0xff: raise ValueError('File name is too long') self.file = open(file_obj, mode) self.name = file_obj elif isinstance(file_obj, file): self.file = file_obj self.name = file_obj.name[:0xff] else: raise TypeError # we are write-only at the moment if mode[0] == 'w': if not iv: self.iv = urandom(self.block_size) elif len(iv) != self.block_size: raise ValueError('IV has to be one block size') else: self.iv = iv # write the symmetric encryption session packet header = '' header += chr((1 << 7) | (1 << 6) | 3) header += chr(0) # header length header += chr(4) # version header += chr(encryption_algo) # sym algo header += chr(key_method) # S2K header += chr(hash_algo) # S2K hash algo # generate 8b salt if key_method in [self.S2K_SALTED, self.S2K_ITERATED]: if not salt: salt = urandom(8) header += salt if key_method == self.S2K_ITERATED: if iterated_count[0] < 16 or iterated_count[0] >= 32: raise ValueError('iterated_count base illegal') if iterated_count[1] < 6 or iterated_count[1] >= 22: raise ValueError('iterated_count exp illegal') count = iterated_count[0] << iterated_count[1] packed_base = iterated_count[0] - 16 packed_exp = iterated_count[1] - 6 << 4 packed_count = chr(packed_exp & packed_base) header += packed_count header = header[0] + chr(len(header)-2) + header[2:] self.file.write(header) # write the encrypted data packet header self.file.write(chr((1 << 7) | (1 << 6) | 9)) else: raise ValueError('Only \'wb\' mode supported') def gen_key(key_method, hash_algo, pass_phrase, salt, it=0): ''' utility function to generate S2K keys ''' hsh = self.HASHES[hash_algo]() hsh.update(chr(0) * it) if key_method == self.S2K_SIMPLE: hsh.update(pass_phrase) elif key_method == self.S2K_SALTED: hsh.update(salt) hsh.update(pass_phrase) elif key_method == self.S2K_ITERATED: # hash <count> number of bytes i = 0 key = salt + pass_phrase while i + len(key) < count: hsh.update(key) i += len(key) hsh.update(key[:count - i]) return hsh.digest() self.key = '' i = 0 while len(self.key) < self.KEY_SIZES[encryption_algo]: self.key += gen_key(key_method, hash_algo, passphrase, salt, i) i += 1 self.key = self.key[:self.KEY_SIZES[encryption_algo]] cipher = self.ENCRYPTION_ALGOS[encryption_algo] self.cipher = cipher.new(self.key, cipher.MODE_OPENPGP, self.iv, block_size = block_size) # add the literal block id byte to the unencrypted buffer self._lit_buffer += chr((1 << 7) | (1 << 6) | 11) # set mode self._raw_buffer += 'b' if self.bin_mode else 't' # write out file name self._raw_buffer += chr(len(self.name)) self._raw_buffer += self.name # write out 4-octet date if timestamp: self._raw_buffer += chr(timestamp >> 24 & 0xff) self._raw_buffer += chr(timestamp >> 16 & 0xff) self._raw_buffer += chr(timestamp >> 8 & 0xff) self._raw_buffer += chr(timestamp & 0xff) else: self._raw_buffer += '\0' * 4 self.count = 0 # handle {with EncryptedFile(...) as f:} notation def __enter__(self): return self def __exit__(self, type, value, traceback): self.close() def _semi_length(self): ''' Produce the byte encoding an intermediate block of data ''' # make sure the buffer size fits the semi-packet length constraints # keep this here, self.buffer_size is user-available power = int(math.log(1024, 2)) assert self.buffer_size == 2**power return chr(224 + power) def _final_length(self, length): ''' Produce the bytes encoding the length of the final data segment ''' if length <= 191: return chr(length) elif length <= 8383: return (chr(((length - 192) >> 8) + 192) + chr((length - 192) & 0xFF)) else: return (chr(0xff) + chr((length >> 24) & 0xff) + chr((length >> 16) & 0xff) + chr((length >> 8) & 0xff) + chr(length & 0xff)) def _write_enc_buffer(self, final=False): ''' Given things in the encrypted buffer, write them ''' while len(self._enc_buffer) >= self.buffer_size: self.file.write(self._semi_length()) # write the encrypted data in blocks self.file.write(self._enc_buffer[:self.buffer_size]) self._enc_buffer = self._enc_buffer[self.buffer_size:] if final: self.file.write(self._final_length(len(self._enc_buffer))) self.file.write(self._enc_buffer) def _encrypt_buffer(self, final=False): ''' Given literal packet data, encrypt it ''' cnt = int(math.floor(len(self._lit_buffer)/self.block_size)) bs = cnt * self.block_size # encrypt all data that fits cleanly in the block size self._enc_buffer += self.cipher.encrypt(self._lit_buffer[:bs]) self._lit_buffer = self._lit_buffer[bs:] if final: self._enc_buffer += self.cipher.encrypt(self._lit_buffer) self._write_enc_buffer(final=final) def _write_buffer(self, final=False): ''' Given things in the raw buffer, attach metadata and put them in the literal buffer ''' # add the literal data packet metadata while len(self._raw_buffer) >= self.buffer_size: self._lit_buffer += self._semi_length() # write/encrypt the literal data in blocks self._lit_buffer += self._raw_buffer[:self.buffer_size] self._raw_buffer = self._raw_buffer[self.buffer_size :] if final: final_len = self._final_length(len(self._raw_buffer)) self._lit_buffer += final_len self._lit_buffer += self._raw_buffer self._encrypt_buffer(final=final) def write(self, data): # make sure the data is there self.count += len(data) self._raw_buffer += data if not self.bin_mode: self._raw_buffer = re.sub('([^\r])\n', '\\1\r\n', self._raw_buffer) self._raw_buffer = re.sub('\r([^\n])', '\r\n\\1', self._raw_buffer) if self._raw_buffer[-1] == '\r': # don't write yet: we might have more coming (\r\n pairs) return self._write_buffer() def writelines(self, lines): if self.bin_mode: raise ValueError('Textual method used with binary data') for line in lines: line = re.sub('([^\r])\n', '\\1\r\n', line) line = re.sub('\r([^\n])', '\r\n\\1', line) self._raw_buffer += line self._raw_buffer += '\r\n' # use CR/LF, network newlines self._write_buffer() # reading is hard def read(self, *args, **kwargs): raise NotImplementedError() def readlines(self, *args, **kwargs): raise NotImplementedError() # so is seeking def seek(self, offset, whence=None): raise NotImplementedError() def tell(self): return self.count def close(self): if self.file.closed: return # make sure we catch a final \r, which was waiting for the next write if not self.bin_mode and self._raw_buffer[-1] == '\r': self._raw_buffer += '\n' self._write_buffer(final=True) self.file.close() def flush(self): ''' Merely flushes the encapsulated file object. If there's stuff in the buffer, there's a good reason for it. ''' self.file.flush() def isatty(self): return False if __name__=='__main__': ''' Documentation and self-testing To decrypt with gpg: gpg <file name> ''' msg = '''Hello world''' print("Encrypted message:") print(msg) b = EncryptedFile('example.gpg', passphrase='w') b.write(msg) b.close() <file_sep>/encrypt/README.md encryptedfile ================================================================================ Write OpenPGP compatible-encrypted files like it ain't no thang. Symmetric ciphers only. Usage -------------------------------------------------------------------------------- Use it by itself: from encryptedfile import EncryptedFile f = EncryptedFile("hello.gpg", pass_phrase=<PASSWORD>(), encryption_algo=EncryptedFile.ALGO_AES256) f.write("super secret message") f.close() Or with something passed through it: from encryptedfile import EncryptedFile import PIL img = ... # obtain image somehow f = EncryptedFile("pic.png.gpg", pass_phrase=<PASSWORD>(), encryption_algo=EncryptedFile.ALGO_BLOWFISH) img.save(f, "png") Or use it in a PEP-343 block: from encryptedfile import EncryptedFile with EncryptedFile("txt.gpg", pass_phrase=<PASSWORD>()) as f: ... use f ... Decrypt -------------------------------------------------------------------------------- Let's say we're using gpg: gpg filename Supply the right passphrase, and tada! FAQ -------------------------------------------------------------------------------- - Do you support reading? No, reading would mean supporting the bajillion ways that OpenPGP files have been created throughout history. License -------------------------------------------------------------------------------- "THE BEER-WARE LICENSE" (Revision 42): <<EMAIL>> wrote this file. As long as you retain this notice you can do whatever you want with this stuff. If we meet some day, and you think this stuff is worth it, you can buy me a beer in return <file_sep>/requirements.txt python>=2.7 python-daemon>=1.5.5 # python-opencv>= pycrypto>=2.6 PIL>=1.1.7
f939f8e30afa905e360367e47fbca5b575db20a9
[ "Markdown", "Python", "Text" ]
5
Python
thenoviceoof/selfspy-img
55e857f15e2f4827e0e92cc3110302adabaeb653
d195a526c10234fe04479c36272d7dbf28d9f705
refs/heads/master
<file_sep>#!/bin/sh MAX_IMG_SIZE=104857600 src=$1 out_png=/home/bot/out.png svg2png () { inkscape --without-gui --file="$1" --export-png="$out_png" 2>&1 | \ grep -v -e 'Failed to get connection' -e 'dbus_g_proxy_' -e 'Background RRGGBBAA:' -e 'Bitmap saved as:' -e 'dbus_g_connection_register_g_object' } case "$src" in *.asm) nasm -f elf64 -o a.o "$src" && ld -s -o a.out a.o && ./a.out ;; *.bc) bc -l "$src" ;; *.bf|*.b) beef -d "$src" ;; *.cpp) clang++ "$src" && ./a.out ;; *.cs) mcs "$src" && mono "${src%.cs}.exe" ;; *.c) gcc "$src" && ./a.out ;; *.dot) dot -T png -o "$out_png" "$src" ;; *.f|*.f90|*.f95) gfortran "$src" && ./a.out ;; *.go) go run "$src" ;; *.hs) runghc "$src" ;; *.java) javac "$src" && java "${src%.java}" ;; *.js) node "$src" ;; *.lsp|*.lisp) clisp -q < "$src" ;; *.lua) lua5.3 "$src" ;; *.ml) ocaml "$src" ;; *.php) php "$src" ;; *.plt|*.gnuplot|*.gpi) gnuplot -e "set terminal png size 800,800; set output 'out.png'" "$src" ;; *.py2) python2 "$src" ;; *.py3|*.py) python3 "$src" ;; *.pl) perl "$src" ;; *.rb) ruby "$src" ;; *.scm) guile -s "$src" 2>/dev/null ;; *.sh|*.bash) bash "$src" ;; *.sql) sqlite3 "${src%.sql}.db" < "$src" ;; *.svg) svg2png "$src" ;; *.ts) tsc "$src" && node "${src%.ts}".js ;; *.vim) LANG=ja_JP.UTF-8 vim -X -N -u NONE -i NONE --not-a-term --cmd "source $src | qall!" | ansi2txt ;; *.zsh) zsh "$src" ;; *.html|*.htm) LANG=ja_JP.UTF-8 xvfb-run phantomjs /usr/local/etc/render.js "$src" 2>/dev/null | grep -P '^[A-Z]+:' | sed -e 's/^CONSOLE://' ;; script) cp "$src" /tmp/ rm -f "$src" mv /tmp/"$src" "$src" chmod +x "$src" && ./"$src" ;; *) echo "This file is not supported." exit ;; esac if [ "$src" != "out.svg" -a -e "out.svg" ]; then svg2png out.svg fi if [ -e "$out_png" ]; then if [ "$(stat --format=%s $out_png)" -gt "$MAX_IMG_SIZE" ]; then rm -f "$out_png" fi fi <file_sep># bot-playground docker image for hello-bot <file_sep>#!/bin/bash cd `dirname "$0"` cd .. docker pull ubuntu:17.04 docker build --tag bot-playground:latest . <file_sep>.separator ", " create table greet_table ( id integer primary key, greeting text, target text ); insert into greet_table values (1, 'hello', 'world'); select greeting, target from greet_table; <file_sep>class Main { constructor() { console.log("hello, world"); } } var main:Main = new Main(); <file_sep>#!/bin/bash CONTAINER_NAME=bot-playground-test MAX_FSIZE=$(( 4096 * 1024)) MAX_DSIZE=$(( 2048 * 1024)) MAX_CPU="15" EXPECT="hello, world" cd `dirname "$0"` cd ../hello-src/ docker kill "$CONTAINER_NAME" 2>/dev/null docker rm "$CONTAINER_NAME" 2>/dev/null for f in [Hh]ello.* do echo "$f" docker run -d -it \ --ulimit fsize="$MAX_FSIZE" \ --ulimit data="$MAX_DSIZE" \ --ulimit cpu="$MAX_CPU" \ --name "$CONTAINER_NAME" \ --network=none \ bot-playground tail -f chmod "777" "$f" docker cp "$f" "$CONTAINER_NAME":/home/bot/"$f" export OUTPUT time OUTPUT=$(/usr/bin/timeout 32s docker exec "$CONTAINER_NAME" timeout "$MAX_CPU"s /usr/local/bin/job.sh "$f" 2>&1 | head -2000) docker cp "$CONTAINER_NAME":/home/bot/out.png "$IMAGE_FILE_NAME" 2>/dev/null || true docker kill "$CONTAINER_NAME" docker rm "$CONTAINER_NAME" echo "$OUTPUT" if [[ "$OUTPUT" =~ $EXPECT ]]; then echo "OK" else echo "NG" echo "expect" _"$EXPECT"_ echo "actual" _"$OUTPUT"_ echo "$f" exit fi done <file_sep>#!/bin/zsh hw="hello, world.txt" echo ${hw:r} <file_sep>#!/bin/sh MAX_FSIZE=$(( 4096 * 1024)) MAX_DSIZE=$(( 1024 * 1024)) MAX_CPU="30" WORKER_ID=$$ EXEC_CONtINER=bot-"$WORKER_ID" cd `dirname "$0"` cd .. docker run --rm -it --network=none \ --ulimit fsize="$MAX_FSIZE" \ --ulimit data="$MAX_DSIZE" \ --ulimit cpu="$MAX_CPU" \ --hostname "$EXEC_CONtINER" \ --name "$EXEC_CONtINER" bot-playground bash <file_sep>#!/bin/bash CONTAINER_NAME=bot-playground-test MAX_FSIZE=$(( 4096 * 1024)) MAX_DSIZE=$(( 2048 * 1024)) MAX_CPU="15" OUT_PNG=/tmp/out.$$.png docker kill "$CONTAINER_NAME" 2>/dev/null docker rm "$CONTAINER_NAME" 2>/dev/null cd `dirname "$0"` cd ../out-png-src/ for f in *.* do echo "--------------------------------------------------------" echo "$f" docker run -d -it \ --ulimit fsize="$MAX_FSIZE" \ --ulimit data="$MAX_DSIZE" \ --ulimit cpu="$MAX_CPU" \ --name "$CONTAINER_NAME" \ --network=none \ bot-playground tail -f chmod "777" "$f" docker cp "$f" "$CONTAINER_NAME":/home/bot/"$f" export OUTPUT time OUTPUT=$(/usr/bin/timeout 32s docker exec "$CONTAINER_NAME" timeout "$MAX_CPU"s /usr/local/bin/job.sh "$f" 2>&1 | head -2000) docker cp "$CONTAINER_NAME":/home/bot/out.png "$OUT_PNG" || true docker kill "$CONTAINER_NAME" docker rm "$CONTAINER_NAME" echo "$OUTPUT" display -delay 1 "$OUT_PNG" rm -f "$OUT_PNG" done
d0a4ad47b206a7250f81ab78cd8d3044d3146d1a
[ "Markdown", "SQL", "TypeScript", "Shell" ]
9
Shell
HiroshiOkada/bot-playground
d707c57667c9ecb1f4850cc4d00a647af90316aa
b768d30a8fc8a737a5eec5867bd418c4cfe45818
refs/heads/master
<repo_name>tofigf/AccountingApi<file_sep>/AccountingApi/Dtos/Purchase/Expense/ExpenseItemGetDto.cs using System; namespace AccountingApi.Dtos.Purchase.Expense { public class ExpenseItemGetDto { public int Id { get; set; } public bool IsBank { get; set; } public double? PaidMoney { get; set; } public double? Residue { get; set; } public int ExpenseInvoiceId { get; set; } public int? AccountDebitId { get; set; } public int? AccountKreditId { get; set; } public DateTime? Date { get; set; } } } <file_sep>/AccountingApi/Migrations/20190627164754_BalanceSheetIncomeIttemId.cs using Microsoft.EntityFrameworkCore.Migrations; namespace AccountingApi.Migrations { public partial class BalanceSheetIncomeIttemId : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<string>( name: "InvoiceNumber", table: "IncomeItems", maxLength: 300, nullable: true, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AddColumn<int>( name: "IncomeItemId", table: "BalanceSheets", nullable: true); migrationBuilder.CreateIndex( name: "IX_BalanceSheets_IncomeItemId", table: "BalanceSheets", column: "IncomeItemId"); migrationBuilder.AddForeignKey( name: "FK_BalanceSheets_IncomeItems_IncomeItemId", table: "BalanceSheets", column: "IncomeItemId", principalTable: "IncomeItems", principalColumn: "Id", onDelete: ReferentialAction.NoAction); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_BalanceSheets_IncomeItems_IncomeItemId", table: "BalanceSheets"); migrationBuilder.DropIndex( name: "IX_BalanceSheets_IncomeItemId", table: "BalanceSheets"); migrationBuilder.DropColumn( name: "IncomeItemId", table: "BalanceSheets"); migrationBuilder.AlterColumn<string>( name: "InvoiceNumber", table: "IncomeItems", nullable: true, oldClrType: typeof(string), oldMaxLength: 300, oldNullable: true); } } } <file_sep>/AccountingApi/Models/ViewModel/VwCreateExpenseInvoice.cs using AccountingApi.Dtos.Company; using AccountingApi.Dtos.Nomenklatura.Kontragent; using AccountingApi.Dtos.Purchase.ExpenseInvoice; using System.Collections.Generic; namespace AccountingApi.Models.ViewModel { public class VwCreateExpenseInvoice { public ExpenseInvoicePostDto ExpenseInvoicePostDto { get; set; } public List<ExpenseInvoiceItemPostDto> ExpenseInvoiceItemPostDtos { get; set; } public CompanyPutProposalDto CompanyPutProposalDto { get; set; } public ContragentPutInProposalDto ContragentPutInProposalDto { get; set; } } } <file_sep>/AccountingApi/Models/ExpenseInvoiceItem.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models { public class ExpenseInvoiceItem { [Key] public int Id { get; set; } public int? Qty { get; set; } public double? Price { get; set; } public double? TotalOneProduct { get; set; } public int? ProductId { get; set; } public int? ExpenseInvoiceId { get; set; } public virtual Product Product { get; set; } public virtual ExpenseInvoice ExpenseInvoice { get; set; } } } <file_sep>/AccountingApi/Models/Worker.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models { public class Worker { [Key] public int Id { get; set; } [MaxLength(75)] public string Name { get; set; } [MaxLength(75)] public string SurName { get; set; } [MaxLength(75)] public string Positon { get; set; } public double? Salary { get; set; } [MaxLength(75)] public string Departament { get; set; } [MaxLength(75)] public string PartofDepartament { get; set; } [MaxLength(75)] public string Role { get; set; } public DateTime RegisterDate { get; set; } public string PhotoFile { get; set; } public string PhotoUrl { get; set; } public bool IsState { get; set; } public bool IsDeleted { get; set; } = false; public int CompanyId { get; set; } public virtual Company Company { get; set; } public virtual ICollection<Worker_Detail> Worker_Details { get; set; } } } <file_sep>/AccountingApi/Dtos/Nomenklatura/Product/ProductGetEditDto.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Nomenklatura.Product { public class ProductGetEditDto { public string Name { get; set; } public string PhotoUrl { get; set; } public string Category { get; set; } public bool IsServiceOrProduct { get; set; } public int UnitId { get; set; } public string UnitName { get; set; } public double? Price { get; set; } public double? SalePrice { get; set; } public string Desc { get; set; } public bool IsSale { get; set; } public bool IsPurchase { get; set; } } } <file_sep>/AccountingApi/Dtos/Sale/Income/IncomeInvoiceGetDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Sale.Income { public class IncomeInvoiceGetDto { public int InvoiceId { get; set; } public string InvoiceNumber { get; set; } public double? TotalPrice { get; set; } public double? Residue { get; set; } public DateTime? PreparingDate { get; set; } public DateTime? EndDate { get; set; } public int? AccountDebitId { get; set; } public int? AccountKreditId { get; set; } } } <file_sep>/AccountingApi/Models/InvoiceItem.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models { public class InvoiceItem { [Key] public int Id { get; set; } public int? Qty { get; set; } public double? Price { get; set; } public double? SellPrice { get; set; } public double? TotalOneProduct { get; set; } public int? ProductId { get; set; } public int? InvoiceId { get; set; } public virtual Product Product { get; set; } public virtual Invoice Invoice { get; set; } } } <file_sep>/AccountingApi/Controllers/V1/AccountsPlanController.cs using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using AccountingApi.Data.Repository.Interface; using AccountingApi.Dtos.AccountsPlan; using AccountingApi.Models; using AutoMapper; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace AccountingApi.Controllers.V1 { [Authorize] [Route("api/[controller]")] [ApiController] public class AccountsPlanController : ControllerBase { private readonly IAccountsPlanRepository _repo; private readonly IMapper _mapper; public AccountsPlanController(IAccountsPlanRepository repo, IMapper mapper) { _repo = repo; _mapper = mapper; } //Get [baseUrl]/api/accountsplan/accountplanimportfromexcel [HttpGet] [Route("accountplanimportfromexcel")] public async Task<IActionResult> AccountPlanImportFromExcel([FromHeader] int? companyId) { if (companyId == null) return StatusCode(409, "companyId null"); await _repo.ImportFromExcel(companyId); return Ok(); } //Get [baseUrl]/api/accountsplan/getaccountsplan [HttpGet] [Route("getaccountsplan")] public async Task<IActionResult> GetAccountsPlan([FromHeader] int? companyId) { if (companyId == null) return StatusCode(409, "companyId null"); List<AccountsPlan> accounts = await _repo.GetAccountsPlans(companyId); if (accounts == null) return StatusCode(409, "object null"); var accountsToReturn = _mapper.Map<IEnumerable<AccountsPlanGetDto>>(accounts); return Ok (accountsToReturn); } //Get [baseUrl]/api/accountsplan/balancesheet [HttpGet] [Route("balancesheet")] public async Task<IActionResult> BalanceSheet([FromHeader] int? companyId, [FromQuery] DateTime? startDate, [FromQuery] DateTime? endDate) { if (companyId == null) return StatusCode(409, "companyId null"); var balance = await _repo.BalanceSheet(companyId, startDate, endDate); if(balance == null) { return StatusCode(409,"object null"); } return Ok(balance); } //ManualJournal #region ManualJournal //Get [baseUrl]/api/accountsplan/getoperationcategory [HttpGet] [Route("getoperationcategory")] public async Task<IActionResult> GetOperationCategory() { return Ok(await _repo.GetOperationCategories()); } //Post [baseUrl]/api/accountsplan/createmanualjournal [HttpPost] [Route("createmanualjournal")] public async Task<IActionResult> CreateManualJournal([FromHeader] int? companyId, ManualJournalPostDto journalPostDto) { //mapping for creating var mappedJournal = _mapper.Map<ManualJournal>(journalPostDto); //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); #endregion //creating repo ManualJournal ToReturn = await _repo.CreateManualJournal(companyId, mappedJournal); return Ok(ToReturn); } //Get [baseUrl]/api/accountsplan/getmanualjournal [HttpGet] [Route("getmanualjournal")] public async Task<IActionResult> GetManualJournal([FromHeader] int? companyId) { //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); #endregion var ManualJournalFromRepo = await _repo.GetManualJournals(companyId); var ToReturn = _mapper.Map<IEnumerable<ManualJournalGetDto>>(ManualJournalFromRepo); return Ok(ToReturn); } //Get [baseUrl]/api/accountsplan/geteditmanualjournal [HttpGet] [Route("geteditmanualjournal")] public async Task<IActionResult> GetEditManualJournal([FromHeader] int? companyId,[FromHeader] int? journalId) { //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); #endregion var editRepo = await _repo.GetEditManualJournal(companyId, journalId); var ToReturn = _mapper.Map<ManualJournalGetEditDto>(editRepo); return Ok(ToReturn); } //Put [baseUrl]/api/accountsplan/editmanualjournal [HttpPut] [Route("editmanualjournal")] public async Task<IActionResult>EditManualJournal(ManualJournalPostDto journalPostDto ,[FromHeader]int? companyId,[FromHeader] int? journalId) { //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); #endregion var getEditRepo = await _repo.GetEditManualJournal(companyId, journalId); //Account: var UpdateAccountDebit = _repo.UpdateManualJournalAccountDebit(journalId, companyId, journalPostDto, getEditRepo.AccountDebitId); var UpdateAccountKredit = _repo.UpdateManualJournalAccountKredit(journalId, companyId, journalPostDto, getEditRepo.AccountKreditId); var Mapped = _mapper.Map(journalPostDto, getEditRepo); var edited = await _repo.EditManualJournal(Mapped); var ToReturn = _mapper.Map<ManualJournalGetEditDto>(edited); return Ok(ToReturn); } //Delete [baseUrl]/api/accountsplan/deletemanualjournal [HttpDelete] [Route("deletemanualjournal")] public async Task<IActionResult> DeleteManualJournal([FromHeader] int? companyId, [FromHeader] int? journalId) { //Check #region Check if (companyId == null) return StatusCode(409, "companyId null"); if (journalId == null) return StatusCode(409, "invoiceId null"); if (await _repo.DeleteManualJournal(companyId, journalId) == null) return StatusCode(409, "object null"); #endregion await _repo.DeleteManualJournal(companyId, journalId); return Ok(); } //Get [baseUrl]/api/accountsplan/getjournal [HttpGet] [Route("getjournal")] public async Task<IActionResult> GetJournal([FromHeader] int? companyId, [FromQuery] DateTime? startDate, [FromQuery] DateTime? endDate) { var FromRepo = await _repo.GetJournal(companyId, startDate, endDate); return Ok(FromRepo); } #endregion } }<file_sep>/AccountingApi/Helpers/FileManager.cs using Microsoft.AspNetCore.Http; using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Helpers { public class FileManager { public static string Upload(string FileRaw) { string data = ""; try { data = FileRaw.Substring(0, 5); } catch (Exception) { } string ext = ""; /*Define mimetype*/ switch (data.ToUpper()) { case "IVBOR": ext = "png"; break; case "/9J/4": ext = "jpg"; break; case "AAABA": ext = "ico"; break; default: return null; } string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "." + ext; var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Uploads", filename); var imageDataByteArray = Convert.FromBase64String(FileRaw); if (imageDataByteArray.Length > 5000000) { return null; } ResizeOptions option = new ResizeOptions { Mode = ResizeMode.Max, Position = AnchorPositionMode.Center, Size = new SixLabors.Primitives.Size(250, 250) }; using (Image<Rgba32> image = Image.Load(imageDataByteArray)) { //while (image.size/time>100 && image.Height/time>100) //{ //} image.Mutate(x => x .Resize(option)); image.Save(path); } //var imageDataStream = new MemoryStream(imageDataByteArray) //{ // Position = 0 //}; ////int i = FileName.LastIndexOf('.'); ////FileName = FileName.Substring(0, i); //using (var file = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.Read)) //{ // imageDataStream.WriteTo(file); //} return filename; } public static bool Delete(string FileName) { var path = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot/Uploads", FileName); if (File.Exists(path)) { File.Delete(path); return true; } return false; } public static void FileSave(string filename, IFormFile file) { var stream = file.OpenReadStream(); var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads", filename); FileStream filestream = new FileStream(path, FileMode.Create, System.IO.FileAccess.Write); stream.CopyTo(filestream); } } } <file_sep>/AccountingApi/Models/ViewModel/VwCreateIncome.cs using AccountingApi.Dtos.Sale.Income; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models.ViewModel { public class VwCreateIncome { public List<IncomeItemPostDto> IncomeItemPostDtos { get; set; } public IncomePostDto IncomePostDto { get; set; } public int[] Ids { get; set; } } } <file_sep>/AccountingApi/Controllers/V1/ExpenseController.cs using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using AccountingApi.Data.Repository.Interface; using AccountingApi.Dtos.Company; using AccountingApi.Dtos.Purchase.Expense; using AccountingApi.Dtos.Purchase.ExpenseInvoice; using AccountingApi.Helpers.Extentions; using AccountingApi.Models; using AccountingApi.Models.ViewModel; using AutoMapper; using EOfficeAPI.Helpers.Pagination; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace EOfficeAPI.Controllers.V1 { [Authorize] [Route("api/[controller]")] [ApiController] public class ExpenseController : ControllerBase { private readonly IPurchaseRepository _repo; private readonly ISaleRepository _saleRepo; private readonly IMapper _mapper; public ExpenseController(IPurchaseRepository repo, ISaleRepository saleRepo, IMapper mapper) { _repo = repo; _mapper = mapper; _saleRepo = saleRepo; } //ExpenseInvoice #region ExpenseInvoice //Post [baseUrl]/api/expense/addexpenseinvoice [HttpPost] [Route("addexpenseinvoice")] public async Task<IActionResult> AddExpenseInvoice(VwCreateExpenseInvoice expenseInvoice, [FromHeader]int? companyId) { //mapping for creating invoice var mappedInvoice = _mapper.Map<ExpenseInvoice>(expenseInvoice.ExpenseInvoicePostDto); //mapping for creating invoiceitems var mappeditemInvoice = _mapper.Map<List<ExpenseInvoiceItem>>(expenseInvoice.ExpenseInvoiceItemPostDtos); //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckExpenseInvoice(currentUserId, companyId)) return Unauthorized(); //cheking product id if (await _repo.CheckExpenseInvoiceProductId(mappeditemInvoice)) return StatusCode(409, "productId doesnt exist"); if (mappedInvoice.ContragentId == null) return StatusCode(409, "contragentId null"); if (await _saleRepo.CheckContragentId(mappedInvoice.ContragentId, companyId)) return StatusCode(409, "contragentId doesnt exist"); if (_repo.CheckInvoiceNegativeValue(mappedInvoice, mappeditemInvoice)) return StatusCode(428, "negative value is detected"); #endregion //creating repo var invoiceToReturn = await _repo.CreateInvoice(mappedInvoice, companyId); //creating repo var itemToRetun = await _repo.CreateInvoiceItems(mappeditemInvoice, mappedInvoice.Id); //mapping for return var ToReturn = _mapper.Map<ExpenseInvoiceGetDto>(invoiceToReturn); //Company //id ye gore sirketi getiririk Company companyFromRepo = await _saleRepo.GetEditCompany(companyId); //map edirik Company companyForUpdate = _mapper.Map(expenseInvoice.CompanyPutProposalDto, companyFromRepo); //edit etmek reposu Company updatedCompany = await _saleRepo.EditCompany(companyForUpdate, companyId, currentUserId); //Contragent //idye goe sirketi getiririk Contragent contragentFromRepo = await _saleRepo.GetEditContragent(companyId); //map edirik Contragent contragentForUpdate = _mapper.Map(expenseInvoice.ContragentPutInProposalDto, contragentFromRepo); //edit etmek reposu Contragent updatedContragent = await _saleRepo.EditContragent(contragentForUpdate, companyId); //qaytaracagimiz info CompanyAfterPutDto companyToReturn = _mapper.Map<CompanyAfterPutDto>(updatedCompany); return Ok(); } //Get [baseUrl]/api/expense/getexpensiveinvoice [HttpGet] [Route("getexpensiveinvoice")] public async Task<IActionResult> GetExpensiveInvoice([FromQuery]PaginationParam productParam, [FromHeader]int? companyId) { //Checking #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckExpenseInvoice(currentUserId, companyId)) return Unauthorized(); #endregion //Repo Get var invoices = await _repo.GetInvoice(productParam, companyId); //Mapped object var invoiceToReturn = _mapper.Map<IEnumerable<ExpenseInvoiceGetDto>>(invoices); return Ok(invoiceToReturn); } //Get [baseUrl]/api/expense/geteditexpenseinvoice [HttpGet] [Route("geteditexpenseinvoice")] public async Task<IActionResult> GetEditExpenseInvoice([FromHeader] int? invoiceId, [FromHeader] int? companyId) { //Checking #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (invoiceId == null) return StatusCode(409, "invoiceId null"); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckExpenseInvoice(currentUserId, companyId)) return Unauthorized(); if (await _repo.CheckExpenseInvoiceId(invoiceId, companyId)) return StatusCode(406, "Not Acceptable"); #endregion //get company by id Company company = await _saleRepo.GetEditCompany(companyId); //get contragent by invoce id Contragent contragent = await _repo.GetContragentInvoice(companyId, invoiceId); //get invoice by id ExpenseInvoice fromRepo = await _repo.GetDetailInvoice(invoiceId, companyId); //mapping merge 3 table var ToReturn = _mapper.MergeInto<ExpensiveInvoiceEditGetDto>(contragent, company, fromRepo); return Ok(ToReturn); } //Put [baseUrl]/api/expense/updateexpenseinvoice [HttpPut] [Route("updateexpenseinvoice")] public async Task<IActionResult> UpdateExpenseInvoice([FromBody] VwExpenseInvoicePutDto proposalPut, [FromHeader]int? invoiceId, [FromHeader]int? companyId) { ExpenseInvoice fromRepo = await _repo.GetEditInvoice(invoiceId, companyId); List<ExpenseInvoiceItem> invoiceItemsFromRepo = await _repo.GetEditInvoiceItem(invoiceId); ExpenseInvoice Mapped = _mapper.Map(proposalPut.ExpenseInvoicePutDto, fromRepo); List<ExpenseInvoiceItem> MapperdInvoiceItems = _mapper.Map(proposalPut.ExpenseInvoiceItemPutDtos, invoiceItemsFromRepo); //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckExpenseInvoice(currentUserId, companyId)) return Unauthorized(); if (_repo.CheckInvoiceNegativeValue(Mapped, MapperdInvoiceItems)) return StatusCode(428, "negative value is detected"); if (await _repo.CheckExpenseInvoiceItem(invoiceId, MapperdInvoiceItems)) return StatusCode(409, "invoiceItem not correct"); //cheking product id //if (await _repo.CheckExpenseInvoiceProductId(mappeditemInvoice)) // return StatusCode(409, "productId doesnt exist"); #endregion //Accounting var UpdateAccountDebit = _repo.UpdateInvoiceAccountDebit(invoiceId, companyId, proposalPut.ExpenseInvoicePutDto, fromRepo.AccountDebitId); var UpdateAccountKredit = _repo.UpdateInvoiceAccountKredit(invoiceId, companyId, proposalPut.ExpenseInvoicePutDto, fromRepo.AccountKreditId); //Company Contragent Edit #region Company Contragent Edit //Company //id ye gore sirketi getiririk Company companyFromRepo = await _saleRepo.GetEditCompany(companyId); //map edirik Company companyForUpdate = _mapper.Map(proposalPut.CompanyPutProposalDto, companyFromRepo); //edit etmek reposu Company updatedCompany = await _saleRepo.EditCompany(companyForUpdate, companyId, currentUserId); //Contragent //idye goe sirketi getiririk Contragent contragentFromRepo = await _saleRepo.GetEditContragent(companyId); //map edirik Contragent contragentForUpdate = _mapper.Map(proposalPut.ContragentPutInProposalDto, contragentFromRepo); //edit etmek reposu Contragent updatedContragent = await _saleRepo.EditContragent(contragentForUpdate, companyId); //qaytaracagimiz info CompanyAfterPutDto companyToReturn = _mapper.Map<CompanyAfterPutDto>(updatedCompany); #endregion ExpenseInvoice invoice = await _repo.EditInvoice(Mapped, MapperdInvoiceItems, invoiceId); return Ok(); } //Delete [baseUrl]/api/expense/deleteexpenseinvoiceitem [HttpDelete] [Route("deleteexpenseinvoiceitem")] public async Task<IActionResult> DeleteExpenseInvoiceItem([FromHeader] int? expenseInvoiceItemId) { //Check #region Check if (expenseInvoiceItemId == null) return StatusCode(409, "expenseInvoiceItemId null"); //if (await _repo.DeleteInvoiceItem(invoiceItemId) == null) // return NotFound(); #endregion await _repo.DeleteInvoiceItem(expenseInvoiceItemId); return Ok(); } //Delete [baseUrl]/api/expense/deleteexpenseinvoice [HttpDelete] [Route("deleteexpenseinvoice")] public async Task<IActionResult> DeleteExpenseInvoice([FromHeader] int? companyId, [FromHeader] int? invoiceId) { //Check #region Check if (companyId == null) return StatusCode(409, "companyId null"); if (invoiceId == null) return StatusCode(409, "expenseInvoiceId null"); //if (await _repo.DeleteInvoice(companyId, invoiceId) == null) // return StatusCode(409, "object null"); #endregion await _repo.DeleteInvoice(companyId, invoiceId); return Ok(); } #endregion //Expense #region Expense //Get [baseUrl]/api/expense/getexpenseinvoicebycontragentid [HttpGet] [Route("getexpenseinvoicebycontragentid")] public IActionResult GetExpenseInvoiceByContragentId([FromHeader]int? contragentId, [FromHeader] int? companyId) { if (contragentId == null) return StatusCode(409, "contragentId null"); var invoice = _repo.GetExpenseInvoiceByContragentId(contragentId, companyId); if (invoice == null) return StatusCode(409, "invoice null"); var invoiceToReturn = _mapper.Map<IEnumerable<ExpenseExInvoiceGetDto>>(invoice); return Ok(invoice); } //Get [baseUrl]/api/expense/getexpense [HttpGet] [Route("getexpense")] public async Task<IActionResult> GetExpense([FromQuery]PaginationParam productParam, [FromHeader]int? companyId) { //Checking #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckExpense(currentUserId, companyId)) return Unauthorized(); #endregion //Repo Get var invoices = await _repo.GetExpense(productParam, companyId); //Mapped object var invoiceToReturn = _mapper.Map<IEnumerable<ExpenseGetDto>>(invoices); return Ok(invoices); } //Post [baseUrl]/api/expense/createexpense [HttpPost] [Route("createexpense")] public async Task<IActionResult> CreateExpense([FromHeader] int? companyId, [FromHeader] int? contragentId, [FromBody]VwCreateExpense createExpense) { //mapped expense var mappedExpese = _mapper.Map<Expense>(createExpense.ExpensePostDto); //mapped incomeitems var mappedExpenseItem = _mapper.Map<List<ExpenseItem>>(createExpense.ExpenseItemPostDtos); //Check: #region Check if (companyId == null) return StatusCode(409, "companyId null"); if (contragentId == null) return StatusCode(409, "contragentId null"); if (createExpense.ExpensePostDto == null) return StatusCode(409, "ExpensePostDto null"); if (createExpense.ExpenseItemPostDtos == null) return StatusCode(409, "ExpenseItemPostDtos null"); //checking incomeitems paidmoney big than invoice total price if (await _repo.CheckExpenseEqualingInvoiceTotalPriceForCreate(mappedExpenseItem)) return StatusCode(411, "paidmoney big than totalmoney or one invoiceId doesnt exist"); int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckExpense(currentUserId, companyId)) return Unauthorized(); // id-sinin olmasini yoxlayiriq. if (await _repo.CheckIncomeContragentIdInvoiceId(contragentId, companyId)) return StatusCode(409, "contragentId doesnt exist"); if (_repo.CheckExpenseNegativeValue(mappedExpese, mappedExpenseItem)) return StatusCode(428, "negative value is detected"); #endregion var FromRepoIncomes = await _repo.CreateExpense(companyId, contragentId, mappedExpese, mappedExpenseItem); return Ok(FromRepoIncomes); } // get edit income //Get [baseUrl]/api/expense/geteditexpense [HttpGet] [Route("geteditexpense")] public async Task<IActionResult> GetEditExpense([FromHeader] int? companyId, [FromHeader] int? expenseInvoiceId) { if (expenseInvoiceId == null) return StatusCode(409, "expenseInvoiceId null"); if (companyId == null) return StatusCode(409, "companyId null"); //Repo Get //var incomeItemsinvoices = await _repo.GetEditAllIncomes(companyId,invoiceId); var expenseItemsinvoices = await _repo.GetExpenseExpenseItem(companyId, expenseInvoiceId); //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckExpense(currentUserId, companyId)) return Unauthorized(); if (expenseItemsinvoices == null) return StatusCode(406, "object null"); #endregion // Mapped object var ToReturn = _mapper.Map<ExpenseExInvoiceEditGetDto>(expenseItemsinvoices); return Ok(ToReturn); } //Put [baseUrl]/api/income/updateexpense [HttpPut] [Route("updateexpense")] public async Task<IActionResult> UpdateExpense(VwExpensePut incomePut,[FromHeader] int? expenseInvoiceId, [FromHeader] int? companyId,[FromHeader] int? expenseId) { //Get edit income //didnt use yet Expense fromRepo = await _repo.GetEditExpense(expenseId, companyId); //mapping income Expense Mapped = _mapper.Map(incomePut.IncomePutDto, fromRepo); //Get edit incomeitems List<ExpenseItem> expenseItemsRepo = await _repo.GetEditExpenseItems(expenseId); //mapping incomeitems List<ExpenseItem> expenseItemsMapped = _mapper.Map(incomePut.ExpenseItemGetDtos, expenseItemsRepo); //Check: #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckExpense(currentUserId, companyId)) return Unauthorized(); if (await _repo.CheckExpenseEqualingInvoiceTotalPriceForUpdate(incomePut.ExpenseItemGetDtos)) return StatusCode(411, "paidmoney big than totalmoney or that expenseinvoice doesn't exist"); if (_repo.CheckExpenseUpdateNegativeValue(incomePut.ExpenseItemGetDtos)) return StatusCode(428, "negative value is detected"); #endregion //Account: var UpdateAccountDebit = _repo.UpdateExpenseAccountDebit(companyId, incomePut.ExpenseItemGetDtos); var UpdateAccountKredit = _repo.UpdateExpenseAccountKredit(companyId, incomePut.ExpenseItemGetDtos); //Put expense and expenseitems var income = await _repo.EditExpense(incomePut.ExpenseItemGetDtos, expenseInvoiceId); return Ok(); } //Delete [baseUrl]/api/income/deleteexpenseitem [HttpDelete] [Route("deleteexpenseitem")] public async Task<IActionResult> DeleteExpenseItem([FromHeader] int? expenseItemId) { if (expenseItemId == null) return StatusCode(409, "incomeItemId null"); await _repo.DeleteExpenseItem(expenseItemId); return Ok(); } #endregion } }<file_sep>/AccountingApi/Dtos/Sale/Proposal/ProposalEditGetDto.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Sale.Proposal { public class ProposalEditGetDto { public string ProposalNumber { get; set; } public DateTime? PreparingDate { get; set; } public DateTime? EndDate { get; set; } public double? TotalPrice { get; set; } public double? TotalTax { get; set; } public double? Sum { get; set; } public double? TaxRate { get; set; } public int? TaxId { get; set; } public int? ContragentId { get; set; } //company public string CompanyCompanyName { get; set; } public string CompanyVoen { get; set; } //contragent public string ContragentCompanyName { get; set; } public string ContragentVoen { get; set; } public byte IsPaid { get; set; } public ICollection<ProposalItemGetDto> ProposalItemGetDtos { get; set; } public ProposalEditGetDto() { ProposalItemGetDtos = new Collection<ProposalItemGetDto>(); } } } <file_sep>/AccountingApi/Dtos/Nomenklatura/Product/ProductGetDto.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Nomenklatura.Product { public class ProductGetDto { public int Id { get; set; } public string Name { get; set; } public string PhotoUrl { get; set; } public string Category { get; set; } public double? SalePrice { get; set; } public double? Price { get; set; } public bool IsSale { get; set; } public bool IsPurchase { get; set; } public string UnitName { get; set; } //public ProductGetDto() //{ // StockGet = new Collection<StockGetDto>(); //} } } <file_sep>/AccountingApi/Data/Repository/Interface/ISettingRepository.cs using AccountingApi.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Data.Repository.Interface { public interface ISettingRepository { Task<List<Tax>> GetTaxs(int? companyId); Task<Tax> GetEditTax(int? companyId, int? taxId); Task<Tax> CreateTax(Tax tax, int? companyId); Task<Tax> UpdateTax(Tax tax); Task<List<Product_Unit>> GetProduct_Units(int? companyId); //check Task<bool> CheckUnit(int? currentUserId, int? companyId); Task<bool> CheckTax(int? currentUserId, int? companyId); //delete Task<Tax> DeleteTax(int? companyId, int? taxId); } } <file_sep>/AccountingApi/Migrations/20190623185523_UserAndcompany.cs using System; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace AccountingApi.Migrations { public partial class UserAndcompany : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Users", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(maxLength: 75, nullable: true), SurName = table.Column<string>(maxLength: 100, nullable: true), Email = table.Column<string>(maxLength: 50, nullable: true), Token = table.Column<string>(maxLength: 150, nullable: true), IsDeleted = table.Column<bool>(nullable: false), Status = table.Column<bool>(nullable: false), Password = table.Column<string>(maxLength: 150, nullable: true) }, constraints: table => { table.PrimaryKey("PK_Users", x => x.Id); }); migrationBuilder.CreateTable( name: "Companies", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), PhotoFile = table.Column<string>(nullable: true), PhotoUrl = table.Column<string>(maxLength: 150, nullable: true), CompanyName = table.Column<string>(maxLength: 75, nullable: true), Name = table.Column<string>(maxLength: 75, nullable: true), Surname = table.Column<string>(maxLength: 75, nullable: true), Postion = table.Column<string>(maxLength: 75, nullable: true), FieldOfActivity = table.Column<string>(maxLength: 75, nullable: true), VOEN = table.Column<string>(maxLength: 100, nullable: true), Country = table.Column<string>(maxLength: 50, nullable: true), Street = table.Column<string>(maxLength: 75, nullable: true), Phone = table.Column<string>(maxLength: 20, nullable: true), Mobile = table.Column<string>(maxLength: 20, nullable: true), Website = table.Column<string>(maxLength: 30, nullable: true), Linkedin = table.Column<string>(maxLength: 30, nullable: true), Facebok = table.Column<string>(maxLength: 30, nullable: true), Instagram = table.Column<string>(maxLength: 30, nullable: true), Behance = table.Column<string>(maxLength: 30, nullable: true), City = table.Column<string>(maxLength: 50, nullable: true), Email = table.Column<string>(maxLength: 100, nullable: true), IsCompany = table.Column<bool>(nullable: false), CreatedAt = table.Column<DateTime>(nullable: false), IsDeleted = table.Column<bool>(nullable: false), UserId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Companies", x => x.Id); table.ForeignKey( name: "FK_Companies_Users_UserId", column: x => x.UserId, principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.NoAction); }); migrationBuilder.CreateIndex( name: "IX_Companies_UserId", table: "Companies", column: "UserId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Companies"); migrationBuilder.DropTable( name: "Users"); } } } <file_sep>/AccountingApi/Models/Stock.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models { public class Stock { [Key] public int Id { get; set; } public double? Price { get; set; } public double? SalePrice { get; set; } [MaxLength(275)] public string Desc { get; set; } public int? Count { get; set; } public bool IsSale { get; set; } = false; public bool IsPurchase { get; set; } = false; public bool IsDeleted { get; set; } = false; public int ProductId { get; set; } public virtual Product Product { get; set; } } } <file_sep>/AccountingApi/Models/ViewModel/VwCreateExpense.cs using AccountingApi.Dtos.Purchase.Expense; using System.Collections.Generic; namespace AccountingApi.Models.ViewModel { public class VwCreateExpense { public List<ExpenseItemPostDto> ExpenseItemPostDtos { get; set; } public ExpensePostDto ExpensePostDto { get; set; } } } <file_sep>/AccountingApi/Dtos/Sale/Income/IncomePutDto.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Sale.Income { public class IncomePutDto { public double? TotalPrice { get; set; } //public ICollection<IncomeItemGetEditDto> IncomeItemGetEditDtos { get; set; } //public IncomePutDto() //{ // IncomeItemGetEditDtos = new Collection<IncomeItemGetEditDto>(); //} } } <file_sep>/AccountingApi/Dtos/Nomenklatura/Kontragent/ContragentPutInProposalDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Nomenklatura.Kontragent { public class ContragentPutInProposalDto { public string VOEN { get; set; } } } <file_sep>/AccountingApi/Dtos/Company/CompanyPutProposalDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Company { public class CompanyPutProposalDto { public string CompanyName { get; set; } public string VOEN { get; set; } } } <file_sep>/AccountingApi/Models/ProcudureDto/GetInvoiceProductCountByIdDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models.ProcudureDto { public class GetInvoiceProductCountByIdDto { public int Qty { get; set; } public string CompanyName { get; set; } public double? Price { get; set; } } } <file_sep>/AccountingApi/Models/User.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models { public class User { [Key] public int Id { get; set; } [MaxLength(75)] public string Name { get; set; } [MaxLength(100)] public string SurName { get; set; } [MaxLength(50)] public string Email { get; set; } [MaxLength(150)] public string Token { get; set; } public bool IsDeleted { get; set; } = false; public bool Status { get; set; } = true; [MaxLength(150)] public string Password { get; set; } public ICollection<Company> Companies { get; set; } public ICollection<UserSendMailChangePassword> UserSendMailChangePasswords { get; set; } } } <file_sep>/AccountingApi/Models/ProcudureDto/JournalDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models.ProcudureDto { public class JournalDto { public string Number { get; set; } public string AccDebitNumber { get; set; } public string DebitName { get; set; } public string AccKreditNumber { get; set; } public string KreditName { get; set; } public double? Price { get; set; } public DateTime? Date { get; set; } public string CategoryName { get; set; } } } <file_sep>/AccountingApi/Data/Repository/Interface/IAuthRepository.cs using AccountingApi.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Data.Repository.Interface { public interface IAuthRepository { Task<User> Register(User user, string password); Task<User> Login(string username, string password); Task<bool> UserExists(string email, string password); Task<bool> CompanyCount(int userId); Task<IEnumerable<Company>> UserCompanies(int? userId); Task<Company> UserCompany(int? userId); Task<bool> CheckUsersMail(string email); Task<bool> CompanyCountForRegister(int userId); } } <file_sep>/AccountingApi/Controllers/V1/SettingController.cs using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using AccountingApi.Data.Repository.Interface; using AccountingApi.Models; using AccountingApi.Models.ViewModel; using AutoMapper; using EOfficeAPI.Helpers; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace AccountingApi.Controllers.V1 { [Authorize] [Route("api/[controller]")] [ApiController] public class SettingController : ControllerBase { private readonly ISettingRepository _repo; private readonly IMapper _mapper; public SettingController(ISettingRepository repo, IMapper mapper) { _repo = repo; _mapper = mapper; } //Get [baseUrl]/api/setting/getunits [HttpGet] [Route("getunits")] public async Task<IActionResult> GetUnits([FromHeader]int? companyId) { //Yoxlamaq int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckUnit(currentUserId, companyId)) return Unauthorized(); var fromRepo = await _repo.GetProduct_Units(companyId); return Ok(fromRepo); } //Get [baseUrl]/api/setting/gettaxes [HttpGet] [Route("gettaxes")] public async Task<IActionResult> GetTaxes([FromHeader]int? companyId) { //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckTax(currentUserId, companyId)) return Unauthorized(); #endregion var fromRepo = await _repo.GetTaxs(companyId); return Ok(fromRepo); } //Get [baseUrl]/api/setting/getedittax [HttpGet] [Route("getedittax")] public async Task<IActionResult> GetEditTax([FromHeader]int? companyId, [FromHeader] int? taxId) { //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (taxId == null) return null; if (currentUserId == null) return Unauthorized(); if (await _repo.CheckTax(currentUserId, companyId)) return Unauthorized(); #endregion return Ok(await _repo.GetEditTax(companyId, taxId)); } //Post [baseUrl]/api/setting/sendmail [HttpPost] [Route("sendmail")] public IActionResult SendMail(Mail email) { MailExtention.Send(email.Subject, email.Body, email.Email); return NoContent(); } //Post [baseUrl]/api/setting/createtax [HttpPost] [Route("createtax")] public async Task<IActionResult> CreateTax(Tax tax, [FromHeader] int? companyId) { var createdTax = await _repo.CreateTax(tax, companyId); return Ok(createdTax); } //Put [baseUrl]/api/setting/updatetax [HttpPut] [Route("updatetax")] public async Task<IActionResult> UpdateTax(Tax tax) { if (tax == null) return StatusCode(406, "content null"); Tax updatedTax = await _repo.UpdateTax(tax); return Ok(updatedTax); } //Put [baseUrl]/api/setting/deletetax [HttpPut] [Route("deletetax")] public async Task<IActionResult> Deletetax([FromHeader] int? companyId, [FromHeader] int? taxId) { //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (taxId == null) return null; if (currentUserId == null) return Unauthorized(); if (await _repo.CheckTax(currentUserId, companyId)) return Unauthorized(); #endregion await _repo.DeleteTax(companyId, taxId); return Ok(); } } }<file_sep>/AccountingApi/Models/Proposal.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models { public class Proposal { [Key] public int Id { get; set; } [MaxLength(500)] public string ProposalNumber { get; set; } public DateTime? PreparingDate { get; set; } public DateTime? EndDate { get; set; } public DateTime CreatedAt { get; set; } public double? TotalPrice { get; set; } public double? TotalTax { get; set; } public double? Sum { get; set; } [MaxLength(300)] public string Desc { get; set; } public bool IsDeleted { get; set; } = false; public int? ContragentId { get; set; } public int CompanyId { get; set; } public int? TaxId { get; set; } public virtual Company Company { get; set; } public virtual Contragent Contragent { get; set; } public virtual Tax Tax { get; set; } public virtual ICollection<ProposalItem> ProposalItems { get; set; } public virtual ICollection<ProposalSentMail> ProposalSentMails { get; set; } } } <file_sep>/AccountingApi/Dtos/Sale/Income/IncomePostDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Sale.Income { public class IncomePostDto { //paid money total public double? TotalPrice { get; set; } } } <file_sep>/AccountingApi/Migrations/20190624062939_Worker.cs using System; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace AccountingApi.Migrations { public partial class Worker : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Workers", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(maxLength: 75, nullable: true), SurName = table.Column<string>(maxLength: 75, nullable: true), Positon = table.Column<string>(maxLength: 75, nullable: true), Salary = table.Column<double>(nullable: true), Departament = table.Column<string>(maxLength: 75, nullable: true), PartofDepartament = table.Column<string>(maxLength: 75, nullable: true), Role = table.Column<string>(maxLength: 75, nullable: true), RegisterDate = table.Column<DateTime>(nullable: false), PhotoFile = table.Column<string>(nullable: true), PhotoUrl = table.Column<string>(nullable: true), IsState = table.Column<bool>(nullable: false), IsDeleted = table.Column<bool>(nullable: false), CompanyId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Workers", x => x.Id); table.ForeignKey( name: "FK_Workers_Companies_CompanyId", column: x => x.CompanyId, principalTable: "Companies", principalColumn: "Id", onDelete: ReferentialAction.NoAction); }); migrationBuilder.CreateTable( name: "Worker_Details", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), FatherName = table.Column<string>(maxLength: 75, nullable: true), Email = table.Column<string>(maxLength: 75, nullable: true), Adress = table.Column<string>(maxLength: 75, nullable: true), DSMF = table.Column<string>(maxLength: 75, nullable: true), Voen = table.Column<string>(maxLength: 75, nullable: true), Phone = table.Column<string>(maxLength: 75, nullable: true), MobilePhone = table.Column<string>(maxLength: 75, nullable: true), Education = table.Column<string>(maxLength: 75, nullable: true), EducationLevel = table.Column<string>(maxLength: 75, nullable: true), Gender = table.Column<string>(maxLength: 20, nullable: true), Birthday = table.Column<DateTime>(nullable: true), WorkerId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Worker_Details", x => x.Id); table.ForeignKey( name: "FK_Worker_Details_Workers_WorkerId", column: x => x.WorkerId, principalTable: "Workers", principalColumn: "Id", onDelete: ReferentialAction.NoAction); }); migrationBuilder.CreateIndex( name: "IX_Worker_Details_WorkerId", table: "Worker_Details", column: "WorkerId"); migrationBuilder.CreateIndex( name: "IX_Workers_CompanyId", table: "Workers", column: "CompanyId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Worker_Details"); migrationBuilder.DropTable( name: "Workers"); } } } <file_sep>/AccountingApi/Models/Contragent.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models { public class Contragent { [Key] public int Id { get; set; } public string PhotoFile { get; set; } [MaxLength(150)] public string PhotoUrl { get; set; } [MaxLength(100)] public string CompanyName { get; set; } [MaxLength(100)] public string Fullname { get; set; } [MaxLength(75)] public string Position { get; set; } [MaxLength(75)] public string FieldOfActivity { get; set; } [MaxLength(75)] public string Phone { get; set; } [MaxLength(75)] public string Email { get; set; } [MaxLength(75)] public string VOEN { get; set; } public DateTime CreetedAt { get; set; } public bool IsDeleted { get; set; } public bool IsCostumer { get; set; } public int CompanyId { get; set; } public Company Company { get; set; } public virtual ICollection<Contragent_Detail> Contragent_Details { get; set; } public virtual ICollection<Proposal> Proposals { get; set; } public virtual ICollection<Invoice> Invoices { get; set; } public virtual ICollection<Income> Incomes { get; set; } public virtual ICollection<Expense> Expenses { get; set; } public virtual ICollection<ExpenseInvoice> ExpenseInvoices { get; set; } } } <file_sep>/AccountingApi/Controllers/V1/UserController.cs using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using AccountingApi.Data.Repository.Interface; using AccountingApi.Dtos.Company; using AccountingApi.Dtos.User; using AccountingApi.Models; using AutoMapper; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace AccountingApi.Controllers.V1 { [Authorize] [Route("api/[controller]")] [ApiController] public class UserController : ControllerBase { private readonly IUserRepository _repo; private readonly IAccountsPlanRepository _accountsPlanRepo; private readonly IMapper _mapper; public UserController(IUserRepository repo, IMapper mapper,IAccountsPlanRepository accountsPlanRepo) { _repo = repo; _mapper = mapper; _accountsPlanRepo = accountsPlanRepo; } //Post [baseUrl]/api/user/addcompany [HttpPost("addcompany")] public async Task<IActionResult> AddCompany(CompanyPostDto companyPost) { if (!ModelState.IsValid) return BadRequest(); Company company = _mapper.Map<Company>(companyPost); int userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); Company CompanyToReturn = await _repo.CreateCompany(company, userId); CompanyGetDto CompanyToGet = _mapper.Map<CompanyGetDto>(CompanyToReturn); //Create AccoutnPlan by companyId await _accountsPlanRepo.ImportFromExcel(CompanyToReturn.Id); return Ok(CompanyToGet); } //Get [baseUrl]/api/user/geteditcompany [HttpGet] [Route("geteditcompany")] public async Task<IActionResult> GetEditCompany([FromHeader]int? companyId) { if (companyId == null) return BadRequest("companyId null"); Company company = await _repo.GetEditCompany(companyId); CompanyEditDto userToReturn = _mapper.Map<CompanyEditDto>(company); return Ok(userToReturn); } //Get [baseUrl]/api/user/getcompany [HttpGet] [Route("getcompany")] public async Task<IActionResult> GetCompany() { int? userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (userId == null) return StatusCode(409, "userId null"); var companies = await _repo.GetCompany(userId); return Ok(companies); } //Get [baseUrl]/api/user/getcompanybyid [HttpGet] [Route("getcompanybyid")] public async Task<IActionResult> GetCompanyById([FromHeader]int? companyId) { int? userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (userId == null) return StatusCode(409, "userId null"); if (companyId == null) return StatusCode(409, "companyId null"); var companyToReturn = await _repo.GetCompanyById(userId, companyId); if (companyToReturn == null) return StatusCode(409, "object null"); // System.Globalization.CultureInfo var culture = new System.Globalization.CultureInfo("az"); var weekday = culture.DateTimeFormat.GetDayName(DateTime.Today.DayOfWeek); var weekdayCase = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(weekday.ToLower()); CompanyGetDto companyToGet = _mapper.Map<CompanyGetDto>(companyToReturn); companyToGet.Culture = DateTime.UtcNow.ToString("dd MMMM yyyy", culture); companyToGet.Weekday = weekdayCase; return Ok(companyToGet); } //Put [baseUrl]/api/user/editcompany [HttpPut] [Route("editcompany")] public async Task<IActionResult> EditCompany([FromBody]CompanyPutDto companyForeditDto, [FromHeader] int? companyId) { //Check: #region Check int? thisuserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (thisuserId == null) return StatusCode(409, "thisuserId null"); #endregion if (!ModelState.IsValid) return BadRequest(); //id ye gore sirketi getiririk Company companyFromRepo = await _repo.GetEditCompany(companyId); //map edirik Company companyForUpdate = _mapper.Map(companyForeditDto, companyFromRepo); //edit etmek reposu Company updatedCompany = await _repo.EditCompany(companyForUpdate); //qaytaracagimiz info CompanyAfterPutDto companyToReturn = _mapper.Map<CompanyAfterPutDto>(updatedCompany); return Ok(companyToReturn); } //Get [baseUrl]/api/user/getuser [HttpGet] [Route("getuser")] public async Task<IActionResult> GetUser() { //Check: #region Check int? thisuserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (thisuserId == null) return StatusCode(409, "thisuserId null"); #endregion var user = await _repo.GetEditUser(thisuserId); if (user == null) return StatusCode(409, "object null"); var userToReturn = _mapper.Map<UserGetEditDto>(user); return Ok(userToReturn); } //Put [baseUrl]/api/user/edituser [HttpPut] [Route("edituser")] public async Task<IActionResult> EditUser([FromBody]UserPutDto userPutDto) { //Check #region Check int? thisuserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); string email = User.FindFirst(ClaimTypes.Name).Value; if (thisuserId == null) return StatusCode(409, "thisuserId null"); if (_repo.CheckOldPassword(userPutDto.OldPassword, thisuserId)) return StatusCode(409, "OldPassword not correct or token Id no correct"); #endregion User userFromRepo = await _repo.GetEditUser(thisuserId); //map edirik User userForUpdate = _mapper.Map(userPutDto, userFromRepo); //if (email != userForUpdate.Email) // return StatusCode(409, "email not correct"); var editedUser = _repo.EditUser(userForUpdate, userPutDto.OldPassword); var userToReturn = _mapper.Map<UserGetEditDto>(userForUpdate); return Ok(new { userToReturn, thisuserId, email } ); } } }<file_sep>/AccountingApi/Models/ProcudureDto/ParamsObject/ReportFilter.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models.ProcudureDto.ParamsObject { public class ReportFilter { public DateTime? StartDate { get; set; } public DateTime? EndDate { get; set; } public short? IsPaid { get; set; } } } <file_sep>/AccountingApi/Dtos/Sale/Invoice/InvoicePostDto.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Sale.Invoice { public class InvoicePostDto { public string InvoiceNumber { get; set; } public DateTime? PreparingDate { get; set; } public DateTime? EndDate { get; set; } public double? TotalPrice { get; set; } public double? TotalTax { get; set; } public double? Sum { get; set; } public string Desc { get; set; } [Required, Range(1, 4)] public byte IsPaid { get; set; } = 1; public int? ContragentId { get; set; } public int CompanyId { get; set; } public int? TaxId { get; set; } public int? AccountDebitId { get; set; } public int? AccountKreditId { get; set; } public ICollection<InvoiceItemPostDto> InvoiceItemPostDtos { get; set; } public InvoicePostDto() { InvoiceItemPostDtos = new Collection<InvoiceItemPostDto>(); } } } <file_sep>/AccountingApi/Controllers/V1/InvoiceController.cs using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using AccountingApi.Data.Repository.Interface; using AccountingApi.Dtos.Company; using AccountingApi.Dtos.Sale.Invoice; using AccountingApi.Helpers.Extentions; using AccountingApi.Models; using AccountingApi.Models.ViewModel; using AutoMapper; using EOfficeAPI.Helpers.Pagination; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace AccountingApi.Controllers.V1 { [Route("api/[controller]")] [ApiController] public class InvoiceController : ControllerBase { private readonly ISaleRepository _repo; private readonly ISettingRepository _repoSetting; private readonly IMapper _mapper; public InvoiceController(ISaleRepository repo, ISettingRepository settingRepo, IMapper mapper) { _repo = repo; _mapper = mapper; _repoSetting = settingRepo; } //Post [baseUrl]/api/invoice/addinvoice [Authorize] [HttpPost] [Route("addinvoice")] public async Task<IActionResult> AddInvoice(VwInvoice invoice, [FromHeader] int? companyId) { //mapping for creating invoice var mappedInvoice = _mapper.Map<Invoice>(invoice.InvoicePostDto); //mapping for creating invoiceitems var mappeditemInvoice = _mapper.Map<List<InvoiceItem>>(invoice.InvoiceItemPosts); //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (mappedInvoice == null) return StatusCode(409, "[Header]companyId or invoiceId not correct"); if (await _repo.CheckInvoice(currentUserId, companyId)) return Unauthorized(); //cheking product id if (await _repo.CheckInvoiceProductId(mappeditemInvoice)) return StatusCode(409, "productId doesnt exist"); if (mappedInvoice.ContragentId == null) return StatusCode(409, "contragentId null"); if (await _repo.CheckContragentId(mappedInvoice.ContragentId, companyId)) return StatusCode(409, "contragentId doesnt exist"); if (_repo.CheckInvoiceNegativeValue(mappedInvoice, mappeditemInvoice)) return StatusCode(428, "negative value is detected"); #endregion //creating repo var invoiceToReturn = await _repo.CreateInvoice(mappedInvoice, companyId); //creating repo var itemToRetun = await _repo.CreateInvoiceItems(mappeditemInvoice, mappedInvoice.Id); //mapping for return var ToReturn = _mapper.Map<InvoiceGetDto>(invoiceToReturn); //Company and Contragent #region Company and Contragent //id ye gore sirketi getiririk Company companyFromRepo = await _repo.GetEditCompany(companyId); //map edirik Company companyForUpdate = _mapper.Map(invoice.CompanyPutProposalDto, companyFromRepo); //edit etmek reposu Company updatedCompany = await _repo.EditCompany(companyForUpdate, companyId, currentUserId); //Contragent //idye goe sirketi getiririk Contragent contragentFromRepo = await _repo.GetEditContragent(mappedInvoice.ContragentId); //map edirik Contragent contragentForUpdate = _mapper.Map(invoice.ContragentPutInProposalDto, contragentFromRepo); //edit etmek reposu Contragent updatedContragent = await _repo.EditContragent(contragentForUpdate, companyId); //qaytaracagimiz info CompanyAfterPutDto companyToReturn = _mapper.Map<CompanyAfterPutDto>(updatedCompany); #endregion return Ok(ToReturn); } [Authorize] //Get [baseUrl]/api/invoice/getinvoice [HttpGet] [Route("getinvoice")] public async Task<IActionResult> GetInvoice([FromQuery]PaginationParam productParam, [FromHeader]int? companyId) { //Checking #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckInvoice(currentUserId, companyId)) return Unauthorized(); #endregion //Repo Get var invoices = await _repo.GetInvoice(productParam, companyId); //Mapped object var invoiceToReturn = _mapper.Map<IEnumerable<InvoiceGetDto>>(invoices); return Ok(invoiceToReturn); } [Authorize] //Get [baseUrl]/api/invoice/geteditinvoice [HttpGet] [Route("geteditinvoice")] public async Task<IActionResult> GetEditInvoice([FromHeader]int? invoiceId, [FromHeader]int? companyId) { //Checking #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (invoiceId == null) return StatusCode(409, "InvoiceId null"); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckInvoice(currentUserId, companyId)) return Unauthorized(); if (await _repo.CheckInvoiceId(invoiceId, companyId)) return StatusCode(406, "Not Acceptable"); #endregion //get company by id Company company = await _repo.GetEditCompany(companyId); //get contragent by invoce id Contragent contragent = await _repo.GetContragentInvoice(companyId, invoiceId); //get invoice by id Invoice fromRepo = await _repo.GetDetailInvoice(invoiceId, companyId); Tax tax = await _repoSetting.GetEditTax(companyId, fromRepo.TaxId); //mapping merge 3 table var ToReturn = _mapper.MergeInto<InvoiceEditGetDto>(contragent, company, fromRepo, tax); return Ok(ToReturn); } [Authorize] //Put [baseUrl]/api/invoice/updateinvoice [HttpPut] [Route("updateinvoice")] public async Task<IActionResult> UpdateInvoice([FromBody] VwInvoicePut invoicePut, [FromHeader]int? invoiceId, [FromHeader]int? companyId) { Invoice fromRepo = await _repo.GetEditInvoice(invoiceId, companyId); List<InvoiceItem> invoiceItemsFromRepo = await _repo.GetEditInvoiceItem(invoiceId); Invoice Mapped = _mapper.Map(invoicePut.InvoicePutDto, fromRepo); List<InvoiceItem> MapperdInvoiceItems = _mapper.Map(invoicePut.InvoiceItemPutDtos, invoiceItemsFromRepo); //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (fromRepo == null) return StatusCode(409, "[Header]companyId or invoiceId not correct"); if (await _repo.CheckInvoice(currentUserId, companyId)) return StatusCode(409, "company id not correct"); if (await _repo.CheckInvoiceId(invoiceId, companyId)) return StatusCode(409, "invoiceId doesnt exist"); if (_repo.CheckInvoiceNegativeValue(Mapped, MapperdInvoiceItems)) return StatusCode(428, "negative value is detected"); if (await _repo.CheckInvoiceItem(invoiceId, MapperdInvoiceItems)) return StatusCode(409, "invoiceItem not correct"); //cheking product id //if (await _repo.CheckInvoiceProductId(Mapped.InvoiceItems)) // return StatusCode(409, "productId doesnt exist"); #endregion //Accounting var UpdateAccountDebit = _repo.UpdateInvoiceAccountDebit(invoiceId, companyId, invoicePut.InvoicePutDto, fromRepo.AccountDebitId); var UpdateAccountKredit = _repo.UpdateInvoiceAccountKredit(invoiceId, companyId, invoicePut.InvoicePutDto, fromRepo.AccountKreditId); //Company Contragent Edit #region Company Contragent Edit // Company // id ye gore sirketi getiririk Company companyFromRepo = await _repo.GetEditCompany(companyId); //map edirik Company companyForUpdate = _mapper.Map(invoicePut.CompanyPutProposalDto, companyFromRepo); //edit etmek reposu Company updatedCompany = await _repo.EditCompany(companyForUpdate, companyId, currentUserId); //Contragent //idye goe sirketi getiririk Contragent contragentFromRepo = await _repo.GetEditContragent(fromRepo.ContragentId); //map edirik Contragent contragentForUpdate = _mapper.Map(invoicePut.ContragentPutInProposalDto, contragentFromRepo); //edit etmek reposu Contragent updatedContragent = await _repo.EditContragent(contragentForUpdate, companyId); //qaytaracagimiz info CompanyAfterPutDto companyToReturn = _mapper.Map<CompanyAfterPutDto>(updatedCompany); #endregion Invoice invoice = await _repo.EditInvoice(Mapped, MapperdInvoiceItems, invoiceId); return Ok(); } [Authorize] //Post [baseUrl]/api/invoice/sendinvoice [HttpPost] [Route("sendinvoice")] public IActionResult SendInvoice([FromHeader]int? invoiceId, Mail mail) { if (invoiceId == null) return StatusCode(409, "invoiceId null"); return Ok(_repo.CreateInvoiceSentMail(invoiceId, mail.Email).Token); } //Get [baseUrl]/api/invoice/getinvoicebytoken [HttpGet] [Route("getinvoicebytoken")] public async Task<IActionResult> GetInvoiceByToken(string token, [FromHeader]int? invoiceId, [FromHeader]int? companyId) { //Checking #region Check if (invoiceId == null) return StatusCode(409, "invoiceId null"); if (companyId == null) return StatusCode(409, "companyId null"); if (await _repo.CheckProposalId(invoiceId, companyId)) return StatusCode(406, "Not Acceptable"); #endregion Company company = await _repo.GetEditCompany(companyId); Contragent contragent = await _repo.GetContragentInvoice(companyId, invoiceId); Invoice invoiceFromRepo = _repo.GetInvoiceByToken(token); var ToReturn = _mapper.MergeInto<InvoiceEditGetDto>(contragent, company, invoiceFromRepo); return Ok(ToReturn); } [Authorize] //Get[baseUrl]/api/invoice/existincome [HttpGet] [Route("existincome")] public async Task<bool> ExistIncome([FromHeader] int? invoiceId) { if (await _repo.CheckExistIncomeByInvoiceId(invoiceId)) return true; return false; } //Delete [baseUrl]/api/invoice/deleteinvoiceitem [HttpDelete] [Route("deleteinvoiceitem")] public async Task<IActionResult> DeleteInvoiceItem([FromHeader] int? invoiceItemId) { //Check #region Check if (invoiceItemId == null) return StatusCode(409, "invoiceItemId null"); //if (await _repo.DeleteInvoiceItem(invoiceItemId) == null) // return NotFound(); #endregion await _repo.DeleteInvoiceItem(invoiceItemId); return Ok(); } //Delete [baseUrl]/api/invoice/deleteinvoice [HttpDelete] [Route("deleteinvoice")] public async Task<IActionResult> DeleteInvoice([FromHeader] int? companyId, [FromHeader] int? invoiceId) { //Check #region Check if (companyId == null) return StatusCode(409, "companyId null"); if (invoiceId == null) return StatusCode(409, "invoiceId null"); if (await _repo.DeleteInvoice(companyId, invoiceId) == null) return StatusCode(409, "object null"); #endregion await _repo.DeleteInvoice(companyId, invoiceId); return Ok(); } } }<file_sep>/AccountingApi/Migrations/20190704081008_Journal.cs using System; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace AccountingApi.Migrations { public partial class Journal : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<int>( name: "ManualJournalId", table: "BalanceSheets", nullable: true); migrationBuilder.CreateTable( name: "OperationCategories", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(maxLength: 250, nullable: true), ShortName = table.Column<string>(maxLength: 50, nullable: true) }, constraints: table => { table.PrimaryKey("PK_OperationCategories", x => x.Id); }); migrationBuilder.CreateTable( name: "ManualJournals", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), JurnalNumber = table.Column<string>(maxLength: 250, nullable: true), CreatedAt = table.Column<DateTime>(nullable: false), Desc = table.Column<string>(maxLength: 300, nullable: true), Price = table.Column<double>(nullable: true), ContragentId = table.Column<int>(nullable: true), CompanyId = table.Column<int>(nullable: false), AccountDebitId = table.Column<int>(nullable: true), AccountKreditId = table.Column<int>(nullable: true), OperationCategoryId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_ManualJournals", x => x.Id); table.ForeignKey( name: "FK_ManualJournals_AccountsPlans_AccountDebitId", column: x => x.AccountDebitId, principalTable: "AccountsPlans", principalColumn: "Id", onDelete: ReferentialAction.NoAction); table.ForeignKey( name: "FK_ManualJournals_AccountsPlans_AccountKreditId", column: x => x.AccountKreditId, principalTable: "AccountsPlans", principalColumn: "Id", onDelete: ReferentialAction.NoAction); table.ForeignKey( name: "FK_ManualJournals_Companies_CompanyId", column: x => x.CompanyId, principalTable: "Companies", principalColumn: "Id", onDelete: ReferentialAction.NoAction); table.ForeignKey( name: "FK_ManualJournals_Contragents_ContragentId", column: x => x.ContragentId, principalTable: "Contragents", principalColumn: "Id", onDelete: ReferentialAction.NoAction); table.ForeignKey( name: "FK_ManualJournals_OperationCategories_OperationCategoryId", column: x => x.OperationCategoryId, principalTable: "OperationCategories", principalColumn: "Id", onDelete: ReferentialAction.NoAction); }); migrationBuilder.CreateIndex( name: "IX_BalanceSheets_ManualJournalId", table: "BalanceSheets", column: "ManualJournalId"); migrationBuilder.CreateIndex( name: "IX_ManualJournals_AccountDebitId", table: "ManualJournals", column: "AccountDebitId"); migrationBuilder.CreateIndex( name: "IX_ManualJournals_AccountKreditId", table: "ManualJournals", column: "AccountKreditId"); migrationBuilder.CreateIndex( name: "IX_ManualJournals_CompanyId", table: "ManualJournals", column: "CompanyId"); migrationBuilder.CreateIndex( name: "IX_ManualJournals_ContragentId", table: "ManualJournals", column: "ContragentId"); migrationBuilder.CreateIndex( name: "IX_ManualJournals_OperationCategoryId", table: "ManualJournals", column: "OperationCategoryId"); migrationBuilder.AddForeignKey( name: "FK_BalanceSheets_ManualJournals_ManualJournalId", table: "BalanceSheets", column: "ManualJournalId", principalTable: "ManualJournals", principalColumn: "Id", onDelete: ReferentialAction.NoAction); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_BalanceSheets_ManualJournals_ManualJournalId", table: "BalanceSheets"); migrationBuilder.DropTable( name: "ManualJournals"); migrationBuilder.DropTable( name: "OperationCategories"); migrationBuilder.DropIndex( name: "IX_BalanceSheets_ManualJournalId", table: "BalanceSheets"); migrationBuilder.DropColumn( name: "ManualJournalId", table: "BalanceSheets"); } } } <file_sep>/AccountingApi/Data/Repository/AccountsPlanRepository.cs using AccountingApi.Data.Repository.Interface; using AccountingApi.Dtos.Account; using AccountingApi.Dtos.AccountsPlan; using AccountingApi.Models; using AccountingApi.Models.ProcudureDto; using ClosedXML.Excel; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Security.Policy; using System.Threading.Tasks; namespace AccountingApi.Data.Repository { public class AccountsPlanRepository : IAccountsPlanRepository { private readonly DataContext _context; private readonly IPathProvider _pathProvider; public AccountsPlanRepository(DataContext context, IPathProvider pathProvider) { _context = context; _pathProvider = pathProvider; } public async Task<List<AccountsPlan>> ImportFromExcel(int? companyId) { var path = _pathProvider.MapPath("Files/Template.xlsx"); if (path == null) return null; var workbook = new XLWorkbook(path); IXLWorksheet ws = workbook.Worksheet(1); foreach (var row in ws.RowsUsed()) { int.TryParse(row.Cell(1).Value.ToString(), out int index); if (index > 0) { AccountsPlan accountsplan = new AccountsPlan { AccPlanNumber = row.Cell(1).Value.ToString(), Name = row.Cell(2).Value.ToString(), Level = Convert.ToInt32(row.Cell(4).Value), Obeysto = row.Cell(5).Value.ToString(), CompanyId = Convert.ToInt32 (companyId), Category = row.Cell(7).Value.ToString(), }; _context.AccountsPlans.Add(accountsplan); await _context.SaveChangesAsync(); } } List<AccountsPlan> accounts = await _context.AccountsPlans.Where(w => w.CompanyId == companyId).ToListAsync(); if (accounts == null) return null; return accounts; } public async Task<List<AccountsPlan>> GetAccountsPlans(int? companyId) { if (companyId == null) return null; List<AccountsPlan> accountsPlans = await _context.AccountsPlans.Where(w => w.CompanyId == companyId).ToListAsync(); if (accountsPlans == null) return null; return accountsPlans; } //BalanceSheet public async Task<List<BalanceSheetReturnDto>> BalanceSheet(int? companyId, DateTime? startDate, DateTime? endDate) { var balanceSheetQuery = await _context.BalanceSheetDtos .FromSql("exec Balance {0},{1},{2}", companyId,startDate,endDate).ToListAsync(); List<BalanceSheetReturnDto> sheetReturnDto = new List<BalanceSheetReturnDto>(); var balansReturn = balanceSheetQuery.Where(w=>w.allCircleDebit != 0 || w.allCircleKredit != 0 || w.startCircleDebit != 0 || w.startCircleKredit != 0 || w.endCircleDebit != 0 || w.endCircleKredit != 0 ).Select(s => new BalanceSheetReturnDto { AccPlanNumber = s.AccPlanNumber, Name = s.Name, startCircleDebit = s.startCircleDebit, startCircleKredit = s.startCircleKredit, allCircleDebit = s.allCircleDebit, allCircleKredit = s.allCircleKredit, endCircleDebit = s.endCircleDebit, endCircleKredit = s.endCircleKredit }).ToList(); return balansReturn; } //OperationCategory public async Task<List<OperationCategory>> GetOperationCategories() { var operationCategory = await _context.OperationCategories.ToListAsync(); return operationCategory; } //ManualJournal //Post public async Task<ManualJournal> CreateManualJournal(int? companyId, ManualJournal manualJournal) { if (companyId == null) return null; if (manualJournal == null) return null; manualJournal.CreatedAt = DateTime.UtcNow.AddHours(4); manualJournal.CompanyId = Convert.ToInt32(companyId); await _context.ManualJournals.AddAsync(manualJournal); await _context.SaveChangesAsync(); //AccountPlan #region AccountPlan AccountsPlan accountDebit = await _context.AccountsPlans.FirstOrDefaultAsync(f => f.Id == manualJournal.AccountDebitId); if (accountDebit.Debit == null || accountDebit.Debit == 0) { accountDebit.Debit = manualJournal.Price; } else { accountDebit.Debit += manualJournal.Price; } AccountsPlan accountkredit = await _context.AccountsPlans.FirstOrDefaultAsync(f => f.Id == manualJournal.AccountKreditId); if (accountkredit.Kredit == null || accountkredit.Kredit == 0) { accountkredit.Kredit = manualJournal.Price; } else { accountkredit.Kredit += manualJournal.Price; } BalanceSheet balanceSheetDebit = new BalanceSheet { CreatedAt = DateTime.UtcNow.AddHours(4), CompanyId = Convert.ToInt32(companyId), DebitMoney = manualJournal.Price, AccountsPlanId = manualJournal.AccountDebitId, ManualJournalId = manualJournal.Id }; await _context.BalanceSheets.AddAsync(balanceSheetDebit); BalanceSheet balanceSheetKredit = new BalanceSheet { CreatedAt = DateTime.UtcNow.AddHours(4), CompanyId = Convert.ToInt32(companyId), KreditMoney = manualJournal.Price, AccountsPlanId = manualJournal.AccountKreditId, ManualJournalId = manualJournal.Id }; await _context.BalanceSheets.AddAsync(balanceSheetKredit); await _context.SaveChangesAsync(); #endregion return manualJournal; } //Get public async Task<List<ManualJournal>> GetManualJournals(int? companyId) { if (companyId == null) return null; List<ManualJournal> manualJournals = await _context.ManualJournals. Include(a=>a.AccountsPlanDebit). Include(i=>i.AccountsPlanKredit). Where(w => w.CompanyId == companyId).ToListAsync(); if (manualJournals == null) return null; return manualJournals; } //Edit Get public async Task<ManualJournal>GetEditManualJournal(int? companyId, int? journalId) { var manual = await _context.ManualJournals.Include(i=>i.AccountsPlanDebit). Include(a=>a.AccountsPlanKredit). FirstOrDefaultAsync(f => f.CompanyId == companyId && f.Id == journalId); return manual; } //Edit public async Task<ManualJournal>EditManualJournal(ManualJournal manualJournal) { if (manualJournal == null) return null; _context.Entry(manualJournal).State = EntityState.Modified; _context.Entry(manualJournal).Property(a => a.CompanyId).IsModified = false; _context.Entry(manualJournal).Property(a => a.CreatedAt).IsModified = false; await _context.SaveChangesAsync(); return manualJournal; } // Accounting Update public ManualJournalPostDto UpdateManualJournalAccountDebit(int? journalId, int? companyId, ManualJournalPostDto journalPostDto, int? OldDebitId) { if (journalId == null) return null; if (journalPostDto == null) return null; double? dbInvoiceTotalPrice = _context.ManualJournals.FirstOrDefault(f => f.Id == journalId).Price; //Debit if (OldDebitId == journalPostDto.AccountDebitId) { //AccountPlan AccountsPlan accountDebit = _context.AccountsPlans.FirstOrDefault(f => f.Id == OldDebitId); if (accountDebit.Debit == null || accountDebit.Debit == 0) { accountDebit.Debit = journalPostDto.Price; } else { accountDebit.Debit -= dbInvoiceTotalPrice; _context.SaveChanges(); accountDebit.Debit += journalPostDto.Price; } _context.SaveChanges(); //Balancsheet BalanceSheet balanceSheetDebit = _context.BalanceSheets. FirstOrDefault(f => f.AccountsPlanId == OldDebitId && f.ManualJournalId == journalId); if (balanceSheetDebit != null) { balanceSheetDebit.DebitMoney = journalPostDto.Price; balanceSheetDebit.AccountsPlanId = journalPostDto.AccountDebitId; _context.SaveChanges(); } } else { //AccountPlan AccountsPlan oldAccountDebit = _context.AccountsPlans.FirstOrDefault(f => f.Id == OldDebitId); oldAccountDebit.Debit -= dbInvoiceTotalPrice; _context.SaveChanges(); AccountsPlan accountDebit = _context.AccountsPlans.FirstOrDefault(f => f.Id == journalPostDto.AccountDebitId); if (accountDebit.Debit == null || accountDebit.Debit == 0) { accountDebit.Debit = journalPostDto.Price; } else { accountDebit.Debit += journalPostDto.Price; } _context.SaveChanges(); //Balancsheet //remove old balancesheet BalanceSheet oldBalanceSheetDebit = _context.BalanceSheets .FirstOrDefault(f => f.ManualJournalId == journalId && f.AccountsPlanId == OldDebitId); if (oldBalanceSheetDebit != null) { _context.BalanceSheets.Remove(oldBalanceSheetDebit); _context.SaveChanges(); } //new balancesheet BalanceSheet balanceSheetDebit = new BalanceSheet { CreatedAt = DateTime.Now, CompanyId = Convert.ToInt32(companyId), DebitMoney = journalPostDto.Price, AccountsPlanId = journalPostDto.AccountDebitId, ManualJournalId = journalId }; _context.BalanceSheets.Add(balanceSheetDebit); _context.SaveChanges(); } return journalPostDto; } public ManualJournalPostDto UpdateManualJournalAccountKredit(int? journalId, int? companyId, ManualJournalPostDto journalPostDto, int? OldKeditId) { if (journalId == null) return null; if (journalPostDto == null) return null; double? dbInvoiceTotalPrice = _context.ManualJournals.FirstOrDefault(f => f.Id == journalId).Price; //Kredit if (OldKeditId == journalPostDto.AccountKreditId) { //AccountPlann AccountsPlan accountkredit = _context.AccountsPlans.FirstOrDefault(f => f.Id == OldKeditId); if (accountkredit.Kredit == null || accountkredit.Kredit == 0) { accountkredit.Kredit = journalPostDto.Price; } else { accountkredit.Kredit -= dbInvoiceTotalPrice; _context.SaveChanges(); accountkredit.Kredit += journalPostDto.Price; } _context.SaveChanges(); //Balancsheet BalanceSheet balanceSheetKredit = _context.BalanceSheets. FirstOrDefault(f => f.AccountsPlanId == OldKeditId && f.ManualJournalId == journalId); if (balanceSheetKredit != null) { balanceSheetKredit.KreditMoney = journalPostDto.Price; balanceSheetKredit.AccountsPlanId = journalPostDto.AccountKreditId; _context.SaveChanges(); } } else { //AccountPlan AccountsPlan oldAccountKredit = _context.AccountsPlans.FirstOrDefault(f => f.Id == OldKeditId); oldAccountKredit.Kredit -= dbInvoiceTotalPrice; _context.SaveChanges(); AccountsPlan accountkredit = _context.AccountsPlans.FirstOrDefault(f => f.Id == journalPostDto.AccountKreditId); if (accountkredit.Kredit == null || accountkredit.Kredit == 0) { accountkredit.Kredit = journalPostDto.Price; } else { accountkredit.Kredit += journalPostDto.Price; } _context.SaveChanges(); //Balancsheet //remove old balancesheet BalanceSheet oldBalanceSheetKredit = _context.BalanceSheets .FirstOrDefault(f => f.ManualJournalId == journalId && f.AccountsPlanId == OldKeditId); if (oldBalanceSheetKredit != null) { _context.BalanceSheets.Remove(oldBalanceSheetKredit); _context.SaveChanges(); } //new balancesheet BalanceSheet balanceSheetKredit = new BalanceSheet { CreatedAt = DateTime.Now, CompanyId = Convert.ToInt32(companyId), KreditMoney = journalPostDto.Price, AccountsPlanId = journalPostDto.AccountKreditId, ManualJournalId = journalId }; _context.BalanceSheets.Add(balanceSheetKredit); _context.SaveChanges(); } return journalPostDto; } //Delete: public async Task<ManualJournal> DeleteManualJournal(int? companyId, int? journalId) { if (companyId == null) return null; if (journalId == null) return null; var manualJournal = await _context.ManualJournals.FirstOrDefaultAsync(f => f.Id == journalId && f.CompanyId == companyId); if (manualJournal == null) return null; //Accounting #region Accounting var balancesheet = await _context.BalanceSheets.Where(w => w.CompanyId == companyId && w.ManualJournalId == journalId).ToListAsync(); var accountPlanDebit = _context.AccountsPlans.FirstOrDefault(f => f.Id == manualJournal.AccountDebitId); accountPlanDebit.Debit -= manualJournal.Price; _context.SaveChanges(); var accoutPlanKredit = _context.AccountsPlans.FirstOrDefault(f => f.Id == manualJournal.AccountKreditId); accoutPlanKredit.Kredit -= manualJournal.Price; _context.SaveChanges(); #endregion if (balancesheet != null) { _context.BalanceSheets.RemoveRange(balancesheet); } _context.ManualJournals.Remove(manualJournal); await _context.SaveChangesAsync(); return manualJournal; } public async Task<List<JournalDto>> GetJournal(int? companyId, DateTime? startDate, DateTime? endDate) { var JournalSheetQuery = await _context.JournalFromQuery .FromSql("exec GetJournal {0},{1},{2}", companyId, startDate, endDate).ToListAsync(); return JournalSheetQuery; } } } <file_sep>/AccountingApi/Models/ProcudureDto/GetExpenseInvoiceProductCountByIdDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models.ProcudureDto { public class GetExpenseInvoiceProductCountByIdDto { public string CompanyName { get; set; } public int? Qty { get; set; } public double? Price { get; set; } } } <file_sep>/AccountingApi/Models/Product.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models { public class Product { [Key] public int Id { get; set; } [MaxLength(75)] public string Name { get; set; } public string PhotoFile { get; set; } [MaxLength(150)] public string PhotoUrl { get; set; } [MaxLength(75)] public string Category { get; set; } public bool IsServiceOrProduct { get; set; } public DateTime CreatedAt { get; set; } public bool IsDeleted { get; set; } = false; public int? UnitId { get; set; } public int CompanyId { get; set; } public virtual Product_Unit Unit { get; set; } public virtual Company Company { get; set; } public virtual ICollection<Stock> Stocks { get; set; } public virtual ICollection<ExpenseInvoiceItem> ExpenseInvoices { get; set; } } } <file_sep>/AccountingApi/Models/ViewModel/VwIncomePut.cs using AccountingApi.Dtos.Sale.Income; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models.ViewModel { public class VwIncomePut { public IncomePutDto IncomePutDto { get; set; } public List<IncomeItemGetEditDto> IncomeItemGetEditDtos { get; set; } } } <file_sep>/AccountingApi/Migrations/20190624083244_ContragentsAndAccounsPlan.cs using System; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace AccountingApi.Migrations { public partial class ContragentsAndAccounsPlan : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "AccountsPlans", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), AccPlanNumber = table.Column<string>(maxLength: 100, nullable: true), Name = table.Column<string>(maxLength: 350, nullable: true), Active = table.Column<bool>(nullable: true), Level = table.Column<int>(nullable: true), Obeysto = table.Column<string>(nullable: true), ContraAccount = table.Column<bool>(nullable: true), Debit = table.Column<double>(nullable: true), Kredit = table.Column<double>(nullable: true), CompanyId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AccountsPlans", x => x.Id); table.ForeignKey( name: "FK_AccountsPlans_Companies_CompanyId", column: x => x.CompanyId, principalTable: "Companies", principalColumn: "Id", onDelete: ReferentialAction.NoAction); }); migrationBuilder.CreateTable( name: "Contragents", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), PhotoFile = table.Column<string>(nullable: true), PhotoUrl = table.Column<string>(maxLength: 150, nullable: true), CompanyName = table.Column<string>(maxLength: 100, nullable: true), Fullname = table.Column<string>(maxLength: 100, nullable: true), Position = table.Column<string>(maxLength: 75, nullable: true), FieldOfActivity = table.Column<string>(maxLength: 75, nullable: true), Phone = table.Column<string>(maxLength: 75, nullable: true), Email = table.Column<string>(maxLength: 75, nullable: true), VOEN = table.Column<string>(maxLength: 75, nullable: true), CreetedAt = table.Column<DateTime>(nullable: false), IsDeleted = table.Column<bool>(nullable: false), IsCostumer = table.Column<bool>(nullable: false), CompanyId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Contragents", x => x.Id); table.ForeignKey( name: "FK_Contragents_Companies_CompanyId", column: x => x.CompanyId, principalTable: "Companies", principalColumn: "Id", onDelete: ReferentialAction.NoAction); }); migrationBuilder.CreateTable( name: "Contragent_Details", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), City = table.Column<string>(maxLength: 75, nullable: true), Country = table.Column<string>(maxLength: 75, nullable: true), Adress = table.Column<string>(maxLength: 75, nullable: true), WebSite = table.Column<string>(maxLength: 75, nullable: true), Linkedin = table.Column<string>(maxLength: 75, nullable: true), Instagram = table.Column<string>(maxLength: 75, nullable: true), Facebook = table.Column<string>(maxLength: 75, nullable: true), Behance = table.Column<string>(maxLength: 75, nullable: true), ContragentId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Contragent_Details", x => x.Id); table.ForeignKey( name: "FK_Contragent_Details_Contragents_ContragentId", column: x => x.ContragentId, principalTable: "Contragents", principalColumn: "Id", onDelete: ReferentialAction.NoAction); }); migrationBuilder.CreateIndex( name: "IX_AccountsPlans_CompanyId", table: "AccountsPlans", column: "CompanyId"); migrationBuilder.CreateIndex( name: "IX_Contragent_Details_ContragentId", table: "Contragent_Details", column: "ContragentId"); migrationBuilder.CreateIndex( name: "IX_Contragents_CompanyId", table: "Contragents", column: "CompanyId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AccountsPlans"); migrationBuilder.DropTable( name: "Contragent_Details"); migrationBuilder.DropTable( name: "Contragents"); } } } <file_sep>/AccountingApi/Models/Contragent_Detail.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models { public class Contragent_Detail { [Key] public int Id { get; set; } [MaxLength(75)] public string City { get; set; } [MaxLength(75)] public string Country { get; set; } [MaxLength(75)] public string Adress { get; set; } [MaxLength(75)] public string WebSite { get; set; } [MaxLength(75)] public string Linkedin { get; set; } [MaxLength(75)] public string Instagram { get; set; } [MaxLength(75)] public string Facebook { get; set; } [MaxLength(75)] public string Behance { get; set; } public int ContragentId { get; set; } public Contragent Contragent { get; set; } } } <file_sep>/AccountingApi/Controllers/V1/ProductController.cs using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using AccountingApi.Data.Repository.Interface; using AccountingApi.Dtos.Nomenklatura.Product; using AccountingApi.Helpers.Extentions; using AccountingApi.Models; using AutoMapper; using EOfficeAPI.Helpers.Pagination; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace AccountingApi.Controllers.V1 { [Authorize] [Route("api/[controller]")] [ApiController] public class ProductController : ControllerBase { private readonly INomenklaturaRepository _repo; private readonly IMapper _mapper; public ProductController(INomenklaturaRepository repo, IMapper mapper) { _repo = repo; _mapper = mapper; } //Post [baseUrl]/api/product/addproduct [HttpPost] [Route("addproduct")] public async Task<IActionResult> AddProduct(ProductPostDto productStock, [FromHeader]int? companyId) { //Yoxlamaq #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckProduct(currentUserId, companyId)) return Unauthorized(); //if (!ModelState.IsValid) // return BadRequest(); #endregion //productpostdto-nu worker table-na mapp etmek Product product = _mapper.Map<Product>(productStock); //mapp olunmus productu CreateProduct reposuna gonderirik. Product productToGet = await _repo.CreateProduct(product, companyId); //Stock hissesi Stock stocks = _mapper.Map<Stock>(productStock); //mapp olunmus stocku CreateStock reposuna gonderirik. Stock stockToGet = await _repo.CreateStock(stocks, product.Id); //database elave olunmus workeri qaytarmaq ucun //ProductGetDto productForReturn = _mapper.Map<ProductGetDto>(productToGet); //2 obyekti bir obyekte birlesdirmek var productToReturn = _mapper.MergeInto<ProductGetDto>(productToGet, stockToGet); return Ok(productToReturn); } //Get [baseUrl]/api/product/getproducts [HttpGet] [Route("getproducts")] public async Task<IActionResult> GetProducts([FromQuery]PaginationParam productParam, [FromHeader]int? companyId) { //Yoxlamaq int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckProduct(currentUserId, companyId)) return Unauthorized(); var producstock = await _repo.GetProducts(productParam, companyId); //var stocks = await _repo.GetStocks(productParam, companyId); var productsToReturn = _mapper.Map<IEnumerable<ProductGetDto>>(producstock); //2 obyekti bir obyekte birlesdirmek //var productsToReturn = _mapper.MergeInto<IEnumerable<ProductGetDto>>(products); //Response.AddPagination(products.CurrentPage, products.PageSize, // products.TotalCount, products.TotalPages); return Ok(productsToReturn); } //Get [baseUrl]/api/product/getpurchaseproducts [HttpGet] [Route("getpurchaseproducts")] public async Task<IActionResult> GetPurchaseProducts([FromQuery]PaginationParam productParam, [FromHeader]int? companyId) { //Checking int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckProduct(currentUserId, companyId)) return Unauthorized(); var producstock = await _repo.GetPurchaseProducts(productParam, companyId); //var stocks = await _repo.GetStocks(productParam, companyId); var productsToReturn = _mapper.Map<IEnumerable<ProductGetDto>>(producstock); //2 obyekti bir obyekte birlesdirmek //var productsToReturn = _mapper.MergeInto<IEnumerable<ProductGetDto>>(products); //Response.AddPagination(products.CurrentPage, products.PageSize, // products.TotalCount, products.TotalPages); return Ok(productsToReturn); } //Get [baseUrl]/api/product/getsaleproducts [HttpGet] [Route("getsaleproducts")] // pagination yazilmsdi public async Task<IActionResult> GetsSaleProducts([FromQuery]PaginationParam productParam, [FromHeader]int? companyId) { //Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckProduct(currentUserId, companyId)) return Unauthorized(); var producstock = await _repo.GetSaleProducts(productParam, companyId); //var stocks = await _repo.GetStocks(productParam, companyId); var productsToReturn = _mapper.Map<IEnumerable<ProductGetDto>>(producstock); //2 obyekti bir obyekte birlesdirmek //var productsToReturn = _mapper.MergeInto<IEnumerable<ProductGetDto>>(products); //Response.AddPagination(products.CurrentPage, products.PageSize, // products.TotalCount, products.TotalPages); return Ok(productsToReturn); } //Get [baseUrl]/api/product/geteditproduct [HttpGet] [Route("geteditproduct")] public async Task<IActionResult> GetEditProduct([FromHeader]int? productId, [FromHeader] int? companyId) { //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (productId == null) return StatusCode(409, "productId null"); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckProduct(currentUserId, companyId)) return NotFound(); if (await _repo.CheckProductId(productId, companyId)) return StatusCode(406, "Not Acceptable"); #endregion Product product = await _repo.GetEditProduct(productId, companyId); Stock stock = await _repo.GetEditStock(productId); //2 obyekti bir obyekte birlesdirmek var productToReturn = _mapper.MergeInto<ProductGetEditDto>(product, stock); return Ok(productToReturn); } //Put [baseUrl]/api/product/updateproduct [HttpPut] [Route("updateproduct")] //Update zamani bu metodla dolduracayiq public async Task<IActionResult> UpdateProduct([FromBody] ProductPutDto productPut, [FromHeader]int? productId, [FromHeader]int? companyId) { //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (!ModelState.IsValid) return BadRequest(); if (productId == null) return StatusCode(409, "productId null"); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckProduct(currentUserId, companyId)) return NotFound(); if (await _repo.CheckProductId(productId, companyId)) return StatusCode(406, "Not Acceptable"); #endregion //repoya id gonderirik ve o bize lazim olan mehsulu getirir. Product product_FromRepo = await _repo.GetEditProduct(productId, companyId); Stock stock_FromRepo = await _repo.GetEditStock(productId); //mapp olunmus mehsul Product productMapped = _mapper.Map(productPut, product_FromRepo); Stock stockToMapped = _mapper.Map(productPut, stock_FromRepo); //repoda mehsulu yenileyirik Product updatedProduct = await _repo.EditProduct(product_FromRepo, productId); Stock updatedStock = await _repo.EditStock(stock_FromRepo, productId); //2 obyekti bir obyekte birlesdirmek var productToReturn = _mapper.MergeInto<ProductGetDto>(product_FromRepo, stock_FromRepo); return Ok(productToReturn); } //Delete [baseUrl]/api/product/deleteproduct [HttpGet] [Route("deleteproduct")] public async Task<IActionResult> DeleteProduct([FromHeader]int? productId, [FromHeader]int? companyId) { //Check #region Check if (productId == null) return StatusCode(409, "workerId null"); if (companyId == null) return StatusCode(409, "companyId null"); if (await _repo.DeleteProduct(productId, companyId) == null) return NotFound(); #endregion Product DeletedProduct = await _repo.DeleteProduct(productId, companyId); return Ok(); } } }<file_sep>/AccountingApi/Models/ExpenseItem.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace AccountingApi.Models { public class ExpenseItem { [Key] public int Id { get; set; } public double? Residue { get; set; } public double? TotalOneInvoice { get; set; } public double? PaidMoney { get; set; } public bool IsBank { get; set; } = false; public string InvoiceNumber { get; set; } public int ExpenseInvoiceId { get; set; } public int ExpenseId { get; set; } public DateTime? Date { get; set; } public int? AccountDebitId { get; set; } public int? AccountKreditId { get; set; } [ForeignKey("AccountDebitId")] public virtual AccountsPlan AccountsPlanDebit { get; set; } [ForeignKey("AccountKreditId")] public virtual AccountsPlan AccountsPlanKredit { get; set; } public virtual ICollection<BalanceSheet> BalanceSheets { get; set; } public virtual ExpenseInvoice ExpenseInvoice { get; set; } public virtual Expense Expense { get; set; } } } <file_sep>/AccountingApi/Controllers/V1/ProposalController.cs using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using AccountingApi.Data.Repository.Interface; using AccountingApi.Dtos.Company; using AccountingApi.Dtos.Sale.Proposal; using AccountingApi.Helpers.Extentions; using AccountingApi.Models; using AccountingApi.Models.ViewModel; using AutoMapper; using EOfficeAPI.Helpers.Pagination; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace AccountingApi.Controllers.V1 { [Authorize] [Route("api/[controller]")] [ApiController] public class ProposalController : ControllerBase { private readonly ISaleRepository _repo; private readonly IMapper _mapper; public ProposalController(ISaleRepository repo, IMapper mapper) { _repo = repo; _mapper = mapper; } [Authorize] //Post [baseUrl]/api/proposal/addproposal [HttpPost] [Route("addproposal")] public async Task<IActionResult> AddProposal(VwProposal proposal, [FromHeader]int? companyId) { var mappedProposal = _mapper.Map<Proposal>(proposal.ProposalPost); var itemProposal = _mapper.Map<IEnumerable<ProposalItem>>(proposal.ProposalItemPosts); //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (mappedProposal == null) return StatusCode(409, "[Header]companyId or proposalId not correct"); if (await _repo.CheckProposal(currentUserId, companyId)) return Unauthorized(); //mehsulun id-sinin olmasini yoxlayiriq. if (await _repo.CheckProposalProductId(itemProposal)) return StatusCode(409, "productId doesnt exist"); //contrageti id-ni yoxluyuruq if ((await _repo.CheckContragentId(mappedProposal.ContragentId, companyId))) return StatusCode(409, "contragetnId doesnt exist"); #endregion var proposalToReturn = await _repo.CreateProposal(mappedProposal, companyId); var itemToRetun = await _repo.CreateProposalItems(itemProposal, mappedProposal.Id); var ToReturn = _mapper.Map<Dtos.Sale.Proposal.ProposalGetDto>(proposalToReturn); //Company //id ye gore sirketi getiririk Company companyFromRepo = await _repo.GetEditCompany(companyId); //// //map edirik Company companyForUpdate = _mapper.Map(proposal.CompanyPutProposalDto, companyFromRepo); //// //edit etmek reposu Company updatedCompany = await _repo.EditCompany(companyForUpdate, companyId, currentUserId); //Contragent //id-ye gore sirketi getiririk Contragent contragentFromRepo = await _repo.GetEditContragent(mappedProposal.ContragentId); //map edirik Contragent contragentForUpdate = _mapper.Map(proposal.ContragentPutInProposalDto, contragentFromRepo); //edit etmek reposu Contragent updatedContragent = await _repo.EditContragent(contragentForUpdate, companyId); //qaytaracagimiz info CompanyAfterPutDto companyToReturn = _mapper.Map<CompanyAfterPutDto>(updatedCompany); return Ok(ToReturn); } [Authorize] //Get[baseUrl]/api/proposal/getproposal [HttpGet] [Route("getproposal")] public async Task<IActionResult> GetProposal([FromQuery]PaginationParam productParam, [FromHeader]int? companyId) { //Yoxlamaq #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckProposal(currentUserId, companyId)) return Unauthorized(); #endregion var producstock = await _repo.GetProposal(productParam, companyId); var productsToReturn = _mapper.Map<IEnumerable<ProposalGetDto>>(producstock); return Ok(productsToReturn); } [Authorize] //Get[baseUrl]/api/proposal/geteditproposal [HttpGet] [Route("geteditproposal")] public async Task<IActionResult> GetEditProposal([FromHeader]int? proposalId, [FromHeader]int? companyId) { //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (proposalId == null) return StatusCode(409, "proposalId null"); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckProposal(currentUserId, companyId)) return Unauthorized(); if (await _repo.CheckProposalId(proposalId, companyId)) return StatusCode(406, "Not Acceptable"); #endregion Company company = await _repo.GetEditCompany(companyId); Contragent contragent = await _repo.GetContragentProposal(companyId, proposalId); Proposal fromRepo = await _repo.GetDetailProposal(proposalId, companyId); var ToReturn = _mapper.MergeInto<ProposalEditGetDto>(contragent, company, fromRepo); return Ok(ToReturn); } [Authorize] //Put [baseUrl]/api/proposal/updateproposal [HttpPut] [Route("updateproposal")] public async Task<IActionResult> UpdateProposal([FromBody] VwProposalPut proposalPut, [FromHeader]int? proposalId, [FromHeader]int? companyId) { //get proposal for updating Proposal proposalfromRepo = await _repo.GetEditProposal(proposalId, companyId); //get proposalitems for updating List<ProposalItem> proposalItemsFromRepo = await _repo.GetEditProposalItem(proposalId); //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (proposalId == null) return StatusCode(409, "proposalId null"); if (currentUserId == null) return Unauthorized(); if (proposalfromRepo == null) return StatusCode(409, "[Header]companyId or proposalId not correct"); if (proposalItemsFromRepo == null) return StatusCode(409); if (await _repo.CheckProposal(currentUserId, companyId)) return Unauthorized(); #endregion //Mapping proposal dto with proposalfromRepo Proposal Mapped = _mapper.Map(proposalPut.ProposalPutDto, proposalfromRepo); //Mapping proposalitems dto with proposalItemsFromRepo List<ProposalItem> MapperdProposalItems = _mapper.Map(proposalPut.ProposalItemPutDtos, proposalItemsFromRepo); //Company //id ye gore sirketi getiririk Company companyFromRepo = await _repo.GetEditCompany(companyId); //map edirik Company companyForUpdate = _mapper.Map(proposalPut.CompanyPutProposalDto, companyFromRepo); //edit etmek reposu Company updatedCompany = await _repo.EditCompany(companyForUpdate, companyId, currentUserId); //Contragent //idye goe sirketi getiririk Contragent contragentFromRepo = await _repo.GetEditContragent(Mapped.ContragentId); //map edirik Contragent contragentForUpdate = _mapper.Map(proposalPut.ContragentPutInProposalDto, contragentFromRepo); //edit etmek reposu Contragent updatedContragent = await _repo.EditContragent(contragentForUpdate, companyId); //qaytaracagimiz info CompanyAfterPutDto companyToReturn = _mapper.Map<CompanyAfterPutDto>(updatedCompany); Proposal proposal = await _repo.EditProposal(Mapped, MapperdProposalItems, proposalId); return Ok(proposal); } [Authorize] //Post [baseUrl]/api/proposal/sendproposal [HttpPost] [Route("sendproposal")] public IActionResult SendProposal([FromHeader]int? proposalId, Mail mail) { if (proposalId == null) return StatusCode(409, "proposalId null"); return Ok(_repo.CreateProposalSentMail(proposalId, mail.Email).Token); } //Get [baseUrl]/api/proposal/getproposalbytoken [HttpGet] [Route("getproposalbytoken")] public async Task<IActionResult> GetProposalByToken(string token, [FromHeader]int? proposalId, [FromHeader]int? companyId) { //Checking #region Check if (proposalId == null) return StatusCode(409, "proposalId null"); if (companyId == null) return StatusCode(409, "companyId null"); if (await _repo.CheckProposalId(proposalId, companyId)) return StatusCode(406, "Not Acceptable"); #endregion Company company = await _repo.GetEditCompany(companyId); Contragent contragent = await _repo.GetContragentProposal(companyId, proposalId); Proposal proposalFromRepo = _repo.GetProposalByToken(token); var ToReturn = _mapper.MergeInto<ProposalEditGetDto>(contragent, company, proposalFromRepo); return Ok(ToReturn); } //Delete [baseUrl]/api/proposal/deleteproposalitem [HttpDelete] [Route("deleteproposalitem")] public async Task<IActionResult> DeleteProposalItem([FromHeader] int? proposalItemId) { //Check #region Check if (proposalItemId == null) return StatusCode(409, "incomeItemId null"); #endregion await _repo.DeleteProposalItem(proposalItemId); return Ok(); } //Delete [baseUrl]/api/proposal/deleteproposal [HttpDelete] [Route("deleteproposal")] public async Task<IActionResult> DeleteProposal([FromHeader]int? companyId, [FromHeader] int? proposalId) { //Check #region Check if (companyId == null) return StatusCode(409, "companyId null"); if (proposalId == null) return StatusCode(409, "proposalId null"); #endregion await _repo.DeleteProposal(companyId, proposalId); return Ok(); } } }<file_sep>/AccountingApi/Controllers/V1/ContragentController.cs using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using AccountingApi.Data.Repository.Interface; using AccountingApi.Dtos.Nomenklatura.Kontragent; using AccountingApi.Helpers.Extentions; using AccountingApi.Models; using AutoMapper; using EOfficeAPI.Helpers.Extentions; using EOfficeAPI.Helpers.Pagination; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace AccountingApi.Controllers.V1 { [Authorize] [Route("api/[controller]")] [ApiController] public class ContragentController : ControllerBase { private readonly INomenklaturaRepository _repo; private readonly IMapper _mapper; public ContragentController(INomenklaturaRepository repo, IMapper mapper) { _repo = repo; _mapper = mapper; } [HttpPost] [Route("addcontragent")] public async Task<IActionResult> AddContragent(ContragentPostDto vwContragent, [FromHeader]int? companyId) { int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckContragent(currentUserId, companyId)) return Unauthorized(); if (!ModelState.IsValid) return BadRequest(); //workerpostdto-nu worker table-na mapp etmek Contragent contragent = _mapper.Map<Contragent>(vwContragent); //mapp olunmus workeri CreateWorker reposuna gonderirik. Contragent ContragentToGet = await _repo.CreateContragent(contragent, companyId); //database elave olunmus workeri qaytarmaq ucun ContragentGetDto contragentForReturn = _mapper.Map<ContragentGetDto>(ContragentToGet); //Worker_Detail hissesi Contragent_Detail contragent_Details = _mapper.Map<Contragent_Detail>(vwContragent); Contragent_Detail contragent_DetailToGet = await _repo.CreateContragent_Detail(contragent_Details, contragent.Id); //ContragentGetDto contragent_DetailForReturn = _mapper.Map<ContragentGetDto>(contragent_DetailToGet); return Ok(contragentForReturn); } //Get [baseUrl]/api/contragent/getcontragents [HttpGet] [Route("getcontragents")] // pagination yazilmsdi public async Task<IActionResult> GetContragents([FromQuery]PaginationParam contragentParam, [FromHeader]int? companyId) { int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckContragent(currentUserId, companyId)) return Unauthorized(); var contragents = await _repo.GetContragents(contragentParam, companyId); var contragentToReturn = _mapper.Map<IEnumerable<ContragentGetDto>>(contragents); Response.AddPagination(contragents.CurrentPage, contragents.PageSize, contragents.TotalCount, contragents.TotalPages); return Ok(contragentToReturn); } //Get [baseUrl]/api/contragent/getsalecontragents //getsalecontragents (where added contragent selecting sale) [HttpGet] [Route("getsalecontragents")] // pagination yazilmsdi public async Task<IActionResult> GetSaleContragents([FromQuery]PaginationParam contragentParam, [FromHeader]int? companyId) { int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckContragent(currentUserId, companyId)) return Unauthorized(); var contragents = await _repo.GetSallerContragents(contragentParam, companyId); var contragentToReturn = _mapper.Map<IEnumerable<ContragentGetDto>>(contragents); Response.AddPagination(contragents.CurrentPage, contragents.PageSize, contragents.TotalCount, contragents.TotalPages); return Ok(contragentToReturn); } //Get [baseUrl]/api/contragent/getcostumercontragents //getcostumercontragents (where added contragent selecting customer) [HttpGet] [Route("getcostumercontragents")] // pagination yazilmsdi public async Task<IActionResult> GetCostumerContragents([FromQuery]PaginationParam contragentParam, [FromHeader]int? companyId) { int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckContragent(currentUserId, companyId)) return Unauthorized(); var contragents = await _repo.GetCostumerContragents(contragentParam, companyId); var contragentToReturn = _mapper.Map<IEnumerable<ContragentGetDto>>(contragents); Response.AddPagination(contragents.CurrentPage, contragents.PageSize, contragents.TotalCount, contragents.TotalPages); return Ok(contragentToReturn); } //deyisilik etmek ucun iscini getiririk [HttpGet] [Route("geteditcontragent")] public async Task<IActionResult> GetEditContragent([FromHeader]int? contragentId, [FromHeader]int? companyId) { int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (contragentId == null) return StatusCode(409, "contragentId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckContragent(currentUserId, companyId)) return Unauthorized(); if (await _repo.CheckContragentId(contragentId, companyId)) return StatusCode(406, "Not Acceptable"); Contragent contragent = await _repo.GetEditContragent(contragentId, companyId); Contragent_Detail contragent_Detail = await _repo.GetEditContragent_Detail(contragentId); //2 obyekti birlesdirmek var contragentToReturn = _mapper.MergeInto<ContragentGetEditDto>(contragent, contragent_Detail); return Ok(contragentToReturn); } //deyismek [HttpPut] [Route("updatecontragent")] //Update zamani bu metodla dolduracayiq public async Task<IActionResult> UpdateContragent([FromBody]ContragentPutDto contragentPut, [FromHeader]int? contragentId, [FromHeader] int? companyId) { int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (contragentId == null) return StatusCode(409, "contragentId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckContragent(currentUserId, companyId)) return Unauthorized(); if (!ModelState.IsValid) return BadRequest(); //isciler //repoya id gonderirik ve o bize lazim olan iscini ve detail-ni getirir. Contragent contragent_FromRepo = await _repo.GetEditContragent(contragentId, companyId); Contragent_Detail Detail_FromRepo = await _repo.GetEditContragent_Detail(contragentId); //mapp olunmus Contragent contragentMapped = _mapper.Map(contragentPut, contragent_FromRepo); //repoda yenileyirik Contragent updatedContragent = await _repo.EditContragent(contragent_FromRepo, contragentId); //qaytarmaq ucun ContragentGetDto contragentToReturn = _mapper.Map<ContragentGetDto>(updatedContragent); //elave melumatlari //mapp olunmus elaqlerin detaili Contragent_Detail contragent_DetailToMapped = _mapper.Map(contragentPut, Detail_FromRepo); //repoda iscini yenileyirik Contragent_Detail updatedContragent_Detail = await _repo.EditContragent_Detail(Detail_FromRepo, contragentId); return Ok(contragentToReturn); } //Delete [baseUrl]/api/contragent/deletecontragent [HttpGet] [Route("deletecontragent")] public async Task<IActionResult> DeleteContragent([FromHeader]int? contragentId, [FromHeader]int? companyId) { //Check #region Check if (contragentId == null) return StatusCode(409, "workerId null"); if (companyId == null) return StatusCode(409, "companyId null"); if (await _repo.DeleteContragent(contragentId, companyId) == null) return NotFound(); #endregion Contragent DeletedContragent = await _repo.DeleteContragent(contragentId, companyId); return Ok(); } } }<file_sep>/AccountingApi/Models/ProcudureDto/ProductsReportDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models.ProcudureDto { public class ProductsReportDto { public int SumQty { get; set; } public string Name { get; set; } public int PercentOfTotal { get; set; } public string Color { get; set; } } } <file_sep>/AccountingApi/Data/Repository/Interface/INomenklaturaRepository.cs using AccountingApi.Dtos.Nomenklatura.Product; using AccountingApi.Models; using EOfficeAPI.Helpers.Pagination; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Data.Repository.Interface { public interface INomenklaturaRepository { //Isciler #region Worker //Isci Task<Worker> CreateWorker(Worker workerCreate, int? companyId); //iscinin elave melumatlari Task<Worker_Detail> CreateWorker_Detail(Worker_Detail worker_DetailCreate, int workerId); //Isci Get Task<PagedList<Worker>> GetWorkers(PaginationParam workerParam, int? companyId); //Isci deyis get Task<Worker> GetEditWorker(int? workerId, int? companyId); Task<Worker_Detail> GetEditWorkerDetail(int? workerId); //Isci deyis Task<Worker> EditWorker(Worker workerEdit, int? id); //Isci elave melumatlari deyis Task<Worker_Detail> EditWorker_Detail(Worker_Detail workerEdit, int? id); //silmek Task<Worker> DeleteWorker(int? workerId, int? companyId); //yoxlamaq Task<bool> Checkworker(int? currentUserId, int? companyId); Task<bool> CheckWorkerId(int? workerId, int? companyId); #endregion //Mehsullar #region Product //mehsul yaratmaq Task<Product> CreateProduct(Product product, int? companyId); //mehsulu anbara elave etmek Task<Stock> CreateStock(Stock stocks, int? productId); //mehsullari getirmek Task<List<ProductGetDto>> GetProducts(PaginationParam productParam, int? companyId); Task<List<ProductGetDto>> GetPurchaseProducts(PaginationParam productParam, int? companyId); //mehsul edit get Task<Product> GetEditProduct(int? productId, int? companyId); Task<List<ProductGetDto>> GetSaleProducts(PaginationParam productParam, int? companyId); Task<Stock> GetEditStock(int? productId); //mehsul deyis Task<Product> EditProduct(Product productEdit, int? productId); //anbar deyis Task<Stock> EditStock(Stock stockEdit, int? productId); //mehsulu silmek Task<Product> DeleteProduct(int? workerId, int? companyId); //yoxlamaq Task<bool> CheckProduct(int? currentUserId, int? companyId); Task<bool> CheckProductId(int? productId, int? companyId); #endregion //Elaqeler #region Contragent //Isci Task<Contragent> CreateContragent(Contragent contragentCreate, int? companyId); //iscinin elave melumatlari Task<Contragent_Detail> CreateContragent_Detail(Contragent_Detail contragent_DetailCreate, int? contragentId); //Elaqeler Get Task<PagedList<Contragent>> GetContragents(PaginationParam contragentParam, int? companyId); Task<PagedList<Contragent>> GetSallerContragents(PaginationParam contragentParam, int? companyId); Task<PagedList<Contragent>> GetCostumerContragents(PaginationParam contragentParam, int? companyId); Task<Contragent> GetEditContragent(int? contragentId, int? companyId); Task<Contragent_Detail> GetEditContragent_Detail(int? contragentId); Task<Contragent> EditContragent(Contragent contragentEdit, int? contragentId); Task<Contragent_Detail> EditContragent_Detail(Contragent_Detail contragentDetailEdit, int? contragentId); //Check Task<bool> CheckContragent(int? currentUserId, int? companyId); Task<bool> CheckContragentId(int? contragentId, int? companyId); //Delete Task<Contragent> DeleteContragent(int? contragentId, int? companyId); #endregion } } <file_sep>/AccountingApi/Dtos/Nomenklatura/Worker/WorkerGetDto.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Nomenklatura.Worker { public class WorkerGetDto { public int Id { get; set; } public string Name { get; set; } public string SurName { get; set; } public double Salary { get; set; } public string Departament { get; set; } public string PhotoUrl { get; set; } public bool IsState { get; set; } //public ICollection<Worker_DetailGetDto> Worker_DetailGetDtos { get; set; } //public WorkerGetDto() //{ // Worker_DetailGetDtos = new Collection<Worker_DetailGetDto>(); //} } } <file_sep>/AccountingApi/Models/Income.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models { public class Income { [Key] public int Id { get; set; } //paid money total public double? TotalPrice { get; set; } public DateTime CreatedAt { get; set; } public bool IsDeleted { get; set; } = false; public int CompanyId { get; set; } public int ContragentId { get; set; } public virtual Contragent Contragent { get; set; } public virtual Company Company { get; set; } public virtual ICollection<IncomeItem> IncomeItems { get; set; } } } <file_sep>/AccountingApi/Models/ProcudureDto/ExpenseInvoiceReportByContragentDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models.ProcudureDto { public class ExpenseInvoiceReportByContragentDto { public int Id { get; set; } public string CompanyName { get; set; } public int? Qty { get; set; } public double? Price { get; set; } } } <file_sep>/AccountingApi/Controllers/V1/ReportsController.cs using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using AccountingApi.Data.Repository.Interface; using AccountingApi.Helpers.Extentions; using AccountingApi.Models.ProcudureDto; using AccountingApi.Models.ProcudureDto.ParamsObject; using AutoMapper; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace AccountingApi.Controllers.V1 { [Authorize] [Route("api/[controller]")] [ApiController] public class ReportsController : ControllerBase { private readonly IAccountRepository _repo; private readonly IMapper _mapper; public ReportsController(IAccountRepository repo, IMapper mapper) { _repo = repo; _mapper = mapper; } // Mənfəət və Zərər //Get [baseUrl]/api/reports/inexeportquery [HttpGet] [Route("inexeportquery")] public async Task<IActionResult> InExReportQuery([FromQuery] ReportFilter reportFilter, [FromHeader] int? companyId) { var Inreport = await _repo.ReportQueryByCompanyId(reportFilter, companyId); var ExPensereport = await _repo.ReportExpenseQueryByCompanyId(reportFilter, companyId); var ToReturn = _mapper.MergeInto<InExReportDto>(Inreport, ExPensereport); return Ok(ToReturn); } //Get [baseUrl]/api/reports/incomereportquery [HttpGet] [Route("incomereportquery")] public async Task<IActionResult> IncomeReportQuery([FromQuery] ReportFilter reportFilter, [FromHeader] int? companyId) { //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); #endregion var incomesFromQuery = await _repo.IncomesQueryByCompanyId(reportFilter, companyId); var ToReturn = _mapper.Map<List<IncomeReportDto>>(incomesFromQuery); return Ok(ToReturn); } //Get [baseUrl]/api/reports/expensereportquery [HttpGet] [Route("expensereportquery")] public async Task<IActionResult> ExpenseReportQuery([FromQuery] ReportFilter reportFilter, [FromHeader] int? companyId) { //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); #endregion var expenseFromQuery = await _repo.ExpensesQueryByCompanyId(reportFilter, companyId); var ToReturn = _mapper.Map<List<ExpenseReportDto>>(expenseFromQuery); return Ok(ToReturn); } //Get [baseUrl]/api/reports/productreportquery [HttpGet] [Route("productreportquery")] public async Task<IActionResult> ProductReportQuery([FromHeader] int? companyId, [FromHeader] int? DateUntil) { //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); #endregion var expenseFromQuery = await _repo.ProductsQueryByCompanyId(companyId, DateUntil); var ToReturn = _mapper.Map<List<ProductsReportDto>>(expenseFromQuery); return Ok(ToReturn); } //Get [baseUrl]/api/reports/invoicereportquery [HttpGet] [Route("invoicereportquery")] public async Task<IActionResult> InvoiceReportQuery([FromHeader] int? companyId, [FromHeader] int? DateUntil) { //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); #endregion var invoiceFromQuery = await _repo.InvoiceReportQueryByCompanyId(companyId, DateUntil); var ToReturn = _mapper.Map<List<InvoiceReportDto>>(invoiceFromQuery); return Ok(ToReturn); } //Get [baseUrl]/api/reports/expenseinvoicereportquery [HttpGet] [Route("expenseinvoicereportquery")] public async Task<IActionResult> ExpenseInvoiceReportQuery([FromHeader] int? companyId, [FromHeader] int? DateUntil) { //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); #endregion var invoiceFromQuery = await _repo.ExpenseInvoiceReportQueryByCompanyId(companyId, DateUntil); var ToReturn = _mapper.Map<List<ExpenseInvoiceReportDto>>(invoiceFromQuery); return Ok(ToReturn); } //Get [baseUrl]/api/reports/contragentreportquery [HttpGet] [Route("contragentreportquery")] public async Task<IActionResult> ContragentReportQuery([FromHeader] int? companyId, [FromHeader] int? DateUntil) { //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); #endregion var invoiceFromQuery = await _repo.ContragentReportQueryByCompanyId(companyId, DateUntil); var ToReturn = _mapper.Map<List<ContragentFromQueryDto>>(invoiceFromQuery); return Ok(ToReturn); } //Get [baseUrl]/api/reports/workerreportquery [HttpGet] [Route("workerreportquery")] public async Task<IActionResult> WorkerReportQuery([FromHeader] int? companyId, [FromHeader] int? DateUntil) { //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); #endregion var workerFromQuery = await _repo.WorkerReportQueryByCompanyId(companyId, DateUntil); var ToReturn = _mapper.Map<List<WorkerFromQueryDto>>(workerFromQuery); return Ok(ToReturn); } //Get [baseUrl]/api/reports/netincomereportquery [HttpGet] [Route("netincomereportquery")] public async Task<IActionResult> NetIncomeReportQuery([FromHeader] int? companyId, [FromHeader] int? DateUntil) { //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); #endregion var netIncomeFromQuery = await _repo.NetIncomeReportQueryByCompanyId(companyId, DateUntil); var ToReturn = _mapper.Map<List<NetIncomeFromQueryDto>>(netIncomeFromQuery); return Ok(ToReturn); } //Get [baseUrl]/api/reports/InvoiceReportByContragent [HttpGet] [Route("invoicereportbycontragent")] public async Task<IActionResult> InvoiceReportByContragent([FromHeader] int? companyId) { //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); #endregion var FromQuery = await _repo.InvoiceReportByContragents(companyId); var ToReturn = _mapper.Map<List<InvoiceReportByContragentDto>>(FromQuery); return Ok(ToReturn); } //Get [baseUrl]/api/reports/ProductReportAll [HttpGet] [Route("productreportall")] public async Task<IActionResult> ProductReportAll([FromHeader] int? companyId, [FromQuery] ReportFilter reportFilter) { //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); #endregion var FromQuery = await _repo.ProductAll(companyId, reportFilter); var ToReturn = _mapper.Map<List<ProductAllDto>>(FromQuery); return Ok(ToReturn); } //Get [baseUrl]/api/reports/expenseinvoicereportbycontragent [HttpGet] [Route("expenseinvoicereportbycontragent")] public async Task<IActionResult> ExpenseInvoiceReportByContragent([FromHeader] int? companyId) { //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); #endregion var FromQuery = await _repo.ExpenseInvoiceReportByContragents(companyId); var ToReturn = _mapper.Map<List<ExpenseInvoiceReportByContragentDto>>(FromQuery); return Ok(ToReturn); } //Get [baseUrl]/api/reports/ProductReportAllExpense [HttpGet] [Route("productreportallexpense")] public async Task<IActionResult> ProductReportAllExpense([FromHeader] int? companyId, [FromQuery] ReportFilter reportFilter) { //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); #endregion var FromQuery = await _repo.ProductAllExpense(companyId, reportFilter); var ToReturn = _mapper.Map<List<ProductExpenseAllDto>>(FromQuery); return Ok(ToReturn); } //Get [baseUrl]/api/reports/getinvoiceproductcountbyId [HttpGet] [Route("getinvoiceproductcountbyId")] public async Task<IActionResult> GetInvoiceProductCountById([FromHeader] int? companyId, [FromHeader] int? productId) { //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); #endregion var FromQuery = await _repo.GetInvoiceProductCountById(companyId,productId); var ToReturn = _mapper.Map<List<GetInvoiceProductCountByIdDto>>(FromQuery); return Ok(ToReturn); } //Get [baseUrl]/api/reports/invoicesreportbycontragentid [HttpGet] [Route("invoicesreportbycontragentid")] public async Task<IActionResult> InvoicesReportByContragentId([FromHeader] int? companyId, [FromHeader] int? contragentId) { //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); #endregion var FromQuery = await _repo.InvoicesReportByContragentId(companyId, contragentId); var ToReturn = _mapper.Map<List<InvoicesReportByContragentIdDto>>(FromQuery); return Ok(ToReturn); } //Get [baseUrl]/api/reports/getexpenseinvoiceproductcountbyid [HttpGet] [Route("getexpenseinvoiceproductcountbyid")] public async Task<IActionResult> GetExpenseInvoiceProductCountById([FromHeader] int? companyId, [FromHeader] int? productId) { //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); #endregion var FromQuery = await _repo.GetExpenseInvoiceProductCountById(companyId, productId); var ToReturn = _mapper.Map<List<GetExpenseInvoiceProductCountByIdDto>>(FromQuery); return Ok(ToReturn); } //Get [baseUrl]/api/reports/expenseinvoicereportbycontragentid [HttpGet] [Route("expenseinvoicereportbycontragentid")] public async Task<IActionResult> ExpenseInvoiceReportByContragentId([FromHeader] int? companyId, [FromHeader] int? contragentId) { //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); #endregion var FromQuery = await _repo.ExpenseInvoiceReportByContragentId(companyId, contragentId); var ToReturn = _mapper.Map<List<ExpenseInvoiceReportByContragentIdDto>>(FromQuery); return Ok(ToReturn); } } }<file_sep>/AccountingApi/Data/Repository/Interface/IAccountsPlanRepository.cs using AccountingApi.Dtos.Account; using AccountingApi.Dtos.AccountsPlan; using AccountingApi.Models; using AccountingApi.Models.ProcudureDto; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Data.Repository.Interface { public interface IAccountsPlanRepository { Task<List<AccountsPlan>> ImportFromExcel(int? companyId); Task<List<AccountsPlan>> GetAccountsPlans(int? companyId); //From Procedure Task<List<BalanceSheetReturnDto>> BalanceSheet(int? companyId, DateTime? startDate, DateTime? endDate); //ManualJournal Task<List<OperationCategory>> GetOperationCategories(); Task<ManualJournal> CreateManualJournal(int? companyId, ManualJournal manualJournal); Task<List<ManualJournal>> GetManualJournals(int? companyId); Task<ManualJournal> GetEditManualJournal(int? companyId, int? journalId); Task<ManualJournal> EditManualJournal(ManualJournal manualJournal); ManualJournalPostDto UpdateManualJournalAccountDebit(int? journalId, int? companyId, ManualJournalPostDto journalPostDto, int? OldDebitId); ManualJournalPostDto UpdateManualJournalAccountKredit(int? journalId, int? companyId, ManualJournalPostDto journalPostDto, int? OldKeditId); Task<ManualJournal> DeleteManualJournal(int? companyId, int? journalId); Task<List<JournalDto>> GetJournal(int? companyId, DateTime? startDate, DateTime? endDate); } } <file_sep>/AccountingApi/Dtos/AccountsPlan/ManualJournalGetDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.AccountsPlan { public class ManualJournalGetDto { public int Id { get; set; } public string JurnalNumber { get; set; } public string JurnalName { get; set; } public DateTime? Date { get; set; } public string Desc { get; set; } public double? Price { get; set; } //Manual Journal public string AccountsPlanDebitAccPlanNumber { get; set; } public string AccountsPlanDebitName { get; set; } public string AccountsPlanKreditAccPlanNumber { get; set; } public string AccountsPlanKreditName { get; set; } } } <file_sep>/AccountingApi/Dtos/Sale/Proposal/ProposalGetDto.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Sale.Proposal { public class ProposalGetDto { public int Id { get; set; } public string ProposalNumber { get; set; } public DateTime? PreparingDate { get; set; } public DateTime? EndDate { get; set; } public double? TotalPrice { get; set; } //contragent companyname public string ContragentCompanyName { get; set; } public byte IsPaid { get; set; } } } <file_sep>/AccountingApi/Migrations/20190627130219_IncomeAccount.cs using Microsoft.EntityFrameworkCore.Migrations; namespace AccountingApi.Migrations { public partial class IncomeAccount : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<int>( name: "AccountDebitId", table: "IncomeItems", nullable: true); migrationBuilder.AddColumn<int>( name: "AccountKreditId", table: "IncomeItems", nullable: true); migrationBuilder.CreateIndex( name: "IX_IncomeItems_AccountDebitId", table: "IncomeItems", column: "AccountDebitId"); migrationBuilder.CreateIndex( name: "IX_IncomeItems_AccountKreditId", table: "IncomeItems", column: "AccountKreditId"); migrationBuilder.AddForeignKey( name: "FK_IncomeItems_AccountsPlans_AccountDebitId", table: "IncomeItems", column: "AccountDebitId", principalTable: "AccountsPlans", principalColumn: "Id", onDelete: ReferentialAction.NoAction); migrationBuilder.AddForeignKey( name: "FK_IncomeItems_AccountsPlans_AccountKreditId", table: "IncomeItems", column: "AccountKreditId", principalTable: "AccountsPlans", principalColumn: "Id", onDelete: ReferentialAction.NoAction); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_IncomeItems_AccountsPlans_AccountDebitId", table: "IncomeItems"); migrationBuilder.DropForeignKey( name: "FK_IncomeItems_AccountsPlans_AccountKreditId", table: "IncomeItems"); migrationBuilder.DropIndex( name: "IX_IncomeItems_AccountDebitId", table: "IncomeItems"); migrationBuilder.DropIndex( name: "IX_IncomeItems_AccountKreditId", table: "IncomeItems"); migrationBuilder.DropColumn( name: "AccountDebitId", table: "IncomeItems"); migrationBuilder.DropColumn( name: "AccountKreditId", table: "IncomeItems"); } } } <file_sep>/AccountingApi/Dtos/Sale/Invoice/InvoiceItemPostDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Sale.Invoice { public class InvoiceItemPostDto { public int? Qty { get; set; } public double? SellPrice { get; set; } public double? TotalOneProduct { get; set; } public int? ProductId { get; set; } public int? InvoiceId { get; set; } } } <file_sep>/AccountingApi/Models/ProcudureDto/ContragentFromQueryDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models.ProcudureDto { public class ContragentFromQueryDto { public int? MonthNumber { get; set; } public string MonthName { get; set; } public int? SellerCount { get; set; } //public string SellerName { get; set; } public int? CostumerCount { get; set; } //public string CostumerName { get; set; } } } <file_sep>/AccountingApi/Dtos/Purchase/Expense/ExpenseGetDto.cs using System; namespace AccountingApi.Dtos.Purchase.Expense { public class ExpenseGetDto { public int Id { get; set; } public DateTime CreatedAt { get; set; } public string ExpenseInvoiceNumber { get; set; } //contragent public string ContragentCompanyName { get; set; } public string ContragentFullname { get; set; } public double? TotalPrice { get; set; } public bool IsBank { get; set; } public double? PaidMoney { get; set; } public double? Residue { get; set; } public int InvoiceId { get; set; } public double? SumPaidMoney { get; set; } public double? TotalOneInvoice { get; set; } } } <file_sep>/AccountingApi/Dtos/Purchase/ExpenseInvoice/ExpenseInvoicePutDto.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Purchase.ExpenseInvoice { public class ExpenseInvoicePutDto { public string ExpenseInvoiceNumber { get; set; } public DateTime? PreparingDate { get; set; } public double? TotalPrice { get; set; } public double? TotalTax { get; set; } public double? Sum { get; set; } public string Desc { get; set; } public int? TaxId { get; set; } public int? ContragentId { get; set; } public int? AccountDebitId { get; set; } public int? AccountKreditId { get; set; } //public ICollection<ExpenseInvoiceItemPostDto> ExpenseInvoiceItemPostDtos { get; set; } //public ExpenseInvoicePutDto() //{ // ExpenseInvoiceItemPostDtos = new Collection<ExpenseInvoiceItemPostDto>(); //} } } <file_sep>/AccountingApi/Helpers/Extentions/MappExtention.cs using AutoMapper; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Helpers.Extentions { public static class MappExtention { public static TResult MergeInto<TResult>(this IMapper mapper, object item1, object item2) { return mapper.Map(item2, mapper.Map<TResult>(item1)); } public static TResult MergeInto<TResult>(this IMapper mapper, params object[] objects) { var res = mapper.Map<TResult>(objects.First()); return objects.Skip(1).Aggregate(res, (r, obj) => mapper.Map(obj, r)); } //ignore all doesnt use public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression) { var sourceType = typeof(TSource); var destinationType = typeof(TDestination); var existingMaps = Mapper.Configuration.GetAllTypeMaps().First(x => x.SourceType.Equals(sourceType) && x.DestinationType.Equals(destinationType)); foreach (var property in existingMaps.GetUnmappedPropertyNames()) { expression.ForMember(property, opt => opt.Ignore()); } return expression; } } } <file_sep>/AccountingApi/Controllers/V1/AuthController.cs using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using AccountingApi.Data.Repository.Interface; using AccountingApi.Dtos; using AccountingApi.Dtos.Company; using AccountingApi.Dtos.User; using AccountingApi.Models; using AutoMapper; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; namespace AccountingApi.Controllers.V1 { [Route("api/[controller]")] [ApiController] public class AuthController : ControllerBase { private readonly IAuthRepository _repo; private readonly IConfiguration _config; private readonly IMapper _mapper; public AuthController(IAuthRepository repo, IConfiguration config, IMapper mapper) { _mapper = mapper; _config = config; _repo = repo; } //Post [baseUrl]/api/auth/register [HttpPost("register")] public async Task<IActionResult> Register(UserForRegisterDto registerDto) { //Check #region Check if (await _repo.CheckUsersMail(registerDto.Email)) return StatusCode(409, "This email already exist"); registerDto.Email = registerDto.Email.ToLower(); var userToCreate = _mapper.Map<User>(registerDto); if (!ModelState.IsValid) return BadRequest(); #endregion //Register var createdUser = await _repo.Register(userToCreate, registerDto.Password); //User to return var userToReturn = _mapper.Map<UserForReturnDto>(createdUser); //Company Dto //CompanyPostDto companyPost = new CompanyPostDto //{ // Name = registerDto.Name, // Surname = registerDto.SurName //}; //return true false for companyCreating page showing var companyCount = _repo.CompanyCountForRegister(createdUser.Id); //Company For Create //Company company = _mapper.Map<Company>(companyPost); ////created company //var createCompany = _userRepo.CreateCompany(company, createdUser.Id); ////didnt use //var userCompany = await _repo.UserCompany(createdUser.Id); //// return company //var companyToReturn = _mapper.Map<CompanyGetDto>(createCompany); //GWT #region GWT var claims = new[] { new Claim(ClaimTypes.NameIdentifier, createdUser.Id.ToString()), new Claim(ClaimTypes.Name, createdUser.Email) }; var key = new SymmetricSecurityKey(Encoding.UTF8 .GetBytes(_config.GetSection("AppSettings:Token").Value)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.Now.AddDays(1), SigningCredentials = creds }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); #endregion return Ok(new { userToReturn, token = tokenHandler.WriteToken(token), companyCount.Result }); } //Post [baseUrl]/api/auth/login [HttpPost("login")] public async Task<IActionResult> Login(UserForLoginDto userForLoginDto) { if (await _repo.UserExists(userForLoginDto.Email, userForLoginDto.Password)) return StatusCode(401, "email or password in correct"); if (userForLoginDto == null) return Unauthorized(); User userFromRepo = await _repo.Login(userForLoginDto.Email.ToLower(), userForLoginDto.Password); //return true false for companyCreating page showing var companyCount = _repo.CompanyCountForRegister(userFromRepo.Id); //qaytardigimiz istifadeci melumatlari var user = _mapper.Map<UserForReturnDto>(userFromRepo); //Istifadecinin sriketlerini tapmaq var userCompanies = await _repo.UserCompanies(user.Id); //GWT #region GWT var claims = new[] { new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()), new Claim(ClaimTypes.Name, userFromRepo.Email) }; var key = new SymmetricSecurityKey(Encoding.UTF8 .GetBytes(_config.GetSection("AppSettings:Token").Value)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.Now.AddDays(1), SigningCredentials = creds }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); #endregion // sirketleri qaytarmaq var companyToReturn = _mapper.Map<IEnumerable<CompanyGetDto>>(userCompanies); return Ok(new { token = tokenHandler.WriteToken(token), user, companyToReturn, companyCount.Result }); } } } <file_sep>/AccountingApi/Startup.cs using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Threading.Tasks; using AccountingApi.Data; using AccountingApi.Data.Repository; using AccountingApi.Data.Repository.Interface; using AccountingApi.Helpers; using AccountingApi.Helpers.Extentions; using AutoMapper; using AutoMapper.EquivalencyExpression; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; namespace AccountingApi { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<DataContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); // Add service and create Policy with options services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials() ); }); services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddJsonOptions(opt => { opt.SerializerSettings.Culture = new CultureInfo("en-GB"); opt.SerializerSettings.DateFormatString = "dd/MM/yyyy"; //ReferenceLooping errorunun qarsini almaq ucundur opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; }); //Dependency Injection to resolve DbContext //services.AddDbContext<DbContext>(ServiceLifetime.Transient); //Globalizaton datetime format services.Configure<RequestLocalizationOptions>(options => { options.DefaultRequestCulture = new RequestCulture("en-GB"); options.SupportedCultures = new List<CultureInfo> { new CultureInfo("en-GB") }; options.RequestCultureProviders.Clear(); }); //Url-ni goturmek ucun MyHttpContext classinda middlware yaradiriq app-de de cagiririq. bunu yaziriq ki baseUrl-ni goture bilek services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>(); //autoMapper services.AddAutoMapper(cfg => { cfg.AddCollectionMappers(); }); //If you have other mapping profiles defined, that profiles will be loaded too //Repository interface oxutdururuq services.AddScoped<IAuthRepository, AuthRepository>(); services.AddScoped<IUserRepository, UserRepository>(); services.AddScoped<INomenklaturaRepository, NomenklaturaRepository>(); services.AddScoped<IPathProvider, PathProvider>(); services.AddScoped<IAccountsPlanRepository, AccountsPlanRepository>(); services.AddScoped<ISaleRepository, SaleRepository>(); services.AddScoped<ISettingRepository, SettingRepository>(); services.AddScoped<IPurchaseRepository, PurchaseRepository>(); services.AddScoped<IAccountRepository, AccountRepository>(); //JWT servis edirik services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII .GetBytes(Configuration.GetSection("AppSettings:Token").Value)), ValidateIssuer = false, ValidateAudience = false }; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler(builder => { builder.Run(async context => { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; var error = context.Features.Get<IExceptionHandlerFeature>(); if (error != null) { context.Response.AddApplicationError(error.Error.Message); await context.Response.WriteAsync(error.Error.Message); } }); }); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. //app.UseHsts(); } //seeder.SeedUsers(); //Globalization datetime var defaultCulture = new CultureInfo("en-GB"); app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture(defaultCulture), SupportedCultures = new List<CultureInfo> { defaultCulture }, SupportedUICultures = new List<CultureInfo> { defaultCulture } }); app.UseAuthentication(); app.UseHttpsRedirection(); //Faylari yuklemek ucun app.UseStaticFiles(); //BaseUrl-ni elde etmek ucun app.UseHttpContext(); app.UseCors(builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); app.UseMvc(); } } } <file_sep>/AccountingApi/Data/Repository/UserRepository.cs using AccountingApi.Data.Repository.Interface; using AccountingApi.Helpers; using AccountingApi.Models; using EOfficeAPI.Helpers; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Data.Repository { public class UserRepository: IUserRepository { private readonly DataContext _context; public UserRepository(DataContext context) { _context = context; } //Post: public async Task<Company> CreateCompany(Company companyCreate, int userId) { companyCreate.UserId = userId; companyCreate.CreatedAt = DateTime.Now; companyCreate.IsDeleted = false; //sekil yuklemek funksiyasi base 64 companyCreate.PhotoFile = FileManager.Upload(companyCreate.PhotoFile); //seklini url-ni geri qaytarmaq ucun companyCreate.PhotoUrl = companyCreate.PhotoFile; await _context.Companies.AddAsync(companyCreate); await _context.SaveChangesAsync(); Tax tax = new Tax { Name = "Vergisiz", IsDeleted = false, Rate = 0.0, CompanyId = companyCreate.Id }; if (tax == null) return null; _context.Taxes.Add(tax); await _context.SaveChangesAsync(); return companyCreate; } //Get: //get edit public async Task<Company> GetEditCompany(int? companyId) { if (companyId == null) return null; Company company = await _context.Companies.FindAsync(companyId); if (company == null) return null; return company; } public async Task<List<Company>> GetCompany(int? userId) { if (userId == null) return null; var company = await _context.Companies.Where(w => w.IsDeleted == false && w.UserId == userId).ToListAsync(); return company; } public async Task<Company> GetCompanyById(int? userId, int? companyId) { if (userId == null) return null; if (companyId == null) return null; await _context.SaveChangesAsync(); var company = await _context.Companies.FirstOrDefaultAsync(w => w.IsDeleted == false && w.UserId == userId && w.Id == companyId); if (company == null) return null; return company; } //Put: public async Task<Company> EditCompany(Company companyEdit) { if (companyEdit == null) return null; if (companyEdit.PhotoFile != null && companyEdit.PhotoFile != "") { //database-de yoxlayiriq eger bize gelen iscinin id-si ile eyni olan sekili silsin. string dbFileName = _context.Companies.FirstOrDefault(f => f.Id == companyEdit.Id).PhotoUrl; if (dbFileName != null) { FileManager.Delete(dbFileName); } companyEdit.PhotoFile = FileManager.Upload(companyEdit.PhotoFile); //seklin url teyin edirik companyEdit.PhotoUrl = companyEdit.PhotoFile; } //update entitynin metodudu. _context.Entry(companyEdit).State = EntityState.Modified; _context.Entry(companyEdit).Property(a => a.UserId).IsModified = false; //Commit the transaction await _context.SaveChangesAsync(); return companyEdit; } //Get Edit User public async Task<User> GetEditUser(int? userId) { if (userId == null) return null; User user = await _context.Users.FirstOrDefaultAsync(f => f.Id == userId); if (user == null) return null; return user; } //Put: User public async Task<User> EditUser(User user, string password) { User userForUpdate = _context.Users.Find(user.Id); userForUpdate.Password = CryptoHelper.Crypto.HashPassword(user.Password); //didnt use userForUpdate.Token = CryptoHelper.Crypto.HashPassword(DateTime.Now.ToLongDateString() + user.Email); userForUpdate.Status = true; await _context.SaveChangesAsync(); return null; } //Check: public bool CheckOldPassword(string OldPassword, int? userId) { if (userId == null) return true; User user = _context.Users.Find(userId); if (!CryptoHelper.Crypto.VerifyHashedPassword(user.Password, OldPassword)) return true; return false; } public UserSendMailChangePassword CreateUserSentMail(int? userId, string email) { UserSendMailChangePassword userSent = new UserSendMailChangePassword { UserId = Convert.ToInt32(userId), Email = email, Token = CryptoHelper.Crypto.HashPassword(DateTime.Now.ToLongDateString()).Replace('+', 't').Replace('=', 't'), }; _context.UserSendMailChangePasswords.Add(userSent); _context.SaveChanges(); MailExtention.SendPasswordEmail(userSent.Email, userSent.Token); return userSent; } } } <file_sep>/AccountingApi/Models/ViewModel/VwProposal.cs using AccountingApi.Dtos.Company; using AccountingApi.Dtos.Nomenklatura.Kontragent; using AccountingApi.Dtos.Sale.Proposal; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models.ViewModel { public class VwProposal { public ProposalPostDto ProposalPost { get; set; } public ICollection<ProposalItemPostDto> ProposalItemPosts { get; set; } public CompanyPutProposalDto CompanyPutProposalDto { get; set; } public ContragentPutInProposalDto ContragentPutInProposalDto { get; set; } } } <file_sep>/AccountingApi/Models/Worker_Detail.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models { public class Worker_Detail { [Key] public int Id { get; set; } [MaxLength(75)] public string FatherName { get; set; } [MaxLength(75)] public string Email { get; set; } [MaxLength(75)] public string Adress { get; set; } [MaxLength(75)] public string DSMF { get; set; } [MaxLength(75)] public string Voen { get; set; } [MaxLength(75)] public string Phone { get; set; } [MaxLength(75)] public string MobilePhone { get; set; } [MaxLength(75)] public string Education { get; set; } [MaxLength(75)] public string EducationLevel { get; set; } [MaxLength(20)] public string Gender { get; set; } public DateTime? Birthday { get; set; } public int WorkerId { get; set; } public virtual Worker Worker { get; set; } } } <file_sep>/AccountingApi/Models/ExpenseInvoice.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models { public class ExpenseInvoice { [Key] public int Id { get; set; } [MaxLength(250)] public string ExpenseInvoiceNumber { get; set; } public DateTime? PreparingDate { get; set; } public DateTime? EndDate { get; set; } public DateTime CreatedAt { get; set; } public double? TotalPrice { get; set; } //for calculating totalprice every adding income public double? ResidueForCalc { get; set; } public double? TotalTax { get; set; } public double? Sum { get; set; } [Required, Range(1, 4)] public byte IsPaid { get; set; } = 1; [MaxLength(300)] public string Desc { get; set; } public bool IsDeleted { get; set; } = false; public int? ContragentId { get; set; } public int CompanyId { get; set; } public int? TaxId { get; set; } public int? AccountDebitId { get; set; } public int? AccountKreditId { get; set; } public virtual Company Company { get; set; } public virtual Contragent Contragent { get; set; } [ForeignKey("AccountDebitId")] public virtual AccountsPlan AccountsPlanDebit { get; set; } [ForeignKey("AccountKreditId")] public virtual AccountsPlan AccountsPlanKredit { get; set; } public virtual Tax Tax { get; set; } public virtual ICollection<BalanceSheet> BalanceSheets { get; set; } public virtual ICollection<ExpenseInvoiceItem> ExpenseInvoiceItems { get; set; } public virtual ICollection<ExpenseItem> ExpenseItems { get; set; } } } <file_sep>/AccountingApi/Models/ProcudureDto/InvoicesReportByContragentIdDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models.ProcudureDto { public class InvoicesReportByContragentIdDto { public string InvoiceNumber { get; set; } public double? TotalPrice { get; set; } public DateTime? PreparingDate { get; set; } public DateTime? EndDate { get; set; } } } <file_sep>/AccountingApi/Data/Repository/NomenklaturaRepository.cs using AccountingApi.Data.Repository.Interface; using AccountingApi.Dtos.Nomenklatura.Product; using AccountingApi.Helpers; using AccountingApi.Models; using EOfficeAPI.Helpers.Pagination; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Data.Repository { public class NomenklaturaRepository : INomenklaturaRepository { private readonly DataContext _context; public NomenklaturaRepository(DataContext context) { _context = context; } //Worker #region Workers //Iscileri yaratmaq public async Task<Worker> CreateWorker(Worker workerCreate, int? companyId) { //sirkete gore getireceyik iscileri if (companyId == null) return null; workerCreate.CompanyId = Convert.ToInt32(companyId); //sekil yuklemek funksiyasi base 64 workerCreate.PhotoFile = FileManager.Upload(workerCreate.PhotoFile); //seklini url-ni geri qaytarmaq ucun workerCreate.PhotoUrl = workerCreate.PhotoFile; workerCreate.RegisterDate = DateTime.Now; workerCreate.IsDeleted = false; await _context.Workers.AddAsync(workerCreate); await _context.SaveChangesAsync(); return workerCreate; } //Iscileri elave melumatlarini yaratmaq public async Task<Worker_Detail> CreateWorker_Detail(Worker_Detail worker_DetailCreate, int workerId) { worker_DetailCreate.WorkerId = workerId; await _context.Worker_Details.AddAsync(worker_DetailCreate); await _context.SaveChangesAsync(); return worker_DetailCreate; } //iscileri getirmek sirkete gore public async Task<PagedList<Worker>> GetWorkers(PaginationParam workerParam, int? companyId) { if (companyId == null) return null; var workers = _context.Workers.Where(w => w.CompanyId == companyId && w.IsDeleted == false).Include(i => i.Worker_Details) .OrderByDescending(d => d.Id).AsQueryable(); if (!string.IsNullOrEmpty(workerParam.Name)) { workers = workers.Where(d => d.Name.Contains(workerParam.Name)); } if (!string.IsNullOrEmpty(workerParam.Surname)) { workers = workers.Where(d => d.Name.Contains(workerParam.Surname)); } return await PagedList<Worker>.CreateAsync(workers, workerParam.PageNumber, workerParam.PageSize); } //isci ve elave melumatinin getirilmesi public async Task<Worker> GetEditWorker(int? workerId, int? companyId) { if (workerId == null) return null; Worker worker = await _context.Workers.FirstOrDefaultAsync(f => f.Id == workerId && f.CompanyId == companyId && f.IsDeleted == false); return worker; } //elave melumatinin getirilmesi public async Task<Worker_Detail> GetEditWorkerDetail(int? workerId) { if (workerId == null) return null; Worker_Detail worker_Detail = await _context.Worker_Details.FirstOrDefaultAsync(s => s.WorkerId == workerId); return worker_Detail; } // iscini yenilemek public async Task<Worker> EditWorker(Worker workerEdit, int? id) { if (id == null) return null; if (workerEdit.PhotoFile != null && workerEdit.PhotoFile != "") { //database-de yoxlayiriq eger bize gelen iscinin id-si ile eyni olan sekili silsin. string dbFileName = _context.Workers.FirstOrDefault(f => f.Id == id).PhotoUrl; if (dbFileName != null) { FileManager.Delete(dbFileName); } workerEdit.PhotoFile = FileManager.Upload(workerEdit.PhotoFile); //seklin url teyin edirik workerEdit.PhotoUrl = workerEdit.PhotoFile; } _context.Workers.Update(workerEdit); await _context.SaveChangesAsync(); return workerEdit; } //iscinin elave melumatlarini yenilemek public async Task<Worker_Detail> EditWorker_Detail(Worker_Detail workerEdit, int? id) { if (_context.Worker_Details.Any(a => a.WorkerId == id)) { // iscinin butun elave melumatlaini yenilemek _context.Worker_Details.Update(workerEdit); await _context.SaveChangesAsync(); } return workerEdit; } //Delete public async Task<Worker> DeleteWorker(int? workerId, int? companyId) { if (companyId == null) return null; if (workerId == null) return null; Worker dbWorker = await _context.Workers.FirstOrDefaultAsync(f => f.Id == workerId && f.CompanyId == companyId); if (dbWorker == null) return null; dbWorker.IsDeleted = true; await _context.SaveChangesAsync(); return dbWorker; } //check public async Task<bool> Checkworker(int? currentUserId, int? companyId) { if (currentUserId == null) return true; if (companyId == null) return true; if (await _context.Workers.AnyAsync(a => a.CompanyId == companyId && a.Company.UserId != currentUserId)) return true; //yoxluyuruq sirket databasede var if (await _context.Companies.FirstOrDefaultAsync(a => a.Id == companyId) == null) return true; return false; } public async Task<bool> CheckWorkerId(int? workerId, int? companyId) { if (companyId == null) return true; if (workerId == null) return true; if (await _context.Workers.AnyAsync(a => a.CompanyId != companyId && a.Id == workerId)) return true; return false; } #endregion //Product #region Products // Mehsul yaratmaq public async Task<Product> CreateProduct(Product product, int? companyId) { if (companyId == null) return null; //sekil yuklemek funksiyasi base 64 product.PhotoFile = FileManager.Upload(product.PhotoFile); //seklini url-ni geri qaytarmaq ucun product.PhotoUrl = product.PhotoFile; product.CreatedAt = DateTime.Now; product.CompanyId = Convert.ToInt32(companyId); product.IsDeleted = false; await _context.Products.AddAsync(product); await _context.SaveChangesAsync(); return product; } //Anbar yaratmaq public async Task<Stock> CreateStock(Stock stock, int? productId) { stock.ProductId = Convert.ToInt32(productId); await _context.Stocks.AddAsync(stock); await _context.SaveChangesAsync(); return stock; } //Anbari getirmek public async Task<List<ProductGetDto>> GetProducts(PaginationParam productParam, int? companyId) { if (companyId == null) return null; List<Product> products = await _context.Products.Where(w => w.CompanyId == companyId && w.IsDeleted == false) .OrderByDescending(d => d.CreatedAt).ToListAsync(); List<Stock> stocks = await _context.Stocks.Where(w => w.Product.CompanyId == companyId) .OrderByDescending(d => d.Product.CreatedAt).ToListAsync(); var producstock = products.Join(stocks, m => m.Id, m => m.ProductId, (pro, st) => new ProductGetDto { Name = pro.Name, Category = pro.Category, SalePrice = st.SalePrice, Price = st.Price, IsSale = st.IsSale, IsPurchase = st.IsPurchase, Id = pro.Id, PhotoUrl = pro.PhotoUrl != null ? $"{MyHttpContext.AppBaseUrl}/Uploads/" + pro.PhotoUrl : "" }).ToList(); //if (!string.IsNullOrEmpty(workerParam.Name)) //{ // products = products.Where(d => d.Name.Contains(workerParam.Name)); //} //return producstock; return producstock; } public async Task<List<ProductGetDto>> GetSaleProducts(PaginationParam productParam, int? companyId) { if (companyId == null) return null; List<Product> products = await _context.Products.Include(i => i.Unit).Where(w => w.CompanyId == companyId && w.IsDeleted == false) .OrderByDescending(d => d.CreatedAt).ToListAsync(); List<Stock> stocks = await _context.Stocks.Where(w => w.Product.CompanyId == companyId && w.IsSale) .OrderByDescending(d => d.Product.CreatedAt).ToListAsync(); var producstock = products.Join(stocks, m => m.Id, m => m.ProductId, (pro, st) => new ProductGetDto { Name = pro.Name, Category = pro.Category, SalePrice = st.SalePrice, Price = st.Price, IsSale = st.IsSale, IsPurchase = st.IsPurchase, Id = pro.Id, UnitName = pro.Unit.Name, PhotoUrl = pro.PhotoUrl != null ? $"{MyHttpContext.AppBaseUrl}/Uploads/" + pro.PhotoUrl : "" }).ToList(); //if (!string.IsNullOrEmpty(workerParam.Name)) //{ // products = products.Where(d => d.Name.Contains(workerParam.Name)); //} //return producstock; return producstock; } public async Task<List<ProductGetDto>> GetPurchaseProducts(PaginationParam productParam, int? companyId) { if (companyId == null) return null; List<Product> products = await _context.Products.Include(i => i.Unit).Where(w => w.CompanyId == companyId && w.IsDeleted == false) .OrderByDescending(d => d.CreatedAt).ToListAsync(); List<Stock> stocks = await _context.Stocks.Where(w => w.Product.CompanyId == companyId && w.IsPurchase) .OrderByDescending(d => d.Product.CreatedAt).ToListAsync(); var producstock = products.Join(stocks, m => m.Id, m => m.ProductId, (pro, st) => new ProductGetDto { Name = pro.Name, Category = pro.Category, SalePrice = st.SalePrice, Price = st.Price, IsSale = st.IsSale, IsPurchase = st.IsPurchase, Id = pro.Id, UnitName = pro.Unit.Name, PhotoUrl = pro.PhotoUrl != null ? $"{MyHttpContext.AppBaseUrl}/Uploads/" + pro.PhotoUrl : "" }).ToList(); //if (!string.IsNullOrEmpty(workerParam.Name)) //{ // products = products.Where(d => d.Name.Contains(workerParam.Name)); //} //return producstock; return producstock; } //Deyismek ucun Mehsul ve anbari getirmek public async Task<Product> GetEditProduct(int? productId, int? companyId) { if (productId == null) return null; Product product = await _context.Products.Include(i => i.Unit).FirstOrDefaultAsync(f => f.Id == productId && f.IsDeleted == false && f.CompanyId == companyId); return product; } public async Task<Stock> GetEditStock(int? productId) { if (productId == null) return null; Stock stock = await _context.Stocks.FirstOrDefaultAsync(f => f.ProductId == productId); return stock; } //Mehsulu deyismek public async Task<Product> EditProduct(Product productEdit, int? productId) { if (productId == null) return null; if (productEdit.PhotoFile != null && productEdit.PhotoFile != "") { //database-de yoxlayiriq eger bize gelen iscinin id-si ile eyni olan sekili silsin. string dbFileName = _context.Workers.FirstOrDefault(f => f.Id == productId).PhotoUrl; if (dbFileName != null) { FileManager.Delete(dbFileName); } productEdit.PhotoFile = FileManager.Upload(productEdit.PhotoFile); //seklin url teyin edirik productEdit.PhotoUrl = productEdit.PhotoFile; } _context.Products.Update(productEdit); await _context.SaveChangesAsync(); return productEdit; } //Anbari Deyismek public async Task<Stock> EditStock(Stock stockEdit, int? productId) { if (productId == null) return null; if (_context.Stocks.Any(a => a.ProductId == productId)) { // mehsul butun elave melumatlarini yenilemek _context.Stocks.UpdateRange(stockEdit); await _context.SaveChangesAsync(); } return stockEdit; } //Delete public async Task<Product> DeleteProduct(int? productId, int? companyId) { if (companyId == null) return null; if (productId == null) return null; Product dbProduct = await _context.Products.FirstOrDefaultAsync(f => f.Id == productId && f.CompanyId == companyId); if (dbProduct == null) return null; dbProduct.IsDeleted = true; await _context.SaveChangesAsync(); return dbProduct; } //yoxlamaq public async Task<bool> CheckProduct(int? currentUserId, int? companyId) { if (currentUserId == null) return true; if (companyId == null) return true; if (await _context.Products.AnyAsync(a => a.CompanyId == companyId && a.Company.UserId != currentUserId)) return true; //yoxluyuruq sirket databasede var if (await _context.Companies.FirstOrDefaultAsync(a => a.Id == companyId) == null) return true; return false; } public async Task<bool> CheckProductId(int? productId, int? companyId) { if (companyId == null) return true; if (productId == null) return true; if (await _context.Products.AnyAsync(a => a.CompanyId != companyId && a.Id == productId)) return true; return false; } #endregion //Elaqeler #region Contragent //elaqeleri yaratmaq public async Task<Contragent> CreateContragent(Contragent contragentCreate, int? companyId) { //sirkete gore getireceyik elaqeleri if (companyId == null) return null; contragentCreate.CompanyId = Convert.ToInt32(companyId); //sekil yuklemek funksiyasi base 64 contragentCreate.PhotoFile = FileManager.Upload(contragentCreate.PhotoFile); //seklini url-ni geri qaytarmaq ucun contragentCreate.PhotoUrl = contragentCreate.PhotoFile; contragentCreate.CreetedAt = DateTime.Now; contragentCreate.IsDeleted = false; await _context.Contragents.AddAsync(contragentCreate); await _context.SaveChangesAsync(); return contragentCreate; } public async Task<Contragent_Detail> CreateContragent_Detail(Contragent_Detail contragent_DetailCreate, int? contragentId) { contragent_DetailCreate.ContragentId = Convert.ToInt32(contragentId); await _context.Contragent_Details.AddAsync(contragent_DetailCreate); await _context.SaveChangesAsync(); return contragent_DetailCreate; } //Get public async Task<PagedList<Contragent>> GetContragents(PaginationParam contragentParam, int? companyId) { var contragents = _context.Contragents.Where(w => w.CompanyId == companyId && w.IsDeleted == false) .OrderByDescending(d => d.Id).AsQueryable(); if (!string.IsNullOrEmpty(contragentParam.Name)) { contragents = contragents.Where(d => d.CompanyName.Contains(contragentParam.Name)); } if (!string.IsNullOrEmpty(contragentParam.Surname)) { contragents = contragents.Where(d => d.Fullname.Contains(contragentParam.Surname)); } return await PagedList<Contragent>.CreateAsync(contragents, contragentParam.PageNumber, contragentParam.PageSize); } //GetCostumerContragents public async Task<PagedList<Contragent>> GetCostumerContragents(PaginationParam contragentParam, int? companyId) { var contragents = _context.Contragents.Where(w => w.CompanyId == companyId && w.IsDeleted == false && w.IsCostumer) .OrderByDescending(d => d.Id).AsQueryable(); if (!string.IsNullOrEmpty(contragentParam.Name)) { contragents = contragents.Where(d => d.CompanyName.Contains(contragentParam.Name)); } if (!string.IsNullOrEmpty(contragentParam.Surname)) { contragents = contragents.Where(d => d.Fullname.Contains(contragentParam.Surname)); } return await PagedList<Contragent>.CreateAsync(contragents, contragentParam.PageNumber, contragentParam.PageSize); } //GetSallerContragents public async Task<PagedList<Contragent>> GetSallerContragents(PaginationParam contragentParam, int? companyId) { var contragents = _context.Contragents.Where(w => w.CompanyId == companyId && w.IsDeleted == false && w.IsCostumer == false) .OrderByDescending(d => d.Id).AsQueryable(); if (!string.IsNullOrEmpty(contragentParam.Name)) { contragents = contragents.Where(d => d.CompanyName.Contains(contragentParam.Name)); } if (!string.IsNullOrEmpty(contragentParam.Surname)) { contragents = contragents.Where(d => d.Fullname.Contains(contragentParam.Surname)); } return await PagedList<Contragent>.CreateAsync(contragents, contragentParam.PageNumber, contragentParam.PageSize); } public async Task<Contragent> GetEditContragent(int? contragentId, int? companyId) { if (contragentId == null) return null; Contragent worker = await _context.Contragents.FirstOrDefaultAsync(f => f.Id == contragentId && f.CompanyId == companyId); return worker; } //elave melumatinin getirilmesi public async Task<Contragent_Detail> GetEditContragent_Detail(int? contragentId) { if (contragentId == null) return null; Contragent_Detail worker_Detail = await _context.Contragent_Details.FirstOrDefaultAsync(s => s.ContragentId == contragentId); return worker_Detail; } //deyismek public async Task<Contragent> EditContragent(Contragent contragentEdit, int? contragentId) { if (contragentId == null) return null; if (contragentEdit.PhotoFile != null && contragentEdit.PhotoFile != "") { //database-de yoxlayiriq eger bize gelen elaqe id-si ile eyni olan sekili silsin. string dbFileName = _context.Contragents.FirstOrDefault(f => f.Id == contragentId).PhotoUrl; if (dbFileName != null) { FileManager.Delete(dbFileName); } contragentEdit.PhotoFile = FileManager.Upload(contragentEdit.PhotoFile); //seklin url teyin edirik contragentEdit.PhotoUrl = contragentEdit.PhotoFile; } _context.Contragents.Update(contragentEdit); await _context.SaveChangesAsync(); return contragentEdit; } public async Task<Contragent_Detail> EditContragent_Detail(Contragent_Detail contragentDetailEdit, int? contragentId) { if (_context.Contragent_Details.Any(a => a.ContragentId == contragentId)) { // iscinin butun elave melumatlaini yenilemek _context.Contragent_Details.Update(contragentDetailEdit); await _context.SaveChangesAsync(); } return contragentDetailEdit; } //Check public async Task<bool> CheckContragent(int? currentUserId, int? companyId) { if (currentUserId == null) return true; if (companyId == null) return true; if (await _context.Contragents.AnyAsync(a => a.CompanyId == companyId && a.Company.UserId != currentUserId)) return true; //yoxluyuruq sirket databasede var if (await _context.Companies.FirstOrDefaultAsync(a => a.Id == companyId) == null) return true; return false; } public async Task<bool> CheckContragentId(int? contragentId, int? companyId) { if (companyId == null) return true; if (contragentId == null) return true; if (await _context.Contragents.AnyAsync(a => a.CompanyId != companyId && a.Id == contragentId)) return true; return false; } //Delete public async Task<Contragent> DeleteContragent(int? contragentId, int? companyId) { if (companyId == null) return null; if (contragentId == null) return null; Contragent dbContragent = await _context.Contragents.FirstOrDefaultAsync(f => f.Id == contragentId && f.CompanyId == companyId); if (dbContragent == null) return null; dbContragent.IsDeleted = true; await _context.SaveChangesAsync(); return dbContragent; } #endregion } } <file_sep>/AccountingApi/Data/Repository/SettingRepository.cs using AccountingApi.Data.Repository.Interface; using AccountingApi.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Data.Repository { public class SettingRepository : ISettingRepository { private readonly DataContext _context; public SettingRepository(DataContext context) { _context = context; } //Get public async Task<List<Product_Unit>> GetProduct_Units(int? companyId) { if (companyId == null) return null; List<Product_Unit> units = await _context.Product_Units.Where(w => w.CompanyId == companyId).ToListAsync(); return units; } public async Task<List<Tax>> GetTaxs(int? companyId) { if (companyId == null) return null; List<Tax> taxes = await _context.Taxes.Where(w => w.CompanyId == companyId).ToListAsync(); return taxes; } public async Task<Tax> GetEditTax(int? companyId, int? taxId) { if (companyId == null) return null; if (taxId == null) return null; Tax tax = await _context.Taxes.FirstOrDefaultAsync(f => f.Id == taxId && f.CompanyId == companyId); if (tax == null) return null; return tax; } //Post public async Task<Tax> CreateTax(Tax tax, int? companyId) { if (companyId == null) return null; if (tax == null) return null; tax.CompanyId = Convert.ToInt32(companyId); await _context.Taxes.AddAsync(tax); await _context.SaveChangesAsync(); return tax; } //Check public async Task<bool> CheckUnit(int? currentUserId, int? companyId) { if (currentUserId == null) return true; if (companyId == null) return true; if (await _context.Product_Units.AnyAsync(a => a.CompanyId == companyId && a.Company.UserId != currentUserId)) return true; return false; } public async Task<bool> CheckTax(int? currentUserId, int? companyId) { if (currentUserId == null) return true; if (companyId == null) return true; if (await _context.Taxes.AnyAsync(a => a.CompanyId == companyId && a.Company.UserId != currentUserId)) return true; return false; } //Put public async Task<Tax> UpdateTax(Tax tax) { if (tax == null) return null; _context.Entry(tax).State = EntityState.Modified; _context.Entry(tax).Property(a => a.CompanyId).IsModified = false; await _context.SaveChangesAsync(); return tax; } public async Task<Tax> DeleteTax(int? companyId, int? taxId) { if (companyId == null) return null; Tax tax = await _context.Taxes.FirstOrDefaultAsync(f => f.CompanyId == companyId && f.Id == taxId); tax.IsDeleted = true; await _context.SaveChangesAsync(); return tax; } } } <file_sep>/AccountingApi/Models/ProcudureDto/ExpenseInvoiceReportByContragentIdDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models.ProcudureDto { public class ExpenseInvoiceReportByContragentIdDto { public string ExpenseInvoiceNumber { get; set; } public double? TotalPrice { get; set; } public DateTime? PreparingDate { get; set; } public DateTime? EndDate { get; set; } } } <file_sep>/AccountingApi/Data/Repository/Interface/IUserRepository.cs using AccountingApi.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Data.Repository.Interface { public interface IUserRepository { Task<Company> CreateCompany(Company companyCreate, int userId); Task<Company> GetEditCompany(int? companyId); Task<Company> EditCompany(Company companyEdit); Task<List<Company>> GetCompany(int? userId); Task<Company> GetCompanyById(int? userId, int? companyId); //Get EditUser Task<User> GetEditUser(int? userId); //Put User Task<User> EditUser(User user, string password); //Check: bool CheckOldPassword(string OldPassword, int? userId); } } <file_sep>/AccountingApi/Dtos/Purchase/Expense/ExpenseItemPostDto.cs using System; namespace AccountingApi.Dtos.Purchase.Expense { public class ExpenseItemPostDto { public int ExpenseInvoiceId { get; set; } public string InvoiceNumber { get; set; } public double? TotalOneInvoice { get; set; } public bool IsBank { get; set; } public double? PaidMoney { get; set; } public double? Residue { get; set; } public int? AccountDebitId { get; set; } public int? AccountKreditId { get; set; } public DateTime? Date { get; set; } } } <file_sep>/AccountingApi/Controllers/V1/EmployeeController.cs using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using AccountingApi.Data.Repository.Interface; using AccountingApi.Dtos.Nomenklatura.Worker; using AccountingApi.Helpers.Extentions; using AccountingApi.Models; using AutoMapper; using EOfficeAPI.Helpers.Extentions; using EOfficeAPI.Helpers.Pagination; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace AccountingApi.Controllers.V1 { [Authorize] [Route("api/[controller]")] [ApiController] public class EmployeeController : ControllerBase { private readonly INomenklaturaRepository _repo; private readonly IMapper _mapper; public EmployeeController(INomenklaturaRepository repo, IMapper mapper) { _repo = repo; _mapper = mapper; } //Post [baseUrl]/api/employee/addworker [HttpPost] [Route("addworker")] public async Task<IActionResult> AddWorker(WorkerPostDto vwWorker, [FromHeader]int? companyId) { //Check #region Check if (vwWorker == null) return StatusCode(409, "object null"); int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.Checkworker(currentUserId, companyId)) return Unauthorized(); //if (!ModelState.IsValid) // return BadRequest(); #endregion //workerpostdto mapping class worker Worker worker = _mapper.Map<Worker>(vwWorker); //mapped worker class sending in create repo Worker workerToGet = await _repo.CreateWorker(worker, companyId); //return added worker object WorkerGetDto workerForReturn = _mapper.Map<WorkerGetDto>(workerToGet); //Worker_Detail Worker_Detail worker_Details = _mapper.Map<Worker_Detail>(vwWorker); Worker_Detail worker_DetailToGet = await _repo.CreateWorker_Detail(worker_Details, worker.Id); return Ok(workerForReturn); } //Get [baseUrl]/api/employee/getworkers [HttpGet] [Route("getworkers")] // pagination yazilmsdi public async Task<IActionResult> GetWorkers([FromQuery]PaginationParam workerParam, [FromHeader]int? companyId) { //Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.Checkworker(currentUserId, companyId)) return Unauthorized(); /////////////////////////////////////////////////////////////////////////////////// //iscileri sirkete gore getirmek var workers = await _repo.GetWorkers(workerParam, companyId); //gelen datani dto ya yazmaq var workersToReturn = _mapper.Map<IEnumerable<WorkerGetDto>>(workers); //sehifelenme Response.AddPagination(workers.CurrentPage, workers.PageSize, workers.TotalCount, workers.TotalPages); return Ok(workersToReturn); } //deyisilik etmek ucun iscini getiririk [HttpGet()] [Route("geteditworker")] public async Task<IActionResult> GetEditWorker([FromHeader]int? workerId, [FromHeader]int? companyId) { //Check #region Check if (workerId == null) return BadRequest("workerId null"); int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.Checkworker(currentUserId, companyId)) return Unauthorized(); if (await _repo.CheckWorkerId(workerId, companyId)) return StatusCode(406, "Not Acceptable"); #endregion /////////////////////////////////////////////////////////////////////////////////// //iscini sirkete gore getirmek Worker worker = await _repo.GetEditWorker(workerId, companyId); //iscini elave melumatlarini getirmek Worker_Detail worker_Detail = await _repo.GetEditWorkerDetail(workerId); //2 obyekti bir obyekte birlesdirmek var workerToReturn = _mapper.MergeInto<WorkerEditDto>(worker, worker_Detail); return Ok(workerToReturn); } //deyismek [HttpPut] [Route("updateworker")] //Update zamani bu metodla dolduracayiq public async Task<IActionResult> UpdateWorker([FromBody]WorkerPutDto workerPut, [FromHeader]int? workerId, [FromHeader] int? companyId) { //Ckeck #region Check if (!ModelState.IsValid) return BadRequest(); if (workerPut == null) return StatusCode(409, "object null"); if (workerId == null) return StatusCode(409, "workerId null"); int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.Checkworker(currentUserId, companyId)) return Unauthorized(); #endregion /////////////////////////////////////////////////////////////////////////////////// //repoya id gonderirik ve o bize lazim olan iscini ve detail-ni getirir. Worker worker_FromRepo = await _repo.GetEditWorker(workerId, companyId); Worker_Detail Detail_FromRepo = await _repo.GetEditWorkerDetail(workerId); //mapp olunmus isci Worker workerMapped = _mapper.Map(workerPut, worker_FromRepo); //repoda iscini yenileyirik Worker updatedWorker = await _repo.EditWorker(worker_FromRepo, workerId); //qaytarmaq ucun WorkerGetDto workToReturn = _mapper.Map<WorkerGetDto>(updatedWorker); //iscilerin elave melumatlari //mapp olunmus iscinin detaili Worker_Detail worker_DetailToMapped = _mapper.Map(workerPut, Detail_FromRepo); //repoda iscini yenileyirik Worker_Detail updatedWorker_Detail = await _repo.EditWorker_Detail(Detail_FromRepo, workerId); return Ok(workToReturn); } [HttpGet] [Route("deleteworker")] public async Task<IActionResult> DeleteWorker([FromHeader]int? workerId, [FromHeader]int? companyId) { //Ckeck #region Check if (workerId == null) return StatusCode(409, "workerId null"); int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.Checkworker(currentUserId, companyId)) return Unauthorized(); #endregion Worker Deletedworker = await _repo.DeleteWorker(workerId, companyId); WorkerGetDto DeletedWorkerToReturn = _mapper.Map<WorkerGetDto>(Deletedworker); return Ok(); } } }<file_sep>/AccountingApi/Dtos/Sale/Invoice/InvoiceGetDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Sale.Invoice { public class InvoiceGetDto { public int Id { get; set; } public string InvoiceNumber { get; set; } public DateTime? PreparingDate { get; set; } public DateTime? EndDate { get; set; } public double? TotalPrice { get; set; } //contragent companyname public string ContragentCompanyName { get; set; } public byte IsPaid { get; set; } } } <file_sep>/AccountingApi/Dtos/Purchase/Expense/ExpenseItemInvoiceGetDto.cs using System; namespace AccountingApi.Dtos.Purchase.Expense { public class ExpenseItemInvoiceGetDto { public int Id { get; set; } public bool IsBank { get; set; } public double? PaidMoney { get; set; } public DateTime ExpenseCreatedAt { get; set; } public double? TotalOneInvoice { get; set; } public int? AccountDebitId { get; set; } public int? AccountKreditId { get; set; } public DateTime? Date { get; set; } } } <file_sep>/AccountingApi/Dtos/Sale/Invoice/InvoiceEditGetDto.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; namespace AccountingApi.Dtos.Sale.Invoice { public class InvoiceEditGetDto { public string InvoiceNumber { get; set; } public DateTime? PreparingDate { get; set; } public DateTime? EndDate { get; set; } public double? TotalPrice { get; set; } public double? TotalTax { get; set; } public double? Sum { get; set; } public int? ContragentId { get; set; } public int? TaxId { get; set; } public double? TaxRate { get; set; } public int? AccountDebitId { get; set; } public int? AccountKreditId { get; set; } //company public string CompanyCompanyName { get; set; } public string CompanyVOEN { get; set; } //contragent public string ContragentCompanyName { get; set; } public string ContragentVoen { get; set; } //AccountPlan public string AccountsPlanDebitAccPlanNumber { get; set; } public string AccountsPlanKreditAccPlanNumber { get; set; } public string AccountsPlanDebitName { get; set; } public string AccountsPlanKreditName { get; set; } public ICollection<InvoiceItemGetDto> InvoiceItemGetDtos { get; set; } public InvoiceEditGetDto() { InvoiceItemGetDtos = new Collection<InvoiceItemGetDto>(); } } } <file_sep>/AccountingApi/Controllers/V1/IncomeController.cs using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using AccountingApi.Data.Repository.Interface; using AccountingApi.Dtos.Sale.Income; using AccountingApi.Models; using AccountingApi.Models.ViewModel; using AutoMapper; using EOfficeAPI.Helpers.Pagination; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace AccountingApi.Controllers.V1 { [Authorize] [Route("api/[controller]")] [ApiController] public class IncomeController : ControllerBase { private readonly ISaleRepository _repo; private readonly IMapper _mapper; public IncomeController(ISaleRepository repo, IMapper mapper) { _repo = repo; _mapper = mapper; } //Get [baseUrl]/api/income/getinvoicebycontragentid [HttpGet] [Route("getinvoicebycontragentid")] public IActionResult GetInvoiceByContragentId([FromHeader]int? contragentId, [FromHeader] int? companyId) { if (contragentId == null) return StatusCode(409, "contragentId null"); var invoice = _repo.GetInvoiceByContragentId(contragentId, companyId); var invoiceToReturn = _mapper.Map<IEnumerable<IncomeInvoiceGetDto>>(invoice); return Ok(invoice); } //Get [baseUrl]/api/income/getincome [HttpGet] [Route("getincome")] public async Task<IActionResult> GetIncome([FromQuery]PaginationParam productParam, [FromHeader]int? companyId) { //Checking #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckIncome(currentUserId, companyId)) return Unauthorized(); #endregion //Repo Get var invoices = await _repo.GetIncome(productParam, companyId); //Mapped object var invoiceToReturn = _mapper.Map<IEnumerable<IncomeGetDto>>(invoices); return Ok(invoices); } // get edit income //Get [baseUrl]/api/income/geteditincome [HttpGet] [Route("geteditincome")] public async Task<IActionResult> GetEditIncome([FromHeader] int? companyId, [FromHeader] int? invoiceId) { //Repo Get //var incomeItemsinvoices = await _repo.GetEditAllIncomes(companyId,invoiceId); var incomeItemsinvoices = await _repo.GetInvoiceIcomeItem(companyId, invoiceId); //Check #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckIncome(currentUserId, companyId)) return Unauthorized(); if (incomeItemsinvoices == null) return StatusCode(406, "content null"); #endregion // Mapped object var ToReturn = _mapper.Map<IncomeInvoiceEditGetDto>(incomeItemsinvoices); return Ok(ToReturn); } //Get [baseUrl]/api/income/getdetailincome [HttpGet] [Route("getdetailincome")] public async Task<IActionResult> GetDetailIncome([FromHeader] int? companyId, [FromHeader] int? incomeId) { //Checking #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckIncome(currentUserId, companyId)) return Unauthorized(); #endregion var invoices = await _repo.DetailIncome(incomeId, companyId); // Mapped object var ToReturn = _mapper.Map<IncomeEditGetDto>(invoices); return Ok(ToReturn); } //Post [baseUrl]/api/income/createincome [HttpPost] [Route("createincome")] public async Task<IActionResult> CreateIncome([FromHeader] int? companyId, [FromHeader] int? contragentId, [FromBody]VwCreateIncome createIncome) { if (companyId == null) return StatusCode(409, "companyId null"); if (contragentId == null) return StatusCode(409, "contragentId null"); //mapped income var mappedIncome = _mapper.Map<Income>(createIncome.IncomePostDto); //mapped incomeitems var mappedIncomeItem = _mapper.Map<List<IncomeItem>>(createIncome.IncomeItemPostDtos); //Check: #region Check //checking incomeitems paidmoney big than invoice total price if (await _repo.CheckIncomeEqualingInvoiceTotalPriceForCreate(mappedIncomeItem)) return StatusCode(411, "paidmoney big than totalmoney or one invoiceId doesnt exist"); int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (await _repo.CheckIncome(currentUserId, companyId)) return Unauthorized(); // id-sinin <NAME>. if (await _repo.CheckIncomeContragentIdInvoiceId(contragentId, companyId)) return StatusCode(409, "contragentId doesnt exist"); if (_repo.CheckIncomeNegativeValue(mappedIncome, mappedIncomeItem)) return StatusCode(428, "negative value is detected"); #endregion var FromRepoIncomes = await _repo.CreateIncome(companyId, contragentId, createIncome.Ids, mappedIncome, mappedIncomeItem); return Ok(FromRepoIncomes); } //Put [baseUrl]/api/income/updateincome [HttpPut] [Route("updateincome")] public async Task<IActionResult> UpdateIncome(VwIncomePut incomePut, [FromHeader] int? companyId, [FromHeader] int? invoiceId, [FromHeader] int? incomeId) { //Get edit income //didnt use yet Income fromRepo = await _repo.GetEditIncome(incomeId, companyId); //Get edit incomeitems List<IncomeItem> incomeItemsRepo = await _repo.GetEditIncomeItems(incomeId); //mapping income Income Mapped = _mapper.Map(incomePut.IncomePutDto, fromRepo); //mapping incomeitems //doesnt work correctly List<IncomeItem> incomeItemsMapped = _mapper.Map(incomePut.IncomeItemGetEditDtos, incomeItemsRepo); //Check: #region Check int? currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value); if (companyId == null) return StatusCode(409, "companyId null"); if (currentUserId == null) return Unauthorized(); if (invoiceId == null) return StatusCode(409, "invocieId null"); if (incomePut.IncomeItemGetEditDtos == null) return StatusCode(409, "incomeitems null"); if (await _repo.CheckIncome(currentUserId, companyId)) return Unauthorized(); if (await _repo.CheckIncomeEqualingInvoiceTotalPriceForUpdate(incomePut.IncomeItemGetEditDtos)) return StatusCode(411, "paidmoney big than totalmoney or that invoice doesn't exist"); if (_repo.CheckIncomeUpdateNegativeValue(incomePut.IncomeItemGetEditDtos)) return StatusCode(428, "negative value is detected"); #endregion //Accounting var UpdateAccountDebit = _repo.UpdateIncomeAccountDebit(companyId, incomePut.IncomeItemGetEditDtos); var UpdateAccountKredit = _repo.UpdateIncomeAccountKredit(companyId, incomePut.IncomeItemGetEditDtos); //Put income and inomeitems var income = await _repo.EditIncome( incomePut.IncomeItemGetEditDtos,invoiceId); return Ok(); } //Delete [baseUrl]/api/income/deleteincomeitem [HttpDelete] [Route("deleteincomeitem")] public async Task<IActionResult> DeleteIncomeItem([FromHeader] int? incomeItemId) { if (incomeItemId == null) return StatusCode(409, "incomeItemId null"); await _repo.DeleteIncomeItem(incomeItemId); return Ok(); } } }<file_sep>/AccountingApi/Data/Repository/AccountRepository.cs using AccountingApi.Data.Repository.Interface; using AccountingApi.Models.ProcudureDto; using AccountingApi.Models.ProcudureDto.ParamsObject; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Data.Repository { public class AccountRepository : IAccountRepository { private readonly DataContext _context; public AccountRepository(DataContext context) { _context = context; } //Return İncome sum //Income Report public async Task<IncomeFromQueryDto> ReportQueryByCompanyId(ReportFilter reportFilter, int? companyId) { var incomeFromQuery = await _context.InExReportQuery .FromSql("exec GetIncome {0},{1},{2},{3}", companyId, reportFilter.IsPaid, reportFilter.StartDate, reportFilter.EndDate).FirstOrDefaultAsync(); return incomeFromQuery; } //Return Expense sum //Expense Report public async Task<ExFromQueryDtoDto> ReportExpenseQueryByCompanyId(ReportFilter reportFilter, int? companyId) { var exFromQuery = await _context.ExFromQuery .FromSql("exec GetExpenseReport {0},{1},{2},{3}", companyId, reportFilter.IsPaid, reportFilter.StartDate, reportFilter.EndDate).FirstOrDefaultAsync(); return exFromQuery; } //List Incomes Report public async Task<List<IncomeReportDto>> IncomesQueryByCompanyId(ReportFilter reportFilter, int? companyId) { var incomeReports = await _context.IncomesFromQuery .FromSql("exec GetIncomesReport {0},{1},{2},{3}", companyId, reportFilter.IsPaid, reportFilter.StartDate, reportFilter.EndDate).ToListAsync(); return incomeReports; } // List Expenses Report public async Task<List<ExpenseReportDto>> ExpensesQueryByCompanyId(ReportFilter reportFilter, int? companyId) { var expenseReports = await _context.ExpensesFromQuery .FromSql("exec GetExpensesReport {0},{1},{2},{3}", companyId, reportFilter.IsPaid, reportFilter.StartDate, reportFilter.EndDate).ToListAsync(); return expenseReports; } //List Products Limited 4 Report public async Task<List<ProductsReportDto>> ProductsQueryByCompanyId(int? companyId, int? DateUntil) { var productsReports = await _context.ProductsFromQuery .FromSql("exec GetProductsCount {0},{1}", companyId, DateUntil).ToListAsync(); List<ProductsReportDto> productsReportDtos = new List<ProductsReportDto>(); for (int i = 0; i < productsReports.Count; i++) { ProductsReportDto products = new ProductsReportDto { Name = productsReports[i].Name, PercentOfTotal = productsReports[i].PercentOfTotal, SumQty = productsReports[i].SumQty, }; productsReportDtos.Add(products); } return productsReportDtos; } //Invoice Report By Paid Status public async Task<List<InvoiceReportDto>> InvoiceReportQueryByCompanyId(int? companyId, int? DateUntil) { var invoiceReports = await _context.InvoiceFromQuery .FromSql("exec InvoiceReport {0},{1}", companyId, DateUntil).ToListAsync(); List<InvoiceReportDto> invoiceReportDtos = new List<InvoiceReportDto>(); for (int i = 0; i < invoiceReports.Count; i++) { InvoiceReportDto invoice = new InvoiceReportDto(); switch (invoiceReports[i].IsPaid) { case 1: invoice.Status = "Gözləmədə"; break; case 2: invoice.Status = "Qismən"; break; case 3: invoice.Status = "Ödənilib"; break; case 4: invoice.Status = "Ödənilməyib"; break; default: invoice.Status = "yoxdu"; break; } invoice.Total = invoiceReports[i].Total; invoice.IsPaid = invoiceReports[i].IsPaid; invoiceReportDtos.Add(invoice); } return invoiceReportDtos; } //Expense Report By Paid Status public async Task<List<ExpenseInvoiceReportDto>> ExpenseInvoiceReportQueryByCompanyId(int? companyId, int? DateUntil) { var invoiceReports = await _context.ExpenseInvoiceFromQuery .FromSql("exec ExpenseInvoiceReport {0},{1}", companyId, DateUntil).ToListAsync(); List<ExpenseInvoiceReportDto> invoiceReportDtos = new List<ExpenseInvoiceReportDto>(); for (int i = 0; i < invoiceReports.Count; i++) { ExpenseInvoiceReportDto invoice = new ExpenseInvoiceReportDto(); switch (invoiceReports[i].IsPaid) { case 1: invoice.Status = "Gözləmədə"; break; case 2: invoice.Status = "Qismən"; break; case 3: invoice.Status = "Ödənilib"; break; case 4: invoice.Status = "Ödənilməyib"; break; default: invoice.Status = "yoxdu"; break; } invoice.Total = invoiceReports[i].Total; invoice.IsPaid = invoiceReports[i].IsPaid; invoiceReportDtos.Add(invoice); } return invoiceReportDtos; } //Contragent Report public async Task<List<ContragentFromQueryDto>> ContragentReportQueryByCompanyId(int? companyId, int? DateUntil) { var contragentReports = await _context.ContragentFromQuery .FromSql("exec ContragentsReport {0},{1}", companyId, DateUntil).ToListAsync(); //Globalization var culture = new System.Globalization.CultureInfo("az"); foreach (var data in contragentReports) { //Changing data monthnumber monnth name string monthName = culture.DateTimeFormat.GetMonthName(data.MonthNumber ?? 0); data.MonthName = monthName; } return contragentReports; } //Worker Report public async Task<List<WorkerFromQueryDto>> WorkerReportQueryByCompanyId(int? companyId, int? DateUntil) { var workerReports = await _context.WorkerFromQuery .FromSql("exec WorkerReport {0},{1}", companyId, DateUntil).ToListAsync(); //Globalization var culture = new System.Globalization.CultureInfo("az"); foreach (var data in workerReports) { //Changing data monthnumber monnth name string monthName = culture.DateTimeFormat.GetMonthName(data.MonthNumber ?? 0); data.MonthName = monthName; } return workerReports; } //NetIncome Report public async Task<List<NetIncomeFromQueryDto>> NetIncomeReportQueryByCompanyId(int? companyId, int? DateUntil) { var netReports = await _context.NetIncomeFromQuery .FromSql("exec GetNetIncomeReport {0},{1}", companyId, DateUntil).ToListAsync(); return netReports; } //InvoiceReportByContragent public async Task<List<InvoiceReportByContragentDto>> InvoiceReportByContragents(int? companyId) { var Reports = await _context.invoiceReportByContragents .FromSql("exec InvoiceReportByContragent {0}", companyId).ToListAsync(); return Reports; } //ProductAll public async Task<List<ProductAllDto>> ProductAll(int? companyId, ReportFilter reportFilter) { var Reports = await _context.ProductAllDtoQuery .FromSql("exec GetProductsAllCount {0}", companyId, reportFilter.StartDate, reportFilter.EndDate).ToListAsync(); return Reports; } //ExpenseInvoiceReportByContragent public async Task<List<ExpenseInvoiceReportByContragentDto>> ExpenseInvoiceReportByContragents(int? companyId) { var Reports = await _context.ExpenseInvoiceReportByContragents .FromSql("exec ExpenseInvoiceReportByContragent {0}", companyId).ToListAsync(); return Reports; } //ProductAllExpense public async Task<List<ProductExpenseAllDto>> ProductAllExpense(int? companyId, ReportFilter reportFilter) { var Reports = await _context.ProductExpenseAllQuery .FromSql("exec GetProductsAllCountByExpense {0},{1},{2}", companyId, reportFilter.StartDate, reportFilter.EndDate).ToListAsync(); return Reports; } //GetInvoiceProductCountById public async Task<List<GetInvoiceProductCountByIdDto>> GetInvoiceProductCountById(int? companyId, int? productId) { var Reports = await _context.GetInvoiceProductCountByIdQuery .FromSql("exec GetInvoiceProductCountById {0},{1}", companyId, productId).ToListAsync(); return Reports; } //InvoicesReportByContragentId public async Task<List<InvoicesReportByContragentIdDto>> InvoicesReportByContragentId(int? companyId, int? contragentId) { var Reports = await _context.InvoicesReportByContragentIdQuery .FromSql("exec InvoicesReportByContragentId {0},{1}", companyId, contragentId).ToListAsync(); return Reports; } //GetExpenseInvoiceProductCountById public async Task<List<GetExpenseInvoiceProductCountByIdDto>> GetExpenseInvoiceProductCountById(int? companyId, int? productId) { var Reports = await _context.GetExpenseInvoiceProductCountByIdQuery .FromSql("exec GetExpenseInvoiceProductCountById {0},{1}", companyId, productId).ToListAsync(); return Reports; } //ExpenseInvoiceReportByContragentId public async Task<List<ExpenseInvoiceReportByContragentIdDto>> ExpenseInvoiceReportByContragentId(int? companyId, int? contragentId) { var Reports = await _context.ExpenseInvoiceReportByContragentIdQuery .FromSql("exec ExpenseInvoiceReportByContragentId {0},{1}", companyId, contragentId).ToListAsync(); return Reports; } } } <file_sep>/AccountingApi/Dtos/Nomenklatura/Kontragent/ContragentGetDto.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Nomenklatura.Kontragent { public class ContragentGetDto { public int Id { get; set; } public string PhotoUrl { get; set; } public string CompanyName { get; set; } public string Fullname { get; set; } public string Phone { get; set; } public string Email { get; set; } public bool IsCostumer { get; set; } public string VOEN { get; set; } } } <file_sep>/AccountingApi/Dtos/Sale/Income/IncomeItemGetEditDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Sale.Income { public class IncomeItemGetEditDto { //public string InvoiceNumber { get; set; } //public double? TotalOneInvoice { get; set; } public int Id { get; set; } public bool IsBank { get; set; } public double? PaidMoney { get; set; } public double? Residue { get; set; } public int InvoiceId { get; set; } public int? AccountDebitId { get; set; } public int? AccountKreditId { get; set; } //public int IncomeId { get; set; } } } <file_sep>/AccountingApi/Dtos/Purchase/Expense/ExpenseExInvoiceEditGetDto.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Purchase.Expense { public class ExpenseExInvoiceEditGetDto { public double? ResidueForCalc { get; set; } public int Id { get; set; } public string ContragentCompanyName { get; set; } public ICollection<ExpenseItemInvoiceGetDto> ExpenseItemInvoiceGetDtos { get; set; } public ExpenseExInvoiceEditGetDto() { ExpenseItemInvoiceGetDtos = new Collection<ExpenseItemInvoiceGetDto>(); } } } <file_sep>/AccountingApi/Models/Tax.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models { public class Tax { [Key] public int Id { get; set; } [MaxLength(75)] public string Name { get; set; } public double Rate { get; set; } public bool IsDeleted { get; set; } = false; public int CompanyId { get; set; } public virtual Company Company { get; set; } public virtual ICollection<Proposal> Proposals { get; set; } public virtual ICollection<Invoice> Invoices { get; set; } public virtual ICollection<ExpenseInvoice> ExpenseInvoices { get; set; } } } <file_sep>/AccountingApi/Models/ProcudureDto/WorkerTotalWorkerFromQueryDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models.ProcudureDto { public class WorkerTotalWorkerFromQueryDto { public int? TotalWorkerCount { get; set; } } } <file_sep>/AccountingApi/Dtos/Sale/Income/IncomeEditGetDto.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Sale.Income { public class IncomeEditGetDto { public int Id { get; set; } //contragent public string ContragentCompanyName { get; set; } public string ContragentFullname { get; set; } public double? TotalPrice { get; set; } public ICollection<IncomeItemGetDto> IncomeItemGetDtos { get; set; } public IncomeEditGetDto() { IncomeItemGetDtos = new Collection<IncomeItemGetDto>(); } } } <file_sep>/AccountingApi/Models/ProcudureDto/IncomeReportDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models.ProcudureDto { public class IncomeReportDto { public string InvoiceNumber { get; set; } //contragent public string CompanyName { get; set; } public double? Total { get; set; } } } <file_sep>/AccountingApi/Dtos/AccountsPlan/AccountsPlanGetDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.AccountsPlan { public class AccountsPlanGetDto { public int Id { get; set; } public string AccPlanNumber { get; set; } public string Name { get; set; } public Nullable<int> Level { get; set; } public string Category { get; set; } } } <file_sep>/AccountingApi/Data/Repository/Interface/IPurchaseRepository.cs using AccountingApi.Dtos.Purchase.Expense; using AccountingApi.Dtos.Purchase.ExpenseInvoice; using AccountingApi.Models; using EOfficeAPI.Helpers.Pagination; using System.Collections.Generic; using System.Threading.Tasks; namespace AccountingApi.Data.Repository.Interface { public interface IPurchaseRepository { //ExpenseInvoice #region ExpenseInvoice //Post Task<ExpenseInvoice> CreateInvoice(ExpenseInvoice invoice, int? companyId); Task<List<ExpenseInvoiceItem>> CreateInvoiceItems(List<ExpenseInvoiceItem> items, int? invoiceId); //Check #region Check Task<bool> CheckExpenseInvoice(int? currentUserId, int? companyId); Task<bool> CheckExpenseInvoiceProductId(List<ExpenseInvoiceItem> invoiceItems); Task<bool> CheckExpenseInvoiceId(int? invoiceId, int? companyId); bool CheckInvoiceNegativeValue(ExpenseInvoice invoice, List<ExpenseInvoiceItem> items); Task<bool> CheckExpenseInvoiceItem(int? invoiceId, List<ExpenseInvoiceItem> invoiceItems); #endregion //Get Task<List<ExpenseInvoiceGetDto>> GetInvoice(PaginationParam productParam, int? companyId); //get for edit invoice by id Task<ExpenseInvoice> GetEditInvoice(int? invoiceId, int? companyId); Task<List<ExpenseInvoiceItem>> GetEditInvoiceItem(int? invoiceId); Task<ExpenseInvoice> GetDetailInvoice(int? invoiceId, int? companyId); Task<Contragent> GetContragentInvoice(int? companyId, int? invoiceId); //Put // edit edit by id Task<ExpenseInvoice> EditInvoice(ExpenseInvoice invoice, List<ExpenseInvoiceItem> invoiceItems, int? invoiceId); Task<ExpenseInvoiceItem> DeleteInvoiceItem(int? invoiceItemId); Task<ExpenseInvoice> DeleteInvoice(int? companyId, int? invoiceId); //Accounting Update ExpenseInvoicePutDto UpdateInvoiceAccountDebit(int? invoiceId, int? companyId, ExpenseInvoicePutDto invoice, int? OldDebitId); ExpenseInvoicePutDto UpdateInvoiceAccountKredit(int? invoiceId, int? companyId, ExpenseInvoicePutDto invoice, int? OldKeditId); #endregion //Expense #region Expense //Get: List<ExpenseExInvoiceGetDto> GetExpenseInvoiceByContragentId(int? contragentId, int? companyId); Task<List<ExpenseGetDto>> GetExpense(PaginationParam productParam, int? companyId); Task<ExpenseInvoice> GetExpenseExpenseItem(int? companyId, int? invoiceId); Task<Expense> GetEditExpense(int? expenseId, int? companyId); Task<List<ExpenseItem>> GetEditExpenseItems(int? invoiceId); //Post: Task<Expense> CreateExpense(int? companyId, int? contragentId, Expense expense, List<ExpenseItem> expenseItems); //Put: Task<ExpenseItem> EditExpense(List<ExpenseItemGetDto> itemGetDtos, int? invoiceId); //Check: #region Check Task<bool> CheckExpense(int? currentUserId, int? companyId); Task<bool> CheckExpenseEqualingInvoiceTotalPriceForUpdate(List<ExpenseItemGetDto> expenseItems); Task<bool> CheckExpenseEqualingInvoiceTotalPriceForCreate(List<ExpenseItem> incomeItems); Task<bool> CheckIncomeContragentIdInvoiceId(int? contragentId, int? companyId); bool CheckExpenseNegativeValue(Expense expense, List<ExpenseItem> expenses); bool CheckExpenseUpdateNegativeValue(List<ExpenseItemGetDto> expenses); #endregion //Account: List<ExpenseItemGetDto> UpdateExpenseAccountDebit(int? companyId, List<ExpenseItemGetDto> incomeItem); List<ExpenseItemGetDto> UpdateExpenseAccountKredit(int? companyId, List<ExpenseItemGetDto> incomeItem); //Delete: Task<ExpenseItem> DeleteExpenseItem(int? expenseItemId); #endregion } } <file_sep>/AccountingApi/Dtos/Sale/Income/IncomeGetDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Sale.Income { public class IncomeGetDto { public int Id { get; set; } public DateTime CreatedAt { get; set; } public string InvoiceNumber { get; set; } //contragent public string ContragentCompanyName { get; set; } public string ContragentFullname { get; set; } public double? TotalPrice { get; set; } public bool IsBank { get; set; } public double? PaidMoney { get; set; } public double? Residue { get; set; } public int InvoiceId { get; set; } public double? SumPaidMoney { get; set; } public double? TotalOneInvoice { get; set; } public DateTime? Date { get; set; } public int? AccountDebitId { get; set; } public int? AccountKreditId { get; set; } } } <file_sep>/AccountingApi/Dtos/AccountsPlan/ManualJournalPostDto.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.AccountsPlan { public class ManualJournalPostDto { [MaxLength(300)] public string JurnalNumber { get; set; } [MaxLength(300)] public string JurnalName { get; set; } public DateTime? Date { get; set; } [MaxLength(300)] public string Desc { get; set; } public double? Price { get; set; } public int? ContragentId { get; set; } public int CompanyId { get; set; } public int? AccountDebitId { get; set; } public int? AccountKreditId { get; set; } public int? OperationCategoryId { get; set; } } } <file_sep>/AccountingApi/Dtos/Nomenklatura/Worker/WorkerPutDto.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Nomenklatura.Worker { public class WorkerPutDto { [MaxLength(75)] public string Name { get; set; } [MaxLength(75)] public string SurName { get; set; } [MaxLength(75)] public string Positon { get; set; } [Required] public double Salary { get; set; } [MaxLength(75)] public string Departament { get; set; } [MaxLength(75)] public string PartofDepartament { get; set; } [MaxLength(75)] public string Role { get; set; } public string PhotoFile { get; set; } public bool IsState { get; set; } public string Voen { get; set; } [MaxLength(75)] public string FatherName { get; set; } [MaxLength(75)] public string Email { get; set; } [MaxLength(75)] public string Adress { get; set; } [MaxLength(75)] public string DSMF { get; set; } [MaxLength(75)] public string Phone { get; set; } [MaxLength(75)] public string MobilePhone { get; set; } [MaxLength(75)] public string Education { get; set; } [MaxLength(75)] public string EducationLevel { get; set; } public string Gender { get; set; } public DateTime? Birthday { get; set; } } } <file_sep>/AccountingApi/Models/AccountsPlan.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models { public class AccountsPlan { [Key] public int Id { get; set; } [MaxLength(100)] public string AccPlanNumber { get; set; } [MaxLength(350)] public string Name { get; set; } public Nullable<bool> Active { get; set; } public Nullable<int> Level { get; set; } [MaxLength(350)] public string Obeysto { get; set; } [MaxLength(350)] public string Category { get; set; } public Nullable<bool> ContraAccount { get; set; } public Nullable<double> Debit { get; set; } public Nullable<double> Kredit { get; set; } public int CompanyId { get; set; } public Company Company { get; set; } [InverseProperty("AccountsPlanDebit")] public virtual ICollection<Invoice> InvoicesDebit { get; set; } [InverseProperty("AccountsPlanKredit")] public virtual ICollection<Invoice> InvoicesKredit { get; set; } [InverseProperty("AccountsPlanDebit")] public virtual ICollection<IncomeItem> IncomeItemsDebit { get; set; } [InverseProperty("AccountsPlanKredit")] public virtual ICollection<IncomeItem> IncomeItemsKredit { get; set; } public virtual ICollection<BalanceSheet> BalanceSheets { get; set; } [InverseProperty("AccountsPlanDebit")] public virtual ICollection<ExpenseInvoice> ExpenseInvoicesDebit { get; set; } [InverseProperty("AccountsPlanKredit")] public virtual ICollection<ExpenseInvoice> ExpenseInvoicesKredit { get; set; } [InverseProperty("AccountsPlanDebit")] public virtual ICollection<ExpenseItem> ExpenseItemsDebit { get; set; } [InverseProperty("AccountsPlanKredit")] public virtual ICollection<ExpenseItem> ExpenseItemsKredit { get; set; } } } <file_sep>/AccountingApi/Models/ViewModel/VwExpenseInvoicePutDto.cs using AccountingApi.Dtos.Company; using AccountingApi.Dtos.Nomenklatura.Kontragent; using AccountingApi.Dtos.Purchase.ExpenseInvoice; using System.Collections.Generic; namespace AccountingApi.Models.ViewModel { public class VwExpenseInvoicePutDto { public ExpenseInvoicePutDto ExpenseInvoicePutDto { get; set; } public List<ExpenseInvoiceItemPutDto> ExpenseInvoiceItemPutDtos { get; set; } public CompanyPutProposalDto CompanyPutProposalDto { get; set; } public ContragentPutInProposalDto ContragentPutInProposalDto { get; set; } } } <file_sep>/AccountingApi/Dtos/Sale/Proposal/ProposalPutDto.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Sale.Proposal { public class ProposalPutDto { public string ProposalNumber { get; set; } public DateTime? PreparingDate { get; set; } public DateTime? EndDate { get; set; } public double? TotalPrice { get; set; } public double? Sum { get; set; } public double? TotalTax { get; set; } public string Desc { get; set; } public int? TaxId { get; set; } public int? ContragentId { get; set; } //public ICollection<ProposalItemPostDto> ProposalItemPostDtos { get; set; } //public ProposalPutDto() //{ // ProposalItemPostDtos = new Collection<ProposalItemPostDto>(); //} } } <file_sep>/AccountingApi/Models/Company.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models { public class Company { [Key] public int Id { get; set; } public string PhotoFile { get; set; } [MaxLength(150)] public string PhotoUrl { get; set; } [MaxLength(75)] public string CompanyName { get; set; } [MaxLength(75)] public string Name { get; set; } [MaxLength(75)] public string Surname { get; set; } [MaxLength(75)] public string Postion { get; set; } [MaxLength(75)] public string FieldOfActivity { get; set; } [MaxLength(100)] public string VOEN { get; set; } [MaxLength(50)] public string Country { get; set; } [MaxLength(75)] public string Street { get; set; } [MaxLength(20)] public string Phone { get; set; } [MaxLength(20)] public string Mobile { get; set; } [MaxLength(30)] public string Website { get; set; } [MaxLength(30)] public string Linkedin { get; set; } [MaxLength(30)] public string Facebok { get; set; } [MaxLength(30)] public string Instagram { get; set; } [MaxLength(30)] public string Behance { get; set; } [MaxLength(50)] public string City { get; set; } [MaxLength(100)] public string Email { get; set; } public bool IsCompany { get; set; } = true; public DateTime CreatedAt { get; set; } = DateTime.Now; public bool IsDeleted { get; set; } = false; public int UserId { get; set; } public virtual User User { get; set; } public virtual ICollection<Tax> Taxes { get; set; } public virtual ICollection<Worker> Workers { get; set; } public virtual ICollection<Product> Products { get; set; } public virtual ICollection<Product_Unit> Product_Units { get; set; } public virtual ICollection<Contragent> Contragents { get; set; } public virtual ICollection<AccountsPlan> AccountsPlans { get; set; } public virtual ICollection<Proposal> Proposals { get; set; } public virtual ICollection<Invoice> Invoices { get; set; } public virtual ICollection<BalanceSheet> BalanceSheets { get; set; } public virtual ICollection<Income> Incomes { get; set; } public virtual ICollection<Expense> Expenses { get; set; } public virtual ICollection<ExpenseInvoice> ExpenseInvoices { get; set; } } } <file_sep>/AccountingApi/Data/Repository/AuthRepository.cs using AccountingApi.Data.Repository.Interface; using AccountingApi.Helpers; using AccountingApi.Models; using CryptoHelper; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Net.Mail; using System.Threading.Tasks; namespace AccountingApi.Data.Repository { public class AuthRepository: IAuthRepository { private readonly DataContext _context; public AuthRepository(DataContext context) { _context = context; } public async Task<bool> CompanyCount(int userId) { var count = await _context.Companies.CountAsync(a => a.UserId == userId); if (count == 1) { return true; } else { return false; } } public async Task<bool> CompanyCountForRegister(int userId) { int? count = await _context.Companies.CountAsync(a => a.UserId == userId); if (count == 0) return true; return false; } //Login: public async Task<User> Login(string email, string password) { var user = await _context.Users.FirstOrDefaultAsync(x => x.Email == email); if (user == null) return null; if (!CryptoHelper.Crypto.VerifyHashedPassword(user.Password, password)) return null; //IsPaid Status var userCompany = await _context.Companies.Where(w => w.UserId == user.Id).ToListAsync(); if (user == null) return null; return user; } //List of user companies public async Task<IEnumerable<Company>> UserCompanies(int? userId) { var userCompanies = await _context.Companies.Where(w => w.UserId == userId).ToListAsync(); return userCompanies; } //When registering return created company public async Task<Company> UserCompany(int? userId) { var userCompany = await _context.Companies.SingleOrDefaultAsync(w => w.UserId == userId); return userCompany; } //Register public async Task<User> Register(User user, string password) { user.Password = <PASSWORD>Helper.Crypto.HashPassword(user.Password); user.Token = CryptoHelper.Crypto.HashPassword(DateTime.Now.ToLongDateString() + user.Email); user.Status = true; await _context.Users.AddAsync(user); await _context.SaveChangesAsync(); //email gondermek //SendUserInviting(user.Id); return user; } //Check: public async Task<bool> UserExists(string email, string password) { var loginned = await _context.Users.FirstOrDefaultAsync(x => x.Email == email); if (!await _context.Users.AnyAsync(x => x.Email == email)) return true; if (!Crypto.VerifyHashedPassword(loginned.Password, password)) return true; return false; } //Check Already Exist User public async Task<bool> CheckUsersMail(string email) { if (await _context.Users.FirstOrDefaultAsync(u => u.Email == email) == null) return false; return true; } } } <file_sep>/AccountingApi/Data/Repository/Interface/IAccountRepository.cs using AccountingApi.Models.ProcudureDto; using AccountingApi.Models.ProcudureDto.ParamsObject; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Data.Repository.Interface { public interface IAccountRepository { Task<IncomeFromQueryDto> ReportQueryByCompanyId(ReportFilter reportFilter, int? companyId); Task<ExFromQueryDtoDto> ReportExpenseQueryByCompanyId(ReportFilter reportFilter, int? companyId); Task<List<IncomeReportDto>> IncomesQueryByCompanyId(ReportFilter reportFilter, int? companyId); Task<List<ExpenseReportDto>> ExpensesQueryByCompanyId(ReportFilter reportFilter, int? companyId); Task<List<ProductsReportDto>> ProductsQueryByCompanyId(int? companyId, int? DateUntil); Task<List<InvoiceReportDto>> InvoiceReportQueryByCompanyId(int? companyId, int? DateUntil); Task<List<ExpenseInvoiceReportDto>> ExpenseInvoiceReportQueryByCompanyId(int? companyId, int? DateUntil); Task<List<ContragentFromQueryDto>> ContragentReportQueryByCompanyId(int? companyId, int? DateUntil); Task<List<WorkerFromQueryDto>> WorkerReportQueryByCompanyId(int? companyId, int? DateUntil); Task<List<NetIncomeFromQueryDto>> NetIncomeReportQueryByCompanyId(int? companyId, int? DateUntil); Task<List<InvoiceReportByContragentDto>> InvoiceReportByContragents(int? companyId); Task<List<ProductAllDto>> ProductAll(int? companyId, ReportFilter reportFilter); Task<List<ExpenseInvoiceReportByContragentDto>> ExpenseInvoiceReportByContragents(int? companyId); Task<List<ProductExpenseAllDto>> ProductAllExpense(int? companyId, ReportFilter reportFilter); Task<List<GetInvoiceProductCountByIdDto>> GetInvoiceProductCountById(int? companyId, int? productId); Task<List<InvoicesReportByContragentIdDto>> InvoicesReportByContragentId(int? companyId, int? contragentId); Task<List<GetExpenseInvoiceProductCountByIdDto>> GetExpenseInvoiceProductCountById(int? companyId, int? productId); Task<List<ExpenseInvoiceReportByContragentIdDto>> ExpenseInvoiceReportByContragentId(int? companyId, int? contragentId); } } <file_sep>/AccountingApi/Dtos/Purchase/Expense/ExpensePostDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Purchase.Expense { public class ExpensePostDto { //paid money total public double? TotalPrice { get; set; } } } <file_sep>/AccountingApi/Dtos/Sale/Proposal/ProposalItemPostDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Sale.Proposal { public class ProposalItemPostDto { public int? Qty { get; set; } public double? SellPrice { get; set; } public double? TotalOneProduct { get; set; } public int? ProductId { get; set; } public int? ProposalId { get; set; } } } <file_sep>/AccountingApi/Models/ViewModel/VwProposalPut.cs using AccountingApi.Dtos.Company; using AccountingApi.Dtos.Nomenklatura.Kontragent; using AccountingApi.Dtos.Sale.Proposal; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models.ViewModel { public class VwProposalPut { public ProposalPutDto ProposalPutDto { get; set; } public List<ProposalItemPutDto> ProposalItemPutDtos { get; set; } public CompanyPutProposalDto CompanyPutProposalDto { get; set; } public ContragentPutInProposalDto ContragentPutInProposalDto { get; set; } } } <file_sep>/AccountingApi/Models/ProcudureDto/InvoiceFromQueryDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models.ProcudureDto { public class InvoiceFromQueryDto { public double? Total { get; set; } public byte? IsPaid { get; set; } } } <file_sep>/AccountingApi/Dtos/Purchase/Expense/ExpenseExInvoiceGetDto.cs using System; namespace AccountingApi.Dtos.Purchase.Expense { public class ExpenseExInvoiceGetDto { public int ExpenseInvoiceId { get; set; } public string ExpenseInvoiceNumber { get; set; } public double? TotalPrice { get; set; } public double? Residue { get; set; } public DateTime? PreparingDate { get; set; } public DateTime? EndDate { get; set; } public int? AccountDebitId { get; set; } public int? AccountKreditId { get; set; } } } <file_sep>/AccountingApi/Migrations/20190710121316_UserSendMails.cs using Microsoft.EntityFrameworkCore.Migrations; namespace AccountingApi.Migrations { public partial class UserSendMails : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_UserSendMailChangePassword_Users_UserId", table: "UserSendMailChangePassword"); migrationBuilder.DropPrimaryKey( name: "PK_UserSendMailChangePassword", table: "UserSendMailChangePassword"); migrationBuilder.RenameTable( name: "UserSendMailChangePassword", newName: "UserSendMailChangePasswords"); migrationBuilder.RenameIndex( name: "IX_UserSendMailChangePassword_UserId", table: "UserSendMailChangePasswords", newName: "IX_UserSendMailChangePasswords_UserId"); migrationBuilder.AddPrimaryKey( name: "PK_UserSendMailChangePasswords", table: "UserSendMailChangePasswords", column: "Id"); migrationBuilder.AddForeignKey( name: "FK_UserSendMailChangePasswords_Users_UserId", table: "UserSendMailChangePasswords", column: "UserId", principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.NoAction); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_UserSendMailChangePasswords_Users_UserId", table: "UserSendMailChangePasswords"); migrationBuilder.DropPrimaryKey( name: "PK_UserSendMailChangePasswords", table: "UserSendMailChangePasswords"); migrationBuilder.RenameTable( name: "UserSendMailChangePasswords", newName: "UserSendMailChangePassword"); migrationBuilder.RenameIndex( name: "IX_UserSendMailChangePasswords_UserId", table: "UserSendMailChangePassword", newName: "IX_UserSendMailChangePassword_UserId"); migrationBuilder.AddPrimaryKey( name: "PK_UserSendMailChangePassword", table: "UserSendMailChangePassword", column: "Id"); migrationBuilder.AddForeignKey( name: "FK_UserSendMailChangePassword_Users_UserId", table: "UserSendMailChangePassword", column: "UserId", principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } } } <file_sep>/AccountingApi/Dtos/Company/CompanyPostDto.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Company { public class CompanyPostDto { public string PhotoFile { get; set; } public string CompanyName { get; set; } [MaxLength(75)] public string Name { get; set; } [MaxLength(75)] public string Surname { get; set; } [MaxLength(75)] public string Postion { get; set; } public bool IsCompany { get; set; } = true; [MaxLength(75)] public string FieldOfActivity { get; set; } } } <file_sep>/AccountingApi/Data/Repository/PurchaseRepository.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AccountingApi.Dtos.Purchase.Expense; using AccountingApi.Dtos.Purchase.ExpenseInvoice; using AccountingApi.Models; using EOfficeAPI.Helpers.Pagination; using Microsoft.EntityFrameworkCore; namespace AccountingApi.Data.Repository.Interface { public class PurchaseRepository:IPurchaseRepository { private readonly DataContext _context; public PurchaseRepository(DataContext context) { _context = context; } //ExpenseInvoice #region ExpenseInvoice //Post public async Task<ExpenseInvoice> CreateInvoice(ExpenseInvoice invoice, int? companyId) { if (companyId == null) return null; if (invoice == null) return null; if (invoice.ContragentId == null) return null; invoice.CreatedAt = DateTime.UtcNow.AddHours(4); invoice.ResidueForCalc = invoice.TotalPrice; if (DateTime.Now > invoice.EndDate && invoice.TotalPrice == invoice.ResidueForCalc) { invoice.IsPaid = 4; } invoice.CompanyId = Convert.ToInt32(companyId); await _context.ExpenseInvoices.AddAsync(invoice); await _context.SaveChangesAsync(); //AccountPlan #region AccountPlan AccountsPlan accountDebit = await _context.AccountsPlans.FirstOrDefaultAsync(f => f.Id == invoice.AccountDebitId); if (accountDebit.Debit == null || accountDebit.Debit == 0) { accountDebit.Debit = invoice.TotalPrice; } else { accountDebit.Debit += invoice.TotalPrice; } AccountsPlan accountkredit = await _context.AccountsPlans.FirstOrDefaultAsync(f => f.Id == invoice.AccountKreditId); if (accountkredit.Kredit == null || accountkredit.Kredit == 0) { accountkredit.Kredit = invoice.TotalPrice; } else { accountkredit.Kredit += invoice.TotalPrice; } BalanceSheet balanceSheetDebit = new BalanceSheet { CreatedAt = DateTime.Now, CompanyId = Convert.ToInt32(companyId), DebitMoney = invoice.TotalPrice, AccountsPlanId = invoice.AccountDebitId, ExpenseInvoiceId = invoice.Id }; await _context.BalanceSheets.AddAsync(balanceSheetDebit); BalanceSheet balanceSheetKredit = new BalanceSheet { CreatedAt = DateTime.Now, CompanyId = Convert.ToInt32(companyId), KreditMoney = invoice.TotalPrice, AccountsPlanId = invoice.AccountKreditId, ExpenseInvoiceId = invoice.Id }; await _context.BalanceSheets.AddAsync(balanceSheetKredit); await _context.SaveChangesAsync(); #endregion return invoice; } public async Task<List<ExpenseInvoiceItem>> CreateInvoiceItems(List<ExpenseInvoiceItem> items, int? invoiceId) { if (invoiceId == null) return null; foreach (var item in items) { item.ExpenseInvoiceId = invoiceId; await _context.ExpenseInvoiceItems.AddAsync(item); await _context.SaveChangesAsync(); } return items; } //Check: #region Check public async Task<bool> CheckExpenseInvoice(int? currentUserId, int? companyId) { if (currentUserId == null) return true; if (companyId == null) return true; if (await _context.ExpenseInvoices.AnyAsync(a => a.CompanyId == companyId && a.Company.UserId != currentUserId)) return true; return false; } public async Task<bool> CheckExpenseInvoiceProductId(List<ExpenseInvoiceItem> invoiceItems) { foreach (var p in invoiceItems) { if (await _context.Products.FirstOrDefaultAsync(a => a.Id == p.ProductId) == null) { return true; } } return false; } public async Task<bool> CheckExpenseInvoiceId(int? productId, int? companyId) { if (companyId == null) return true; if (productId == null) return true; if (await _context.ExpenseInvoices.AnyAsync(a => a.CompanyId != companyId && a.Id == productId)) return true; return false; } public bool CheckInvoiceNegativeValue(ExpenseInvoice invoice, List<ExpenseInvoiceItem> items) { if (invoice.TotalPrice < 0 || invoice.TotalTax < 0 || invoice.Sum < 0) { return true; } foreach (var item in items) { if (item.Price < 0 || item.Qty < 0 || item.TotalOneProduct < 0) { return true; } } return false; } public async Task<bool> CheckExpenseInvoiceItem(int? invoiceId, List<ExpenseInvoiceItem> invoiceItems) { foreach (var item in invoiceItems.Where(w => w.Id != 0)) { ExpenseInvoiceItem dbInvoiceItem = await _context.ExpenseInvoiceItems.AsNoTracking() .FirstOrDefaultAsync(w => w.ExpenseInvoiceId == invoiceId && w.Id == item.Id); if (dbInvoiceItem == null) { return true; } } return false; } #endregion //Get //get all invoice public async Task<List<ExpenseInvoiceGetDto>> GetInvoice(PaginationParam productParam, int? companyId) { if (companyId == null) return null; List<ExpenseInvoice> invoices = await _context.ExpenseInvoices.Where(w => w.CompanyId == companyId) .OrderByDescending(d => d.Id).ToListAsync(); List<Contragent> contragents = await _context.Contragents .OrderByDescending(d => d.Id).ToListAsync(); var invoicecon = invoices.Join(contragents, m => m.ContragentId, m => m.Id, (inv, con) => new ExpenseInvoiceGetDto { ContragentCompanyName = con.CompanyName, ExpenseInvoiceNumber = inv.ExpenseInvoiceNumber, TotalPrice = inv.TotalPrice, PreparingDate = inv.PreparingDate, EndDate = inv.EndDate, IsPaid =inv.IsPaid, Id = inv.Id }).ToList(); return invoicecon; } //used in update action public async Task<ExpenseInvoice> GetEditInvoice(int? invoiceId, int? companyId) { if (invoiceId == null) return null; if (companyId == null) return null; ExpenseInvoice invoice = await _context.ExpenseInvoices.FirstOrDefaultAsync(f => f.Id == invoiceId && f.CompanyId == companyId); return invoice; } //used in update action public async Task<List<ExpenseInvoiceItem>> GetEditInvoiceItem(int? invoiceId) { if (invoiceId == null) return null; List<ExpenseInvoiceItem> invoiceItems = await _context.ExpenseInvoiceItems.Where(w => w.ExpenseInvoiceId == invoiceId).AsNoTracking().ToListAsync(); return invoiceItems; } // detail used in get edit invoice public async Task<ExpenseInvoice> GetDetailInvoice(int? invoiceId, int? companyId) { if (invoiceId == null) return null; if (companyId == null) return null; ExpenseInvoice invoice = await _context.ExpenseInvoices.Include(i => i.Company).Include(i => i.Tax).Include(i => i.ExpenseInvoiceItems).ThenInclude(a => a.Product).FirstOrDefaultAsync(f => f.Id == invoiceId && f.CompanyId == companyId); return invoice; } public async Task<Contragent> GetContragentInvoice(int? companyId, int? invoiceId) { Contragent contragent = await _context.Contragents.SingleOrDefaultAsync(c => c.CompanyId == companyId && c.ExpenseInvoices.SingleOrDefault(w => w.Id == invoiceId) != null); return contragent; } //Put public async Task<ExpenseInvoice> EditInvoice(ExpenseInvoice invoice, List<ExpenseInvoiceItem> invoiceItems, int? invoiceId) { if (invoice == null) return null; var invoiceforpaidmoney = _context.ExpenseInvoices.Find(invoice.Id); if (DateTime.Now > invoice.EndDate && invoice.TotalPrice == invoice.ResidueForCalc) { invoiceforpaidmoney.IsPaid = 4; } else if (DateTime.Now <= invoice.EndDate && invoice.TotalPrice == invoice.ResidueForCalc) { invoiceforpaidmoney.IsPaid = 1; } else if (DateTime.Now <= invoice.EndDate && invoice.TotalPrice != invoice.ResidueForCalc) { invoiceforpaidmoney.IsPaid = 1; } else if (DateTime.Now > invoice.EndDate && invoice.TotalPrice != invoice.ResidueForCalc) { invoiceforpaidmoney.IsPaid = 1; } _context.SaveChanges(); //update invoice _context.Entry(invoice).State = EntityState.Modified; _context.Entry(invoice).Property(a => a.CompanyId).IsModified = false; _context.Entry(invoice).Property(a => a.CreatedAt).IsModified = false; _context.Entry(invoice).Property(a => a.IsDeleted).IsModified = false; //_context.Invoices.Update(invoice); await _context.SaveChangesAsync(); //Update IncomeItems foreach (var item in invoiceItems.Where(w => w.Id != 0)) { _context.Entry(item).State = EntityState.Modified; _context.Entry(item).Property(a => a.ExpenseInvoiceId).IsModified = false; } _context.SaveChanges(); foreach (var inv in invoiceItems.Where(w => w.Id == 0)) { ExpenseInvoiceItem invoiceItem = new ExpenseInvoiceItem { Qty = inv.Qty, Price = inv.Price, TotalOneProduct = inv.TotalOneProduct, ProductId = inv.ProductId, ExpenseInvoiceId = Convert.ToInt32(invoiceId) }; _context.ExpenseInvoiceItems.Add(invoiceItem); } _context.SaveChanges(); // find invoiceById for equal totaprice to resdueForCalc.. because of correct calculating var foundinvoice = await _context.ExpenseInvoices.FindAsync(invoiceId); // for equal foundinvoice.ResidueForCalc = foundinvoice.TotalPrice; _context.SaveChanges(); // for deleting incomesitems var expenseItems = await _context.ExpenseItems.Where(f => f.ExpenseInvoiceId == invoiceId).ToListAsync(); // for deleting income //there is bug when deleting income ,invoiceId maybe declared difference var expense = _context.Expenses.FirstOrDefault(f => f.Id == f.ExpenseItems.FirstOrDefault(a => a.ExpenseInvoiceId == invoiceId).ExpenseId); if (expenseItems.Count > 0) { foreach (var item in expenseItems) { //Accounting #region Accounting var balancesheet = await _context.BalanceSheets.Where(w => w.ExpenseItemId == item.Id).ToListAsync(); var accountPlanDebit = _context.AccountsPlans.FirstOrDefault(f => f.Id == item.AccountDebitId); accountPlanDebit.Debit -= item.PaidMoney; _context.SaveChanges(); var accoutPlanKredit = _context.AccountsPlans.FirstOrDefault(f => f.Id == item.AccountKreditId); accoutPlanKredit.Kredit -= item.PaidMoney; _context.SaveChanges(); if (balancesheet != null) { _context.BalanceSheets.RemoveRange(balancesheet); } #endregion //For Deleting Expenses var dbincome = _context.Expenses.Include(s => s.ExpenseItems).FirstOrDefault(w => w.CompanyId == expense.CompanyId); if (dbincome.ExpenseItems.Count() == 1) { //removing expenseItems _context.ExpenseItems.Remove(item); _context.SaveChanges(); //Remove Expenses _context.Expenses.Remove(expense); _context.SaveChanges(); } else { //removing expenseItems _context.ExpenseItems.Remove(item); _context.SaveChanges(); } } } return invoice; } //Delete:DeleteInvoiceItem public async Task<ExpenseInvoiceItem> DeleteInvoiceItem(int? invoiceItemId) { if (invoiceItemId == null) return null; //InvoicesItems var expenseInvoiceItem = await _context.ExpenseInvoiceItems.Include(i => i.ExpenseInvoice).FirstOrDefaultAsync(f => f.Id == invoiceItemId); if (expenseInvoiceItem == null) return null; //Invoice var expenseInvoice = _context.ExpenseInvoices.Include(t => t.Tax).FirstOrDefault(f => f.Id == expenseInvoiceItem.ExpenseInvoice.Id); //New Invoice Sum value expenseInvoice.Sum -= expenseInvoiceItem.Price * expenseInvoiceItem.Qty; //New Invoice TotalTax value expenseInvoice.TotalTax = expenseInvoice.Sum * expenseInvoice.Tax.Rate / 100; //New Invoice TotalPrice value expenseInvoice.TotalPrice = expenseInvoice.Sum + expenseInvoice.TotalTax; //New Invoice ResidueForCalc value expenseInvoice.ResidueForCalc = expenseInvoice.Sum + expenseInvoice.TotalTax; _context.SaveChanges(); //Accounting #region Accounting var balancesheetDebit = _context.BalanceSheets.FirstOrDefault(w => w.ExpenseInvoiceId == expenseInvoice.Id && w.AccountsPlanId == expenseInvoice.AccountDebitId); if(balancesheetDebit != null) { balancesheetDebit.DebitMoney = expenseInvoice.TotalPrice; } _context.SaveChanges(); var balancesheetKredit = _context.BalanceSheets.FirstOrDefault(w => w.ExpenseInvoiceId == expenseInvoice.Id && w.AccountsPlanId == expenseInvoice.AccountKreditId); if(balancesheetKredit != null) { balancesheetKredit.KreditMoney = expenseInvoice.TotalPrice; } _context.SaveChanges(); var accountPlanDebit = _context.AccountsPlans.FirstOrDefault(f => f.Id == expenseInvoice.AccountDebitId); accountPlanDebit.Debit = expenseInvoice.TotalPrice; _context.SaveChanges(); var accoutPlanKredit = _context.AccountsPlans.FirstOrDefault(f => f.Id == expenseInvoice.AccountKreditId); accoutPlanKredit.Kredit = expenseInvoice.TotalPrice; _context.SaveChanges(); #endregion //Remove InvoiceItems _context.ExpenseInvoiceItems.Remove(expenseInvoiceItem); await _context.SaveChangesAsync(); return expenseInvoiceItem; } //Delete:DeleteInvoice public async Task<ExpenseInvoice> DeleteInvoice(int? companyId, int? invoiceId) { if (companyId == null) return null; if (invoiceId == null) return null; var expenseInvoice = await _context.ExpenseInvoices.FirstOrDefaultAsync(f => f.Id == invoiceId && f.CompanyId == companyId); if (expenseInvoice == null) return null; var expenseInvoiceItems = await _context.ExpenseInvoiceItems.Where(w => w.ExpenseInvoiceId == invoiceId).ToListAsync(); var expenseItems = await _context.ExpenseItems.Where(w => w.ExpenseInvoiceId == invoiceId).ToListAsync(); //Accounting #region Accounting var balancesheet = await _context.BalanceSheets.Where(w => w.CompanyId == companyId && w.ExpenseInvoiceId == invoiceId).ToListAsync(); foreach (var item in expenseInvoiceItems) { var balancesheetExpense = await _context.BalanceSheets.Where(w => w.CompanyId == companyId && w.ExpenseItemId == item.Id).ToListAsync(); if(balancesheetExpense != null && balancesheet.Count != 0) { _context.BalanceSheets.RemoveRange(balancesheetExpense); } } var accountPlanDebit = _context.AccountsPlans.FirstOrDefault(f => f.Id == expenseInvoice.AccountDebitId); accountPlanDebit.Debit -= expenseInvoice.TotalPrice; _context.SaveChanges(); var accoutPlanKredit = _context.AccountsPlans.FirstOrDefault(f => f.Id == expenseInvoice.AccountKreditId); accoutPlanKredit.Kredit -= expenseInvoice.TotalPrice; _context.SaveChanges(); if (balancesheet != null && balancesheet.Count != 0) { _context.BalanceSheets.RemoveRange(balancesheet); } #endregion if (expenseInvoiceItems != null && expenseInvoiceItems.Count != 0) { _context.ExpenseInvoiceItems.RemoveRange(expenseInvoiceItems); } if (expenseItems != null && expenseItems.Count != 0) { _context.ExpenseItems.RemoveRange(expenseItems); } _context.ExpenseInvoices.Remove(expenseInvoice); await _context.SaveChangesAsync(); return expenseInvoice; } // Accounting Update public ExpenseInvoicePutDto UpdateInvoiceAccountDebit(int? invoiceId, int? companyId, ExpenseInvoicePutDto invoice, int? OldDebitId) { if (invoiceId == null) return null; if (invoice == null) return null; double? dbInvoiceTotalPrice = _context.ExpenseInvoices.FirstOrDefault(f => f.Id == invoiceId).TotalPrice; //Debit if (OldDebitId == invoice.AccountDebitId) { //AccountPlan AccountsPlan accountDebit = _context.AccountsPlans.FirstOrDefault(f => f.Id == OldDebitId); if (accountDebit.Debit == null || accountDebit.Debit == 0) { accountDebit.Debit = invoice.TotalPrice; } else { accountDebit.Debit -= dbInvoiceTotalPrice; _context.SaveChanges(); accountDebit.Debit += invoice.TotalPrice; } _context.SaveChanges(); //Balancsheet BalanceSheet balanceSheetDebit = _context.BalanceSheets. FirstOrDefault(f => f.AccountsPlanId == OldDebitId && f.ExpenseInvoiceId == invoiceId); if(balanceSheetDebit != null) { balanceSheetDebit.DebitMoney = invoice.TotalPrice; balanceSheetDebit.AccountsPlanId = invoice.AccountDebitId; _context.SaveChanges(); } } else { //AccountPlan AccountsPlan oldAccountDebit = _context.AccountsPlans.FirstOrDefault(f => f.Id == OldDebitId); oldAccountDebit.Debit -= dbInvoiceTotalPrice; _context.SaveChanges(); AccountsPlan accountDebit = _context.AccountsPlans.FirstOrDefault(f => f.Id == invoice.AccountDebitId); if (accountDebit.Debit == null || accountDebit.Debit == 0) { accountDebit.Debit = invoice.TotalPrice; } else { accountDebit.Debit += invoice.TotalPrice; } _context.SaveChanges(); //Balancsheet //remove old balancesheet BalanceSheet oldBalanceSheetDebit = _context.BalanceSheets .FirstOrDefault(f => f.ExpenseInvoiceId == invoiceId && f.AccountsPlanId == OldDebitId); if (oldBalanceSheetDebit != null) { _context.BalanceSheets.Remove(oldBalanceSheetDebit); _context.SaveChanges(); } //new balancesheet BalanceSheet balanceSheetDebit = new BalanceSheet { CreatedAt = DateTime.Now, CompanyId = Convert.ToInt32(companyId), DebitMoney = invoice.TotalPrice, AccountsPlanId = invoice.AccountDebitId, ExpenseInvoiceId = invoiceId }; _context.BalanceSheets.Add(balanceSheetDebit); _context.SaveChanges(); } return invoice; } public ExpenseInvoicePutDto UpdateInvoiceAccountKredit(int? invoiceId, int? companyId, ExpenseInvoicePutDto invoice, int? OldKeditId) { if (invoiceId == null) return null; if (invoice == null) return null; double? dbInvoiceTotalPrice = _context.ExpenseInvoices.FirstOrDefault(f => f.Id == invoiceId).TotalPrice; //Kredit if (OldKeditId == invoice.AccountKreditId) { //AccountPlann AccountsPlan accountkredit = _context.AccountsPlans.FirstOrDefault(f => f.Id == OldKeditId); if (accountkredit.Kredit == null || accountkredit.Kredit == 0) { accountkredit.Kredit = invoice.TotalPrice; } else { accountkredit.Kredit -= dbInvoiceTotalPrice; _context.SaveChanges(); accountkredit.Kredit += invoice.TotalPrice; } _context.SaveChanges(); //Balancsheet BalanceSheet balanceSheetKredit = _context.BalanceSheets. FirstOrDefault(f => f.AccountsPlanId == OldKeditId && f.ExpenseInvoiceId == invoiceId); if(balanceSheetKredit != null) { balanceSheetKredit.KreditMoney = invoice.TotalPrice; balanceSheetKredit.AccountsPlanId = invoice.AccountKreditId; _context.SaveChanges(); } } else { //AccountPlan AccountsPlan oldAccountKredit = _context.AccountsPlans.FirstOrDefault(f => f.Id == OldKeditId); oldAccountKredit.Kredit -= dbInvoiceTotalPrice; _context.SaveChanges(); AccountsPlan accountkredit = _context.AccountsPlans.FirstOrDefault(f => f.Id == invoice.AccountKreditId); if (accountkredit.Kredit == null || accountkredit.Kredit == 0) { accountkredit.Kredit = invoice.TotalPrice; } else { accountkredit.Kredit += invoice.TotalPrice; } _context.SaveChanges(); //Balancsheet //remove old balancesheet BalanceSheet oldBalanceSheetKredit = _context.BalanceSheets .FirstOrDefault(f => f.ExpenseInvoiceId == invoiceId && f.AccountsPlanId == OldKeditId); if (oldBalanceSheetKredit != null) { _context.BalanceSheets.Remove(oldBalanceSheetKredit); _context.SaveChanges(); } //new balancesheet BalanceSheet balanceSheetKredit = new BalanceSheet { CreatedAt = DateTime.Now, CompanyId = Convert.ToInt32(companyId), KreditMoney = invoice.TotalPrice, AccountsPlanId = invoice.AccountKreditId, ExpenseInvoiceId = invoiceId }; _context.BalanceSheets.Add(balanceSheetKredit); _context.SaveChanges(); } return invoice; } #endregion //Expense #region Expense //Get: public List<ExpenseExInvoiceGetDto> GetExpenseInvoiceByContragentId(int? contragentId, int? companyId) { if (contragentId == null) return null; List<ExpenseExInvoiceGetDto> datas = (from inv in _context.ExpenseInvoices //join itemincome in _context.IncomeItems //on inv.Id equals itemincome.InvoiceId //Left join for take residue in table income //into sr //from x in sr.DefaultIfEmpty() where inv.ContragentId == contragentId && inv.CompanyId == companyId && inv.IsPaid != 3 select new ExpenseExInvoiceGetDto { ExpenseInvoiceId = inv.Id, ExpenseInvoiceNumber = inv.ExpenseInvoiceNumber, TotalPrice = inv.TotalPrice, Residue = inv.ResidueForCalc, PreparingDate = inv.PreparingDate, EndDate = inv.EndDate, AccountDebitId =inv.AccountDebitId, AccountKreditId =inv.AccountKreditId, }).ToList(); return datas; } public async Task<List<ExpenseGetDto>> GetExpense(PaginationParam productParam, int? companyId) { if (companyId == null) return null; var incomeItems = await _context.ExpenseItems.Include(i => i.Expense).Include(a => a.ExpenseInvoice) .ThenInclude(t => t.Contragent) .Where(w => w.Expense.CompanyId == companyId) .OrderByDescending(d => d.Id) .GroupBy(p => p.ExpenseInvoiceId) .Select(g => new { first = g.First(), sum = g.Sum(s => s.PaidMoney) } ).ToListAsync(); var joinIncome = incomeItems.Select(s => new ExpenseGetDto { ContragentCompanyName = s.first.Expense.Contragent.CompanyName, ContragentFullname = s.first.Expense.Contragent.Fullname, ExpenseInvoiceNumber = s.first.InvoiceNumber, Id = s.first.Expense.Id, IsBank = s.first.IsBank, TotalPrice = s.first.Expense.TotalPrice, PaidMoney = s.first.PaidMoney, Residue = s.first.ExpenseInvoice.ResidueForCalc, CreatedAt = s.first.Expense.CreatedAt, TotalOneInvoice = s.first.TotalOneInvoice, InvoiceId = s.first.ExpenseInvoiceId, SumPaidMoney = s.sum }).ToList(); return joinIncome; } //https://localhost:44317/api/income/geteditincome //get edit income public Task<ExpenseInvoice> GetExpenseExpenseItem(int? companyId, int? invoiceId) { if (invoiceId == null) return null; if (companyId == null) return null; var invoice = _context.ExpenseInvoices.Include(i => i.ExpenseItems).ThenInclude(t => t.Expense).Include(c => c.Contragent) .FirstOrDefaultAsync(f => f.CompanyId == companyId && f.Id == invoiceId); if (invoice == null) return null; return invoice; } //get for editing income public async Task<Expense> GetEditExpense(int? expenseId, int? companyId) { if (expenseId == null) return null; if (companyId == null) return null; Expense expense = await _context.Expenses.FirstOrDefaultAsync(f => f.CompanyId == companyId && f.Id == expenseId); return expense; } public async Task<List<ExpenseItem>> GetEditExpenseItems(int? invoiceId) { if (invoiceId == null) return null; List<ExpenseItem> expenseItems = await _context.ExpenseItems .Where(w => w.ExpenseInvoiceId == invoiceId).AsNoTracking().ToListAsync(); return expenseItems; } //Post: public async Task<Expense> CreateExpense(int? companyId, int? contragentId, Expense expense, List<ExpenseItem> expenseItems) { if (companyId == null) return null; if (contragentId == null) return null; expense.CreatedAt = DateTime.UtcNow.AddHours(4); expense.CompanyId = Convert.ToInt32(companyId); expense.ContragentId = Convert.ToInt32(contragentId); await _context.Expenses.AddAsync(expense); await _context.SaveChangesAsync(); //foreach (var id in Ids) //{ foreach (var inc in expenseItems) { //invoice for update IsPaid var invoice = _context.ExpenseInvoices.Find(inc.ExpenseInvoiceId); if (invoice == null) return null; if (invoice.ResidueForCalc <= inc.PaidMoney) { //1=planlinib, 2 = gozlemede,3=odenilib invoice.IsPaid = 3; } else if (invoice.ResidueForCalc > inc.PaidMoney) { //1=planlinib, 2 = gozlemede,3=odenilib invoice.IsPaid = 2; } else { //1=planlinib, 2 = gozlemede,3=odenilib invoice.IsPaid = 1; } if (inc.PaidMoney != null) { invoice.ResidueForCalc -= inc.PaidMoney; } _context.SaveChanges(); inc.ExpenseId = expense.Id; await _context.ExpenseItems.AddAsync(inc); // } //AccountPlan #region Account AccountsPlan accountDebit = _context.AccountsPlans.FirstOrDefault(f => f.Id == inc.AccountDebitId); if (accountDebit.Debit == null || accountDebit.Debit == 0) { accountDebit.Debit = inc.PaidMoney; } else { accountDebit.Debit += inc.PaidMoney; } _context.SaveChanges(); AccountsPlan accountkredit = _context.AccountsPlans.FirstOrDefault(f => f.Id == inc.AccountKreditId); if (accountkredit.Kredit == null || accountkredit.Kredit == 0) { accountkredit.Kredit = inc.PaidMoney; } else { accountkredit.Kredit += inc.PaidMoney; } _context.SaveChanges(); BalanceSheet balanceSheetDebit = new BalanceSheet { CreatedAt = DateTime.Now, CompanyId = Convert.ToInt32(companyId), DebitMoney = inc.PaidMoney, AccountsPlanId = inc.AccountDebitId, ExpenseItemId = inc.Id }; _context.BalanceSheets.Add(balanceSheetDebit); _context.SaveChanges(); BalanceSheet balanceSheetKredit = new BalanceSheet { CreatedAt = DateTime.Now, CompanyId = Convert.ToInt32(companyId), KreditMoney = inc.PaidMoney, AccountsPlanId = inc.AccountKreditId, ExpenseItemId = inc.Id }; _context.BalanceSheets.Add(balanceSheetKredit); _context.SaveChanges(); #endregion } await _context.SaveChangesAsync(); return expense; } //Put //so far stopped this method public async Task<ExpenseItem> EditExpense(List<ExpenseItemGetDto> itemGetDtos,int? invoiceId) { if (invoiceId == null) return null; //Update ExpenseItems foreach (var item in itemGetDtos) { double? sumPaidMoney = itemGetDtos.Where(w => w.ExpenseInvoiceId == invoiceId).Sum(s => s.PaidMoney); var expenseitem = _context.ExpenseItems.Find(item.Id); var invoice = _context.ExpenseInvoices.Find(invoiceId); invoice.ResidueForCalc += expenseitem.PaidMoney; _context.SaveChanges(); expenseitem.PaidMoney = item.PaidMoney; expenseitem.IsBank = item.IsBank; expenseitem.AccountDebitId = item.AccountDebitId; expenseitem.AccountKreditId = item.AccountKreditId; _context.SaveChanges(); invoice.ResidueForCalc -= item.PaidMoney; _context.SaveChanges(); //invoice for update IsPaid if (invoice == null) return null; if (invoice.TotalPrice <= sumPaidMoney) { //1=planlinib, 2 = gozlemede, 3=odenilib invoice.IsPaid = 3; } else if (invoice.TotalPrice > sumPaidMoney) { //1=planlinib, 2 = gozlemede, 3=odenilib invoice.IsPaid = 2; } else { //1=planlinib, 2 = gozlemede, 3=odenilib invoice.IsPaid = 1; } //if (invoice.ResidueForCalc != null) //{ // invoice.ResidueForCalc = invoice.TotalPrice - sumPaidMoney; //} } await _context.SaveChangesAsync(); return null; } //Check: #region Check public async Task<bool> CheckExpense(int? currentUserId, int? companyId) { if (currentUserId == null) return true; if (companyId == null) return true; if (await _context.Expenses.AnyAsync(a => a.CompanyId == companyId && a.Company.UserId != currentUserId)) return true; return false; } //check invoice total price with paidmoney public async Task<bool> CheckExpenseEqualingInvoiceTotalPriceForUpdate(List<ExpenseItemGetDto> expenseItems) { //total paidmoney double? TotalPaidMoney = 0; foreach (var item in expenseItems) { var dbincomeitems = _context.ExpenseItems.Where(w => w.Id == item.Id).ToList(); foreach (var dbitem in dbincomeitems) { var expenseItemsForPaidMoney = await _context.ExpenseInvoices.FirstOrDefaultAsync(f => f.Id == dbitem.ExpenseInvoiceId); if (expenseItemsForPaidMoney == null) return true; TotalPaidMoney += item.PaidMoney; //checkig totalpaidmoney and totaloneinvoice if (expenseItemsForPaidMoney.TotalPrice < TotalPaidMoney) { return true; } if (_context.ExpenseItems.FirstOrDefault(f => f.Id == item.Id) == null) { return true; } } } return false; } public async Task<bool> CheckExpenseEqualingInvoiceTotalPriceForCreate(List<ExpenseItem> incomeItems) { foreach (var item in incomeItems) { var expenseItemsForPaidMoney = await _context.ExpenseInvoices.Where(f => f.Id == item.ExpenseInvoiceId).ToListAsync(); if (expenseItemsForPaidMoney == null) return true; //total paidmoney double? TotalPaidMoney = 0; foreach (var exppaid in expenseItemsForPaidMoney) { TotalPaidMoney += item.PaidMoney; //checkig totalpaidmoney and totaloneinvoice if (exppaid.TotalPrice < TotalPaidMoney) { return true; } } } return false; } public async Task<bool> CheckIncomeContragentIdInvoiceId(int? contragentId, int? companyId) { if (contragentId == null) return true; if (await _context.Contragents.FirstOrDefaultAsync(a => a.CompanyId == companyId && a.Id == contragentId) == null) { return true; } return false; } public bool CheckExpenseNegativeValue(Expense expense, List<ExpenseItem> expenses) { if (expense.TotalPrice < 0) { return true; } foreach (var item in expenses) { if (item.PaidMoney < 0 || item.TotalOneInvoice < 0) { return true; } } return false; } public bool CheckExpenseUpdateNegativeValue(List<ExpenseItemGetDto> expenses) { foreach (var item in expenses) { if (item.PaidMoney < 0) { return true; } } return false; } #endregion // Account: Update public List<ExpenseItemGetDto> UpdateExpenseAccountDebit(int? companyId, List<ExpenseItemGetDto> incomeItem) { if (incomeItem == null) return null; foreach (var item in incomeItem) { var dbincomeItem = _context.ExpenseItems.Where(w => w.Id == item.Id).ToList(); foreach (var dbitem in dbincomeItem) { //Debit if (dbitem.AccountDebitId == item.AccountDebitId) { //AccountPlan AccountsPlan accountDebit = _context.AccountsPlans. FirstOrDefault(f => f.Id == dbitem.AccountDebitId); if (accountDebit.Debit == null || accountDebit.Debit == 0) { accountDebit.Debit = item.PaidMoney; } else { accountDebit.Debit -= dbitem.PaidMoney; _context.SaveChanges(); accountDebit.Debit += item.PaidMoney; } _context.SaveChanges(); //Balancsheet BalanceSheet balanceSheetDebit = _context.BalanceSheets. FirstOrDefault(f => f.AccountsPlanId == dbitem.AccountDebitId && f.ExpenseItemId == dbitem.Id); if (balanceSheetDebit != null) { balanceSheetDebit.DebitMoney = item.PaidMoney; balanceSheetDebit.AccountsPlanId = item.AccountDebitId; _context.SaveChanges(); } _context.SaveChanges(); } else { //AccountPlan AccountsPlan oldAccountDebit = _context.AccountsPlans. FirstOrDefault(f => f.Id == dbitem.AccountDebitId); if (oldAccountDebit.Debit != 0) { oldAccountDebit.Debit -= dbitem.PaidMoney; } _context.SaveChanges(); AccountsPlan accountDebit = _context.AccountsPlans.FirstOrDefault(f => f.Id == item.AccountDebitId); if (accountDebit.Debit == null || accountDebit.Debit == 0) { accountDebit.Debit = item.PaidMoney; } else { accountDebit.Debit += item.PaidMoney; } _context.SaveChanges(); //Balancsheet //remove old balancesheet BalanceSheet oldBalanceSheetDebit = _context.BalanceSheets .FirstOrDefault(f => f.ExpenseItemId == dbitem.Id && f.AccountsPlanId == dbitem.AccountDebitId); if (oldBalanceSheetDebit != null) { _context.BalanceSheets.Remove(oldBalanceSheetDebit); _context.SaveChanges(); } //new balancesheet BalanceSheet balanceSheetDebit = new BalanceSheet { CreatedAt = DateTime.Now, CompanyId = Convert.ToInt32(companyId), DebitMoney = item.PaidMoney, AccountsPlanId = item.AccountDebitId, ExpenseItemId = item.Id }; _context.BalanceSheets.Add(balanceSheetDebit); _context.SaveChanges(); } } } return incomeItem; } public List<ExpenseItemGetDto> UpdateExpenseAccountKredit(int? companyId, List<ExpenseItemGetDto> incomeItem) { if (incomeItem == null) return null; foreach (var item in incomeItem) { var dbincomeItem = _context.ExpenseItems.Where(w => w.Id == item.Id).ToList(); foreach (var dbitem in dbincomeItem) { //Kredit if (dbitem.AccountKreditId == item.AccountKreditId) { //AccountPlan AccountsPlan accountkredit = _context.AccountsPlans. FirstOrDefault(f => f.Id == dbitem.AccountKreditId); if (accountkredit.Kredit == null || accountkredit.Kredit == 0) { accountkredit.Kredit = item.PaidMoney; } else { accountkredit.Kredit -= dbitem.PaidMoney; _context.SaveChanges(); accountkredit.Kredit += item.PaidMoney; _context.SaveChanges(); } _context.SaveChanges(); //Balancsheet BalanceSheet balanceSheetKredit = _context.BalanceSheets. FirstOrDefault(f => f.AccountsPlanId == dbitem.AccountKreditId && f.ExpenseItemId == dbitem.Id); if (balanceSheetKredit != null) { balanceSheetKredit.KreditMoney = item.PaidMoney; balanceSheetKredit.AccountsPlanId = item.AccountKreditId; } _context.SaveChanges(); } else { //AccountPlan AccountsPlan oldAccountKredit = _context.AccountsPlans. FirstOrDefault(f => f.Id == dbitem.AccountKreditId); oldAccountKredit.Kredit -= dbitem.AccountKreditId; _context.SaveChanges(); AccountsPlan accountkredit = _context.AccountsPlans.FirstOrDefault(f => f.Id == item.AccountKreditId); if (accountkredit.Kredit == null || accountkredit.Kredit == 0) { accountkredit.Kredit = item.PaidMoney; } else { accountkredit.Kredit += item.PaidMoney; } _context.SaveChanges(); //Balancsheet //remove old balancesheet BalanceSheet oldBalanceSheetKredit = _context.BalanceSheets .FirstOrDefault(f => f.ExpenseItemId == dbitem.Id && f.AccountsPlanId == dbitem.AccountKreditId); if (oldBalanceSheetKredit != null) { _context.BalanceSheets.Remove(oldBalanceSheetKredit); _context.SaveChanges(); } //new balancesheet BalanceSheet balanceSheetKredit = new BalanceSheet { CreatedAt = DateTime.Now, CompanyId = Convert.ToInt32(companyId), KreditMoney = item.PaidMoney, AccountsPlanId = item.AccountKreditId, ExpenseItemId = dbitem.Id }; _context.BalanceSheets.Add(balanceSheetKredit); _context.SaveChanges(); } } } return incomeItem; } //Delete: public async Task<ExpenseItem> DeleteExpenseItem(int? expenseItemId) { if (expenseItemId == null) return null; // incomeitem var expenseItem = await _context.ExpenseItems.Include(i => i.Expense) .FirstOrDefaultAsync(f => f.Id == expenseItemId); if (expenseItem == null) return null; //Accounting #region Accounting var balancesheet = await _context.BalanceSheets.Where(w => w.ExpenseItemId == expenseItemId).ToListAsync(); var accountPlanDebit = _context.AccountsPlans.FirstOrDefault(f => f.Id == expenseItem.AccountDebitId); accountPlanDebit.Debit -= expenseItem.PaidMoney; _context.SaveChanges(); var accoutPlanKredit = _context.AccountsPlans.FirstOrDefault(f => f.Id == expenseItem.AccountKreditId); accoutPlanKredit.Kredit -= expenseItem.PaidMoney; _context.SaveChanges(); if (balancesheet != null) { _context.BalanceSheets.RemoveRange(balancesheet); } #endregion //invoice for update IsPaid var expenseInvoice = _context.ExpenseInvoices.Find(expenseItem.ExpenseInvoiceId); // deleted paidmoney sum of residueForCalc if (expenseInvoice.ResidueForCalc != null) { expenseInvoice.ResidueForCalc += expenseItem.PaidMoney; } //update invoice status if (expenseInvoice.TotalPrice <= expenseInvoice.ResidueForCalc && DateTime.Now > expenseInvoice.EndDate) { //1=planlinib, 2 = gozlemede, 3=odenilib,4 odenilmeyib expenseInvoice.IsPaid = 4; } else if (expenseInvoice.TotalPrice <= expenseInvoice.ResidueForCalc && DateTime.Now <= expenseInvoice.EndDate) { expenseInvoice.IsPaid = 1; } else if (expenseInvoice.TotalPrice > expenseInvoice.ResidueForCalc) { //1=planlinib, 2 = gozlemede, 3=odenilib expenseInvoice.IsPaid = 2; } else { //1=planlinib, 2 = gozlemede, 3=odenilib expenseInvoice.IsPaid = 3; } //Deleting Income where equal == deleted incomeitem incomeId And incomeItems Count equal 1 var expense = _context.Expenses.Include(d => d.ExpenseItems).FirstOrDefault(f => f.Id == expenseItem.ExpenseId); if (expense.ExpenseItems.Count() == 1) { //first deleting incomeItems _context.ExpenseItems.Remove(expenseItem); await _context.SaveChangesAsync(); //than deleting income _context.Expenses.Remove(expense); await _context.SaveChangesAsync(); return expenseItem; } //deleting incomeItem without income _context.ExpenseItems.Remove(expenseItem); await _context.SaveChangesAsync(); return expenseItem; } #endregion } } <file_sep>/AccountingApi/Dtos/Purchase/ExpenseInvoice/ExpensiveInvoiceEditGetDto.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Purchase.ExpenseInvoice { public class ExpensiveInvoiceEditGetDto { public string ExpenseInvoiceNumber { get; set; } public DateTime? PreparingDate { get; set; } public double? TotalPrice { get; set; } public DateTime? EndDate { get; set; } public double? TotalTax { get; set; } public double? Sum { get; set; } public int? ContragentId { get; set; } public int? TaxId { get; set; } public double? TaxRate { get; set; } public int? AccountDebitId { get; set; } public int? AccountKreditId { get; set; } //company public string CompanyCompanyName { get; set; } public string CompanyVOEN { get; set; } //contragent public string ContragentCompanyName { get; set; } public string ContragentVoen { get; set; } public ICollection<ExpensiveInvoiceItemGetDto> ExpensiveInvoiceItemGetDtos { get; set; } public ExpensiveInvoiceEditGetDto() { ExpensiveInvoiceItemGetDtos = new Collection<ExpensiveInvoiceItemGetDto>(); } } } <file_sep>/AccountingApi/Data/Repository/SaleRepository.cs using AccountingApi.Data.Repository.Interface; using AccountingApi.Dtos.Sale.Income; using AccountingApi.Dtos.Sale.Invoice; using AccountingApi.Dtos.Sale.Proposal; using AccountingApi.Models; using EOfficeAPI.Helpers; using EOfficeAPI.Helpers.Pagination; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Data.Repository { public class SaleRepository : ISaleRepository { private readonly DataContext _context; public SaleRepository(DataContext context) { _context = context; } //Proposal #region Proposal //Post public async Task<Proposal> CreateProposal(Proposal proposal, int? companyId) { if (companyId == null) return null; if (proposal != null) { proposal.CreatedAt = DateTime.UtcNow.AddHours(4); //1=planlinib, 2 = gozlemede,3=odenilib //proposal.IsPaid = 1; proposal.CompanyId = Convert.ToInt32(companyId); await _context.Proposals.AddAsync(proposal); await _context.SaveChangesAsync(); } return proposal; } public async Task<IEnumerable<ProposalItem>> CreateProposalItems(IEnumerable<ProposalItem> items, int? proposalId) { foreach (var item in items) { item.ProposalId = proposalId; //item.TotalOneProduct = item.Qty * item.SellPrice; await _context.ProposalItems.AddAsync(item); await _context.SaveChangesAsync(); } return items; } //Email public ProposalSentMail CreateProposalSentMail(int? proposalId, string email) { ProposalSentMail proposalSent = new ProposalSentMail { ProposalId = Convert.ToInt32(proposalId), Email = email, Token = CryptoHelper.Crypto.HashPassword(DateTime.Now.ToLongDateString()).Replace('+', 't'), //1=planlinib, 2 = gozlemede,3=odenilib IsPaid = 2 }; _context.ProposalSentMails.Add(proposalSent); _context.SaveChanges(); return proposalSent; } public Proposal GetProposalByToken(string token) { if (string.IsNullOrWhiteSpace(token)) return null; Proposal proposal = _context.ProposalSentMails.Include(a => a.Proposal) .ThenInclude(t => t.ProposalItems).ThenInclude(a => a.Product).FirstOrDefault(f => f.Token == token).Proposal; return proposal; } //Update zamani bu metodla dolduracayiq public async Task<Company> GetEditCompany(int? companyId) { if (companyId == null) return null; Company company = await _context.Companies.FindAsync(companyId); return company; } public async Task<Company> EditCompany(Company company, int? companyId, int? userId) { if (company == null) return null; if (companyId == null) return null; if (userId == null) return null; _context.Entry(company).State = EntityState.Modified; _context.Entry(company).Property(a => a.UserId).IsModified = false; await _context.SaveChangesAsync(); return company; } public async Task<Contragent> GetEditContragent(int? contragentId) { if (contragentId == null) return null; Contragent contragent = await _context.Contragents.FindAsync(contragentId); return contragent; } public async Task<Contragent> EditContragent(Contragent contragent, int? companyId) { //update entitynin metodudu. _context.Entry(contragent).State = EntityState.Modified; _context.Entry(contragent).Property(a => a.CompanyId).IsModified = false; //Commit the transaction await _context.SaveChangesAsync(); return contragent; } //Get: Proposal public async Task<List<ProposalGetDto>> GetProposal(PaginationParam productParam, int? companyId) { if (companyId == null) return null; List<Proposal> proposals = await _context.Proposals.Where(w => w.CompanyId == companyId) .OrderByDescending(d => d.Id).ToListAsync(); List<Contragent> contragents = await _context.Contragents .OrderByDescending(d => d.Id).ToListAsync(); var proposalcon = proposals.Join(contragents, m => m.ContragentId, m => m.Id, (pro, con) => new ProposalGetDto { ContragentCompanyName = con.CompanyName, ProposalNumber = pro.ProposalNumber, TotalPrice = pro.TotalPrice, PreparingDate = pro.PreparingDate, EndDate = pro.EndDate, //IsPaid =pro.IsPaid, Id = pro.Id }).ToList(); return proposalcon; } //get edit details public async Task<Proposal> GetDetailProposal(int? proposalId, int? companyId) { if (proposalId == null) return null; if (companyId == null) return null; Proposal proposal = await _context.Proposals.Include(i => i.Company).Include(i => i.Tax).Include(i => i.ProposalItems).ThenInclude(a => a.Product).FirstOrDefaultAsync(f => f.Id == proposalId && f.CompanyId == companyId); if (proposal == null) return null; return proposal; } //get edit proposal public async Task<Proposal> GetEditProposal(int? proposalId, int? companyId) { if (proposalId == null) return null; Proposal proposal = await _context.Proposals.FirstOrDefaultAsync(f => f.Id == proposalId && f.CompanyId == companyId); if (proposal == null) return null; return proposal; } public async Task<Contragent> GetContragentProposal(int? companyId, int? proposalId) { Contragent contragent = await _context.Contragents.SingleOrDefaultAsync(c => c.CompanyId == companyId && c.Proposals.SingleOrDefault(w => w.Id == proposalId) != null); if (contragent == null) return null; if (contragent == null) return null; return contragent; } // get edit proposalitems public async Task<List<ProposalItem>> GetEditProposalItem(int? proposalId) { if (proposalId == null) return null; List<ProposalItem> proposalItems = await _context.ProposalItems.Where(w => w.ProposalId == proposalId).AsNoTracking().ToListAsync(); if (proposalItems == null) return null; return proposalItems; } //Check #region Check public async Task<bool> CheckProposal(int? currentUserId, int? companyId) { if (currentUserId == null) return true; if (companyId == null) return true; if (await _context.Proposals.AnyAsync(a => a.CompanyId == companyId && a.Company.UserId != currentUserId)) return true; return false; } // mehsulun id-sinin olmasini yoxlayiriq. public async Task<bool> CheckProposalProductId(IEnumerable<ProposalItem> proposalItem) { foreach (var p in proposalItem) { if (await _context.Products.FirstOrDefaultAsync(a => a.Id == p.ProductId) == null) { return true; } } return false; } public async Task<bool> CheckProposalId(int? productId, int? companyId) { if (companyId == null) return true; if (productId == null) return true; if (await _context.Proposals.AnyAsync(a => a.CompanyId != companyId && a.Id == productId)) return true; return false; } public async Task<bool> CheckContragentId(int? contragentId, int? companyId) { if (companyId == null) return true; if (contragentId == null) return true; if (await _context.Contragents.FirstOrDefaultAsync(a => a.CompanyId == companyId && a.Id == contragentId) == null) return true; return false; } #endregion //Put public async Task<Proposal> EditProposal(Proposal proposal, List<ProposalItem> proposalItems, int? proposalId) { if (proposalId == null) return null; if (proposal == null) return null; if (proposalItems == null) return null; //update proposal _context.Entry(proposal).State = EntityState.Modified; _context.Entry(proposal).Property(a => a.CompanyId).IsModified = false; await _context.SaveChangesAsync(); //Update IncomeItems foreach (var item in proposalItems.Where(w => w.Id != 0)) { _context.Entry(item).State = EntityState.Modified; _context.Entry(item).Property(a => a.ProposalId).IsModified = false; } _context.SaveChanges(); foreach (var inv in proposalItems.Where(w => w.Id == 0)) { ProposalItem proposalItem = new ProposalItem { Qty = inv.Qty, Price = inv.Price, SellPrice = inv.SellPrice, TotalOneProduct = inv.TotalOneProduct, ProductId = inv.ProductId, ProposalId = Convert.ToInt32(proposalId) }; _context.ProposalItems.Add(proposalItem); } _context.SaveChanges(); return proposal; } //Delete DeleteProposalItem public async Task<ProposalItem> DeleteProposalItem(int? proposalItemId) { if (proposalItemId == null) return null; //ProposalItems var proposalItem = await _context.ProposalItems.Include(i => i.Proposal).FirstOrDefaultAsync(f => f.Id == proposalItemId); if (proposalItem == null) return null; //Proposal var proposal = _context.Proposals.Include(i => i.Tax).FirstOrDefault(f => f.Id == proposalItem.Proposal.Id); //New Proposal Sum value proposal.Sum -= proposalItem.SellPrice * proposalItem.Qty; //New Proposal TotalTax value proposal.TotalTax = proposal.Sum * proposal.Tax.Rate / 100; //New Proposal TotalPrice value proposal.TotalPrice = proposal.Sum + proposal.TotalTax; await _context.SaveChangesAsync(); //Remove PoposalItems _context.ProposalItems.Remove(proposalItem); await _context.SaveChangesAsync(); return proposalItem; } //Delete Proposal public async Task<Proposal> DeleteProposal(int? companyId, int? proposalId) { if (companyId == null) return null; if (proposalId == null) return null; var proposal = await _context.Proposals.FirstOrDefaultAsync(f => f.Id == proposalId && f.CompanyId == companyId); if (proposal == null) return null; var proposalItems = await _context.ProposalItems.Where(w => w.ProposalId == proposalId).ToListAsync(); var proposalSentMails = await _context.ProposalSentMails.Where(w => w.ProposalId == proposalId).ToListAsync(); if (proposalItems != null) { _context.ProposalItems.RemoveRange(proposalItems); } if (proposalSentMails != null) { _context.ProposalSentMails.RemoveRange(proposalSentMails); } _context.Proposals.Remove(proposal); await _context.SaveChangesAsync(); return proposal; } #endregion //Invoice #region Invoice //Post public async Task<Invoice> CreateInvoice(Invoice invoice, int? companyId) { if (companyId == null) return null; if (invoice.ContragentId == null) return null; invoice.CreatedAt = DateTime.UtcNow.AddHours(4); invoice.ResidueForCalc = invoice.TotalPrice; if (invoice == null) return null; if (DateTime.Now > invoice.EndDate && invoice.TotalPrice == invoice.ResidueForCalc) { invoice.IsPaid = 4; } //1=planlinib, 2 = gozlemede,3=odenilib //invoice.IsPaid = 1; invoice.CompanyId = Convert.ToInt32(companyId); await _context.Invoices.AddAsync(invoice); await _context.SaveChangesAsync(); //AccountPlan #region AccountPlan AccountsPlan accountDebit = await _context.AccountsPlans.FirstOrDefaultAsync(f => f.Id == invoice.AccountDebitId); if (accountDebit.Debit == null || accountDebit.Debit == 0) { accountDebit.Debit = invoice.TotalPrice; } else { accountDebit.Debit += invoice.TotalPrice; } AccountsPlan accountkredit = await _context.AccountsPlans.FirstOrDefaultAsync(f => f.Id == invoice.AccountKreditId); if (accountkredit.Kredit == null || accountkredit.Kredit == 0) { accountkredit.Kredit = invoice.TotalPrice; } else { accountkredit.Kredit += invoice.TotalPrice; } BalanceSheet balanceSheetDebit = new BalanceSheet { CreatedAt = DateTime.Now, CompanyId = Convert.ToInt32(companyId), DebitMoney = invoice.TotalPrice, AccountsPlanId = invoice.AccountDebitId, InvoiceId = invoice.Id }; await _context.BalanceSheets.AddAsync(balanceSheetDebit); BalanceSheet balanceSheetKredit = new BalanceSheet { CreatedAt = DateTime.Now, CompanyId = Convert.ToInt32(companyId), KreditMoney = invoice.TotalPrice, AccountsPlanId = invoice.AccountKreditId, InvoiceId = invoice.Id }; await _context.BalanceSheets.AddAsync(balanceSheetKredit); await _context.SaveChangesAsync(); #endregion return invoice; } public async Task<List<InvoiceItem>> CreateInvoiceItems(List<InvoiceItem> items, int? invoiceId) { if (invoiceId == null) return null; foreach (var item in items) { item.InvoiceId = invoiceId; await _context.InvoiceItems.AddAsync(item); await _context.SaveChangesAsync(); } return items; } //Get //get all invoice public async Task<List<InvoiceGetDto>> GetInvoice(PaginationParam productParam, int? companyId) { if (companyId == null) return null; List<Invoice> invoices = await _context.Invoices.Where(w => w.CompanyId == companyId) .OrderByDescending(d => d.Id).ToListAsync(); List<Contragent> contragents = await _context.Contragents .OrderByDescending(d => d.Id).ToListAsync(); var proposalcon = invoices.Join(contragents, m => m.ContragentId, m => m.Id, (inv, con) => new InvoiceGetDto { ContragentCompanyName = con.CompanyName, InvoiceNumber = inv.InvoiceNumber, TotalPrice = inv.TotalPrice, PreparingDate = inv.PreparingDate, EndDate = inv.EndDate, IsPaid = inv.IsPaid, Id = inv.Id }).ToList(); return proposalcon; } // detail used in get edit invoice public async Task<Invoice> GetDetailInvoice(int? invoiceId, int? companyId) { if (invoiceId == null) return null; if (companyId == null) return null; Invoice invoice = await _context.Invoices.Include(i => i.Company) .Include(i => i.Tax).Include(i => i.InvoiceItems) .ThenInclude(a => a.Product).Include(i => i.AccountsPlanDebit) .Include(t => t.AccountsPlanKredit) .FirstOrDefaultAsync(f => f.Id == invoiceId && f.CompanyId == companyId); return invoice; } //used in update action public async Task<Invoice> GetEditInvoice(int? invoiceId, int? companyId) { if (invoiceId == null) return null; if (companyId == null) return null; Invoice invoice = await _context.Invoices.Include(i=>i.AccountsPlanDebit).Include(t=>t.AccountsPlanKredit) .FirstOrDefaultAsync(f => f.Id == invoiceId && f.CompanyId == companyId); return invoice; } //used in update action public async Task<List<InvoiceItem>> GetEditInvoiceItem(int? invoiceId) { if (invoiceId == null) return null; List<InvoiceItem> invoiceItems = await _context.InvoiceItems.Where(w => w.InvoiceId == invoiceId).AsNoTracking().ToListAsync(); return invoiceItems; } //get contragent by invoiceid public async Task<Contragent> GetContragentInvoice(int? companyId, int? invoiceId) { Contragent contragent = await _context.Contragents.SingleOrDefaultAsync(c => c.CompanyId == companyId && c.Invoices.SingleOrDefault(w => w.Id == invoiceId) != null); return contragent; } //Put: // Accounting Update public InvoicePutDto UpdateInvoiceAccountDebit(int? invoiceId,int? companyId, InvoicePutDto invoice, int? OldDebitId) { if (invoiceId == null) return null; if (invoice == null) return null; double? dbInvoiceTotalPrice = _context.Invoices.FirstOrDefault(f => f.Id == invoiceId).TotalPrice; //Debit if (OldDebitId == invoice.AccountDebitId) { //AccountPlan AccountsPlan accountDebit = _context.AccountsPlans.FirstOrDefault(f => f.Id == OldDebitId); if (accountDebit.Debit == null || accountDebit.Debit == 0) { accountDebit.Debit = invoice.TotalPrice; } else { accountDebit.Debit -= dbInvoiceTotalPrice; _context.SaveChanges(); accountDebit.Debit += invoice.TotalPrice; } _context.SaveChanges(); //Balancsheet BalanceSheet balanceSheetDebit = _context.BalanceSheets. FirstOrDefault(f => f.AccountsPlanId == OldDebitId && f.InvoiceId == invoiceId); if(balanceSheetDebit != null) { balanceSheetDebit.DebitMoney = invoice.TotalPrice; balanceSheetDebit.AccountsPlanId = invoice.AccountDebitId; _context.SaveChanges(); } } else { //AccountPlan AccountsPlan oldAccountDebit = _context.AccountsPlans.FirstOrDefault(f => f.Id == OldDebitId); oldAccountDebit.Debit -= dbInvoiceTotalPrice; _context.SaveChanges(); AccountsPlan accountDebit = _context.AccountsPlans.FirstOrDefault(f => f.Id == invoice.AccountDebitId); if (accountDebit.Debit == null || accountDebit.Debit == 0) { accountDebit.Debit = invoice.TotalPrice; } else { accountDebit.Debit += invoice.TotalPrice; } _context.SaveChanges(); //Balancsheet //remove old balancesheet BalanceSheet oldBalanceSheetDebit = _context.BalanceSheets .FirstOrDefault(f => f.InvoiceId == invoiceId && f.AccountsPlanId == OldDebitId); if(oldBalanceSheetDebit != null) { _context.BalanceSheets.Remove(oldBalanceSheetDebit); _context.SaveChanges(); } //new balancesheet BalanceSheet balanceSheetDebit = new BalanceSheet { CreatedAt = DateTime.Now, CompanyId = Convert.ToInt32(companyId), DebitMoney = invoice.TotalPrice, AccountsPlanId = invoice.AccountDebitId, InvoiceId = invoiceId }; _context.BalanceSheets.Add(balanceSheetDebit); _context.SaveChanges(); } return invoice; } public InvoicePutDto UpdateInvoiceAccountKredit(int? invoiceId, int? companyId, InvoicePutDto invoice, int? OldKeditId) { if (invoiceId == null) return null; if (invoice == null) return null; double? dbInvoiceTotalPrice = _context.Invoices.FirstOrDefault(f => f.Id == invoiceId).TotalPrice; //Kredit if (OldKeditId == invoice.AccountKreditId) { //AccountPlann AccountsPlan accountkredit = _context.AccountsPlans.FirstOrDefault(f => f.Id == OldKeditId); if (accountkredit.Kredit == null || accountkredit.Kredit == 0) { accountkredit.Kredit = invoice.TotalPrice; } else { accountkredit.Kredit -= dbInvoiceTotalPrice; _context.SaveChanges(); accountkredit.Kredit += invoice.TotalPrice; } _context.SaveChanges(); //Balancsheet BalanceSheet balanceSheetKredit = _context.BalanceSheets. FirstOrDefault(f => f.AccountsPlanId == OldKeditId && f.InvoiceId == invoiceId); if(balanceSheetKredit != null) { balanceSheetKredit.KreditMoney = invoice.TotalPrice; balanceSheetKredit.AccountsPlanId = invoice.AccountKreditId; _context.SaveChanges(); } } else { //AccountPlan AccountsPlan oldAccountKredit = _context.AccountsPlans.FirstOrDefault(f => f.Id == OldKeditId); oldAccountKredit.Kredit -= dbInvoiceTotalPrice; _context.SaveChanges(); AccountsPlan accountkredit = _context.AccountsPlans.FirstOrDefault(f => f.Id == invoice.AccountKreditId); if (accountkredit.Kredit == null || accountkredit.Kredit == 0) { accountkredit.Kredit = invoice.TotalPrice; } else { accountkredit.Kredit += invoice.TotalPrice; } _context.SaveChanges(); //Balancsheet //remove old balancesheet BalanceSheet oldBalanceSheetKredit = _context.BalanceSheets .FirstOrDefault(f => f.InvoiceId == invoiceId && f.AccountsPlanId == OldKeditId); if(oldBalanceSheetKredit != null) { _context.BalanceSheets.Remove(oldBalanceSheetKredit); _context.SaveChanges(); } //new balancesheet BalanceSheet balanceSheetKredit = new BalanceSheet { CreatedAt = DateTime.Now, CompanyId = Convert.ToInt32(companyId), KreditMoney = invoice.TotalPrice, AccountsPlanId = invoice.AccountKreditId, InvoiceId = invoiceId }; _context.BalanceSheets.Add(balanceSheetKredit); _context.SaveChanges(); } return invoice; } public async Task<Invoice> EditInvoice(Invoice invoice, List<InvoiceItem> invoiceItems, int? invoiceId) { if (invoiceId == null) return null; if (invoice == null) return null; var invoiceforpaidmoney = _context.Invoices.Find(invoice.Id); if (DateTime.Now > invoice.EndDate && invoice.TotalPrice == invoice.ResidueForCalc) { invoiceforpaidmoney.IsPaid = 4; } else if (DateTime.Now <= invoice.EndDate && invoice.TotalPrice == invoice.ResidueForCalc) { invoiceforpaidmoney.IsPaid = 1; } else if (DateTime.Now <= invoice.EndDate && invoice.TotalPrice != invoice.ResidueForCalc) { invoiceforpaidmoney.IsPaid = 1; } else if (DateTime.Now > invoice.EndDate && invoice.TotalPrice != invoice.ResidueForCalc) { invoiceforpaidmoney.IsPaid = 1; } await _context.SaveChangesAsync(); //update invoice _context.Entry(invoice).State = EntityState.Modified; _context.Entry(invoice).Property(a => a.CompanyId).IsModified = false; //_context.Invoices.Update(invoice); await _context.SaveChangesAsync(); //Update IncomeItems foreach (var item in invoiceItems.Where(w => w.Id != 0)) { //InvoiceItem dbInvoiceItem = await _context.InvoiceItems // .FirstOrDefaultAsync(w => w.InvoiceId == invoiceId && w.Id == item.Id); ////Controller de yoxlamaq lazimdi error qaytarmaq lazimdi eger invocittem id-si db yoxdusa //if (dbInvoiceItem == null) //{ // return null; //} _context.Entry(item).State = EntityState.Modified; _context.Entry(item).Property(a => a.InvoiceId).IsModified = false; } await _context.SaveChangesAsync(); foreach (var inv in invoiceItems.Where(w => w.Id == 0)) { InvoiceItem invoiceItem = new InvoiceItem { Qty = inv.Qty, Price = inv.Price, SellPrice = inv.SellPrice, TotalOneProduct = inv.TotalOneProduct, ProductId = inv.ProductId, InvoiceId = Convert.ToInt32(invoiceId) }; _context.InvoiceItems.Add(invoiceItem); } await _context.SaveChangesAsync(); // find invoiceById for equal totaprice to resdueForCalc.. because of correct calculating var foundinvoice = await _context.Invoices.FindAsync(invoiceId); // for equal foundinvoice.ResidueForCalc = foundinvoice.TotalPrice; await _context.SaveChangesAsync(); // for deleting incomesitems var IncomeItems = await _context.IncomeItems.Where(f => f.InvoiceId == invoiceId).ToListAsync(); // for deleting income // there is bug when deleting income, invoiceId maybe declared difference var income = _context.Incomes.FirstOrDefault(f => f.Id == f.IncomeItems.FirstOrDefault(a => a.InvoiceId == invoiceId).IncomeId); if (IncomeItems.Count > 0) { foreach (var item in IncomeItems) { //Accounting #region Accounting var balancesheet = await _context.BalanceSheets.Where(w => w.IncomeItemId == item.Id).ToListAsync(); var accountPlanDebit = _context.AccountsPlans.FirstOrDefault(f => f.Id == item.AccountDebitId); accountPlanDebit.Debit -= item.PaidMoney; _context.SaveChanges(); var accoutPlanKredit = _context.AccountsPlans.FirstOrDefault(f => f.Id == item.AccountKreditId); accoutPlanKredit.Kredit -= item.PaidMoney; _context.SaveChanges(); if (balancesheet != null) { _context.BalanceSheets.RemoveRange(balancesheet); } #endregion //For Deleting income var dbincome = _context.Incomes.Include(s => s.IncomeItems).FirstOrDefault(w => w.CompanyId == income.CompanyId); if (dbincome.IncomeItems.Count() == 1) { //removing incomeitems _context.IncomeItems.Remove(item); _context.SaveChanges(); //Remove Income _context.Incomes.Remove(income); _context.SaveChanges(); } else { //removing incomeitems _context.IncomeItems.Remove(item); _context.SaveChanges(); } } } return invoice; } //Check: #region Check public async Task<bool> CheckInvoice(int? currentUserId, int? companyId) { if (currentUserId == null) return true; if (companyId == null) return true; if (await _context.Invoices.AnyAsync(a => a.CompanyId == companyId && a.Company.UserId != currentUserId)) return true; return false; } public async Task<bool> CheckInvoiceProductId(List<InvoiceItem> invoiceItems) { foreach (var p in invoiceItems) { if (await _context.Products.FirstOrDefaultAsync(a => a.Id == p.ProductId) == null) { return true; } } return false; } public async Task<bool> CheckInvoiceId(int? productId, int? companyId) { if (companyId == null) return true; if (productId == null) return true; if (await _context.Invoices.AnyAsync(a => a.CompanyId != companyId && a.Id == productId)) return true; return false; } public async Task<bool> CheckInvoiceItem(int? invoiceId, List<InvoiceItem> invoiceItems) { foreach (var item in invoiceItems.Where(w => w.Id != 0)) { InvoiceItem dbInvoiceItem = await _context.InvoiceItems.AsNoTracking() .FirstOrDefaultAsync(w => w.InvoiceId == invoiceId && w.Id == item.Id); if (dbInvoiceItem == null) { return true; } } return false; } //checking exist income public async Task<bool> CheckExistIncomeByInvoiceId(int? invoiceId) { var existIncome = await _context.IncomeItems.FirstOrDefaultAsync(f => f.InvoiceId == invoiceId); if (existIncome != null) return true; return false; } public bool CheckInvoiceNegativeValue(Invoice invoice, List<InvoiceItem> items) { if (invoice.TotalPrice < 0 || invoice.TotalTax < 0 || invoice.Sum < 0) { return true; } foreach (var item in items) { if (item.SellPrice < 0 || item.Price < 0 || item.Qty < 0 || item.TotalOneProduct < 0) { return true; } } return false; } #endregion //Delete:DeleteInvoiceItem public async Task<InvoiceItem> DeleteInvoiceItem(int? invoiceItemId) { if (invoiceItemId == null) return null; //InvoicesItems var invoiceItem = await _context.InvoiceItems.Include(i => i.Invoice).FirstOrDefaultAsync(f => f.Id == invoiceItemId); if (invoiceItem == null) return null; //Invoice var invoice = _context.Invoices.Include(t => t.Tax).FirstOrDefault(f => f.Id == invoiceItem.Invoice.Id); //New Invoice Sum value invoice.Sum -= (invoiceItem.SellPrice * invoiceItem.Qty); //New Invoice TotalTax value invoice.TotalTax = invoice.Sum * invoice.Tax.Rate / 100; //New Invoice TotalPrice value invoice.TotalPrice = invoice.Sum + invoice.TotalTax; //New Invoice ResidueForCalc value invoice.ResidueForCalc = invoice.Sum + invoice.TotalTax; _context.SaveChanges(); //Accounting #region Accounting var balancesheetDebit = _context.BalanceSheets.FirstOrDefault(w =>w.InvoiceId == invoice.Id && w.AccountsPlanId == invoice.AccountDebitId); balancesheetDebit.DebitMoney = invoice.TotalPrice; _context.SaveChanges(); var balancesheetKredit = _context.BalanceSheets.FirstOrDefault(w => w.InvoiceId == invoice.Id && w.AccountsPlanId == invoice.AccountKreditId); balancesheetKredit.KreditMoney = invoice.TotalPrice; _context.SaveChanges(); var accountPlanDebit = _context.AccountsPlans.FirstOrDefault(f => f.Id == invoice.AccountDebitId); accountPlanDebit.Debit = invoice.TotalPrice; _context.SaveChanges(); var accoutPlanKredit = _context.AccountsPlans.FirstOrDefault(f => f.Id == invoice.AccountKreditId); accoutPlanKredit.Kredit = invoice.TotalPrice; _context.SaveChanges(); #endregion //Remove InvoiceItems _context.InvoiceItems.Remove(invoiceItem); await _context.SaveChangesAsync(); return invoiceItem; } //Delete:DeleteInvoice public async Task<Invoice> DeleteInvoice(int? companyId, int? invoiceId) { if (companyId == null) return null; if (invoiceId == null) return null; var invoice = await _context.Invoices.FirstOrDefaultAsync(f => f.Id == invoiceId && f.CompanyId == companyId); if (invoice == null) return null; var invoiceItems = await _context.InvoiceItems.Where(w => w.InvoiceId == invoiceId).ToListAsync(); var incomeItems = await _context.IncomeItems.Where(w => w.InvoiceId == invoiceId).ToListAsync(); var invoiceSentMails = await _context.InvoiceSentMails.Where(w => w.InvoiceId == invoiceId).ToListAsync(); //Accounting #region Accounting var balancesheet = await _context.BalanceSheets.Where(w => w.CompanyId == companyId && w.InvoiceId == invoiceId).ToListAsync(); var accountPlanDebit = _context.AccountsPlans.FirstOrDefault(f => f.Id == invoice.AccountDebitId); accountPlanDebit.Debit -= invoice.TotalPrice; _context.SaveChanges(); var accoutPlanKredit = _context.AccountsPlans.FirstOrDefault(f => f.Id == invoice.AccountKreditId); accoutPlanKredit.Kredit -= invoice.TotalPrice; _context.SaveChanges(); #endregion if (invoiceItems != null) { _context.InvoiceItems.RemoveRange(invoiceItems); } //incomeite siilende onun provodkasinida silmek lazimdi if (incomeItems != null) { _context.IncomeItems.RemoveRange(incomeItems); } if (invoiceSentMails != null) { _context.InvoiceSentMails.RemoveRange(invoiceSentMails); } if(balancesheet != null) { _context.BalanceSheets.RemoveRange(balancesheet); } _context.Invoices.Remove(invoice); await _context.SaveChangesAsync(); return invoice; } //Email public InvoiceSentMail CreateInvoiceSentMail(int? invoiceId, string email) { InvoiceSentMail invoiceSent = new InvoiceSentMail { InvoiceId = Convert.ToInt32(invoiceId), Email = email, Token = CryptoHelper.Crypto.HashPassword(DateTime.Now.ToLongDateString()).Replace('+', 't').Replace('=','t'), //1=planlinib, 2 = gozlemede,3=odenilib IsPaid = 2 }; _context.InvoiceSentMails.Add(invoiceSent); _context.SaveChanges(); return invoiceSent; } public Invoice GetInvoiceByToken(string token) { if (string.IsNullOrWhiteSpace(token)) return null; Invoice invoice = _context.InvoiceSentMails.Include(a => a.Invoice) .ThenInclude(t => t.InvoiceItems).ThenInclude(a => a.Product).FirstOrDefault(f => f.Token == token).Invoice; return invoice; } #endregion //Income #region InCome //Get #region Get public List<IncomeInvoiceGetDto> GetInvoiceByContragentId(int? contragentId, int? companyId) { if (contragentId == null) return null; List<IncomeInvoiceGetDto> datas = (from inv in _context.Invoices //join itemincome in _context.IncomeItems //on inv.Id equals itemincome.InvoiceId //Left join for take residue in table income //into sr //from x in sr.DefaultIfEmpty() where inv.ContragentId == contragentId && inv.CompanyId == companyId && inv.IsPaid != 3 select new IncomeInvoiceGetDto { InvoiceId = inv.Id, InvoiceNumber = inv.InvoiceNumber, TotalPrice = inv.TotalPrice, Residue = inv.ResidueForCalc, PreparingDate = inv.PreparingDate, EndDate = inv.EndDate, AccountDebitId = inv.AccountDebitId, AccountKreditId = inv.AccountKreditId }).ToList(); return datas; } public async Task<List<IncomeGetDto>> GetIncome(PaginationParam productParam, int? companyId) { if (companyId == null) return null; var incomeItems = await _context.IncomeItems .Include(i => i.Income) .Include(a => a.Invoice) .ThenInclude(t => t.Contragent) .Where(w => w.Income.CompanyId == companyId) .OrderByDescending(d => d.Id) .GroupBy(p => p.InvoiceId) .Select(g => new { first = g.First(), sum = g.Sum(s => s.PaidMoney) } ).ToListAsync(); var joinIncome = incomeItems.Select(s => new IncomeGetDto { ContragentCompanyName = s.first.Income.Contragent.CompanyName, ContragentFullname = s.first.Income.Contragent.Fullname, InvoiceNumber = s.first.InvoiceNumber, Id = s.first.Income.Id, IsBank = s.first.IsBank, TotalPrice = s.first.Income.TotalPrice, PaidMoney = s.first.PaidMoney, Residue = s.first.Invoice.ResidueForCalc, CreatedAt = s.first.Income.CreatedAt, //income page mebleg TotalOneInvoice = s.first.TotalOneInvoice, InvoiceId = s.first.InvoiceId, SumPaidMoney = s.sum }).ToList(); return joinIncome; } //get for editing income public async Task<Income> GetEditIncome(int? incomeId, int? companyId) { if (incomeId == null) return null; if (companyId == null) return null; Income income = await _context.Incomes.FirstOrDefaultAsync(f => f.CompanyId == companyId && f.Id == incomeId); return income; } public async Task<List<IncomeItem>> GetEditIncomeItems(int? incomeId) { if (incomeId == null) return null; List<IncomeItem> incomeItems = await _context.IncomeItems.Include(i => i.Income).Include(j => j.Invoice) .Include(i => i.AccountsPlanDebit).Include(s => s.AccountsPlanKredit) .Where(w => w.IncomeId == incomeId).AsNoTracking().ToListAsync(); return incomeItems; } //https://localhost:44317/api/income/geteditincome //get edit income public Task<Invoice> GetInvoiceIcomeItem(int? companyId, int? invoiceId) { if (invoiceId == null) return null; if (companyId == null) return null; var invoice = _context.Invoices.Include(i => i.IncomeItems).ThenInclude(t => t.Income).Include(c => c.Contragent) .FirstOrDefaultAsync(f => f.CompanyId == companyId && f.Id == invoiceId); if (invoice == null) return null; return invoice; } //get single income detail public async Task<Income> DetailIncome(int? incomeId, int? companyId) { if (incomeId == null) return null; Income income = await _context.Incomes.Include(i => i.Contragent) .Include(i => i.IncomeItems).FirstOrDefaultAsync(f => f.CompanyId == companyId && f.Id == incomeId); return income; } //Post #endregion //Post public async Task<Income> CreateIncome(int? companyId, int? contragentId, int[] Ids, Income income, List<IncomeItem> incomes) { if (companyId == null) return null; if (contragentId == null) return null; income.CreatedAt = DateTime.UtcNow.AddHours(4); income.CompanyId = Convert.ToInt32(companyId); income.ContragentId = Convert.ToInt32(contragentId); await _context.Incomes.AddAsync(income); await _context.SaveChangesAsync(); //foreach (var id in Ids) //{ foreach (var inc in incomes) { //invoice for update IsPaid var invoice = _context.Invoices.Find(inc.InvoiceId); if (invoice == null) return null; if (invoice.ResidueForCalc <= inc.PaidMoney) { //1=planlinib, 2 = gozlemede,3=odenilib invoice.IsPaid = 3; } else if (invoice.ResidueForCalc > inc.PaidMoney) { //1=planlinib, 2 = gozlemede,3=odenilib invoice.IsPaid = 2; } else { //1=planlinib, 2 = gozlemede,3=odenilib invoice.IsPaid = 1; } if (inc.PaidMoney != null) { invoice.ResidueForCalc -= inc.PaidMoney; } _context.SaveChanges(); inc.IncomeId = income.Id; await _context.IncomeItems.AddAsync(inc); // } //AccountPlan #region Account AccountsPlan accountDebit = _context.AccountsPlans.FirstOrDefault(f => f.Id == inc.AccountDebitId); if(accountDebit.Debit == null || accountDebit.Debit == 0) { accountDebit.Debit = inc.PaidMoney; } else { accountDebit.Debit += inc.PaidMoney; } _context.SaveChanges(); AccountsPlan accountkredit = _context.AccountsPlans.FirstOrDefault(f => f.Id == inc.AccountKreditId); if (accountkredit.Kredit == null || accountkredit.Kredit == 0) { accountkredit.Kredit = inc.PaidMoney; } else { accountkredit.Kredit += inc.PaidMoney; } _context.SaveChanges(); BalanceSheet balanceSheetDebit = new BalanceSheet { CreatedAt = DateTime.Now, CompanyId = Convert.ToInt32(companyId), DebitMoney = inc.PaidMoney, AccountsPlanId = inc.AccountDebitId, IncomeItemId = inc.Id }; _context.BalanceSheets.Add(balanceSheetDebit); _context.SaveChanges(); BalanceSheet balanceSheetKredit = new BalanceSheet { CreatedAt = DateTime.Now, CompanyId = Convert.ToInt32(companyId), KreditMoney = inc.PaidMoney, AccountsPlanId = inc.AccountKreditId, IncomeItemId = inc.Id }; _context.BalanceSheets.Add(balanceSheetKredit); _context.SaveChanges(); #endregion } await _context.SaveChangesAsync(); return income; } //Check #region Check public async Task<bool> CheckIncome(int? currentUserId, int? companyId) { if (currentUserId == null) return true; if (companyId == null) return true; if (await _context.Incomes.AnyAsync(a => a.CompanyId == companyId && a.Company.UserId != currentUserId)) return true; return false; } public async Task<bool> CheckIncomeContragentIdInvoiceId(int? contragentId, int? companyId) { if (contragentId == null) return true; if (await _context.Contragents.FirstOrDefaultAsync(a => a.CompanyId == companyId && a.Id == contragentId) == null) { return true; } return false; } //check invoice total price with paidmoney public async Task<bool> CheckIncomeEqualingInvoiceTotalPriceForUpdate(List<IncomeItemGetEditDto> incomeItems) { //total paidmoney double? TotalPaidMoney = 0; foreach (var item in incomeItems) { var dbincomeitems = _context.IncomeItems.Where(w => w.Id == item.Id).ToList(); foreach (var dbitem in dbincomeitems) { var incomeItemsForPaidMoney = await _context.Invoices.FirstOrDefaultAsync(f => f.Id == dbitem.InvoiceId); if (incomeItemsForPaidMoney == null) return true; TotalPaidMoney += item.PaidMoney; //checkig totalpaidmoney and totaloneinvoice if (incomeItemsForPaidMoney.TotalPrice < TotalPaidMoney) { return true; } if (_context.IncomeItems.FirstOrDefault(f => f.Id == item.Id) == null) { return true; } } } return false; } public async Task<bool> CheckIncomeEqualingInvoiceTotalPriceForCreate(List<IncomeItem> incomeItems) { foreach (var item in incomeItems) { var incomeItemsForPaidMoney = await _context.Invoices.Where(f => f.Id == item.InvoiceId).ToListAsync(); if (incomeItemsForPaidMoney == null) return true; //total paidmoney double? TotalPaidMoney = 0; foreach (var incpaid in incomeItemsForPaidMoney) { TotalPaidMoney += item.PaidMoney; //checkig totalpaidmoney and totaloneinvoice if (incpaid.TotalPrice < TotalPaidMoney) { return true; } } } return false; } public bool CheckIncomeNegativeValue(Income income, List<IncomeItem> incomes) { if (income.TotalPrice < 0) { return true; } foreach (var item in incomes) { if (item.PaidMoney < 0 || item.TotalOneInvoice < 0) { return true; } } return false; } public bool CheckIncomeUpdateNegativeValue(List<IncomeItemGetEditDto> incomes) { foreach (var item in incomes) { if (item.PaidMoney < 0) { return true; } } return false; } #endregion // Accounting Update public List<IncomeItemGetEditDto> UpdateIncomeAccountDebit(int? companyId, List<IncomeItemGetEditDto> incomeItem) { if (incomeItem == null) return null; foreach (var item in incomeItem) { var dbincomeItem = _context.IncomeItems.Where(w => w.Id == item.Id).ToList(); foreach (var dbitem in dbincomeItem) { //Debit if (dbitem.AccountDebitId == item.AccountDebitId) { //AccountPlan AccountsPlan accountDebit = _context.AccountsPlans. FirstOrDefault(f => f.Id == dbitem.AccountDebitId); if (accountDebit.Debit == null || accountDebit.Debit == 0) { accountDebit.Debit = item.PaidMoney; } else { accountDebit.Debit -= dbitem.PaidMoney; _context.SaveChanges(); accountDebit.Debit += item.PaidMoney; } _context.SaveChanges(); //Balancsheet BalanceSheet balanceSheetDebit = _context.BalanceSheets. FirstOrDefault(f => f.AccountsPlanId == dbitem.AccountDebitId && f.IncomeItemId == dbitem.Id); if (balanceSheetDebit.IncomeItemId != null) { balanceSheetDebit.DebitMoney = item.PaidMoney; balanceSheetDebit.AccountsPlanId = item.AccountDebitId; } _context.SaveChanges(); } else { //AccountPlan AccountsPlan oldAccountDebit = _context.AccountsPlans. FirstOrDefault(f => f.Id == dbitem.AccountDebitId); if (oldAccountDebit.Debit != 0) { oldAccountDebit.Debit -= dbitem.PaidMoney; } _context.SaveChanges(); AccountsPlan accountDebit = _context.AccountsPlans.FirstOrDefault(f => f.Id == item.AccountDebitId); if (accountDebit.Debit == null || accountDebit.Debit == 0) { accountDebit.Debit = item.PaidMoney; } else { accountDebit.Debit += item.PaidMoney; } _context.SaveChanges(); //Balancsheet //remove old balancesheet BalanceSheet oldBalanceSheetDebit = _context.BalanceSheets .FirstOrDefault(f => f.IncomeItemId == dbitem.Id && f.AccountsPlanId == dbitem.AccountDebitId); if (oldBalanceSheetDebit != null) { _context.BalanceSheets.Remove(oldBalanceSheetDebit); _context.SaveChanges(); } //new balancesheet BalanceSheet balanceSheetDebit = new BalanceSheet { CreatedAt = DateTime.Now, CompanyId = Convert.ToInt32(companyId), DebitMoney = item.PaidMoney, AccountsPlanId = item.AccountDebitId, IncomeItemId = item.Id }; _context.BalanceSheets.Add(balanceSheetDebit); _context.SaveChanges(); } } } return incomeItem; } public List<IncomeItemGetEditDto> UpdateIncomeAccountKredit(int? companyId, List<IncomeItemGetEditDto> incomeItem) { if (incomeItem == null) return null; foreach (var item in incomeItem) { var dbincomeItem = _context.IncomeItems.Where(w => w.Id == item.Id).ToList(); foreach (var dbitem in dbincomeItem) { //Kredit if (dbitem.AccountKreditId == item.AccountKreditId) { //AccountPlan AccountsPlan accountkredit = _context.AccountsPlans. FirstOrDefault(f => f.Id == dbitem.AccountKreditId); if (accountkredit.Kredit == null || accountkredit.Kredit == 0) { accountkredit.Kredit = item.PaidMoney; } else { if (accountkredit.Kredit != 0) { accountkredit.Kredit -= dbitem.PaidMoney; } _context.SaveChanges(); accountkredit.Kredit += item.PaidMoney; } _context.SaveChanges(); //Balancsheet BalanceSheet balanceSheetKredit = _context.BalanceSheets. FirstOrDefault(f => f.AccountsPlanId == dbitem.AccountKreditId && f.IncomeItemId == dbitem.Id); if (balanceSheetKredit != null) { balanceSheetKredit.KreditMoney = item.PaidMoney; balanceSheetKredit.AccountsPlanId = item.AccountKreditId; } _context.SaveChanges(); } else { //AccountPlan AccountsPlan oldAccountKredit = _context.AccountsPlans. FirstOrDefault(f => f.Id == dbitem.AccountKreditId); oldAccountKredit.Kredit -= dbitem.AccountKreditId; _context.SaveChanges(); AccountsPlan accountkredit = _context.AccountsPlans.FirstOrDefault(f => f.Id == item.AccountKreditId); if (accountkredit.Kredit == null || accountkredit.Kredit == 0) { accountkredit.Kredit = item.PaidMoney; } else { accountkredit.Kredit += item.PaidMoney; } _context.SaveChanges(); //Balancsheet //remove old balancesheet BalanceSheet oldBalanceSheetKredit = _context.BalanceSheets .FirstOrDefault(f => f.IncomeItemId == dbitem.Id && f.AccountsPlanId == dbitem.AccountKreditId); if (oldBalanceSheetKredit != null) { _context.BalanceSheets.Remove(oldBalanceSheetKredit); _context.SaveChanges(); } //new balancesheet BalanceSheet balanceSheetKredit = new BalanceSheet { CreatedAt = DateTime.Now, CompanyId = Convert.ToInt32(companyId), KreditMoney = item.PaidMoney, AccountsPlanId = item.AccountKreditId, IncomeItemId = dbitem.Id }; _context.BalanceSheets.Add(balanceSheetKredit); _context.SaveChanges(); } } } return incomeItem; } //Put public async Task<IncomeItem> EditIncome(List<IncomeItemGetEditDto> itemGetDtos , int? invoiceId) { if (invoiceId == null) return null; //Update IncomeItems double? sumPaidMoney = itemGetDtos.Where(w => w.InvoiceId == invoiceId).Sum(s => s.PaidMoney); foreach (var item in itemGetDtos) { var invitem = _context.IncomeItems.Find(item.Id); var invoice = _context.Invoices.Find(invoiceId); invoice.ResidueForCalc += invitem.PaidMoney; _context.SaveChanges(); invitem.PaidMoney = item.PaidMoney; invitem.IsBank = item.IsBank; invitem.AccountDebitId = item.AccountDebitId; invitem.AccountKreditId = item.AccountKreditId; _context.SaveChanges(); //invoice for update IsPaid invoice.ResidueForCalc -= item.PaidMoney; _context.SaveChanges(); if (invoice == null) return null; if (invoice.TotalPrice <= sumPaidMoney) { //1=planlinib, 2 = gozlemede, 3=odenilib invoice.IsPaid = 3; } else if (invoice.TotalPrice > sumPaidMoney) { //1=planlinib, 2 = gozlemede, 3=odenilib invoice.IsPaid = 2; } else { //1=planlinib, 2 = gozlemede, 3=odenilib invoice.IsPaid = 1; } // if (invoice.ResidueForCalc != null) // { // invoice.ResidueForCalc = invoice.TotalPrice - sumPaidMoney; // _context.SaveChanges(); //} } await _context.SaveChangesAsync(); return null; } //Delete public async Task<IncomeItem> DeleteIncomeItem(int? incomeItemId) { if (incomeItemId == null) return null; // incomeitem var incomeItem = await _context.IncomeItems.Include(i => i.Invoice) .FirstOrDefaultAsync(f => f.Id == incomeItemId); if (incomeItem == null) return null; //Accounting #region Accounting var balancesheet = await _context.BalanceSheets.Where(w =>w.IncomeItemId == incomeItemId).ToListAsync(); var accountPlanDebit = _context.AccountsPlans.FirstOrDefault(f => f.Id == incomeItem.AccountDebitId); accountPlanDebit.Debit -= incomeItem.PaidMoney; _context.SaveChanges(); var accoutPlanKredit = _context.AccountsPlans.FirstOrDefault(f => f.Id == incomeItem.AccountKreditId); accoutPlanKredit.Kredit -= incomeItem.PaidMoney; _context.SaveChanges(); if (balancesheet != null) { _context.BalanceSheets.RemoveRange(balancesheet); } #endregion //invoice for update IsPaid var invoice = _context.Invoices.Find(incomeItem.InvoiceId); // deleted paidmoney sum of residueForCalc if (invoice.ResidueForCalc != null) { invoice.ResidueForCalc += incomeItem.PaidMoney; } //update invoice status if (invoice.TotalPrice <= invoice.ResidueForCalc && DateTime.Now > invoice.EndDate) { //1=planlinib, 2 = gozlemede, 3=odenilib,4 odenilmeyib invoice.IsPaid = 4; } else if (invoice.TotalPrice <= invoice.ResidueForCalc && DateTime.Now <= invoice.EndDate) { invoice.IsPaid = 1; } else if (invoice.TotalPrice > invoice.ResidueForCalc) { //1=planlinib, 2 = gozlemede, 3=odenilib,4 odenilmeyib invoice.IsPaid = 2; } else { //1=planlinib, 2 = gozlemede, 3=odenilib,4 odenilmeyib invoice.IsPaid = 3; } //Deleting Income where equal == deleted incomeitem incomeId And incomeItems Count equal 1 var income = _context.Incomes.Include(d => d.IncomeItems).FirstOrDefault(f => f.Id == incomeItem.IncomeId); if (income.IncomeItems.Count() == 1) { //first deleting incomeItems _context.IncomeItems.Remove(incomeItem); await _context.SaveChangesAsync(); //than deleting income _context.Incomes.Remove(income); await _context.SaveChangesAsync(); return incomeItem; } //deleting incomeItem without income _context.IncomeItems.Remove(incomeItem); await _context.SaveChangesAsync(); return incomeItem; } #endregion } } <file_sep>/AccountingApi/Models/InvoiceSentMail.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models { public class InvoiceSentMail { [Key] public int Id { get; set; } [MaxLength(50)] public string Email { get; set; } [MaxLength(100)] public string Token { get; set; } public int InvoiceId { get; set; } [Required, Range(1, 4)] public byte IsPaid { get; set; } = 1; public virtual Invoice Invoice { get; set; } } } <file_sep>/AccountingApi/Dtos/Nomenklatura/Product/ProductPostDto.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Nomenklatura.Product { public class ProductPostDto { [MaxLength(75)] public string Name { get; set; } public string PhotoFile { get; set; } [MaxLength(75)] public string Category { get; set; } public bool IsServiceOrProduct { get; set; } public int? UnitId { get; set; } public double? Price { get; set; } public double? SalePrice { get; set; } [MaxLength(75)] public string Account { get; set; } [MaxLength(275)] public string Desc { get; set; } public int? Count { get; set; } public bool IsSale { get; set; } public bool IsPurchase { get; set; } public int? TaxId { get; set; } } } <file_sep>/AccountingApi/Migrations/20190627125400_Income.cs using System; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace AccountingApi.Migrations { public partial class Income : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Incomes", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), TotalPrice = table.Column<double>(nullable: true), CreatedAt = table.Column<DateTime>(nullable: false), IsDeleted = table.Column<bool>(nullable: false), CompanyId = table.Column<int>(nullable: false), ContragentId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Incomes", x => x.Id); table.ForeignKey( name: "FK_Incomes_Companies_CompanyId", column: x => x.CompanyId, principalTable: "Companies", principalColumn: "Id", onDelete: ReferentialAction.NoAction); table.ForeignKey( name: "FK_Incomes_Contragents_ContragentId", column: x => x.ContragentId, principalTable: "Contragents", principalColumn: "Id", onDelete: ReferentialAction.NoAction); }); migrationBuilder.CreateTable( name: "IncomeItems", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Residue = table.Column<double>(nullable: true), TotalOneInvoice = table.Column<double>(nullable: true), PaidMoney = table.Column<double>(nullable: true), IsBank = table.Column<bool>(nullable: false), InvoiceNumber = table.Column<string>(nullable: true), InvoiceId = table.Column<int>(nullable: false), IncomeId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_IncomeItems", x => x.Id); table.ForeignKey( name: "FK_IncomeItems_Incomes_IncomeId", column: x => x.IncomeId, principalTable: "Incomes", principalColumn: "Id", onDelete: ReferentialAction.NoAction); table.ForeignKey( name: "FK_IncomeItems_Invoices_InvoiceId", column: x => x.InvoiceId, principalTable: "Invoices", principalColumn: "Id", onDelete: ReferentialAction.NoAction); }); migrationBuilder.CreateIndex( name: "IX_IncomeItems_IncomeId", table: "IncomeItems", column: "IncomeId"); migrationBuilder.CreateIndex( name: "IX_IncomeItems_InvoiceId", table: "IncomeItems", column: "InvoiceId"); migrationBuilder.CreateIndex( name: "IX_Incomes_CompanyId", table: "Incomes", column: "CompanyId"); migrationBuilder.CreateIndex( name: "IX_Incomes_ContragentId", table: "Incomes", column: "ContragentId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "IncomeItems"); migrationBuilder.DropTable( name: "Incomes"); } } } <file_sep>/AccountingApi/Models/BalanceSheet.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models { public class BalanceSheet { [Key] public int Id { get; set; } public double? DebitMoney { get; set; } public double? KreditMoney { get; set; } public DateTime CreatedAt { get; set; } public int CompanyId { get; set; } public int? AccountsPlanId { get; set; } public int? InvoiceId { get; set; } public int? IncomeItemId { get; set; } public int? ExpenseInvoiceId { get; set; } public int? ExpenseItemId { get; set; } public int? ManualJournalId { get; set; } public virtual Company Company { get; set; } public virtual AccountsPlan AccountsPlan { get; set; } public virtual Invoice Invoice { get; set; } public virtual IncomeItem IncomeItem { get; set; } public virtual ManualJournal ManualJournal { get; set; } } } <file_sep>/AccountingApi/Migrations/20190625074150_BalanceSheet.cs using System; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace AccountingApi.Migrations { public partial class BalanceSheet : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "BalanceSheets", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), DebitMoney = table.Column<double>(nullable: true), KreditMoney = table.Column<double>(nullable: true), CreatedAt = table.Column<DateTime>(nullable: false), CompanyId = table.Column<int>(nullable: false), AccountsPlanId = table.Column<int>(nullable: true), InvoiceId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_BalanceSheets", x => x.Id); table.ForeignKey( name: "FK_BalanceSheets_AccountsPlans_AccountsPlanId", column: x => x.AccountsPlanId, principalTable: "AccountsPlans", principalColumn: "Id", onDelete: ReferentialAction.NoAction); table.ForeignKey( name: "FK_BalanceSheets_Companies_CompanyId", column: x => x.CompanyId, principalTable: "Companies", principalColumn: "Id", onDelete: ReferentialAction.NoAction); table.ForeignKey( name: "FK_BalanceSheets_Invoices_InvoiceId", column: x => x.InvoiceId, principalTable: "Invoices", principalColumn: "Id", onDelete: ReferentialAction.NoAction); }); migrationBuilder.CreateIndex( name: "IX_BalanceSheets_AccountsPlanId", table: "BalanceSheets", column: "AccountsPlanId"); migrationBuilder.CreateIndex( name: "IX_BalanceSheets_CompanyId", table: "BalanceSheets", column: "CompanyId"); migrationBuilder.CreateIndex( name: "IX_BalanceSheets_InvoiceId", table: "BalanceSheets", column: "InvoiceId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "BalanceSheets"); } } } <file_sep>/AccountingApi/Models/ProposalSentMail.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models { public class ProposalSentMail { [Key] public int Id { get; set; } [MaxLength(50)] public string Email { get; set; } [MaxLength(100)] public string Token { get; set; } public int ProposalId { get; set; } [Required, Range(1, 4)] public byte IsPaid { get; set; } = 1; public virtual Proposal Proposal { get; set; } } } <file_sep>/AccountingApi/Models/ViewModel/VwInvoice.cs using AccountingApi.Dtos.Company; using AccountingApi.Dtos.Nomenklatura.Kontragent; using AccountingApi.Dtos.Sale.Invoice; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models.ViewModel { public class VwInvoice { public InvoicePostDto InvoicePostDto { get; set; } public List<InvoiceItemPostDto> InvoiceItemPosts { get; set; } public CompanyPutProposalDto CompanyPutProposalDto { get; set; } public ContragentPutInProposalDto ContragentPutInProposalDto { get; set; } } } <file_sep>/AccountingApi/Dtos/Sale/Income/IncomeInvoiceEditGetDto.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Sale.Income { public class IncomeInvoiceEditGetDto { public double? ResidueForCalc { get; set; } public int Id { get; set; } public string ContragentCompanyName { get; set; } public ICollection<IncomeItemInvoiceGetDto> IncomeItemInvoiceGetDtos { get; set; } public IncomeInvoiceEditGetDto() { IncomeItemInvoiceGetDtos = new Collection<IncomeItemInvoiceGetDto>(); } } } <file_sep>/AccountingApi/Models/ManualJournal.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models { public class ManualJournal { [Key] public int Id { get; set; } [MaxLength(300)] public string JurnalNumber { get; set; } [MaxLength(300)] public string JurnalName { get; set; } public DateTime CreatedAt { get; set; } public DateTime? Date { get; set; } [MaxLength(300)] public string Desc { get; set; } public double? Price { get; set; } public int? ContragentId { get; set; } public int CompanyId { get; set; } public int? AccountDebitId { get; set; } public int? AccountKreditId { get; set; } public int? OperationCategoryId { get; set; } public virtual Company Company { get; set; } public virtual Contragent Contragent { get; set; } public virtual OperationCategory OperationCategory { get; set; } [ForeignKey("AccountDebitId")] public virtual AccountsPlan AccountsPlanDebit { get; set; } [ForeignKey("AccountKreditId")] public virtual AccountsPlan AccountsPlanKredit { get; set; } public virtual ICollection<BalanceSheet> BalanceSheets { get; set; } } } <file_sep>/AccountingApi/Models/ViewModel/VwInvoicePut.cs using AccountingApi.Dtos.Company; using AccountingApi.Dtos.Nomenklatura.Kontragent; using AccountingApi.Dtos.Sale.Invoice; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models.ViewModel { public class VwInvoicePut { public InvoicePutDto InvoicePutDto { get; set; } public List<InvoiceItemPutDto> InvoiceItemPutDtos { get; set; } public CompanyPutProposalDto CompanyPutProposalDto { get; set; } public ContragentPutInProposalDto ContragentPutInProposalDto { get; set; } } } <file_sep>/AccountingApi/Data/DataContext.cs using AccountingApi.Models; using AccountingApi.Models.ProcudureDto; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Data { public class DataContext : DbContext { public DataContext(DbContextOptions<DataContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { //modelBuilder.Entity<Invoice>() // .HasRequired(m => m.) // .WithMany(t => t.HomeMatches) // .HasForeignKey(m => m.HomeTeamId) // .WillCascadeOnDelete(false); //modelBuilder.Entity<Match>() // .HasRequired(m => m.GuestTeam) // .WithMany(t => t.AwayMatches) // .HasForeignKey(m => m.GuestTeamId) // .WillCascadeOnDelete(false); base.OnModelCreating(modelBuilder); } //Procedure #region Procedure public DbQuery<BalanceSheetDto> BalanceSheetDtos { get; set; } public DbQuery<IncomeFromQueryDto> InExReportQuery { get; set; } public DbQuery<ExFromQueryDtoDto> ExFromQuery { get; set; } public DbQuery<IncomeReportDto> IncomesFromQuery { get; set; } public DbQuery<ExpenseReportDto> ExpensesFromQuery { get; set; } public DbQuery<ProductsFromQueryDto> ProductsFromQuery { get; set; } public DbQuery<InvoiceFromQueryDto> InvoiceFromQuery { get; set; } public DbQuery<ExpenseInvoiceFromQueryDto> ExpenseInvoiceFromQuery { get; set; } public DbQuery<ContragentFromQueryDto> ContragentFromQuery { get; set; } public DbQuery<WorkerFromQueryDto> WorkerFromQuery { get; set; } public DbQuery<NetIncomeFromQueryDto> NetIncomeFromQuery { get; set; } public DbQuery<JournalDto> JournalFromQuery { get; set; } public DbQuery<InvoiceReportByContragentDto> invoiceReportByContragents { get; set; } public DbQuery<ProductAllDto> ProductAllDtoQuery { get; set; } public DbQuery <ExpenseInvoiceReportByContragentDto> ExpenseInvoiceReportByContragents { get; set; } public DbQuery<ProductExpenseAllDto> ProductExpenseAllQuery { get; set; } public DbQuery<GetInvoiceProductCountByIdDto> GetInvoiceProductCountByIdQuery { get; set; } public DbQuery<InvoicesReportByContragentIdDto> InvoicesReportByContragentIdQuery { get; set; } public DbQuery<GetExpenseInvoiceProductCountByIdDto> GetExpenseInvoiceProductCountByIdQuery { get; set; } public DbQuery<ExpenseInvoiceReportByContragentIdDto> ExpenseInvoiceReportByContragentIdQuery { get; set; } #endregion public DbSet<User> Users { get; set; } public DbSet<Company> Companies { get; set; } public DbSet<Tax> Taxes { get; set; } public DbSet<Worker> Workers { get; internal set; } public DbSet<Worker_Detail> Worker_Details { get; set; } public DbSet<Stock> Stocks { get; set; } public DbSet<Product> Products { get; set; } public DbSet<Product_Unit> Product_Units { get; set; } public DbSet<Contragent> Contragents { get; set; } public DbSet<Contragent_Detail> Contragent_Details { get; set; } public DbSet<AccountsPlan> AccountsPlans { get; set; } public DbSet<Proposal> Proposals { get; set; } public DbSet<ProposalItem> ProposalItems { get; set; } public DbSet<ProposalSentMail> ProposalSentMails { get; set; } public DbSet<Invoice> Invoices { get; set; } public DbSet<InvoiceItem> InvoiceItems { get; set; } public DbSet<InvoiceSentMail> InvoiceSentMails { get; set; } public DbSet<BalanceSheet> BalanceSheets { get; set; } public DbSet<Income> Incomes { get; set; } public DbSet<IncomeItem> IncomeItems { get; set; } public DbSet<Expense> Expenses { get; set; } public DbSet<ExpenseInvoice> ExpenseInvoices { get; set; } public DbSet<ExpenseInvoiceItem> ExpenseInvoiceItems { get; set; } public DbSet<ExpenseItem> ExpenseItems { get; set; } public DbSet<ManualJournal> ManualJournals { get; set; } public DbSet<OperationCategory> OperationCategories { get; set; } public DbSet<UserSendMailChangePassword> UserSendMailChangePasswords { get; set; } } } <file_sep>/AccountingApi/Dtos/AccountsPlan/ManualJournalGetEditDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.AccountsPlan { public class ManualJournalGetEditDto { public string JurnalNumber { get; set; } public string JurnalName { get; set; } public DateTime? Date { get; set; } public string Desc { get; set; } public double? Price { get; set; } //Manual Journal public string AccountsPlanDebitAccPlanNumber { get; set; } public string AccountsPlanDebitName { get; set; } public string AccountsPlanKreditAccPlanNumber { get; set; } public string AccountsPlanKreditName { get; set; } public int? ContragentId { get; set; } public int? AccountDebitId { get; set; } public int? AccountKreditId { get; set; } public int? OperationCategoryId { get; set; } } } <file_sep>/AccountingApi/Helpers/AutoMapperProfile.cs using AccountingApi.Dtos; using AccountingApi.Dtos.Account; using AccountingApi.Dtos.AccountsPlan; using AccountingApi.Dtos.Company; using AccountingApi.Dtos.Nomenklatura.Kontragent; using AccountingApi.Dtos.Nomenklatura.Product; using AccountingApi.Dtos.Nomenklatura.Worker; using AccountingApi.Dtos.Purchase.Expense; using AccountingApi.Dtos.Purchase.ExpenseInvoice; using AccountingApi.Dtos.Sale.Income; using AccountingApi.Dtos.Sale.Invoice; using AccountingApi.Dtos.Sale.Proposal; using AccountingApi.Dtos.User; using AccountingApi.Models; using AccountingApi.Models.ProcudureDto; using AutoMapper; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Helpers { public class AutoMapperProfile: Profile { public AutoMapperProfile() { //App Url var appBaseUrl = MyHttpContext.AppBaseUrl; //Register #region User Company //Istifadeci //Qeydiyyat CreateMap<UserForRegisterDto, User>().ReverseMap(); CreateMap<User, UserForReturnDto>().ReverseMap(); //Sirket yaratmaq CreateMap<CompanyPostDto, Company>().ReverseMap(); CreateMap<CompanyPutDto, Company>().ReverseMap(); CreateMap<Company, CompanyGetDto>() .ForMember(dto => dto.PhotoUrl, opt => opt .MapFrom(src => src.PhotoUrl != null ? $"{appBaseUrl}/Uploads/" + src.PhotoUrl : "")); CreateMap<Company, CompanyEditDto>() .ForMember(dto => dto.PhotoUrl, opt => opt .MapFrom(src => src.PhotoUrl != null ? $"{appBaseUrl}/Uploads/" + src.PhotoUrl : "")); CreateMap<Company, CompanyPutProposalDto>(); // .ForMember(dto => dto.PhotoUrl, opt => opt //.MapFrom(src => $"{appBaseUrl}/Uploads/" + src.PhotoUrl)); CreateMap<Company, CompanyAfterPutDto>() .ForMember(dto => dto.PhotoUrl, opt => opt .MapFrom(src => src.PhotoUrl != null ? $"{appBaseUrl}/Uploads/" + src.PhotoUrl : "")); //Get User Edit CreateMap<User, UserGetEditDto>().ReverseMap(); //Put User CreateMap<UserPutDto, User>().ReverseMap(); #endregion //Employee #region Worker //Post CreateMap<WorkerPostDto, Worker>().ReverseMap(); CreateMap<WorkerPostDto, Worker_Detail>().ReverseMap(); //Get CreateMap<Worker, WorkerGetDto>() .ForMember(dto => dto.PhotoUrl, opt => opt .MapFrom(src => src.PhotoUrl != null ? $"{appBaseUrl}/Uploads/" + src.PhotoUrl : "")); CreateMap<Worker, WorkerEditDto>() .ForMember(dto => dto.PhotoUrl, opt => opt .MapFrom(src => src.PhotoUrl != null ? $"{appBaseUrl}/Uploads/" + src.PhotoUrl : "")); CreateMap<Worker_Detail, WorkerEditDto>(); // .ForMember(dto => dto.Birthday, opt => opt //.MapFrom(src => src.Birthday.Value.ToString("dd.MM.yyy"))); //Put CreateMap<WorkerPutDto, Worker>().ReverseMap(); CreateMap<WorkerPutDto, Worker_Detail>().ReverseMap(); #endregion //Product #region Product //Post CreateMap<ProductPostDto, Product>().ReverseMap(); CreateMap<ProductPostDto, Stock>().ReverseMap(); //Get CreateMap<Product, ProductGetDto>().ReverseMap(); // .ForMember(dto => dto.StockGet, opt => opt //.MapFrom(src => src.Stocks)); CreateMap<Stock, ProductGetDto>().ReverseMap(); CreateMap<Product, ProductGetEditDto>() .ForMember(dto => dto.PhotoUrl, opt => opt .MapFrom(src => src.PhotoUrl != null ? $"{appBaseUrl}/Uploads/" + src.PhotoUrl : "")); CreateMap<Stock, ProductGetEditDto>().ReverseMap(); //Put CreateMap<ProductPutDto, Product>().ReverseMap(); CreateMap<ProductPutDto, Stock>().ReverseMap(); #endregion //Contragent #region Contragent //Get CreateMap<Contragent, ContragentGetDto>() .ForMember(dto => dto.PhotoUrl, opt => opt .MapFrom(src => src.PhotoUrl != null ? $"{appBaseUrl}/Uploads/" + src.PhotoUrl : "")); CreateMap<Contragent, ContragentGetEditDto>() .ForMember(dto => dto.PhotoUrl, opt => opt .MapFrom(src => src.PhotoUrl != null ? $"{appBaseUrl}/Uploads/" + src.PhotoUrl : "")); CreateMap<Contragent_Detail, ContragentGetEditDto>(); //Post CreateMap<ContragentPostDto, Contragent>().ReverseMap(); CreateMap<ContragentPostDto, Contragent_Detail>().ReverseMap(); //Put CreateMap<ContragentPutDto, Contragent>().ReverseMap(); CreateMap<ContragentPutDto, Contragent_Detail>().ReverseMap(); #endregion //AccountsPlan #region AccounstPlan CreateMap<AccountsPlan, AccountsPlanGetDto>().ReverseMap(); CreateMap<BalanceSheetReturnDto, BalanceSheetReturnDto>().ReverseMap(); CreateMap<ManualJournalPostDto, ManualJournal>().ReverseMap(); CreateMap<ManualJournal, ManualJournalGetDto>().ReverseMap(); CreateMap<AccountsPlan, ManualJournalGetDto>().ReverseMap(); CreateMap<ManualJournal, ManualJournalGetEditDto>().ReverseMap(); CreateMap<AccountsPlan, ManualJournalGetEditDto>().ReverseMap(); CreateMap<JournalDto, JournalDto>().ReverseMap(); #endregion //Proposal #region Proposal //Post CreateMap<ProposalPostDto, Proposal>(); CreateMap<ProposalItemPostDto, ProposalItem>(); CreateMap<ContragentPutInProposalDto, Contragent>(); CreateMap<CompanyPutProposalDto, Company>(); //Get CreateMap<Proposal, ProposalGetDto>(); CreateMap<Tax, ProposalEditGetDto>().ReverseMap(); CreateMap<Proposal, ProposalEditGetDto>() .ForMember(dto => dto.ProposalItemGetDtos, opt => opt .MapFrom(src => src.ProposalItems.Select(s => new { ProductName = s.Product.Name, s.Id, s.SellPrice, s.Qty, s.ProductId, s.TotalOneProduct, s.Price }))); CreateMap<Company, ProposalEditGetDto>(); CreateMap<Contragent, ProposalEditGetDto>(); CreateMap<ProposalItem, ProposalItemGetDto>(); // .AfterMap((src, dto) => { dto.ProposalItems = src.ProposalItemPostDtos; }); //Put CreateMap<ProposalPutDto, Proposal>().ReverseMap(); CreateMap<ProposalItemPutDto, ProposalItem>().ReverseMap(); #endregion //Invoice #region Invoice //Post CreateMap<InvoicePostDto, Invoice>().ReverseMap(); CreateMap<InvoiceItemPostDto, InvoiceItem>().ReverseMap(); //Get CreateMap<Invoice, InvoiceGetDto>().ReverseMap(); //get for edit CreateMap<Invoice, InvoiceEditGetDto>() .ForMember(dto => dto.InvoiceItemGetDtos, opt => opt .MapFrom(src => src.InvoiceItems.Select(s => new { ProductName = s.Product.Name, s.Id, s.SellPrice, s.Qty, s.ProductId, s.TotalOneProduct, s.Price }))); CreateMap<Company, InvoiceEditGetDto>(); CreateMap<Contragent, InvoiceEditGetDto>(); CreateMap<Tax, InvoiceEditGetDto>().ReverseMap(); CreateMap<AccountsPlan, InvoiceEditGetDto>().ReverseMap(); CreateMap<InvoiceItem, InvoiceEditGetDto>(); //Put CreateMap<InvoicePutDto, Invoice>().ReverseMap(); CreateMap<InvoiceItemPutDto, InvoiceItem>().ReverseMap(); #endregion //Income #region Income //Get CreateMap<Invoice, IncomeInvoiceGetDto>(); CreateMap<IncomeItem, IncomeGetDto>().ReverseMap(); CreateMap<Income, IncomeEditGetDto>() .ForMember(dto => dto.IncomeItemGetDtos, opt => opt .MapFrom(src => src.IncomeItems.Select(s => new { s.IsBank, s.PaidMoney, s.Id, s.AccountDebitId, s.AccountKreditId, s.InvoiceNumber, s.Residue, s.InvoiceId, s.TotalOneInvoice }).ToList())); //https://localhost:44317/api/income/geteditincome //get edit income CreateMap<Invoice, IncomeInvoiceEditGetDto>().ForMember(dto => dto.IncomeItemInvoiceGetDtos, opt => opt .MapFrom(src => src.IncomeItems.Select(s => new { s.IsBank, s.PaidMoney, s.Id, IncomeCreatedAt = s.Income.CreatedAt, s.TotalOneInvoice, s.AccountDebitId, s.AccountKreditId, s.Date }))); CreateMap<IncomeItem, IncomeItemInvoiceGetDto>().ReverseMap(); CreateMap<Income, IncomeItemInvoiceGetDto>().ReverseMap(); CreateMap<IncomeItem, IncomeItemGetDto>().ReverseMap(); //Post CreateMap<IncomePostDto, Income>(); CreateMap<IncomeItemPostDto, IncomeItem>().ReverseMap(); CreateMap<IncomeItem,IncomeItemGetEditDto>().ReverseMap(); //Put CreateMap<IncomePutDto, Income>().ReverseMap(); //.ForMember(m => m, opt => opt.Ignore()); CreateMap<IncomeItemGetEditDto, IncomeItem>().ReverseMap(); //.EqualityComparison((sir, si) => sir.Id == si.Id); #endregion //ExpenseInvoice #region ExpenseInvoice //Post CreateMap<ExpenseInvoicePostDto, ExpenseInvoice>(); CreateMap<ExpenseInvoiceItemPostDto, ExpenseInvoiceItem>(); //Get CreateMap<ExpenseInvoice, ExpenseInvoiceGetDto>(); CreateMap<Contragent, ExpenseInvoiceGetDto>(); //get for edit CreateMap<ExpenseInvoice, ExpensiveInvoiceEditGetDto>() .ForMember(dto => dto.ExpensiveInvoiceItemGetDtos, opt => opt .MapFrom(src => src.ExpenseInvoiceItems.Select(s => new { ProductName = s.Product.Name, s.Id, s.Price, s.Qty, s.ProductId, s.TotalOneProduct }))); CreateMap<Company, ExpensiveInvoiceEditGetDto>(); CreateMap<Contragent, ExpensiveInvoiceEditGetDto>(); CreateMap<InvoiceItem, ExpensiveInvoiceEditGetDto>(); //Put CreateMap<ExpenseInvoicePutDto, ExpenseInvoice>().ReverseMap(); CreateMap<ExpenseInvoiceItemPutDto, ExpenseInvoiceItem>().ReverseMap(); #endregion //Expense #region Expense //Post: CreateMap<ExpensePostDto, Expense>(); CreateMap<ExpenseItemPostDto, ExpenseItem>(); //Get: CreateMap<Expense, ExpenseGetDto>().ReverseMap(); //get edit expense CreateMap<ExpenseInvoice, ExpenseExInvoiceEditGetDto>().ForMember(dto => dto.ExpenseItemInvoiceGetDtos, opt => opt .MapFrom(src => src.ExpenseItems.Select(s => new { s.IsBank, s.PaidMoney, s.Id, ExpenseCreatedAt = s.Expense.CreatedAt, s.TotalOneInvoice, s.AccountDebitId, s.AccountKreditId, s.Date }))); //Put: CreateMap<ExpenseItemGetDto, ExpenseItem>().ReverseMap(); #endregion //Report #region Report CreateMap<IncomeFromQueryDto, InExReportDto>().ReverseMap(); CreateMap<ExFromQueryDtoDto, InExReportDto>().ReverseMap(); CreateMap<IncomeReportDto, IncomeReportDto>().ReverseMap(); CreateMap<ExpenseReportDto, ExpenseReportDto>().ReverseMap(); CreateMap<ProductsFromQueryDto, ProductsReportDto>().ReverseMap(); CreateMap<InvoiceFromQueryDto, InvoiceReportDto>().ReverseMap(); CreateMap<ExpenseInvoiceFromQueryDto, ExpenseInvoiceFromQueryDto>().ReverseMap(); CreateMap<WorkerFromQueryDto, WorkerFromQueryDto>().ReverseMap(); CreateMap<NetIncomeFromQueryDto, NetIncomeFromQueryDto>().ReverseMap(); CreateMap<InvoiceReportByContragentDto, InvoiceReportByContragentDto>().ReverseMap(); CreateMap<ProductAllDto, ProductAllDto>().ReverseMap(); CreateMap<ExpenseInvoiceReportByContragentDto, ExpenseInvoiceReportByContragentDto>().ReverseMap(); CreateMap<ProductExpenseAllDto, ProductExpenseAllDto>().ReverseMap(); #endregion } } } <file_sep>/AccountingApi/Dtos/Company/CompanyGetDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Company { public class CompanyGetDto { public int Id { get; set; } public string CompanyName { get; set; } public string PhotoUrl { get; set; } public string Name { get; set; } public string Surname { get; set; } public string Postion { get; set; } public string FieldOfActivity { get; set; } public string VOEN { get; set; } public string Culture { get; set; } public string Weekday { get; set; } } } <file_sep>/AccountingApi/Models/IncomeItem.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models { public class IncomeItem { [Key] public int Id { get; set; } public double? Residue { get; set; } public double? TotalOneInvoice { get; set; } public double? PaidMoney { get; set; } public bool IsBank { get; set; } = false; [MaxLength(300)] public string InvoiceNumber { get; set; } public int InvoiceId { get; set; } public int IncomeId { get; set; } public DateTime? Date { get; set; } public int? AccountDebitId { get; set; } public int? AccountKreditId { get; set; } public virtual Invoice Invoice { get; set; } public virtual Income Income { get; set; } [ForeignKey("AccountDebitId")] public virtual AccountsPlan AccountsPlanDebit { get; set; } [ForeignKey("AccountKreditId")] public virtual AccountsPlan AccountsPlanKredit { get; set; } public virtual ICollection<BalanceSheet> BalanceSheets { get; set; } } } <file_sep>/AccountingApi/Dtos/Nomenklatura/Worker/WorkerEditDto.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Nomenklatura.Worker { public class WorkerEditDto { public int Id { get; set; } public string Name { get; set; } public string SurName { get; set; } public string Positon { get; set; } public double Salary { get; set; } public bool IsState { get; set; } public string Voen { get; set; } public string Departament { get; set; } public string PartofDepartament { get; set; } public string Role { get; set; } public string PhotoUrl { get; set; } public string FatherName { get; set; } public string Email { get; set; } public string Adress { get; set; } public string DSMF { get; set; } public string Phone { get; set; } public string MobilePhone { get; set; } public string Education { get; set; } public string EducationLevel { get; set; } public string Gender { get; set; } public DateTime? Birthday { get; set; } //public ICollection<Worker_DetailEditDto> Worker_DetailEditDtos { get; set; } //public WorkerEditDto() //{ // Worker_DetailEditDtos = new Collection<Worker_DetailEditDto>(); //} } } <file_sep>/AccountingApi/Models/ProcudureDto/IncomeFromQueryDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Models.ProcudureDto { public class IncomeFromQueryDto { public double? Total { get; set; } } } <file_sep>/AccountingApi/Data/Repository/Interface/ISaleRepository.cs using AccountingApi.Dtos.Sale.Income; using AccountingApi.Dtos.Sale.Invoice; using AccountingApi.Dtos.Sale.Proposal; using AccountingApi.Models; using EOfficeAPI.Helpers.Pagination; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Data.Repository.Interface { public interface ISaleRepository { //Proposal #region Proposal //Post //Creating proposal repo Task<Proposal> CreateProposal(Proposal proposalRepo, int? companyId); //creating proposalitem repo Task<IEnumerable<ProposalItem>> CreateProposalItems(IEnumerable<ProposalItem> items, int? proposalId); //Email ProposalSentMail CreateProposalSentMail(int? proposalId, string email); Proposal GetProposalByToken(string token); //Get //get company by id Task<Company> GetEditCompany(int? companyId); //get contragent by id Task<Contragent> GetEditContragent(int? companyId); // get all proposal Task<List<ProposalGetDto>> GetProposal(PaginationParam productParam, int? companyId); //get proposal detail Task<Proposal> GetDetailProposal(int? proposalId, int? companyId); //get proposal by id Task<Proposal> GetEditProposal(int? proposalId, int? companyId); //get proposalitem by proposalid Task<List<ProposalItem>> GetEditProposalItem(int? proposalId); //get contragent by contragent id Task<Contragent> GetContragentProposal(int? companyId, int? proposalId); //Put //when creating proposal edit company Task<Company> EditCompany(Company company, int? companyId, int? userId); //when creating proposal edit company Task<Contragent> EditContragent(Contragent contragent, int? companyId); // edit proposal by id Task<Proposal> EditProposal(Proposal proposal, List<ProposalItem> proposalItems, int? proposalId); //Checking Task<bool> CheckProposal(int? currentUserId, int? companyId); Task<bool> CheckProposalProductId(IEnumerable<ProposalItem> proposalItem); Task<bool> CheckProposalId(int? productId, int? companyId); Task<bool> CheckContragentId(int? contragentId, int? companyId); //Delete Task<ProposalItem> DeleteProposalItem(int? proposalItemId); Task<Proposal> DeleteProposal(int? companyId, int? proposalId); #endregion //Invoice #region Invoice //Post Task<Invoice> CreateInvoice(Invoice invoice, int? companyId); Task<List<InvoiceItem>> CreateInvoiceItems(List<InvoiceItem> items, int? invoiceId); //Get //get all invoice Task<List<InvoiceGetDto>> GetInvoice(PaginationParam productParam, int? companyId); //get for edit invoice by id Task<Invoice> GetDetailInvoice(int? invoiceId, int? companyId); Task<Invoice> GetEditInvoice(int? invoiceId, int? companyId); //get for edit invoice by id Task<List<InvoiceItem>> GetEditInvoiceItem(int? invoiceId); Task<Contragent> GetContragentInvoice(int? companyId, int? invoiceId); //Put // edit edit by id Task<Invoice> EditInvoice(Invoice invoice, List<InvoiceItem> invoiceItems, int? invoiceId); //Delete Task<InvoiceItem> DeleteInvoiceItem(int? invoiceItemId); Task<Invoice> DeleteInvoice(int? companyId, int? invoiceId); //Checking Task<bool> CheckInvoice(int? currentUserId, int? companyId); Task<bool> CheckInvoiceProductId(List<InvoiceItem> invoiceItems); Task<bool> CheckInvoiceId(int? invoiceId, int? companyId); Task<bool> CheckInvoiceItem(int? invoiceId, List<InvoiceItem> invoiceItems); bool CheckInvoiceNegativeValue(Invoice invoice, List<InvoiceItem> items); //checking exist income Task<bool> CheckExistIncomeByInvoiceId(int? invoiceId); //Email InvoiceSentMail CreateInvoiceSentMail(int? invoiceId, string email); Invoice GetInvoiceByToken(string token); //Accounting Update InvoicePutDto UpdateInvoiceAccountDebit(int? invoiceId, int? companyId, InvoicePutDto invoice, int? OldDebitId); InvoicePutDto UpdateInvoiceAccountKredit(int? invoiceId, int? companyId, InvoicePutDto invoice, int? OldKeditId); #endregion //Income #region Income //Get List<IncomeInvoiceGetDto> GetInvoiceByContragentId(int? contragentId, int? companyId); Task<List<IncomeGetDto>> GetIncome(PaginationParam productParam, int? companyId); Task<Income> DetailIncome(int? incomeId, int? companyId); Task<Income> GetEditIncome(int? incomeId, int? companyId); Task<List<IncomeItem>> GetEditIncomeItems(int? incomeId); Task<Invoice> GetInvoiceIcomeItem(int? companyId, int? invoiceId); //Post: Task<Income> CreateIncome(int? companyId, int? contagentId, int[] Ids, Income income, List<IncomeItem> incomes); //Put: Task<IncomeItem> EditIncome(List<IncomeItemGetEditDto> itemGetDtos, int? invoiceId); //Check: #region Check Task<bool> CheckIncome(int? currentUserId, int? companyId); Task<bool> CheckIncomeContragentIdInvoiceId(int? contragentId, int? companyId); Task<bool> CheckIncomeEqualingInvoiceTotalPriceForUpdate(List<IncomeItemGetEditDto> incomeItems); Task<bool> CheckIncomeEqualingInvoiceTotalPriceForCreate(List<IncomeItem> incomeItems); bool CheckIncomeNegativeValue(Income income, List<IncomeItem> incomes); bool CheckIncomeUpdateNegativeValue(List<IncomeItemGetEditDto> incomes); //Account: List<IncomeItemGetEditDto> UpdateIncomeAccountDebit( int? companyId, List<IncomeItemGetEditDto> incomeItem); List<IncomeItemGetEditDto> UpdateIncomeAccountKredit( int? companyId, List<IncomeItemGetEditDto> incomeItem); #endregion //Delete: Task<IncomeItem> DeleteIncomeItem(int? incomeItem); #endregion } } <file_sep>/AccountingApi/Migrations/20190629212054_Expense.cs using System; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace AccountingApi.Migrations { public partial class Expense : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<int>( name: "ExpenseInvoiceId", table: "BalanceSheets", nullable: true); migrationBuilder.AddColumn<int>( name: "ExpenseItemId", table: "BalanceSheets", nullable: true); migrationBuilder.CreateTable( name: "ExpenseInvoices", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), ExpenseInvoiceNumber = table.Column<string>(maxLength: 250, nullable: true), PreparingDate = table.Column<DateTime>(nullable: true), EndDate = table.Column<DateTime>(nullable: true), CreatedAt = table.Column<DateTime>(nullable: false), TotalPrice = table.Column<double>(nullable: true), ResidueForCalc = table.Column<double>(nullable: true), TotalTax = table.Column<double>(nullable: true), Sum = table.Column<double>(nullable: true), IsPaid = table.Column<byte>(nullable: false), Desc = table.Column<string>(maxLength: 300, nullable: true), IsDeleted = table.Column<bool>(nullable: false), ContragentId = table.Column<int>(nullable: true), CompanyId = table.Column<int>(nullable: false), TaxId = table.Column<int>(nullable: true), AccountDebitId = table.Column<int>(nullable: true), AccountKreditId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_ExpenseInvoices", x => x.Id); table.ForeignKey( name: "FK_ExpenseInvoices_AccountsPlans_AccountDebitId", column: x => x.AccountDebitId, principalTable: "AccountsPlans", principalColumn: "Id", onDelete: ReferentialAction.NoAction); table.ForeignKey( name: "FK_ExpenseInvoices_AccountsPlans_AccountKreditId", column: x => x.AccountKreditId, principalTable: "AccountsPlans", principalColumn: "Id", onDelete: ReferentialAction.NoAction); table.ForeignKey( name: "FK_ExpenseInvoices_Companies_CompanyId", column: x => x.CompanyId, principalTable: "Companies", principalColumn: "Id", onDelete: ReferentialAction.NoAction); table.ForeignKey( name: "FK_ExpenseInvoices_Contragents_ContragentId", column: x => x.ContragentId, principalTable: "Contragents", principalColumn: "Id", onDelete: ReferentialAction.NoAction); table.ForeignKey( name: "FK_ExpenseInvoices_Taxes_TaxId", column: x => x.TaxId, principalTable: "Taxes", principalColumn: "Id", onDelete: ReferentialAction.NoAction); }); migrationBuilder.CreateTable( name: "Expenses", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), TotalPrice = table.Column<double>(nullable: true), CreatedAt = table.Column<DateTime>(nullable: false), IsDeleted = table.Column<bool>(nullable: false), CompanyId = table.Column<int>(nullable: false), ContragentId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Expenses", x => x.Id); table.ForeignKey( name: "FK_Expenses_Companies_CompanyId", column: x => x.CompanyId, principalTable: "Companies", principalColumn: "Id", onDelete: ReferentialAction.NoAction); table.ForeignKey( name: "FK_Expenses_Contragents_ContragentId", column: x => x.ContragentId, principalTable: "Contragents", principalColumn: "Id", onDelete: ReferentialAction.NoAction); }); migrationBuilder.CreateTable( name: "ExpenseInvoiceItems", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Qty = table.Column<int>(nullable: true), Price = table.Column<double>(nullable: true), TotalOneProduct = table.Column<double>(nullable: true), ProductId = table.Column<int>(nullable: true), ExpenseInvoiceId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_ExpenseInvoiceItems", x => x.Id); table.ForeignKey( name: "FK_ExpenseInvoiceItems_ExpenseInvoices_ExpenseInvoiceId", column: x => x.ExpenseInvoiceId, principalTable: "ExpenseInvoices", principalColumn: "Id", onDelete: ReferentialAction.NoAction); table.ForeignKey( name: "FK_ExpenseInvoiceItems_Products_ProductId", column: x => x.ProductId, principalTable: "Products", principalColumn: "Id", onDelete: ReferentialAction.NoAction); }); migrationBuilder.CreateTable( name: "ExpenseItems", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Residue = table.Column<double>(nullable: true), TotalOneInvoice = table.Column<double>(nullable: true), PaidMoney = table.Column<double>(nullable: true), IsBank = table.Column<bool>(nullable: false), InvoiceNumber = table.Column<string>(nullable: true), ExpenseInvoiceId = table.Column<int>(nullable: false), ExpenseId = table.Column<int>(nullable: false), AccountDebitId = table.Column<int>(nullable: true), AccountKreditId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_ExpenseItems", x => x.Id); table.ForeignKey( name: "FK_ExpenseItems_AccountsPlans_AccountDebitId", column: x => x.AccountDebitId, principalTable: "AccountsPlans", principalColumn: "Id", onDelete: ReferentialAction.NoAction); table.ForeignKey( name: "FK_ExpenseItems_AccountsPlans_AccountKreditId", column: x => x.AccountKreditId, principalTable: "AccountsPlans", principalColumn: "Id", onDelete: ReferentialAction.NoAction); table.ForeignKey( name: "FK_ExpenseItems_Expenses_ExpenseId", column: x => x.ExpenseId, principalTable: "Expenses", principalColumn: "Id", onDelete: ReferentialAction.NoAction); table.ForeignKey( name: "FK_ExpenseItems_ExpenseInvoices_ExpenseInvoiceId", column: x => x.ExpenseInvoiceId, principalTable: "ExpenseInvoices", principalColumn: "Id", onDelete: ReferentialAction.NoAction); }); migrationBuilder.CreateIndex( name: "IX_BalanceSheets_ExpenseInvoiceId", table: "BalanceSheets", column: "ExpenseInvoiceId"); migrationBuilder.CreateIndex( name: "IX_BalanceSheets_ExpenseItemId", table: "BalanceSheets", column: "ExpenseItemId"); migrationBuilder.CreateIndex( name: "IX_ExpenseInvoiceItems_ExpenseInvoiceId", table: "ExpenseInvoiceItems", column: "ExpenseInvoiceId"); migrationBuilder.CreateIndex( name: "IX_ExpenseInvoiceItems_ProductId", table: "ExpenseInvoiceItems", column: "ProductId"); migrationBuilder.CreateIndex( name: "IX_ExpenseInvoices_AccountDebitId", table: "ExpenseInvoices", column: "AccountDebitId"); migrationBuilder.CreateIndex( name: "IX_ExpenseInvoices_AccountKreditId", table: "ExpenseInvoices", column: "AccountKreditId"); migrationBuilder.CreateIndex( name: "IX_ExpenseInvoices_CompanyId", table: "ExpenseInvoices", column: "CompanyId"); migrationBuilder.CreateIndex( name: "IX_ExpenseInvoices_ContragentId", table: "ExpenseInvoices", column: "ContragentId"); migrationBuilder.CreateIndex( name: "IX_ExpenseInvoices_TaxId", table: "ExpenseInvoices", column: "TaxId"); migrationBuilder.CreateIndex( name: "IX_ExpenseItems_AccountDebitId", table: "ExpenseItems", column: "AccountDebitId"); migrationBuilder.CreateIndex( name: "IX_ExpenseItems_AccountKreditId", table: "ExpenseItems", column: "AccountKreditId"); migrationBuilder.CreateIndex( name: "IX_ExpenseItems_ExpenseId", table: "ExpenseItems", column: "ExpenseId"); migrationBuilder.CreateIndex( name: "IX_ExpenseItems_ExpenseInvoiceId", table: "ExpenseItems", column: "ExpenseInvoiceId"); migrationBuilder.CreateIndex( name: "IX_Expenses_CompanyId", table: "Expenses", column: "CompanyId"); migrationBuilder.CreateIndex( name: "IX_Expenses_ContragentId", table: "Expenses", column: "ContragentId"); migrationBuilder.AddForeignKey( name: "FK_BalanceSheets_ExpenseInvoices_ExpenseInvoiceId", table: "BalanceSheets", column: "ExpenseInvoiceId", principalTable: "ExpenseInvoices", principalColumn: "Id", onDelete: ReferentialAction.NoAction); migrationBuilder.AddForeignKey( name: "FK_BalanceSheets_ExpenseItems_ExpenseItemId", table: "BalanceSheets", column: "ExpenseItemId", principalTable: "ExpenseItems", principalColumn: "Id", onDelete: ReferentialAction.NoAction); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_BalanceSheets_ExpenseInvoices_ExpenseInvoiceId", table: "BalanceSheets"); migrationBuilder.DropForeignKey( name: "FK_BalanceSheets_ExpenseItems_ExpenseItemId", table: "BalanceSheets"); migrationBuilder.DropTable( name: "ExpenseInvoiceItems"); migrationBuilder.DropTable( name: "ExpenseItems"); migrationBuilder.DropTable( name: "Expenses"); migrationBuilder.DropTable( name: "ExpenseInvoices"); migrationBuilder.DropIndex( name: "IX_BalanceSheets_ExpenseInvoiceId", table: "BalanceSheets"); migrationBuilder.DropIndex( name: "IX_BalanceSheets_ExpenseItemId", table: "BalanceSheets"); migrationBuilder.DropColumn( name: "ExpenseInvoiceId", table: "BalanceSheets"); migrationBuilder.DropColumn( name: "ExpenseItemId", table: "BalanceSheets"); } } } <file_sep>/AccountingApi/Models/ViewModel/VwExpensePut.cs using AccountingApi.Dtos.Purchase.Expense; using AccountingApi.Dtos.Sale.Income; using System.Collections.Generic; namespace AccountingApi.Models.ViewModel { public class VwExpensePut { public IncomePutDto IncomePutDto { get; set; } public List<ExpenseItemGetDto> ExpenseItemGetDtos { get; set; } } } <file_sep>/AccountingApi/Helpers/MailExtention.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Mail; using System.Threading.Tasks; namespace EOfficeAPI.Helpers { public static class MailExtention { public static void Send(string subject, string body, string email) { var message = new MailMessage(); message.To.Add(new MailAddress(email)); // replace with valid value message.From = new MailAddress("<EMAIL>"); // replace with valid value message.Subject = subject; message.Body = body; message.IsBodyHtml = true; using (var smtp = new SmtpClient()) { var credential = new NetworkCredential { UserName = "<EMAIL>", Password = "<PASSWORD>" }; smtp.Credentials = credential; smtp.Host = "smtp.yandex.com"; //smtp.Host = "smtp.live.com"; smtp.Port = 587; smtp.EnableSsl = true; smtp.Send(message); return; } } public static void SendPasswordEmail(string email, string token) { //calling for creating the email body with html template string body = string.Empty; using (StreamReader reader = new StreamReader("wwwroot/Templates/PasswordChange.html")) { body = reader.ReadToEnd(); } body = body.Replace("{{token}}", token); //replacing the required things Send("eOffice xoşgəldiniz", body, email); return; } } }<file_sep>/AccountingApi/Migrations/20190625071315_Invoice.cs using System; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; namespace AccountingApi.Migrations { public partial class Invoice : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<string>( name: "Obeysto", table: "AccountsPlans", maxLength: 350, nullable: true, oldClrType: typeof(string), oldNullable: true); migrationBuilder.CreateTable( name: "Invoices", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), InvoiceNumber = table.Column<string>(maxLength: 250, nullable: true), PreparingDate = table.Column<DateTime>(nullable: true), EndDate = table.Column<DateTime>(nullable: true), CreatedAt = table.Column<DateTime>(nullable: false), TotalPrice = table.Column<double>(nullable: true), ResidueForCalc = table.Column<double>(nullable: true), TotalTax = table.Column<double>(nullable: true), Sum = table.Column<double>(nullable: true), Desc = table.Column<string>(maxLength: 300, nullable: true), IsPaid = table.Column<byte>(nullable: false), IsDeleted = table.Column<bool>(nullable: false), ContragentId = table.Column<int>(nullable: true), CompanyId = table.Column<int>(nullable: false), TaxId = table.Column<int>(nullable: true), AccountDebitId = table.Column<int>(nullable: true), AccountKreditId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Invoices", x => x.Id); table.ForeignKey( name: "FK_Invoices_AccountsPlans_AccountDebitId", column: x => x.AccountDebitId, principalTable: "AccountsPlans", principalColumn: "Id", onDelete: ReferentialAction.NoAction); table.ForeignKey( name: "FK_Invoices_AccountsPlans_AccountKreditId", column: x => x.AccountKreditId, principalTable: "AccountsPlans", principalColumn: "Id", onDelete: ReferentialAction.NoAction); table.ForeignKey( name: "FK_Invoices_Companies_CompanyId", column: x => x.CompanyId, principalTable: "Companies", principalColumn: "Id", onDelete: ReferentialAction.NoAction); table.ForeignKey( name: "FK_Invoices_Contragents_ContragentId", column: x => x.ContragentId, principalTable: "Contragents", principalColumn: "Id", onDelete: ReferentialAction.NoAction); table.ForeignKey( name: "FK_Invoices_Taxes_TaxId", column: x => x.TaxId, principalTable: "Taxes", principalColumn: "Id", onDelete: ReferentialAction.NoAction); }); migrationBuilder.CreateTable( name: "InvoiceItems", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Qty = table.Column<int>(nullable: true), Price = table.Column<double>(nullable: true), SellPrice = table.Column<double>(nullable: true), TotalOneProduct = table.Column<double>(nullable: true), ProductId = table.Column<int>(nullable: true), InvoiceId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_InvoiceItems", x => x.Id); table.ForeignKey( name: "FK_InvoiceItems_Invoices_InvoiceId", column: x => x.InvoiceId, principalTable: "Invoices", principalColumn: "Id", onDelete: ReferentialAction.NoAction); table.ForeignKey( name: "FK_InvoiceItems_Products_ProductId", column: x => x.ProductId, principalTable: "Products", principalColumn: "Id", onDelete: ReferentialAction.NoAction); }); migrationBuilder.CreateTable( name: "InvoiceSentMails", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Email = table.Column<string>(maxLength: 50, nullable: true), Token = table.Column<string>(maxLength: 100, nullable: true), InvoiceId = table.Column<int>(nullable: false), IsPaid = table.Column<byte>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_InvoiceSentMails", x => x.Id); table.ForeignKey( name: "FK_InvoiceSentMails_Invoices_InvoiceId", column: x => x.InvoiceId, principalTable: "Invoices", principalColumn: "Id", onDelete: ReferentialAction.NoAction); }); migrationBuilder.CreateIndex( name: "IX_InvoiceItems_InvoiceId", table: "InvoiceItems", column: "InvoiceId"); migrationBuilder.CreateIndex( name: "IX_InvoiceItems_ProductId", table: "InvoiceItems", column: "ProductId"); migrationBuilder.CreateIndex( name: "IX_Invoices_AccountDebitId", table: "Invoices", column: "AccountDebitId"); migrationBuilder.CreateIndex( name: "IX_Invoices_AccountKreditId", table: "Invoices", column: "AccountKreditId"); migrationBuilder.CreateIndex( name: "IX_Invoices_CompanyId", table: "Invoices", column: "CompanyId"); migrationBuilder.CreateIndex( name: "IX_Invoices_ContragentId", table: "Invoices", column: "ContragentId"); migrationBuilder.CreateIndex( name: "IX_Invoices_TaxId", table: "Invoices", column: "TaxId"); migrationBuilder.CreateIndex( name: "IX_InvoiceSentMails_InvoiceId", table: "InvoiceSentMails", column: "InvoiceId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "InvoiceItems"); migrationBuilder.DropTable( name: "InvoiceSentMails"); migrationBuilder.DropTable( name: "Invoices"); migrationBuilder.AlterColumn<string>( name: "Obeysto", table: "AccountsPlans", nullable: true, oldClrType: typeof(string), oldMaxLength: 350, oldNullable: true); } } } <file_sep>/AccountingApi/Dtos/Purchase/ExpenseInvoice/ExpenseInvoicePostDto.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Purchase.ExpenseInvoice { public class ExpenseInvoicePostDto { public string ExpenseInvoiceNumber { get; set; } public DateTime? PreparingDate { get; set; } public DateTime? EndDate { get; set; } public double? TotalPrice { get; set; } public double? TotalTax { get; set; } public double? Sum { get; set; } public string Desc { get; set; } public int? ContragentId { get; set; } public int CompanyId { get; set; } public int? TaxId { get; set; } public int? AccountDebitId { get; set; } public int? AccountKreditId { get; set; } public ICollection<ExpenseInvoiceItemPostDto> ExpenseInvoiceItemPostDtos { get; set; } public ExpenseInvoicePostDto() { ExpenseInvoiceItemPostDtos = new Collection<ExpenseInvoiceItemPostDto>(); } } } <file_sep>/AccountingApi/Dtos/Account/BalanceSheetReturnDto.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AccountingApi.Dtos.Account { public class BalanceSheetReturnDto { public string AccPlanNumber { get; set; } public string Name { get; set; } public double? startCircleDebit { get; set; } public double? startCircleKredit { get; set; } public double? allCircleDebit { get; set; } public double? allCircleKredit { get; set; } public double? endCircleDebit { get; set; } public double? endCircleKredit { get; set; } } }
13a9136c2712aa58d2c40c4a740e49de83425cf5
[ "C#" ]
130
C#
tofigf/AccountingApi
e1da609ad757416be2e6537663d1d16d0d11fc75
cd2ac6157e5e660debe75ebee0b23a0651bda426
refs/heads/master
<repo_name>hansguichuideng/dubbo_zk<file_sep>/mypay/src/main/java/com/summer/mypay/pojo/ClientMessage.java package com.summer.mypay.pojo; /** * 客户端发送到系统的pojo类,要求,每个客户端信息要带上clientName字段 */ public class ClientMessage { public static int init = 0; public static int living = 1; //保活 public static int qr_query = 2; //二维码请求 public static int orderInfo = 3; //查看订单信息 public static int cookie_query = 4; //查看订单信息 public static int requestOrderNoSend = 5; //查看订单信息 public static int log = 6; //日志信息 private String clientName; private Integer type; //0:表示初始化, 1:保活信息 2:业务信息需要逻辑处理, 3二维码请求 private String mid; private String content; public ClientMessage() { } public ClientMessage(String clientName, String content) { this.clientName = clientName; this.mid = new StringBuffer(clientName).append("_").append(System.currentTimeMillis()).toString(); this.content = content; } public String getClientName() { return clientName; } public void setClientName(String clientName) { this.clientName = clientName; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getMid() { return mid; } public void setMid(String mid) { this.mid = mid; } } <file_sep>/consumer/src/main/java/com/summer/service/DemoServiceImpl.java package com.summer.service; import com.alibaba.dubbo.config.annotation.Reference; import org.springframework.stereotype.Service; @Service public class DemoServiceImpl { @Reference private DemoService demoService; public String test() { return demoService.hello("summer"); } } <file_sep>/mypay/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.summer</groupId> <artifactId>mypay</artifactId> <version>1.1-SNAPSHOT</version> <!-- Inherit defaults from Spring Boot --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> </parent> <!-- Add typical dependencies for a web application --> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp --> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.10.0</version> </dependency> <!-- https://mvnrepository.com/artifact/com.google.guava/guava --> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>22.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.6</version> </dependency> <!-- https://mvnrepository.com/artifact/org.jsoup/jsoup --> <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.8.3</version> </dependency> <!-- https://mvnrepository.com/artifact/com.jolbox/bonecp --> <dependency> <groupId>com.jolbox</groupId> <artifactId>bonecp</artifactId> <version>0.8.0.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.34</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-collections4</artifactId> <version>4.1</version> </dependency> <!-- https://mvnrepository.com/artifact/cn.hutool/hutool-core --> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-core</artifactId> <version>4.1.12</version> </dependency> <!-- https://mvnrepository.com/artifact/com.warrenstrange/googleauth --> <dependency> <groupId>com.warrenstrange</groupId> <artifactId>googleauth</artifactId> <version>1.2.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> <version>2.0.1.RELEASE</version> </dependency> </dependencies> <!-- Package as an executable jar --> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project><file_sep>/mypay/src/main/java/com/summer/mypay/Test.java package com.summer.mypay; public class Test { int a = 0; volatile int b = 0; public void t1() { int r2 = a; System.out.println("---r2 : " + r2); b = 1; } public void t2() { int r1 = b; System.out.println("---r1 : " + r1); a = 2; } public static void main(String[] args) { Test t = new Test(); Thread t2 = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("t2"); } }); Thread t1 = new Thread(new Runnable() { @Override public void run() { System.out.println("t1"); } }); // t2.start(); t1.start(); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } try { // t2.join(); System.out.println(t1.isAlive()); t1.wait(); // Thread.yield(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("------"); } } <file_sep>/mypay/src/main/java/com/summer/mypay/pojo/WebSocketResult.java package com.summer.mypay.pojo; import java.util.HashMap; public class WebSocketResult extends HashMap<String, String> { public static String mid = "mid"; public static String content = "content"; public WebSocketResult(String _mid, String _content) { super.put(mid, _mid); super.put(content, _content); } public static void main(String[] args) { System.out.println(new WebSocketResult("1", "hello my test")); } } <file_sep>/mypay/src/main/java/com/summer/mypay/controller/websocket/WebsocketController.java package com.summer.mypay.controller.websocket; import com.alibaba.fastjson.JSONObject; import com.summer.mypay.pojo.ClientMessage; import com.summer.mypay.pojo.ReturnResult; import com.summer.mypay.pojo.WebSocketResult; import com.summer.mypay.service.websocket.WebSocketService; import com.summer.mypay.view.JsonView; import com.summer.mypay.view.WebsocketView; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; /** * websocket的controller层 * <p> * <p> * 当外界请求websocket数据时,得到请求的参数会包装成ClientMessage对像 * clientName: 请求客户端 * mid: 请求id全局唯一 * content: json串格式的请求内容 * <p> * 返回数据永远为 ReturnResult 格式, 在视图解释器里做操作 */ @RestController public class WebsocketController { @Autowired private WebSocketService webSocketService; /** * 请求二维码 * * @param clientName 请求客户端 * @param money 金额 * @param mark 自定义交易号 * @return */ @RequestMapping("requestQR") public Object requestQR(@RequestParam("clientName") String clientName, @RequestParam("money") String money, @RequestParam("mark") String mark, String type) { JSONObject params = new JSONObject(); params.put("clientName", clientName); params.put("money", money); params.put("mark", mark); params.put("type", type); ClientMessage clientMessage = new ClientMessage(clientName, params.toJSONString()); clientMessage.setType(ClientMessage.qr_query); ReturnResult tmpResult = webSocketService.sendMessage(clientMessage); if (tmpResult.getCode() != 200) { return new ModelAndView(JsonView.BEANNAME, new WebSocketResult(clientMessage.getMid(), JSONObject.toJSONString(tmpResult))); } return new ModelAndView(WebsocketView.BEANNAME, new WebSocketResult(clientMessage.getMid(), null)); } /** * 请求交易信息 * * @param clientName 请求客户端 * @param mark 自定义交易号 * @return */ @RequestMapping("requestOrderInfo") public ModelAndView requestOrderInfo(@RequestParam("clientName") String clientName, @RequestParam("mark") String mark) { JSONObject params = new JSONObject(); params.put("clientName", clientName); params.put("mark", mark); ClientMessage clientMessage = new ClientMessage(clientName, params.toJSONString()); clientMessage.setType(ClientMessage.orderInfo); ReturnResult tmpResult = webSocketService.sendMessage(clientMessage); if (tmpResult.getCode() != 200) { return new ModelAndView(JsonView.BEANNAME, new WebSocketResult(clientMessage.getMid(), JSONObject.toJSONString(tmpResult))); } return new ModelAndView(WebsocketView.BEANNAME, new WebSocketResult(clientMessage.getMid(), null)); } /** * 请求交易信息 * * @param clientName 请求客户端 * @return */ @RequestMapping("requestCookies") public ModelAndView requestCookies(@RequestParam("clientName") String clientName) { JSONObject params = new JSONObject(); params.put("clientName", clientName); ClientMessage clientMessage = new ClientMessage(clientName, params.toJSONString()); clientMessage.setType(ClientMessage.cookie_query); ReturnResult tmpResult = webSocketService.sendMessage(clientMessage); if (tmpResult.getCode() != 200) { return new ModelAndView(JsonView.BEANNAME, new WebSocketResult(clientMessage.getMid(), JSONObject.toJSONString(tmpResult))); } return new ModelAndView(WebsocketView.BEANNAME, new WebSocketResult(clientMessage.getMid(), null)); } /** * 请求交易信息 * * @param clientName 请求客户端 * @return */ @RequestMapping("requestOrderNoSend") public ModelAndView requestOrderNoSend(@RequestParam("clientName") String clientName) { JSONObject params = new JSONObject(); params.put("clientName", clientName); ClientMessage clientMessage = new ClientMessage(clientName, params.toJSONString()); clientMessage.setType(ClientMessage.requestOrderNoSend); ReturnResult tmpResult = webSocketService.sendMessage(clientMessage); if (tmpResult.getCode() != 200) { return new ModelAndView(JsonView.BEANNAME, new WebSocketResult(clientMessage.getMid(), JSONObject.toJSONString(tmpResult))); } return new ModelAndView(WebsocketView.BEANNAME, new WebSocketResult(clientMessage.getMid(), null)); } /** * 请求交易信息 * * @param clientName 请求客户端 * @return */ @RequestMapping("isLive") @ResponseBody public Object isLive(@RequestParam("clientName") String clientName) { ReturnResult tmpResult = webSocketService.isLive(clientName); return tmpResult; } } <file_sep>/mypay/src/main/java/com/summer/mypay/pojo/ReturnResult.java package com.summer.mypay.pojo; public class ReturnResult { private int code = 200; private Object data; private String msg; public ReturnResult() { } public ReturnResult(Object data) { this.data = data; } public ReturnResult(int code, String msg) { this.code = code; this.msg = msg; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } } <file_sep>/mypay/src/main/resources/application.properties server.port=18888 logging.config=classpath:log4j.xml
e808a122ef0281c30c8158e2bc16308dfd00c7e8
[ "Java", "Maven POM", "INI" ]
8
Java
hansguichuideng/dubbo_zk
685cd9e0ca456799959c632cda03ab02540958f0
74b1fd5e3eef099f44cb31c2b3865a21a1743bea
refs/heads/master
<repo_name>anseljh/redis-io<file_sep>/lib/interactive/session.rb require File.expand_path(File.dirname(__FILE__) + "/redis") module Interactive # Create and find actions have race conditions, but I don't # really care about them right now... class Session TIMEOUT = 3600 # Create new instance. def self.create(namespace) raise "Already exists" if redis.zscore("sessions", namespace) touch(namespace) new(namespace) end # Return instance if namespace exists in sorted set. def self.find(namespace) if timestamp = redis.zscore("sessions", namespace) if Time.now.to_i - timestamp.to_i < TIMEOUT touch(namespace) new(namespace) end end end # Try to clean up old sessions def self.clean! now = Time.now.to_i threshold = now - TIMEOUT namespace, timestamp = redis.zrangebyscore("sessions", "-inf", threshold, :with_scores => true, :limit => [0, 1]) return if namespace.nil? if redis.zrem("sessions", namespace) keys = redis.smembers("session:#{namespace}:keys") redis.del(*keys.map { |key| "#{namespace}:#{key}" }) if !keys.empty? redis.del("session:#{namespace}:keys") redis.del("session:#{namespace}:commands") end end # This should only be created through #new or #create private_class_method :new attr :namespace def initialize(namespace) @namespace = namespace self.class.clean! end def run(line) _run(line) rescue => error format_reply(ErrorReply.new("ERR " + error.message)) end private def self.touch(namespace) redis.zadd("sessions", Time.now.to_i, namespace) end def register(arguments) # TODO: Only store keys that receive writes. keys = ::Interactive.keys(arguments) redis.pipelined do keys.each do |key| redis.sadd("session:#{namespace}:keys", key) end end # Command counter, not yet used redis.incr("session:#{namespace}:commands") end # This method is extracted from the shellwords library. It's # replicated here because the gsub for double quoted and escaped # text had to be removed. def shellsplit(line) words = [] field = '' line.scan(/\G\s*(?>([^\s\\\'\"]+)|'([^\']*)'|"((?:[^\"\\]|\\.)*)"|(\\.?)|(\S))(\s|\z)?/) do |word, sq, dq, esc, garbage, sep| raise ArgumentError, "Unmatched double quote: #{line.inspect}" if garbage field << (word || sq || (dq || esc)) if sep words << field field = '' end end words end def _run(line) begin arguments = shellsplit(line) rescue => error raise error.message.split(":").first end if arguments.empty? raise "No command" end if arguments.size > 100 || arguments.any? { |arg| arg.size > 100 } raise "Web-based interface is limited" end case arguments[0].downcase when "setbit" if arguments[2].to_i >= 2048 raise "Web-based interface is limited" end when "setrange" if arguments[2].to_i + arguments[3].to_s.size >= 256 raise "Web-based interface is limited" end end namespaced = ::Interactive.namespace(namespace, arguments) if namespaced.empty? raise "Unknown or disabled command '%s'" % arguments.first end # Register the call register(arguments) # Make the call reply = ::Interactive.redis.client.call(namespaced) case arguments.first.downcase when "keys" # Strip namespace for KEYS if reply.respond_to?(:map) format_reply(reply.map { |key| key[/^\w+:(.*)$/,1] }) else format_reply(reply) end when "info" # Don't #inspect the string reply for INFO reply.to_s else format_reply(reply) end end def format_reply(reply, prefix = "") case reply when LineReply reply.to_s + "\n" when Integer "(integer) " + reply.to_s + "\n" when String reply.inspect + "\n" when NilClass "(nil)\n" when Array if reply.empty? "(empty list or set)\n" else out = "" index_size = reply.size.to_s.size reply.each_with_index do |element, index| out << prefix if index > 0 out << "%#{index_size}d) " % (index + 1) out << format_reply(element, prefix + (" " * (index_size + 2))) end out end else raise "Don't know how to format #{reply.inspect}" end end end end
50918715e31cda57addbbedc71c15870715ef2f2
[ "Ruby" ]
1
Ruby
anseljh/redis-io
506bb4bafc3ced3104c4d714cacf2e330a70fd08
c98881226693c931f7977fac6ac3c061e3f4a4b8
refs/heads/master
<repo_name>miguelluna93/herencia<file_sep>/Persona.cs using System; namespace Herencias { abstract class Persona { private string nombre; private string apellido; public string Nombre { get { return nombre; } set { nombre = value; } } public string Apellido { get { return apellido; } set { apellido = value; } } public abstract int Clave { get; set; } public abstract string ConsultarTodosLosDatos(); public string ObtenerNombreCompleto() { return this.Nombre + " " + this.Apellido; } } } <file_sep>/Empleado.cs using System; namespace Herencias { class Empleado : Persona { private int claveEmpleado; public override int Clave { get { return claveEmpleado; } set { claveEmpleado = value; } } public override string ConsultarTodosLosDatos() { return "------Datos del Empleado: \n" + this.Clave + " " + this.Nombre + " " + this.Apellido; } } class Cliente : Persona { private int claveCliente; public override int Clave { get { return claveCliente; } set { claveCliente = value; } } public override string ConsultarTodosLosDatos() { return "******Datos del Cliente: \n" + this.Clave + " " + this.Nombre + " " + this.Apellido; } } } <file_sep>/Main.cs using System; namespace Herencias { class MainClass { public static void Main (string[] args) { Empleado unEmpleado = new Empleado(); unEmpleado.Nombre = "Daniel"; unEmpleado.Apellido = "Gonzalez"; unEmpleado.Clave = 1; Console.WriteLine( unEmpleado.ConsultarTodosLosDatos() ); Console.WriteLine( unEmpleado.ObtenerNombreCompleto() ); Cliente unCliente = new Cliente(); unCliente.Nombre = "Jonathan"; unCliente.Apellido = "Ramirez"; unCliente.Clave = 34; Console.WriteLine( unCliente.ConsultarTodosLosDatos() ); Console.WriteLine( unCliente.ObtenerNombreCompleto()); Console.ReadLine(); } } }
93eefbfef25028435518b6e9a2a450a9832b7971
[ "C#" ]
3
C#
miguelluna93/herencia
6280593530c6f0e4e456169e9faf07753423f9ea
4e36140bf960bf6d4bd278b5a1921a12d8069ee2
refs/heads/master
<repo_name>shibichakkaravarthy/nyx-learning-backend<file_sep>/Models/Course.model.js const mongoose = require("mongoose"); const CourseSchema = new mongoose.Schema({ faculty: { type: mongoose.Types.ObjectId, ref: "profile" }, name: { type: String, required: true, }, department: { type: String, required: true }, room: { type: String, required: true }, description: { type: String, required: true }, team: { type: String, required: true }, waitlistCapacity: { type: Number, required: true, }, currentEnrolls: { type: Number, required: true }, totalModules: { type: Number, required: true, }, }); module.exports = mongoose.model("course", CourseSchema);<file_sep>/Controllers/StudentController.js const Course = require('../Models/Course.model'); const Enroll = require('../Models/Enroll.model'); exports.getEnrolledCourses = async (req, res, next) => { try { const enrolledCourses = await Enroll.find({userId: res.locals.account.accountId}).populate([{path: 'courseId', model: 'course'}]) res.status(200).json({status: "SUCCESS", result: enrolledCourses}) } catch(err) { res.status(500).json({status: "ERROR", message: "Something went wrong!"}) } } exports.enroll = async (req, res, next) => { try { console.log("NEW ENROLL", {userId: res.locals.account.accountId, courseId: req.params.courseId }) const newEnroll = await Enroll.create({userId: res.locals.account.accountId, courseId: req.params.courseId }) res.status(200).json({status: "SUCCESS", result: newEnroll}) } catch (error) { console.log("ENROLL ERROR", error) res.status(500).json({status: "ERROR", message: "Something went wrong!"}) } } exports.getAllCourses = async (req, res, next) => { try { const courses = await Course.find({}); res.status(200).json({status: "SUCCESS", result: courses}) } catch (error) { console.log("STUDENT GET ALL COURSES ERROR", error) res.status(500).json({status: "ERROR", message: "Something went wrong!"}) } }<file_sep>/Models/Profile.model.js const mongoose = require("mongoose"); const ProfileSchema = new mongoose.Schema({ accountId: { type: mongoose.Types.ObjectId, required: true, ref: 'account' }, name: { type: String, required: true, }, phone: { type: String, required: true }, city: { type: String, required: true }, country: { type: String, required: true }, gender: { type: String, required: true }, languages: { type: Array, required: true }, bio: { type: Array, required: true }, alterEmail: String, institution: String, hometown: String, profileImg: String, }); module.exports = mongoose.model("profile", ProfileSchema);<file_sep>/Routes/FacultyRoutes.js const jwt = require("jsonwebtoken"); const FacultyController = require('../Controllers/FacultyController'); const FacultyRouter = require("express").Router(); FacultyRouter.get('/courses', FacultyController.getCourses) FacultyRouter.post('/courses/create', FacultyController.createCourse); module.exports = FacultyRouter;<file_sep>/Routes/ProfileRoutes.js const ProfileController = require('../Controllers/ProfileController'); const ProfileRouter = require("express").Router(); ProfileRouter.get('/', ProfileController.getProfile) ProfileRouter.post('/', ProfileController.upserProfile) module.exports = ProfileRouter;<file_sep>/Routes/AuthRoutes.js const AuthRouter = require('express').Router() const AuthController = require('../Controllers/AuthController'); AuthRouter.post('/signup', AuthController.createAccount); AuthRouter.post('/signin', AuthController.login); AuthRouter.post('/refresh', AuthController.refreshToken); module.exports = AuthRouter;<file_sep>/Routes/ProtectedRoutes.js const ProtectedRouter = require('express').Router() const FacultyRouter = require('./FacultyRoutes') const StudentRouter = require('./StudentRoutes') const ProfileRouter = require('./ProfileRoutes') const jwt = require('jsonwebtoken'); ProtectedRouter.use((req, res, next) => { try { if(!req.headers.authorization) { throw {code: 401, message: "TOKEN NOT FOUND"} } const bearer = req.headers.authorization; const token = bearer.slice(7); const isValid = jwt.verify(token, "PRIVATE_KEY"); if (isValid.accountId) { console.log("IS VALID", isValid) res.locals.account = {...isValid} next(); } else { throw {code: 401, message: "INVALID TOKEN"} } } catch (error) { res .status(401) .json({ status: "ERROR", result: { message: "Invalid token" } }); } }); ProtectedRouter.use('/faculty', FacultyRouter) ProtectedRouter.use('/student', StudentRouter) ProtectedRouter.use('/profile', ProfileRouter) module.exports = ProtectedRouter;<file_sep>/Controllers/AuthController.js const bcrypt = require('bcrypt'); const jwt = require('jsonwebtoken'); const Account = require('../Models/Account.model') exports.createAccount = async (req, res, next) => { try { const {emailId, password, role} = req.body; const refreshToken = jwt.sign({emailId, role}, "PRIVATE_KEY", { algorithm: "HS256", expiresIn: "14d" }) const hashedPassword = bcrypt.hashSync(password, 16); const newAccount = await Account.create({...req.body, refreshToken, hash: hashedPassword}) const accessToken = jwt.sign({emailId, accountId: newAccount._id, role: newAccount.role}, "PRIVATE_KEY", { algorithm: "HS256", expiresIn: "15m" }) const {hash, ...sharableDetails} = newAccount._doc res.status(201).json({status: "SUCCESS", result: {...sharableDetails, accessToken}}) } catch (error) { if(error.code === 11000) { res.status(409).json({staus: "ERROR", message: "User already exists! Please sign-in with your password"}) } else if(error.errors) { res.status(400).json({status: "ERROR", message: "Please fill out all the required fields"}) } else { res.status(500).json({error}) } } } exports.login = async (req, res, next) => { try { const {emailId, password} = req.body; const account = await Account.findOne({emailId}) console.log("ACCOUNT", account); const isPasswordValid = await bcrypt.compare(password, account.hash) if(!isPasswordValid) { throw {code: 403} } const refreshToken = jwt.sign({emailId, accountId: account._id}, "PRIVATE_KEY", { algorithm: "HS256", expiresIn: "14d" }) const accessToken = jwt.sign({accountId: account._id, role: account.role}, "PRIVATE_KEY", { algorithm: "HS256", expiresIn: "15m" }) const updatedAccount = await Account.findByIdAndUpdate({_id: account._id}, {refreshToken}) const {hash, ...sharableDetails} = updatedAccount._doc res.status(200).json({status: "SUCCESS", result: {...sharableDetails, accessToken}}) } catch (error) { console.log("ERROR", error) if(error.code === 400) { res.status(400).json({status: "ERROR", message: "Please fill out all the required fields"}) } else if(error.code === 403) { res.status(403).json({status: "ERROR", message: "Please check your credentials"}) } else { res.status(500).json({error}) } } } exports.refreshToken = async (req, res, next) => { console.log("STARTED CHECKING JWT REFDRESH", req.headers.authorization); try { const token = req.headers.authorization; const isValid = jwt.verify(token, "PRIVATE_KEY"); if (isValid.accountId) { const account = await Account.findById(isValid.accountId); console.log("ACCOUNT", account, isValid); if(account) { const accessToken = jwt.sign({accountId: account._id, role: account.role}, "PRIVATE_KEY", { algorithm: "HS256", expiresIn: "15m" }) res.status(200).json({status:"SUCCESS", result: {accessToken}}) } else { throw {code: 401, message: "INVALID ACCOUNT"} } } else { throw {code: 401, message: "INVALID TOKEN"} } } catch (error) { console.log("FAILRD AUTH REQUEST", error) res .status(401) .json({ status: "ERROR", message: "Invalid token" }); } }
ec7135d038d45f49127c669c8d9de655946f2a2d
[ "JavaScript" ]
8
JavaScript
shibichakkaravarthy/nyx-learning-backend
29d7d8024e366c62829105d57a1ab068db255c69
1958e2a8493f64b8cdc69edddab55d7d6e6e6969
refs/heads/master
<repo_name>PaulJanvier/Paul-JANVIER---EXO-JS-MMI2<file_sep>/td.js var nb_1 = 1; var nb_2 = 10; var result_ex1 = nb_1 + nb_2; function Addition(){ document.getElementById('result-exo-1-1').innerHTML = result_ex1; } var nb_3 = 1; var nb_4 = 10; var result_ex1_2 = nb_3 * nb_4; function Multiplication(){ document.getElementById('result-exo-1-2').innerHTML = result_ex1_2; } var nb_5 = 12; var nb_6 = 5; var result_ex1_3 = nb_5 % nb_6; function Division(){ document.getElementById('result-exo-1-3').innerHTML = result_ex1_3; } function largeurEcran(){ document.getElementById("largeurEcran").innerHTML = "La largeur disponible de votre écran est " + screen.availWidth; } function resolution() { largeur = window.innerWidth hauteur = window.innerHeight document.getElementById("resEcran").innerHTML = largeur + "x" + hauteur; } largeurEcran(); resolution(); function Soustraction(){ var x = document.getElementById("x").value; var y = document.getElementById("y").value; var resultat_1_4 = x - y; document.getElementById('resultat_1_4').innerHTML = resultat_1_4; } function Multiplication(){ var x = document.getElementById("xx").value; var y = document.getElementById("yy").value; var resultat_1_5 = x * y; document.getElementById('resultat_1_5').innerHTML = resultat_1_5; } function Division(){ var xxx = document.getElementById("xxx").value; var yyy = document.getElementById("yyy").value; var resultat_2_1 = xxx / yyy; document.getElementById('resultat_2_1').innerHTML = resultat_2_1; } function Addition(){ var xxxx = document.getElementById("xxxx").value; var yyyy = document.getElementById("yyyy").value; var resultat_2_2 = xxxx*1 + yyyy*1; document.getElementById('resultat_2_2').innerHTML = resultat_2_2; } function DivisionEuclidienne(){ var xxxxx = 82; var yyyyy = 8; var resultat_3 = xxxxx % yyyyy; document.getElementById('resultat_3').innerHTML = resultat_3; } window.onload = DivisionEuclidienne; var ex4_result = 0; document.getElementById('ex4_result').innerHTML = ex4_result; function plusten(){ ex4_result += 10; document.getElementById('ex4_result').innerHTML = ex4_result; } var ex4_result = 0; document.getElementById('ex4_result').innerHTML = ex4_result; function diviseFive(){ ex4_result /= 5; document.getElementById('ex4_result').innerHTML = ex4_result; } var ex4_result = 0; document.getElementById('ex4_result').innerHTML = ex4_result; function multiplyHeight(){ ex4_result *= 8; document.getElementById('ex4_result').innerHTML = ex4_result; } var ex4_result = 0; document.getElementById('ex4_result').innerHTML = ex4_result; function multiplyHeight(){ ex4_result *= 8; document.getElementById('ex4_result').innerHTML = ex4_result; } var ex4_result = 0; document.getElementById('ex4_result').innerHTML = ex4_result; function minusTwo(){ ex4_result -= 2; document.getElementById('ex4_result').innerHTML = ex4_result; } var ex4_result = 0; document.getElementById('ex4_result').innerHTML = ex4_result; function minusTwo(){ ex4_result -= 2; document.getElementById('ex4_result').innerHTML = ex4_result; } var ex4_result = 0; document.getElementById('ex4_result').innerHTML = ex4_result; function combinePlusTenMinusTwo(){ ex4_result += 10-2; document.getElementById('ex4_result').innerHTML = ex4_result; } var ex4_result = 0; document.getElementById('ex4_result').innerHTML = ex4_result; function resetExo4(){ ex4_result = 0; document.getElementById('ex4_result').innerHTML = ex4_result; } var ex5 = Math.floor(Math.random()*(1000-50)+50); // Math;floor = nombre entier // function ex5_result(){ document.getElementById('ex5_result').innerHTML = ex5; } ex5_result(); // la même chose que window.onload = myFunctionName // function ex6_result(arg){ arg /= 2; document.getElementById('ex6_result').innerHTML = arg; } ex6_result(10); var ex7_result = 0; function ex7_resultat(arg1, arg2){ ex7_result = arg1 - arg2; document.getElementById('ex7_result').innerHTML = ex7_result; } ex7_resultat(10, 5); var ex8_result_1 = 0; function ex8_resultat(arg3, arg4, arg5){ ex8_result_1 = arg3 % arg4; ex8_result = ex8_result_1 % arg5; document.getElementById('ex8_result').innerHTML = ex8_result; } ex8_resultat(10, 8, 5); function convertToPound(){ var kg = document.getElementById('ex9_input1').value; var convertToPound = kg * 2.20462; document.getElementById('ex9_1_result').innerHTML = convertToPound; } function convertToKg(){ var pound = document.getElementById('ex9_input2').value; var convertToKg = pound * 0.453591830542594; document.getElementById('ex9_2_result').innerHTML = convertToKg; } var sentence = ""; function iterateWords(){ var word = document.getElementById("word").value; sentence = sentence + word; document.getElementById('sentence').innerHTML = sentence; } function resetWords(){ sentence = ""; document.getElementById('sentence').innerHTML = sentence; } var cote = (Math.random() * (30.00 - 1.00) + 1.00).toFixed(2); function tiragecote(){ document.getElementById('cote').innerHTML = cote; } tiragecote(); function calculgain(){ var mise = document.getElementById("mise").value; var gain = mise * cote; document.getElementById('gain').innerHTML = gain } function convertkmtotemps(){ var km = document.getElementById('ex12_input1').value; var convertkmtotemps = km / 1000; document.getElementById('ex12_result').innerHTML = convertkmtotemps; } function converttempstokm(){ var heures = document.getElementById('ex12_input2').value; var converttempstokm = heures * 1000; document.getElementById('ex12_result_2').innerHTML = converttempstokm; } /* function Display(){ var nb_test = document.getElementById('input-test').value; var resultat = eval(nb_test +"+ 1"); document.getElementById('result-test').innerHTML = resultat; }*/
7eeb482b90db936eb4d6a0685e0757c5a886352a
[ "JavaScript" ]
1
JavaScript
PaulJanvier/Paul-JANVIER---EXO-JS-MMI2
08f3a528cb1d69c8381adf1f9fcc62f15ad9ccff
76003f493dccbdd8f166a29b7198db8b398fc1a9
refs/heads/master
<file_sep>import time import random import tkinter as tk from tkinter import messagebox root = tk.Tk() root.title("BlackJack") canvas = tk.Canvas(root,height = 700,width = 800) canvas.pack() balance = 0 values = {'2': 2 , '3' : 3 , '4' : 4 , '5' : 5 , '6' : 6 , '7' : 7 , '8' : 8 , '9' : 9 , '10' : 10 , 'J' : 10 , 'Q' : 10 , 'K' : 10 , 'A' : 11} class Cards(): cs = ['A','2','3','4','5','6','7','8','9','10','J','Q','K'] def __init__(self,suit): self.suit = suit class Deck(): l=[] def __init__(self): suits = [Cards('Hearts'),Cards('Diamond'),Cards('Spades'),Cards('Clubs')] for k in range(0,4): for j in range(0,13): self.l.append((suits[k].suit,suits[k].cs[j])) self.ShuffleDeck() def Deal(self): return self.l.pop() def ShuffleDeck(self): random.shuffle(self.l) def thankyou(gameframe): tyframe = tk.Frame(gameframe, bg = 'black') tyframe.place(relwidth = 1, relheight = 1) tylabel = tk.Label(tyframe,fg = 'gray',text="THANK YOU\nFOR PLAYING",height = 300,width = 1500,bg = 'black',anchor = 'center') tylabel.config(font = ('courier',45,'bold')) tylabel.place(relx = 0.1,rely = 0.1,relwidth = 0.8,relheight = 0.4) tybutton = tk.Button(tyframe, text="EXIT" , activeforeground = 'red' , fg = 'red' , bg = 'gray',height = 3,width = 20, command = root.destroy) tybutton.config(font = ('times',15,'bold')) tybutton.place(relx = 0.4,rely = 0.7,relwidth = 0.2 , relheight = 0.1) def game(p1,d1,deck,root): gameframe = tk.Frame(root, bg = 'green' ) gameframe.place(relwidth = 1 ,relheight = 1) dlabel = tk.Label(gameframe , text = "Dealer's Hand:" , bg = 'green' , fg = 'white' ) dlabel.config(font = ('courier', 15,'bold')) dlabel.place(relwidth = 0.3 , relheight = 0.1) cardfont = ('courier' , 15 , 'bold') dclabel = tk.Label(gameframe , text = str(d1.cards[0]) + " , <UNKNOWN>" , bg = 'green' , fg = 'white') dclabel.config(font = cardfont) dclabel.place(relx = 0.1, rely = 0.25) plabel = tk.Label(gameframe , text = "Player's Hand:" , bg = 'green' , fg = 'white') plabel.config(font = ('courier', 15, 'bold')) plabel.place(rely = 0.4, relwidth = 0.3 , relheight = 0.1) p1.printHands(gameframe,d1,deck,root) def checkBet(p1,d1,deck,bet,root,betframe): global balance if bet > balance: if not tk.messagebox.askretrycancel("Error!",'Cannot place your bet , as the bet exceeds the balance!'): thankyou(root) elif bet < 50: if not tk.messagebox.askretrycancel('Error!','Minimum Bet is 50'): thankyou(betframe) else: p1.bet = bet balance -= p1.bet game(p1,d1,deck,root) def placeBet(root,p1,d1,deck): betframe = tk.Frame(root, bg = 'gray', bd = 5 , relief = 'groove') betframe.place(relwidth = 1.0 , relheight = 1.0) bfont = ('times',30, 'bold') blabel1 = tk.Label(betframe, text = 'Place your Bet:',bg = 'gray' , fg = 'black') blabel1.config(font = bfont) blabel1.pack(side = 'top') bentry = tk.Entry(betframe , font = bfont ,justify = 'center', bg = 'black' , fg = 'white' , relief = 'sunken') bentry.place(relx = 0.35,rely = 0.2 , relwidth = 0.3 , relheight = 0.1) bsubmit = tk.Button(betframe , text = 'SUBMIT' , fg = 'red' ,font = 30, height = 3 , width = 300 , bg ='black' , relief = 'raised' , activeforeground = 'red', command = lambda : checkBet(p1,d1,deck,int(bentry.get()),root,betframe)) bsubmit.pack(side = 'bottom') class Player(): import tkinter def __init__(self,deck,d1,root,tk): self.cards = [] self.deck = deck self.aces = 0 for i in range (0,2): self.cards.append(deck.Deal()) for card in self.cards: if card[1] == 'A': self.aces += 1 self.score = self.handValue() self.tk = tk self.bet = placeBet(root,self,d1,deck) def handValue(self): val = 0 for card in self.cards: val += int(values[card[1]]) self.aceCase(val) return val def Hit(self,gameframe,x,deck,root): self.cards.append(deck.Deal()) if self.cards[-1][1] == 'A': self.aces += 1 self.score = self.handValue() self.printHands(gameframe,x,deck,root) def aceCase(self,val): if val > 21 and self.aces > 0: val -= 10 self.aces -= 1 return val def pWins(self,gameframe,d1,root): global balance balance += 2 * self.bet if tk.messagebox.askyesno("Hand Result","Player Wins this hand.\nPlayer Balance : {}\nDo you want to play again?".format(balance)): create_player(root,tk) else: thankyou(gameframe) def pBusts(self,gameframe,d1,root): global balance if tk.messagebox.askyesno("Hand Result","Player Busts.\nDealer wins this hand.\nPlayer Balance : {}\nDo you want to play again?".format(balance)): create_player(root,tk) else: thankyou(gameframe) def dWins(self,gameframe,d1,root): global balance if tk.messagebox.askyesno("Hand Result","Dealer wins this hand.\nPlayer Balance : {}\nDo you want to play again?".format(balance)): create_player(root,tk) else: thankyou(gameframe) def dBusts(self,gameframe,d1,root): global balance balance += 2 * self.bet if tk.messagebox.askyesno("Hand Result","Dealer Busts.\nPlayer wins this hand.\nPlayer Balance : {}\nDo you want to play again?".format(balance)): create_player(root,tk) else: thankyou(gameframe) def push(self,gameframe,d1,root): global balance balance += self.bet if tk.messagebox.askyesno("Hand Result","This hand was tied\nPlayer Balance : {}\nDo you want to play again?".format(balance)): create_player(root,tk) else: thankyou(gameframe) def printHands(self,gameframe,d1,deck,root): cardfont = ('courier' , 15 , 'bold') pclabel = self.tk.Label(gameframe, text = str(self.cards) , bg = 'green' , fg = 'white') pclabel.config(font = cardfont) pclabel.place(relx = 0.1 ,rely = 0.55) if self.score == 21 and d1.score != 21: self.pWins(gameframe,d1,root) elif self.score == 21 and d1.score == 21: d1.printHands(gameframe,self,deck,root) elif self.score > 21: self.pBusts(gameframe,d1,root) pbutton1 = self.tk.Button(gameframe, text = 'HIT' , bg = 'white' , fg = 'green' , font = 30 , relief = 'raised' , command = lambda : self.Hit(gameframe,d1,deck,root)) pbutton1.place(relx = 0.1 , rely = 0.8,relwidth = 0.2 , relheight=0.1) pbutton2 = self.tk.Button(gameframe, text = 'STAY' , bg = 'white' , fg = 'green' , font = 30 , relief = 'raised' , command = lambda : d1.printHands(gameframe,self,deck,root)) pbutton2.place(relx = 0.4 , rely = 0.8,relwidth = 0.2 , relheight=0.1) class Dealer(): def __init__(self,deck,root,tk): self.cards = [] self.aces = 0 for i in range (0,2): self.cards.append(deck.Deal()) self.score = self.handValue() for card in self.cards: if card[1] == 'A': self.aces += 1 self.score = self.handValue() self.tk = tk def handValue(self): val = 0 for card in self.cards: val += int(values[card[1]]) self.aceCase(val) return val def Hit(self,gameframe,x,deck,root): self.cards.append(deck.Deal()) if self.cards[-1][1] == 'A': self.aces += 1 self.score = self.handValue() self.printHands(gameframe,x,deck,root) def aceCase(self,val): if val > 21 and self.aces > 0: val -= 10 self.aces -= 1 return val def printHands(self,gameframe,p1,deck,root): cardfont = ('courier' , 15 , 'bold') dclabel = self.tk.Label(gameframe, text = str(self.cards) , bg = 'green' , fg = 'white') dclabel.config(font = cardfont) dclabel.place(relx = 0.1 , rely=0.25) if self.score == 21 and p1.score == 21: p1.push(gameframe,self,root) elif self.score < 21 and self.score < p1.score : self.Hit(gameframe,p1,deck,root) elif self.score > p1.score and self.score <= 21: p1.dWins(gameframe,self,root) elif self.score == 21: p1.dWins(gameframe,self,root) else: p1.dBusts(gameframe,self,root) def create_player(root,tk): deck = Deck() d1 = Dealer(deck,root,tk) p1 = Player(deck,d1,root,tk) def get_balance(root,bal,tk,frame): global balance if bal < 500: if not tk.messagebox.askretrycancel("Error!",'Cannot accept value less than 500 $'): thankyou(frame) else: balance = bal create_player(root,tk) def play(root,tk): frame = tk.Frame(root, bg = 'gray', bd = 4 , relief = 'groove') frame.place(relwidth = 1 , relheight = 1) font = ('times' , 30 , 'bold') blabel1 = tk.Label(frame, text = 'Please Enter your Bank Balance:',bg = 'gray' , fg = 'black') blabel1.config(font = font) blabel1.pack(side = 'top') blabel2 = tk.Label(frame, text = '(minimum should 500$)' , bg = 'gray' , fg = 'black') blabel2.config(font = ('times',20,'bold')) blabel2.pack(side = 'top') bentry = tk.Entry(frame, font =font ,bg = 'black' , justify = 'center' , fg = 'white' , relief = 'sunken') bentry.place(relx = 0.35,rely = 0.2 , relwidth = 0.3 , relheight = 0.1) bsubmit = tk.Button(frame , text = 'SUBMIT' , fg = 'red' ,font = 30, height = 3 , width = 300 , bg ='black' , relief = 'raised' , activeforeground = 'red' , command = lambda : get_balance(root,int(bentry.get()),tk,frame)) bsubmit.pack(side = 'bottom') def welcome(root,tk): frame = tk.Frame(root,bg = 'gray',bd = 5,relief = 'groove') frame.place(relwidth = 1.0 , relheight = 1.0) welcomefont = ('courier',45,'bold') welcome1 = tk.Label(frame,fg = 'white',text="WELCOME TO",height = 300,width = 1500,bg = 'gray',anchor = 'center') welcome1.config(font = welcomefont) welcome1.place(relx = 0.1,rely = 0.1,relwidth = 0.8,relheight = 0.4) welcome2 = tk.Label(frame,fg = 'black',text="BLACKJACK!!!",height = 300,width = 1500,bg = 'gray',anchor = 'center') welcome2.config(font = welcomefont) welcome2.place(relx = 0.1,rely = 0.4,relwidth = 0.8,relheight = 0.2) playfont = ('times',15,'bold') button = tk.Button(frame, text="PLAY",activeforeground = 'red' , fg = 'red' , bg = 'black',height = 3,width = 20, command = lambda : play(root,tk) ) button.config(font = playfont) button.place(relx = 0.4,rely = 0.7,relwidth = 0.2 , relheight = 0.1) return welcome(root,tk) root.mainloop()
5d00b018d8b11976f095f4559554db49c5b25e94
[ "Python" ]
1
Python
Ethan0507/Blackjack
63576807aa190b401bd257d693e7e2859dfc2845
4c9da8d060cf11f6b46169440a395d7c6310d251
refs/heads/main
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; using System; using UnityEngine.UI; using UnityEngine.SceneManagement; public class UI_Script : MonoBehaviour { public TextMeshProUGUI timerText; public TextMeshProUGUI pauseText; public Button continueButton; public TextMeshProUGUI deathText; public Button restartButton; public Button quitButton; public TextMeshProUGUI victoryText; public Button nextLevelButton; public void PauseMenu() { pauseText.gameObject.SetActive(true); restartButton.gameObject.SetActive(true); continueButton.gameObject.SetActive(true); quitButton.gameObject.SetActive(true); } public void GameOver() { deathText.gameObject.SetActive(true); restartButton.gameObject.SetActive(true); } public void Victory() { victoryText.gameObject.SetActive(true); nextLevelButton.gameObject.SetActive(true); restartButton.gameObject.SetActive(true); quitButton.gameObject.SetActive(true); } public void ContinueButton() { pauseText.gameObject.SetActive(false); continueButton.gameObject.SetActive(false); restartButton.gameObject.SetActive(false); quitButton.gameObject.SetActive(false); } public void RestartButton() { SceneManager.LoadScene(SceneManager.GetActiveScene().name); } public void NextLevelButton() { SceneManager.LoadScene(SceneManager.GetActiveScene().name); } public void QuitToMenu() { SceneManager.LoadScene("Main Menu"); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class BulletController : MonoBehaviour { public float speed; public float destroyBullet = 4; public int damageToGive = 1; void Update() { //cotrol projectile movement transform.Translate(Vector3.forward * speed * Time.deltaTime); Destroy(gameObject, destroyBullet); } private void OnCollisionEnter(Collision collision) { if(collision.gameObject.tag == "Wall" || collision.gameObject.tag == "Enemy") { Destroy(gameObject); } if(collision.gameObject.tag == "Player" && gameObject.tag == "Purple") { collision.gameObject.GetComponent<PlayerHealthManager>().HurtPlayer(damageToGive); Destroy(gameObject); } if(collision.gameObject.tag == "Player" && gameObject.tag == "Orange") { collision.gameObject.GetComponent<PlayerHealthManager>().HurtPlayer(damageToGive); Destroy(gameObject); } if(collision.gameObject.tag == "Bullet" && gameObject.tag == "Orange") { Destroy(collision.gameObject); Destroy(gameObject); Debug.Log("Bullets collided"); } } private void OnTriggerEnter(Collider collision) { if (collision.gameObject.tag == "Wall" || collision.gameObject.tag == "Enemy") { Destroy(gameObject); } if (collision.gameObject.tag == "Enemy" && gameObject.tag == "Bullet") { collision.gameObject.GetComponent<EnemyManager>().HurtEnemy(damageToGive); Destroy(gameObject); } if (collision.gameObject.tag == "Bullet" && gameObject.tag == "Orange") { Destroy(collision.gameObject); Destroy(gameObject); Debug.Log("Bullets collided"); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class LevelSelectScript : MonoBehaviour { public void SelectLevel() { Debug.Log("This.Button.Name: " + this.gameObject.name); switch (this.gameObject.name) { case "Level_1_Button": SceneManager.LoadScene("Level_1"); break; case "Level_2_Button": SceneManager.LoadScene("Level_2"); break; case "Level_3_Button": SceneManager.LoadScene("Level_3"); break; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class GunController : MonoBehaviour { public BulletController bullet; public BulletController bullet2; public Transform firePoint; public float bulletSpeed; public float coolDownDefault = 0.1f; public float changeBulletTimer; float coolDown = 0; public bool isFiring = false; public bool changeProjectile = false; public bool isPlayer; private bool isEnemy; public bool IsEnemy { get => isEnemy; set => isEnemy = value; } private void Awake() { InvokeRepeating("Switch", 0, changeBulletTimer); } void Switch() { changeProjectile = !changeProjectile; } public void Update() { //is player if (isPlayer == true) { //A new projectile can be shot once coolDown reaches coolDownDefault coolDown += Time.deltaTime; if (isFiring && coolDown > coolDownDefault) { BulletController newBullet = Instantiate(bullet, firePoint.position, firePoint.rotation) as BulletController; newBullet.speed = bulletSpeed; coolDown = 0; } } //is enemy if (IsEnemy == true) { //A new projectile can be shot once coolDown reaches coolDownDefault coolDown += Time.deltaTime; if (isFiring && coolDown > coolDownDefault) { if (changeProjectile == true) { BulletController newBullet = Instantiate(bullet, firePoint.position, firePoint.rotation) as BulletController; newBullet.speed = bulletSpeed; coolDown = 0; } if (changeProjectile == false) { BulletController newBullet = Instantiate(bullet2, firePoint.position, firePoint.rotation) as BulletController; newBullet.speed = bulletSpeed; coolDown = 0; } } } } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; using UnityEngine.SceneManagement; public class MainMenuManager : MonoBehaviour { public GameObject mainMenu; public GameObject levelMenu; public void SetMainMenu() { mainMenu.SetActive(true); levelMenu.SetActive(false); } public void SetLevelMenu() { mainMenu.SetActive(false); levelMenu.SetActive(true); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; using UnityEngine.SceneManagement; using UnityEngine.UI; public class GameManager : MonoBehaviour { public TextMeshProUGUI titleText; public TextMeshProUGUI healthText; public TextMeshProUGUI waveText; public TextMeshProUGUI gameOverText; public Button startButton; public Button restartButton; public PlayerController playerControl; public EnemyManager enemyManager; public GameObject enemyPrefab; private float spawnRange = 14f; private int enemyCount; private int waveNumber = 0; private int wave; private bool isGameActive; private void Start() { Time.timeScale = 0; } public void GameStart() { isGameActive = true; Time.timeScale = 1; //activate and deactivate certain UI elements at start of game startButton.gameObject.SetActive(false); titleText.gameObject.SetActive(false); waveText.gameObject.SetActive(true); healthText.gameObject.SetActive(true); wave = 0; } void Update() { if(isGameActive == true) { //When there are no enemies increase enemy- and wave count by 1 for the next wave enemyCount = FindObjectsOfType<EnemyManager>().Length; if (enemyCount == 0) { waveNumber++; SpawnEnemyWave(waveNumber); UpdateWave(1); } } } //Show wave count public void UpdateWave(int waveToAdd) { wave += waveToAdd; waveText.text = "Wave: " + wave; } //Game is over public void GameOver() { gameOverText.gameObject.SetActive(true); restartButton.gameObject.SetActive(true); isGameActive = false; Time.timeScale = 0; } //Restart the game public void RestartGame() { SceneManager.LoadScene(SceneManager.GetActiveScene().name); } //Calculates how manny enemies are to be spawned public void SpawnEnemyWave(int enemiesToSpawn) { for (int i = 0; i < enemiesToSpawn; i++) { Instantiate(enemyPrefab, GenerateSpawnPos(), enemyPrefab.transform.rotation); } } //Gives an enemy a random position to spawn at private Vector3 GenerateSpawnPos() { float spawnPosX = Random.Range(-spawnRange, spawnRange); float spawnPosZ = Random.Range(-spawnRange, spawnRange); Vector3 randomPos = new Vector3(spawnPosX, 0.5f, spawnPosZ); return randomPos; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerHealthManager : MonoBehaviour { private Renderer rend; public GameManager gameManager; public float flashLength; private float flashCounter; public int startingHealth; public int currentHealth; private Color storedColor; public int wallDamage = 1; void Start() { currentHealth = startingHealth; rend = GetComponent<Renderer>(); storedColor = rend.material.GetColor("_Color"); } void Update() { //Game over happens if player health is equal to 0 if (currentHealth <= 0) { gameObject.SetActive(false); gameManager.GameOver(); } //Player color is restored to normal if (flashCounter > 0) { flashCounter -= Time.deltaTime; if (flashCounter <= 0) { rend.material.SetColor("_Color", storedColor); } } gameManager.healthText.text = "Health: " + currentHealth; } //When player is hurt they lose health and their color turns red public void HurtPlayer(int damageAmount) { currentHealth -= damageAmount; flashCounter = flashLength; rend.material.SetColor("_Color", Color.red); } private void OnCollisionEnter(Collision collision) { if (collision.gameObject.tag == "DamageWall") { HurtPlayer(wallDamage); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyManager : MonoBehaviour { private Rigidbody enemyRb; private PlayerController thePlayer; public GameObject enemy; public GunController theGun; public float speed = 3; public float damping = 5; public int health = 3; private int currentHealth; public bool canShoot = false; Vector3 offSet = new Vector3(0, 0, 1); void Start() { enemyRb = GetComponent<Rigidbody>(); thePlayer = FindObjectOfType<PlayerController>(); //set current health to be equal to starting health currentHealth = health; } void Update() { //Enemy rotates to look at the player var rotation = Quaternion.LookRotation(thePlayer.transform.position - enemy.transform.position); enemy.transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping); //Destroy enemy object when its health is 0 if (currentHealth <= 0) { Destroy(gameObject); } //Enemy can fire their gun when canShoot is true if (canShoot == true) { theGun.isFiring = true; } } //Enemy movement private void FixedUpdate() { enemyRb.velocity = (transform.forward * speed); } //Enemy takes damage public void HurtEnemy(int damage) { currentHealth -= damage; } }
ee5421682de62f2e58f11580670614eeea38a723
[ "C#" ]
8
C#
Bondorudo/Nier-Automata-BulletHell-Clone-Assets
9f04536fc6fba71d2b7f0fc4f79fe97849d93ed2
63baa50f40883e8680a6088fdb53de234fae7969
refs/heads/master
<repo_name>anikoshkaryan/foodi<file_sep>/foodi_js.js $.validator.setDefaults({ submitHandler: function () { alert("submitted!"); } }); $("document").ready(function () { let menuIcon = document.querySelector('.hamburger-menu'); let navBar = document.querySelector(".navBar"); menuIcon.addEventListener("click", (event) => { event.stopPropagation(); navBar.classList.toggle("change"); }); $(".nav-list .nav-link").click(function () { let id = $(this).attr("href"); let scrollElem = $(id); let offsetTop = $(scrollElem).offset().top; $("html, body").animate({ scrollTop: offsetTop - 100, }, 1000); }); $("body").click(function () { $(".navBar").removeClass("change"); $(".hamburger-menu").removeClass("change"); }); $(".food-gallery-text").click(function () { $(".modal").addClass("open"); let img = $(this).closest(".food-gallery-item").attr("data-picture"); let title = $(this).closest(".food-gallery-item").find(".food-gallery-text-title").text(); let text = $(this).closest(".food-gallery-item").find(".food-gallery-text-desc").text(); let price = $(this).closest(".food-gallery-item").find(".food-gallery-text-money").text(); setDishInfo(img, title, text, price); }); function setDishInfo(img, title, text, price) { $(".modal-image img").attr("src", img); $(".modal-title").text(title); $(".modal-price").text(price); $(".modal-text").text(text); } $(".close-button").click(function () { $(".modal").removeClass("open"); }); $(".modal").click(function (event) { $(".modal").removeClass("open"); }); $(".modal-content").click(function (event) { event.stopPropagation(); }); $("#form_container").validate( { rules: { firstname: { required: true, }, email: { required: true, email: true }, message: "required" }, messages: { firstname: "Please enter your firstname", email: "Please enter a valid email address", message: "Please enter your message" } } ); $(".chef-link").click(function () { $(".mCHef").addClass("open"); }); $(".closeButtonChef").click(function () { $(".mCHef").removeClass("open"); }); $(".mCHef").click(function (event) { $(".mCHef").removeClass("open"); }); $(".mContentChef").click(function (event) { event.stopPropagation(); }); /*slider*/ $('.owl-carousel').owlCarousel({ animateIn: 'animate__backInUp', items: 1, loop: true, nav: true, margin: 30, stagePadding: 30, smartSpeed: 450, dots: false, }); /*slider end*/ });
5c2ff851c3287b2c7f0f9ff65bf87e40d30ca149
[ "JavaScript" ]
1
JavaScript
anikoshkaryan/foodi
9e2d81611c3ec06bba3e2c1b852436d3794cbf75
af109a1f7aa38a30090560b62befc39f0304e134
refs/heads/master
<file_sep>package phoswald.webnotes.notes; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import org.joda.time.LocalDateTime; import phoswald.webnotes.framework.LocalDateTimeConverter; /** * The domain class for notes. * <p> * This class is used for: * <ul> * <li>JPA (using annotations on fields) * <li>JSON serialization (using property accessors) * </ul> */ @Entity public class Note { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long noteId; @Column private String userId; @Column private String name; @Column private String content; @Column // @Convert(converter = LocalDateTimeConverter.class) private String timestamp; // should be LocalDateTime when JPA 2.1 will work public long getNoteId() { return noteId == null ? 0 : noteId; } public void setNoteId(long noteId) { this.noteId = noteId == 0 ? null : noteId; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public LocalDateTime getTimestamp() { return new LocalDateTimeConverter().convertToEntityAttribute(timestamp); } public void setTimestamp(LocalDateTime timestamp) { this.timestamp = new LocalDateTimeConverter().convertToDatabaseColumn(timestamp); } } <file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>phoswald</groupId> <artifactId>web-notes</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <properties> <app.id>web-notes-1069</app.id> <app.version>1</app.version> <appengine.version>1.9.27</appengine.version> <gcloud.plugin.version>2.0.9.76.v20150902</gcloud.plugin.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.showDeprecation>true</maven.compiler.showDeprecation> <datanucleus.version>3.1.3</datanucleus.version> </properties> <prerequisites> <maven>3.1.0</maven> </prerequisites> <dependencies> <!-- Compile/runtime dependencies --> <!-- GAE --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.google.appengine</groupId> <artifactId>appengine-api-1.0-sdk</artifactId> <version>${appengine.version}</version> <scope>runtime</scope> </dependency> <!-- JPA using DataNucleus for GAE --> <!-- JPA 2.1 is not yet available in datanucleus 3.1 (and datanucleus 4.x is not working with appengine) --> <dependency> <groupId>org.apache.geronimo.specs</groupId> <artifactId>geronimo-jpa_2.0_spec</artifactId> <version>1.0</version> <scope>compile</scope> </dependency> <!-- <dependency> <groupId>org.datanucleus</groupId> <artifactId>javax.persistence</artifactId> <version>2.1.2</version> <scope>compile</scope> </dependency> --> <dependency> <groupId>com.google.appengine.orm</groupId> <artifactId>datanucleus-appengine</artifactId> <version>2.1.2</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.datanucleus</groupId> <artifactId>datanucleus-api-jpa</artifactId> <version>${datanucleus.version}</version> <scope>compile</scope> <!-- compile instead of runtime for enhance. --> </dependency> <dependency> <groupId>org.datanucleus</groupId> <artifactId>datanucleus-core</artifactId> <version>${datanucleus.version}</version> <scope>compile</scope> <!-- compile instead of runtime for enhance. --> </dependency> <!-- JAX-RS using Jersey and Jackson --> <dependency> <groupId>javax.ws.rs</groupId> <artifactId>javax.ws.rs-api</artifactId> <version>2.0.1</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.glassfish.jersey.containers</groupId> <artifactId>jersey-container-servlet</artifactId> <version>2.21</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>jersey-media-json-jackson</artifactId> <version>2.21</version> <scope>compile</scope> </dependency> <!-- Other libraries --> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.8.2</version> </dependency> <!-- Test Dependencies --> <dependency> <groupId>com.google.appengine</groupId> <artifactId>appengine-testing</artifactId> <version>${appengine.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>com.google.appengine</groupId> <artifactId>appengine-api-stubs</artifactId> <version>${appengine.version}</version> <scope>test</scope> </dependency> <!-- Webjars --> <dependency> <groupId>org.webjars</groupId> <artifactId>webjars-servlet-2.x</artifactId> <version>1.1</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>2.1.4</version> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>hoganjs</artifactId> <version>3.0.2</version> </dependency> <dependency> <groupId>phoswald</groupId> <artifactId>polymer-webjar</artifactId> <version>1.2.0-SNAPSHOT</version> </dependency> </dependencies> <build> <!-- for hot reload of the web application--> <outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/classes</outputDirectory> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>versions-maven-plugin</artifactId> <version>2.2</version> <executions> <execution> <phase>compile</phase> <goals> <goal>display-dependency-updates</goal> <goal>display-plugin-updates</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.3</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <archiveClasses>true</archiveClasses> <webResources> <!-- in order to interpolate version from pom into appengine-web.xml --> <resource> <directory>${basedir}/src/main/webapp/WEB-INF</directory> <filtering>true</filtering> <targetPath>WEB-INF</targetPath> </resource> </webResources> </configuration> </plugin> <plugin> <groupId>com.google.appengine</groupId> <artifactId>appengine-maven-plugin</artifactId> <version>${appengine.version}</version> <configuration> <enableJarClasses>false</enableJarClasses> <version>${app.version}</version> <!-- Comment in the below snippet to bind to all IPs instead of just localhost --> <!-- address>0.0.0.0</address> <port>8080</port --> <!-- Comment in the below snippet to enable local debugging with a remote debugger like those included with Eclipse or IntelliJ --> <!-- jvmFlags> <jvmFlag>-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n</jvmFlag> </jvmFlags --> </configuration> </plugin> <plugin> <groupId>com.google.appengine</groupId> <artifactId>gcloud-maven-plugin</artifactId> <version>${gcloud.plugin.version}</version> <configuration> <set_default>true</set_default> </configuration> </plugin> <plugin> <groupId>org.datanucleus</groupId> <artifactId>maven-datanucleus-plugin</artifactId> <version>${datanucleus.version}</version> <configuration> <api>JPA</api> <mappingIncludes>**/phoswald/webnotes/entities/*.class</mappingIncludes> <verbose>false</verbose> </configuration> <dependencies> <dependency> <groupId>org.datanucleus</groupId> <artifactId>datanucleus-core</artifactId> <version>${datanucleus.version}</version> </dependency> </dependencies> <executions> <execution> <phase>compile</phase> <goals> <goal>enhance</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project> <file_sep>package phoswald.webnotes.notes; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.CookieParam; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.joda.time.LocalDateTime; import phoswald.webnotes.framework.BaseService; import phoswald.webnotes.framework.EntityTransaction; @Path("/notes") public class NoteService extends BaseService { @CookieParam(ATTRIBUTE_USER) private String sessionUserId; @GET @Path("/list") @Produces(MediaType.APPLICATION_JSON) public Response list() { if(sessionUserId == null) { return Response.status(Status.FORBIDDEN).cacheControl(getNoCache()).build(); } try(EntityTransaction txn = new EntityTransaction()) { List<Note> notes = txn.findQuery(Note.class, "select n from Note n where n.userId = ?1 order by n.timestamp", sessionUserId); return Response.ok(notes).cacheControl(getNoCache()).build(); } } @POST @Path("/add") @Consumes(MediaType.APPLICATION_JSON) public Response post(Note note) { if(sessionUserId == null) { return Response.status(Status.FORBIDDEN).build(); } note.setNoteId(0); note.setUserId(sessionUserId); note.setTimestamp(LocalDateTime.now()); try(EntityTransaction txn = new EntityTransaction()) { txn.persist(note); txn.markSuccessful(); return Response.ok().build(); } } @GET @Path("/single/{id}") @Produces(MediaType.APPLICATION_JSON) public Response get(@PathParam("id") long noteId) { if(sessionUserId == null) { return Response.status(Status.FORBIDDEN).cacheControl(getNoCache()).build(); } try(EntityTransaction txn = new EntityTransaction()) { Note note = txn.find(Note.class, noteId); return Response.ok(note).cacheControl(getNoCache()).build(); } } @PUT @Path("/single/{id}") @Consumes(MediaType.APPLICATION_JSON) public Response put(@PathParam("id") long noteId, Note note) { if(sessionUserId == null) { return Response.status(Status.FORBIDDEN).build(); } note.setNoteId(noteId); note.setTimestamp(LocalDateTime.now()); try(EntityTransaction txn = new EntityTransaction()) { txn.merge(note); // works for both insert and update txn.markSuccessful(); return Response.ok().build(); } } @DELETE @Path("/single/{id}") public Response delete(@PathParam("id") long noteId) { if(sessionUserId == null) { return Response.status(Status.FORBIDDEN).build(); } try(EntityTransaction txn = new EntityTransaction()) { txn.remove(Note.class, noteId); txn.markSuccessful(); return Response.ok().build(); } } } <file_sep> function checkLogin() { $.ajax({ type: "GET", url: "rest/users/current", dataType: "json" }) .done(function(data, textStatus, jqXHR) { window.location.href = "notes.html"; }) .fail(function(jqXHR, textStatus, errorThrown) { $("#loading").hide(); $("#ready").show(); }); } function login() { var data = { userId: $("#username").val(), password: $("#<PASSWORD>").val() }; $.ajax({ type: "POST", url: "rest/users/login", data: JSON.stringify(data), contentType: "application/json; charset=UTF-8" }) .done(function(data, textStatus, jqXHR) { window.location.href = "notes.html"; }) .fail(function(jqXHR, textStatus, errorThrown) { // Note: jQuery's $("#login_denied").show() does not work for <paper-toast>. document.querySelector("#login_denied").show(); }); } $(document).ready(function() { // Note: jQuery's $(...).show() and hide() only works for <div>, but not for <paper-material>. $("#loading").show(); $("#ready").hide(); $("#login_button").click(login); // checkLogin(); window.setTimeout(checkLogin, 1000); }); <file_sep>package phoswald.webnotes.users; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Objects; public class SecurityUtils { private static final Charset UTF_8 = Charset.forName("UTF-8"); private static final char[] HEX_CHARS = "0123456789ABCDEF".toCharArray(); private static final String HASH_ALGORITHM = "SHA-1"; public static String computeHash(String secret) { try { Objects.requireNonNull(secret); String salt = Long.toString(System.nanoTime() ^ System.currentTimeMillis()); String digest = encode(hash(salt, secret)); return salt + ";" +digest; } catch(NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e); } } public static boolean verifyHash(String hash, String secret) { try { Objects.requireNonNull(hash); Objects.requireNonNull(secret); int sep = hash.lastIndexOf(';'); String salt = hash.substring(0, sep); String digest = encode(hash(salt, secret)); return hash.equals(salt + ";" + digest); } catch(NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e); } } private static byte[] hash(String salt, String secret) throws NoSuchAlgorithmException { return MessageDigest.getInstance(HASH_ALGORITHM).digest((salt + ";" + secret).getBytes(UTF_8)); } private static String encode(byte[] buf) { StringBuilder sb = new StringBuilder(); for(byte b : buf) { sb.append(HEX_CHARS[(b & 0xF0) >>> 4]); sb.append(HEX_CHARS[ b & 0x0F]); } return sb.toString(); } } <file_sep>package phoswald.webnotes.framework; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaQuery; public class EntityTransaction implements AutoCloseable { private static final EntityManagerFactory factory = Persistence.createEntityManagerFactory("default"); private final EntityManager em; private boolean success; public EntityTransaction() { em = factory.createEntityManager(); em.getTransaction().begin(); } @Override public void close() { if(success) { em.getTransaction().commit(); } else { em.getTransaction().rollback(); } em.close(); } public void markSuccessful() { success = true; } public <T> T find(Class<T> clazz, Object id) { return em.find(clazz, id); } public <T> List<T> findAll(Class<T> clazz) { CriteriaQuery<T> query = em.getCriteriaBuilder().createQuery(clazz); return em.createQuery(query.select(query.from(clazz))).getResultList(); } public <T> List<T> findQuery(Class<T> clazz, String string, Object... params) { TypedQuery<T> query = em.createQuery(string, clazz); for(int i = 0; i < params.length; i++) { query.setParameter(i+1, params[i]); } return query.getResultList(); } public void persist(Object entity) { em.persist(entity); // insert } public <T> T merge(T entity) { return em.merge(entity); // works for both insert and update } public <T> void remove(Class<T> clazz, Object id) { T entity = em.find(clazz, id); if(entity != null) { em.remove(entity); // delete } } } <file_sep>var templateNotes = null; function compile() { templateNotes = Hogan.compile($("#template_notes").text()); } function checkLogin() { $.ajax({ type: "GET", url: "rest/users/current", dataType: "json" }) .done(function(data, textStatus, jqXHR) { $("#current_user").text("Logged in as: " + data.name + " (" + data.userId + ")"); query(); }) .fail(function(jqXHR, textStatus, errorThrown) { window.location.href = "login.html"; }); } function logout() { $.ajax({ type: "POST", url: "rest/users/logout" }) .done(function(data, textStatus, jqXHR) { window.location.href = "login.html"; }) } function query() { $.ajax({ type: "GET", url: "rest/notes/list", dataType: "json" }) .done(function(data, textStatus, jqXHR) { //$("#status").text("found " + data.length + " items"); $("#notes").html(templateNotes.render({ notes: data })); $(".remove_button").click(function() { remove($(this).attr("data-id")); }); }) .fail(function(jqXHR, textStatus, errorThrown) { $("#query_errormsg").text(errorThrown); document.querySelector("#query_failed").show(); }); } function store() { var note = { name: $("#store_name").val(), content: $("#store_content").val() }; $.ajax({ type: "POST", url: "rest/notes/add", data: JSON.stringify(note), contentType: "application/json; charset=UTF-8" }) .done(function(data, textStatus, jqXHR) { $("#store_name").val(""); $("#store_content").val(""); document.querySelector("#store_successful").show(); query(); }) .fail(function(jqXHR, textStatus, errorThrown) { $("#store_errormsg").text(errorThrown); document.querySelector("#store_failed").show(); }); } function remove(noteId) { $.ajax({ type: "DELETE", url: "rest/notes/single/" + noteId }) .done(function(data, textStatus, jqXHR) { document.querySelector("#remove_successful").show(); query(); }) .fail(function(jqXHR, textStatus, errorThrown) { $("#remove_errormsg").text(errorThrown); document.querySelector("#remove_failed").show(); }); } $(document).ready(function() { compile(); $("#query_button").click(query); $("#store_button").click(store); checkLogin(); }); <file_sep>package phoswald.webnotes.users; import java.util.List; import java.util.Objects; import javax.ws.rs.Consumes; import javax.ws.rs.CookieParam; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.NewCookie; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import phoswald.webnotes.framework.BaseService; import phoswald.webnotes.framework.EntityTransaction; @Path("/users") public class UserService extends BaseService { @CookieParam(ATTRIBUTE_USER) private String sessionUserId; // TODO: the cookie __MUST__ be verified @POST @Path("/login") @Consumes(MediaType.APPLICATION_JSON) public Response login(User body) { try(EntityTransaction txn = new EntityTransaction()) { User user = txn.find(User.class, body.getUserId()); if(user == null && Objects.equals(body.getUserId(), "admin")) { user = new User(); user.setUserId(body.getUserId()); user.setPassword(SecurityUtils.computeHash("<PASSWORD>")); user.setName("Administrator"); user.setActive(true); txn.persist(user); txn.markSuccessful(); } if(user == null || user.getActive() == false) { return Response.status(Status.FORBIDDEN).build(); } if(!SecurityUtils.verifyHash(user.getPassword(), body.getPassword())) { return Response.status(Status.FORBIDDEN).build(); } NewCookie cookie = new NewCookie(ATTRIBUTE_USER, user.getUserId(), "/", null, 1, null, -1, null, false, false); // TODO: the cookie __MUST__ be encrypted return Response.ok().cookie(cookie).build(); } } @POST @Path("/logout") public Response logout() { NewCookie cookie = new NewCookie(ATTRIBUTE_USER, null, "/", null, 1, null, -1, null, false, false); return Response.ok().cookie(cookie).build(); } @GET @Path("/current") @Produces(MediaType.APPLICATION_JSON) public Response current() { if(sessionUserId == null) { return Response.status(Status.FORBIDDEN).cacheControl(getNoCache()).build(); } try(EntityTransaction txn = new EntityTransaction()) { User user = null; if(sessionUserId != null && sessionUserId.length() > 0) { user = txn.find(User.class, sessionUserId); } if(user == null) { return Response.status(Status.NOT_FOUND).cacheControl(getNoCache()).build(); } return Response.ok(user).cacheControl(getNoCache()).build(); } } @GET @Path("/list") @Produces(MediaType.APPLICATION_JSON) public Response list() { if(sessionUserId == null) { return Response.status(Status.FORBIDDEN).cacheControl(getNoCache()).build(); } try(EntityTransaction txn = new EntityTransaction()) { List<User> users = txn.findAll(User.class); for(User user : users) { user.setPassword(<PASSWORD>); } return Response.ok(users).cacheControl(getNoCache()).build(); } } @GET @Path("/single/{id}") @Produces(MediaType.APPLICATION_JSON) public Response get(@PathParam("id") String userId) { if(sessionUserId == null) { return Response.status(Status.FORBIDDEN).cacheControl(getNoCache()).build(); } try(EntityTransaction txn = new EntityTransaction()) { User user = txn.find(User.class, userId); if(user == null) { return Response.status(Status.NOT_FOUND).cacheControl(getNoCache()).build(); } user.setPassword(<PASSWORD>); return Response.ok(user).cacheControl(getNoCache()).build(); } } @PUT @Path("/single/{id}") @Consumes(MediaType.APPLICATION_JSON) public Response put(@PathParam("id") String userId, User user) { if(sessionUserId == null) { return Response.status(Status.FORBIDDEN).build(); } user.setUserId(userId); user.setPassword(SecurityUtils.computeHash(user.getPassword())); try(EntityTransaction txn = new EntityTransaction()) { txn.merge(user); txn.markSuccessful(); return Response.ok().build(); } } @DELETE @Path("/single/{id}") public Response delete(@PathParam("id") String userId) { if(sessionUserId == null) { return Response.status(Status.FORBIDDEN).build(); } try(EntityTransaction txn = new EntityTransaction()) { txn.remove(User.class, userId); txn.markSuccessful(); return Response.ok().build(); } } } <file_sep>package phoswald.webnotes.framework; import javax.ws.rs.core.CacheControl; public class BaseService { protected static final String ATTRIBUTE_USER = "userid"; protected static CacheControl getNoCache() { CacheControl cc = new CacheControl(); cc.setNoCache(true); return cc; } }
d9930f85cd1c3d4f67a3be5d2ac0df8e27401f73
[ "JavaScript", "Java", "Maven POM" ]
9
Java
phoswald/web-notes
d3bb3fec71237c9e805558d7f74e841154710c03
07799b01d048318ddae6174bae805b73da8fa7dd
refs/heads/master
<repo_name>FawadJavid/lost-found<file_sep>/app/app.py from flask import Flask,request,session,redirect,render_template from flask_mysqldb import MySQL import yaml import os app=Flask(__name__) #database Configuration db=yaml.load(open('db.yaml')) app.config['MYSQL_HOST']= db['mysql_host'] app.config['MYSQL_USER']= db['mysql_user'] app.config['MYSQL_PASSWORD']= db['mysql_password'] app.config['MYSQL_DB']= db['mysql_db'] mysql=MySQL(app) @app.route('/') def index(): return '<h1><center>Welcome to Lost and Found</center></h1><br><br><br>' \ '<h1>Routes:</h1><br>' \ '<h4>localhost:5000/register?username=(your username)&password=(<PASSWORD>)</h4>'' \ ''<h4>localhost:5000/signIn?(your username)&password=(<PASSWORD>)</h4>' @app.route('/home') def home(): if 'name' in session: return '<h1><center>Welcome '+session['name']+' to Lost and Found</center></h1>' \ '<br><br><br>'' \ ''<h1>Routes:</h1><br>localhost:5000/home/add' else: return "</h1>Login First</h1>" @app.route('/register') def register(): username=request.args.get('username') password=request.args.get('password') cur=mysql.connection.cursor() cur.execute("INSERT INTO USER(username,password) VALUES(%s, %s)",(username,password)) mysql.connection.commit() cur.close() return username+'! You are Successfully Registered' @app.route('/login') def login(): username=request.args.get('username') #password=request.args.get('password') cur=mysql.connection.cursor() cur.execute("""SELECT * FROM USER WHERE username = %s""", (username,)) user=cur.fetchone() cur.close() if user is None: return "<center><h1 style='color:red;'>!!! wrong username or password !!!</h1></center>" else: session['name']=user[0] return redirect('/home') @app.route('/logout') def logout(): session.clear() return redirect('/') @app.route('/home/add',methods=['GET','POST']) def add(): if 'name' in session: #getting file and saving it render_template('form.html') path = os.path.abspath(__file__) dir_path = os.path.dirname(path) target=os.path.join(dir_path,'images/') if not os.path.isdir(target): os.mkdir(target,mode=0o777) file=request.files["file"] filename=file.filename destination="/".join([target,filename]) file.save(destination) #getting remaining data from the form item_name=request.form['item_name'] location=request.form['location'] descrip=request.form['descrip'] datee=request.form['datee'] #sending the data to db cur=mysql.connection.cursor() query="""INSERT INTO LOSTFOUND(item_name,location,descrip,datee,picture) VALUES(%s, %s, %s, %s, %s)""" data=(item_name, location, descrip, datee, destination) cur.execute(query, data) mysql.connection.commit() cur.close() return '<h1><center>Welcome ' + session['name'] + ' to Lost and Found</center></h1>' \ '<br><h1>report registered<br>Go back to home: localhost:5000/home</h1> ' else: return "</h1>Login First</h1>" @app.route('/home/delete') def delete(): if 'name' in session: item_name=request.args.get('item') cur = mysql.connection.cursor() query = """DELETE FROM LOSTFOUND WHERE item_name=%s""" data = (item_name,) cur.execute(query, data) mysql.connection.commit() cur.close() return "<h1>Item deleted<h1>" else: return "</h1>Login First</h1>" @app.route('/home/view') def view(): if 'name' in session: cur=mysql.connection.cursor() query="""SELECT * FROM LOSTFOUND""" cur.execute(query) mysql.connection.commit() data=cur.fetchall() cur.close() return render_template('view.html', data=data) else: return "</h1>Login First</h1>" @app.route('/home/search',methods=['GET','POST']) def search(): if 'name' in session: render_template('search.html') itemname=request.form['item_name'] location=request.form['location'] cur = mysql.connection.cursor() query = """SELECT * FROM LOSTFOUND WHERE item_name=%s AND location=%s""" data = (itemname,location,) cur.execute(query, data) mysql.connection.commit() data=cur.fetchall() cur.close() return render_template('searchview.html', data=data) else: return "</h1>Login First</h1>" if __name__=="__main__": app.secret_key="th3g3ntl3m4n" app.run(debug='TRUE') <file_sep>/app/requirements.txt Click==7.0 Flask==1.1.1 Flask-MySQL==1.4.0 Flask-MySQLdb==0.2.0 Flask-WTF==0.14.2 itsdangerous==1.1.0 Jinja2==2.10.3 MarkupSafe==1.1.1 mysqlclient==1.4.4 PyMySQL==0.9.3 PyYAML==5.1.2 Werkzeug==0.16.0
ff2500343ee32ab4ca3e9c719c49f319a8b12394
[ "Python", "Text" ]
2
Python
FawadJavid/lost-found
3f239a918a754ef55948d52b66798539c35ee130
b3eb7e6ab4b19fb05e00e985f8d35d4ccb865bac
refs/heads/master
<repo_name>ikeessa/spring<file_sep>/README.md # Introduction 대학교 3학년 마치고 휴학중 2018년 IT 회사 인턴으로 일하면서 프로그래밍에 재미를 느끼기 시작하였습니다. </br> 2019년 1월 현재 대학교 4학년 1학기를 마치고 스프링을 공부하면서 취업 활동을 하고 있습니다. </br> 아래의 ASP 프로젝트들은 인턴 생활하면서 공부하면서 만들었습니다. # 스프링 프로젝트 개발 환경 OS - Win10</br> IDE - Eclipse(VERSION : Oxygen)</br> Language - JAVA(VERSION : JDK 1.8),JSTL(2.5),JSP,HTML5,BOOTSTRAP TEMPLATE(DASHGUM)</br> 미들웨어 - TOMCAT(VERSION : 8.0)</br> DBMS - MySQL (VERSION : 5.6.42)</br> FRAMEWORK : SPRING@MVC (VERSION :4.1.6)</br> ORM : MYBATIS (VERSION : 1.2.2) # Spring Project 1.게시판 만들기 ![default](https://user-images.githubusercontent.com/21051557/51041208-c2768580-15fc-11e9-9718-2d440107b396.PNG) ![default](https://user-images.githubusercontent.com/21051557/51041209-c2768580-15fc-11e9-9eb4-6bbd6730e9b9.png) Spring Framework 와 mysql 을 이용해 게시판 작성 및 목록을 만들고 </br> 기본적인 CRUD 구현을 하였습니다. # ASP Project 1.게시판 만들기 ![default](https://user-images.githubusercontent.com/21051557/50974604-faaf9280-152e-11e9-8bb6-09fd5000e4a0.png) ASP 언어를 이용해 작성하였고 검색,페이징,파일 업로드 및 다운로드 기능을 구현하였습니다.</br> https://github.com/ikeessa/asp/blob/master/ASP/list.asp 2.트리 구조 만들기(클릭시 그 안의 트리 내용이 펼쳐짐),파일이 존재할 경우 빨강색 ![default](https://user-images.githubusercontent.com/21051557/50974608-faaf9280-152e-11e9-9408-c9958b78042d.png) ASP 언어를 이용해 작성하여 트리 구조 만들었고 제이쿼리를 이용해 트리 클릭시 하위 트리 내용이 펼쳐지게 하였습니다.</br> 파일이 존재하는가에 대해서는 파일에 확장자명 .png , .jpg 등을 split 으로 잘라서 체크하였습니다.</br> 파일이 존재할 경우 빨강색표시로 나타납니다.</br> https://github.com/ikeessa/asp/blob/master/ASP/index.do 3.엑셀 데이터를 DB에 간편하게 넣을 수 있는 프로그램 ![split](https://user-images.githubusercontent.com/21051557/50974609-fb482900-152e-11e9-82c5-fcf5abbdfbb7.png) 처음에 acro editor 를 이용해 db insert value 값에 각각의 엑셀의 열을 넣고 insert 하는 식으로 하였지만 </br> 반복작업이 너무 심해서 프로그램을 만들었습니다.</br> 엑셀의 각 셀이 탭으로 구분 되어있고 줄이 내려가면 엔터로 되어있기 때문에 탭과 엔터를 split으로 잘라서 </br> 해당 내용들을 각 칼럼에 맞게 버튼 클릭시 한꺼번에 insert 되도록 하는 프로그램을 만들었습니다. </br> https://github.com/ikeessa/asp/blob/master/ASP/insert.do </br> https://github.com/ikeessa/asp/blob/master/ASP/insert_proc.do 4.기타 업무 ![default](https://user-images.githubusercontent.com/21051557/50974606-faaf9280-152e-11e9-910a-cd441c53db03.png) 선임의 기존의 소스와 홈페이지에 적용된 템플릿 소스를 이용해 이러한 폼 등을 새로 만들고 수정하는 작업 등을 하였습니다. </br> +버튼을 누를시 제이쿼리 클론을 이용해 행이 추가 되는 작업을 하였습니다. </br> 부트 스트랩(템플릿) 뿐만 아니라 ASP,JQuery,AJAX 백엔드 소스도 작성 하였습니다. <file_sep>/startPrj1/src/main/java/com/spring/dao/StudentDAO.java package com.spring.dao; import com.spring.vo.BbsVO; import com.spring.vo.StudentVO; import org.apache.ibatis.session.SqlSession; import org.springframework.stereotype.Repository; import javax.inject.Inject; import java.util.List; @Repository public class StudentDAO { @Inject private SqlSession sqlSession; //db 연동 public void insert(StudentVO studentVO) throws Exception { sqlSession.insert("insert",studentVO); } public BbsVO read(Integer bid) throws Exception { return sqlSession.selectOne("read", bid); } public void update(StudentVO studentVO) throws Exception { sqlSession.update("update", studentVO); } public void delete(Integer bid) throws Exception { sqlSession.delete("delete", bid); } public List<BbsVO> list(Integer bcount) throws Exception { return sqlSession.selectList("list"); } public int readAll() throws Exception { return sqlSession.selectOne("readAll"); } } <file_sep>/startPrj1/src/main/java/com/spring/vo/PageCriteria.java package com.spring.vo; public class PageCriteria { private int page; private int numPerPage; public PageCriteria() { this.page =2; this.numPerPage =10; } public int getPage() { return page; } public void setPage(int page) { if(page<=0) { this.page=1; return; } this.page = page; } public int getNumPerPage() { return numPerPage; } public void setNumPerPage(int numPerPage) { if(numPerPage <=0) { this.numPerPage =10; return; } this.numPerPage = numPerPage; } public int getStartPage() { return (this.page-1)*numPerPage; } @Override public String toString() { return "PageCriteria [page="+page+",numPerPage="+numPerPage+"]"; } } <file_sep>/startPrj1/src/main/java/com/spring/service/StudentService.java package com.spring.service; import com.spring.dao.SeatDAO; import com.spring.dao.StudentDAO; import com.spring.vo.BbsVO; import com.spring.vo.SeatVO; import com.spring.vo.StudentVO; import org.springframework.stereotype.Service; import javax.inject.Inject; import java.util.List; @Service public class StudentService { @Inject private StudentDAO studentDAO; public void write(StudentVO studentVO) throws Exception { studentDAO.insert(studentVO); } public BbsVO read(Integer bid) throws Exception { return studentDAO.read(bid); } public void modify(StudentVO studentVO) throws Exception { studentDAO.update(studentVO); } public void remove(Integer bid) throws Exception { studentDAO.delete(bid); } public List<BbsVO> list(Integer bcount) throws Exception { return studentDAO.list(bcount); } } <file_sep>/startPrj1/src/main/java/com/spring/service/BbsServiceImpl.java package com.spring.service; import java.util.List; import javax.inject.Inject; import org.springframework.stereotype.Service; import com.spring.dao.BbsDAO; import com.spring.vo.BbsVO; import com.spring.vo.FindCriteria; import com.spring.vo.PageCriteria; @Service public class BbsServiceImpl implements BbsService { @Inject private BbsDAO bdao; @Override public void write(BbsVO bvo) throws Exception { bdao.insert(bvo); } @Override public BbsVO read(Integer bid) throws Exception { return bdao.read(bid); } @Override public void modify(BbsVO bvo) throws Exception { bdao.update(bvo); } @Override public void remove(Integer bid) throws Exception { bdao.delete(bid); } @Override public List<BbsVO> list(Integer bcount) throws Exception { return bdao.list(bcount); } @Override public List<BbsVO> listCriteria(PageCriteria pageCri) throws Exception { return bdao.listCriteria(pageCri); } @Override public List<BbsVO> listFind(FindCriteria findCri) throws Exception { return bdao.listFind(findCri); } @Override public int totalPage() throws Exception { return bdao.readAll(); } @Override public int findCountData(FindCriteria findCri) throws Exception { return bdao.findCountData(findCri); } } <file_sep>/startPrj1/src/main/java/com/spring/vo/BbsVO.java package com.spring.vo; import java.util.Date; public class BbsVO { private Integer bid; private String subject; private String content; private String writer; private Date regdate; private int hit; public Integer getBid() { return bid; } public void setBid(Integer bid) { this.bid = bid; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getWriter() { return writer; } public void setWriter(String writer) { this.writer = writer; } public Date getRegdate() { return regdate; } public void setRegdate(Date regdate) { this.regdate = regdate; } public int getHit() { return hit; } public void setHit(int hit) { this.hit = hit; } @Override public String toString() { return "BbsVO [bid=" + bid + ", subject=" + subject + ", content=" + content + ", writer=" + writer + ", regdate=" + regdate + ", hit=" + hit + "]"; } } <file_sep>/startPrj1/src/main/java/com/spring/dao/BbsDAO.java package com.spring.dao; import java.util.List; import com.spring.vo.BbsVO; import com.spring.vo.FindCriteria; import com.spring.vo.PageCriteria; public interface BbsDAO { public void insert(BbsVO bvo) throws Exception; public BbsVO read(Integer bid) throws Exception; public void update(BbsVO bvo) throws Exception; public void delete(Integer bid) throws Exception; public List<BbsVO> list(Integer bcount) throws Exception; /*public List<BbsVO> listPage(int page) throws Exception;*/ public List<BbsVO> listCriteria(PageCriteria pageCri) throws Exception; public int readAll() throws Exception; public List<BbsVO> listFind(FindCriteria findCri) throws Exception; public int findCountData(FindCriteria findCri) throws Exception; } <file_sep>/startPrj1/src/main/java/com/spring/vo/PagingMaker.java package com.spring.vo; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; public class PagingMaker { private int totalData; private int startPage; private int endPage; private boolean prev; private boolean next; private int PageNum = 10; public PageCriteria pageCri; //private FindCriteria findCri; public void setpageCria(PageCriteria pageCri) { this.pageCri = pageCri; } public void setTotalData(int totalData) { this.totalData = totalData; } public void getPagingData() { endPage = (int) (Math.ceil(pageCri.getPage()/(double)PageNum)*PageNum); startPage = (endPage - PageNum)+1; int finalEndPage = (int) (Math.ceil(totalData/(double)pageCri.getNumPerPage())); if(endPage > finalEndPage) { endPage = finalEndPage; } prev = startPage ==1? false : true; next = endPage * pageCri.getNumPerPage() >= totalData ? false : true; } public String makeURI(int page){ UriComponents uriComponents = UriComponentsBuilder.newInstance() .queryParam("page", page) .queryParam("numPerPage", pageCri.getNumPerPage()) .queryParam("findType", ((FindCriteria) pageCri).getFindType()) .queryParam("keyword", ((FindCriteria) pageCri).getKeyword()) .build(); return uriComponents.toUriString(); } public String makeURISearch(int page) { UriComponents uriComponents = UriComponentsBuilder.newInstance() .queryParam("page", page) .queryParam("numPerPage", pageCri.getNumPerPage()) .build(); return uriComponents.toUriString(); } public int getStartPage() { return startPage; } public void setStartPage(int startPage) { this.startPage = startPage; } public int getEndPage() { return endPage; } public void setEndPage(int endPage) { this.endPage = endPage; } public boolean isPrev() { return prev; } public void setPrev(boolean prev) { this.prev = prev; } public boolean isNext() { return next; } public void setNext(boolean next) { this.next = next; } public int getPageNum() { return PageNum; } public void setPageNum(int pageNum) { PageNum = pageNum; } public PageCriteria getPageCri() { return pageCri; } public void setPageCri(PageCriteria pageCri) { this.pageCri = pageCri; } public int getTotalData() { return totalData; } } <file_sep>/startPrj1/src/main/java/com/spring/dao/MemberDAOImpl.java package com.spring.dao; import javax.inject.Inject; import org.apache.ibatis.session.SqlSession; import org.springframework.stereotype.Repository; import com.spring.vo.MemberVO; @Repository //DAO를 스프링에 인식하겟다. public class MemberDAOImpl implements MemberDAO { @Inject private SqlSession sqlSession; @Override public String getTime() { return sqlSession.selectOne("getTime"); //return sqlSession.selectOne(namespace+".getTime"); } @Override public void insertMember(MemberVO mvo) { sqlSession.insert("insertMember",mvo); //sqlSession.selectOne(namespace+".insertMember",mvo); } }
7cd47254e03e43f3097592cb6ea08213653dfbf3
[ "Markdown", "Java" ]
9
Markdown
ikeessa/spring
69f74bc625c8a55c0a1b2b5970507c4d182bf872
fdd32224bbbb7ab07f015f5da264cdd8a9b68822
refs/heads/master
<repo_name>KulikovskyIgor/lingualeo-word-list<file_sep>/server/server.js const express = require("express"); const bodyParser = require('body-parser'); const fileUpload = require('express-fileupload'); const wordParsers = require('./parsers/word'); const lingualeoAPI = require('./api/lingualeo'); const app = express(); app.use(bodyParser.json()); app.use(fileUpload()); app.set("port", process.env.PORT || 3001); // Express only serves static assets in production if (process.env.NODE_ENV === "production") { app.use(express.static("client/build")); } app.post("/api/login", (req, res) => { const { email, password } = req.body; lingualeoAPI.login(email, password) .then(data => res.json(data)) .catch(e => res.error(e.message)); }); app.post("/api/addword", (req, res) => { const { word, translation } = req.body; const adaptedTranslation = wordParsers.adaptUAToRU(translation); lingualeoAPI.addWord(word, adaptedTranslation) .then(data => res.json(data)) .catch(e => res.error(e.message)); }); app.post("/api/addwords", (req, res) => { const words = wordParsers.getParsedWords(req.files.file.data.toString()); const addWordRequests = words.map(word => lingualeoAPI.addWord(word.word, word.translation)); Promise.all(addWordRequests) .then(data => res.json(data)) .catch(e => res.error(e.message)); }); app.listen(app.get("port"), () => { console.log(`Find the server at: http://localhost:${app.get("port")}/`); // eslint-disable-line no-console }); <file_sep>/client/src/services/word.js import { parseJSON, checkStatus } from './generic'; export const addWord = (word, translation) => { return fetch('api/addword', { method: 'post', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json' }, body: JSON.stringify({ word, translation }) }) .then(checkStatus) .then(parseJSON) }; export const addWords = file => { const formData = new FormData(); formData.append('file', file); return fetch('api/addwords', { method: 'post', body: formData }) .then(checkStatus) .then(parseJSON) };<file_sep>/client/src/app.js import React, { Component } from "react"; import LoginPage from './components/login-page/login-page'; import AddWordPage from './components/add-word-page/add-word-page'; class App extends Component { state = { isAuth: sessionStorage.getItem('isAuth') || false }; changeAuthStatus = isAuth => { this.setState({ isAuth }); sessionStorage.setItem('isAuth', isAuth); }; render() { const { isAuth } = this.state; return ( <div> { !isAuth && <LoginPage onLogin={ this.changeAuthStatus }/> } { isAuth && <AddWordPage/> } </div> ); } } export default App; <file_sep>/client/src/components/add-word-page/add-word-page.js import React, { Component } from 'react'; import AddWordFormComponent from './components/add-word-form-component'; import AddWordDropzoneComponent from './components/add-word-dropzone-component'; class AddWordPage extends Component { render() { return ( <div className="ui middle aligned center aligned grid add-word-page"> <div className="five wide computer"> <h2 className="ui teal image header"> <div className="content"> <div className="text-shadow"> Add words to your Lingualeo's library </div> <div className="text-shadow"> Just put any word to form or drop file with words </div> </div> </h2> <AddWordFormComponent/> <div className="ui middle aligned center aligned grid add-word-page-dropzone"> <AddWordDropzoneComponent/> </div> </div> </div> ); } } export default AddWordPage; <file_sep>/server/parsers/word.js const WORDS_ROW_SEPARATOR = '\n'; const WORDS_COL_SEPARATOR = ','; const WORDS_COL_LENGTH = 4; const getParsedWords = (words) => { return [...parseOneLineWord(words)]; }; const parseOneLineWord = words => { const wordsList = words.split(WORDS_ROW_SEPARATOR); return wordsList.reduce((acc, wordLine) => { const wordLineList = wordLine.split(WORDS_COL_SEPARATOR); if (wordLineList.length === WORDS_COL_LENGTH) { const word = wordLineList[2]; const translation = adaptUAToRU(wordLineList[3]); acc.push({ word, translation }); } return acc; }, []); }; const adaptUAToRU = word => { return word .replace(/і/g, 'i') .replace(/ї/g, 'i') .replace(/є/g, 'е'); }; exports.getParsedWords = getParsedWords; exports.adaptUAToRU = adaptUAToRU;<file_sep>/client/src/components/add-word-page/components/add-word-dropzone-component.js import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Dropzone from 'react-dropzone'; import { UPLOAD_STATUS } from '../../../constants/app'; import { addWords } from '../../../services/word'; const initState = { allUploadedCount: 0, successfullyUploadedCount: 0, uploadStatus: UPLOAD_STATUS.DEFAULT, error: null }; const dropzoneStyle = { borderRadius: '50%', borderWidth: 1, height: 300, width: 300, padding: 20, display: 'flex', alignItems: 'center', justifyContent: 'center', textAlign: 'center', borderStyle: 'dashed', borderColor: '#00b5ad', background: 'rgba(0, 181, 173, 0.25)', color: '#00b5ad', fontFamily: 'Lato,Helvetica Neue,Arial,Helvetica,sans-serif', fontSize: 20, cursor: 'pointer' }; class AddWordDropzoneComponent extends Component { state = initState; handleDrop = (files) => { addWords(files[files.length - 1]) .then((data) => { this.setState({ uploadStatus: UPLOAD_STATUS.SUCCESS, allUploadedCount: data.length, successfullyUploadedCount: data.filter(i => !i.error_msg).length }); this.updateUploadStatusToDefault(); }) .catch((e) => { this.setState({ error: e.message }); this.updateUploadStatusToDefault(); }); this.setState({ uploadStatus: UPLOAD_STATUS.IN_PROGRESS }); }; updateUploadStatusToDefault = () => { setTimeout(() => { this.setState(initState); }, 5000); }; render() { const { uploadStatus, allUploadedCount, successfullyUploadedCount, error } = this.state; return ( <Dropzone style={ dropzoneStyle } onDrop={ this.handleDrop }> { uploadStatus === UPLOAD_STATUS.IN_PROGRESS && ( <i style={ { fontSize: 50 } } className="spinner loading icon"></i> ) } { uploadStatus === UPLOAD_STATUS.DEFAULT && ( <p className="text-shadow">Try dropping some files here, or click to select files to upload.</p> ) } { uploadStatus === UPLOAD_STATUS.SUCCESS && ( <div> Successfully uploaded { successfullyUploadedCount } from { allUploadedCount } </div> ) } { error && <div className="ui red message"> { error } </div> } </Dropzone> ); } } AddWordDropzoneComponent.propTypes = { onLogin: PropTypes.func }; export default AddWordDropzoneComponent; <file_sep>/server/api/lingualeo.js const axios = require('axios'); let cookie = null; const login = (email, password) => { return new Promise((resolve, reject) => { axios(`http://api.lingualeo.com/login?utm_source=ll_plugin&utm_medium=plugin&utm_campaign=options&email=${email}&password=${password}`, { method: "post", withCredentials: true, headers: { 'Access-Control-Allow-Credentials': true } }) .then(function (response) { cookie = response.headers['set-cookie']; resolve(response.data); }) .catch(function (error) { reject(error.message); }); }); }; const addWord = (word, translation) => { return new Promise((resolve, reject) => { axios('http://api.lingualeo.com/addword', { method: "post", withCredentials: true, headers: { 'Access-Control-Allow-Credentials': true, 'Cookie': cookie }, data: { word, tword: translation }, }) .then(function (response) { resolve(response.data); }) .catch(function (error) { reject(error.message); }); }); }; exports.login = login; exports.addWord = addWord;<file_sep>/client/src/services/login.js import { parseJSON, checkStatus } from './generic'; export const login = (email, password) => { return fetch('api/login', { method: 'post', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password }) }) .then(checkStatus) .then(parseJSON) };
77103215674057c85bc737bed1a6bb80c7e95cfc
[ "JavaScript" ]
8
JavaScript
KulikovskyIgor/lingualeo-word-list
1187ba7a4504f83bf28655177d5bedcac550764d
b9feb6ab72f7d6fefb95ef18d75942eb6293f9ec
refs/heads/master
<file_sep>const Discord = require("discord.js"); const client = new Discord.Client(); client.on("ready", () => { console.log('By : m7md'); client.user.setPresence({ status: 'dnd', game: { type: 0, name: '<NAME>', details: `رويال القمة والعظمة`, url: 'http://twitch.tv/M7md_Salih', state: `رويال القمة والعظمة`, application_id: '377479790195769345', assets: { small_image: `377480550207717376`, small_text: 'رويال القمة والعظمة', large_image: `377480353259978752`, large_text: `رويال القمة والعظمة` } } }); }); اقولها client.login("<KEY>");
6b8afc337bf18a1ac7866737ec5a79697ae96c81
[ "JavaScript" ]
1
JavaScript
Spam127/2easd
4de4c4c336980dc22ad5d68f1630fa71e458f4c0
f8ffb57f9d7f2d98c2e26d3dac6b60a7fa829c18
refs/heads/main
<file_sep>import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String doAgain = "yes"; while(doAgain.equals("yes")){ System.out.print("Enter the number:"); byte input = scanner.nextByte(); if (input % 3 == 0 && input % 5 == 0) System.out.println("FizzBuzz"); else if (input % 3 == 0) System.out.println("Fizz"); else if (input % 5 == 0) System.out.println("Buzz"); else System.out.println(input); System.out.print("Enter yes to continue:"); doAgain = scanner.next().toLowerCase(); } } } <file_sep># FizzBuzz Take the input from User. If divisible by only 3- Fizz. If divisible by only 5- Buzz. If divisible by both 3 & 5 FizzBuzz. Else return the number. After one implementation ask if the user wants to continue, if yes continue again else break from the program.
f7e6a8e5a4136a2d672aa38f1fe0bc8237e30332
[ "Markdown", "Java" ]
2
Java
kshv41/FizzBuzz
5499df396be32d38de90beb23546183ba499c4ea
fc202777d8d223329607cb183a6524fc68d61ade
refs/heads/master
<repo_name>traba-dev/RestConsume<file_sep>/RestConsume/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace RestConsume { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Action_Click(object sender, EventArgs e) { RestClient rest = new RestClient(); Company company = new Company(); rest.SetEndPoint(Input.Text); rest.SetHttpVerb("POST"); company.name = txtName.Text; company.address = txtAddress.Text; company.phone = txtPhone.Text; company.lat = txtLat.Text; company.lon = txtLon.Text; company.email = txtEmail.Text; if (company.name.Equals("") || company.address.Equals("") || company.phone.Equals("") || company.lat.Equals("") || company.lon.Equals("") || company.email.Equals("")) { MessageBox.Show("All fields are Require"); return; } string response = rest.RequestRequest<Company>(company); OutputApi(response); } private void OutputApi(string text) { Output.Text = Output.Text + text + Environment.NewLine; } private void btnGet_Click(object sender, EventArgs e) { RestClient rest = new RestClient(); Company company = new Company(); rest.SetEndPoint(Input.Text); rest.SetHttpVerb("POST"); string response = rest.RequestRequest<Company>(null); OutputApi(response); } } } <file_sep>/RestConsume/RestClient.cs using System; using System.Threading.Tasks; using System.Net; using System.IO; using System.Web.Script.Serialization; namespace RestConsume { class RestClient { public enum HttpVerbs { GET, POST, PUT, DELETE } private string EndPoint; private HttpVerbs Httpverb; public RestClient() { this.EndPoint = String.Empty; this.Httpverb = HttpVerbs.GET; } public void SetEndPoint(string EndPoint) { this.EndPoint = EndPoint; } public void SetHttpVerb(string verb) { HttpVerbs newVerb; switch(verb) { case "POST": newVerb = HttpVerbs.POST; break; case "PUT": newVerb = HttpVerbs.PUT; break; case "DELETE": newVerb = HttpVerbs.DELETE; break; default: newVerb = HttpVerbs.GET; break; } this.Httpverb = newVerb; } public string RequestRequest<T>(T ObjectRequest) { string strResponse = string.Empty; WebRequest request; try { request = WebRequest.Create(this.EndPoint); request.Method = this.Httpverb.ToString(); request.PreAuthenticate = true; request.ContentType = "application/json;charset=utf-8'"; if (ObjectRequest != null) { //serializamos el objeto string json = Newtonsoft.Json.JsonConvert.SerializeObject(ObjectRequest); //Construye el body del request using (var streamWriter = new StreamWriter(request.GetRequestStream())) { streamWriter.Write(json); streamWriter.Flush(); } } WebResponse response = (WebResponse)request.GetResponse(); using (StreamReader read = new StreamReader(response.GetResponseStream())) { if (read != null) { strResponse = read.ReadToEnd(); } } } catch (Exception ex) { throw new ApplicationException("Error was Ocurred: " + ex.Message); } return strResponse; } } } <file_sep>/RestConsume/Company.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RestConsume { class Company { public int id { get; set; } public string name { get; set; } public string email { get; set; } public string phone { get; set; } public string lat { get; set; } public string lon { get; set; } public string status { get; set; } public string logo { get; set; } public string address { get; set; } public Company() { this.id = 0; this.name = string.Empty; this.email = string.Empty; this.phone = string.Empty; this.phone = string.Empty; this.lat = string.Empty; this.lon = string.Empty; this.status = "A"; this.address = string.Empty; this.logo = string.Empty; } } }
2e587a69f578896e702d5bcc581f41a011d8c2d0
[ "C#" ]
3
C#
traba-dev/RestConsume
6185c6b7e2116cc97595771cd269df0cb37c62fd
d9029438e458efdf5cac9605c3d2d0ff503ba154
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; #region Autodesk using Autodesk.AutoCAD.Runtime; using Autodesk.AutoCAD.EditorInput; using Autodesk.AutoCAD.DatabaseServices; using Autodesk.AutoCAD.ApplicationServices; using Autodesk.AutoCAD.Geometry; #endregion namespace ExplodeProxyMgd { class cEntity { private Entity _EntProxy; public Entity EntProxy { get { return _EntProxy; } set { _EntProxy = value; } } public SelectionSet Selection(Document doc, Transaction tr) { try { PromptSelectionResult acSSPrompt = doc.Editor.GetSelection(); if (acSSPrompt.Status == PromptStatus.OK) { SelectionSet acSSet = acSSPrompt.Value; return acSSet; } } catch (Autodesk.AutoCAD.Runtime.Exception ex) { } return null; } public void CreateBlock() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; using (Transaction tr = db.TransactionManager.StartOpenCloseTransaction()) { DBObjectCollection objs = new DBObjectCollection(); BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); EntProxy.Explode(objs); string blkName = EntProxy.Handle.ToString(); if (bt.Has(blkName) == false) { BlockTableRecord btr = new BlockTableRecord(); btr.Name = blkName; bt.UpgradeOpen(); ObjectId btrId = bt.Add(btr); tr.AddNewlyCreatedDBObject(btr, true); foreach (DBObject obj in objs) { Entity ent = (Entity)obj; btr.AppendEntity(ent); tr.AddNewlyCreatedDBObject(ent, true); } BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); BlockReference br = new BlockReference(Point3d.Origin, btrId); ms.AppendEntity(br); tr.AddNewlyCreatedDBObject(br, true); } tr.Commit(); } } public List<ProxyEntity> GetProxies() { Database db = HostApplicationServices.WorkingDatabase; List<ProxyEntity> result = new List<ProxyEntity>(); using (Transaction tr = db.TransactionManager.StartOpenCloseTransaction()) { BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead); foreach (ObjectId btrId in bt) { BlockTableRecord btr = (BlockTableRecord)tr.GetObject(btrId, OpenMode.ForRead); foreach (ObjectId entId in btr) { if (entId.ObjectClass.Name == "AcDbZombieEntity") { ProxyEntity ent = (ProxyEntity)tr.GetObject(entId, OpenMode.ForRead); result.Add(ent); } } } tr.Commit(); return result; } return null; } public void RemoveProxy() { Database db = HostApplicationServices.WorkingDatabase; ObjectId id = EntProxy.ObjectId; using (Transaction tr = db.TransactionManager.StartOpenCloseTransaction()) { BlockTable bt = (BlockTable)tr.GetObject( db.BlockTableId, OpenMode.ForRead); foreach (ObjectId btrId in bt) { BlockTableRecord btr = (BlockTableRecord)tr.GetObject(btrId, OpenMode.ForRead); foreach (ObjectId entId in btr) { if (entId.ObjectClass.Name == "AcDbZombieEntity" && entId == id) { ProxyEntity ent = (ProxyEntity)tr.GetObject(entId, OpenMode.ForRead); ent.UpgradeOpen(); using (DBObject newEnt = new Line()) { ent.HandOverTo(newEnt, false, false); newEnt.Erase(); } } } } tr.Commit(); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; #region Autodesk using Autodesk.AutoCAD.Runtime; using Autodesk.AutoCAD.EditorInput; using Autodesk.AutoCAD.DatabaseServices; using Autodesk.AutoCAD.ApplicationServices; using Autodesk.AutoCAD.Geometry; #endregion [assembly: CommandClass(typeof(ExplodeProxyMgd.ExplodeProxy))] namespace ExplodeProxyMgd { public class ExplodeProxy { private static ObjectIdCollection ids = new ObjectIdCollection(); [CommandMethod("proxy-explode-to-block")] public void ProxyExplodeToBlock() { Document doc = Application.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; int incr = 0; try { cEntity oEnt = new cEntity(); List<ProxyEntity> proxies = oEnt.GetProxies(); foreach (ProxyEntity e in proxies) { oEnt.EntProxy = e as Entity; oEnt.CreateBlock(); oEnt.RemoveProxy(); incr++; //e.Clone(); } ed.WriteMessage(string.Format("\n" + incr + " Proxies in Blocks converted.")); } catch(System.Exception ex) { } //using (Transaction tr = db.TransactionManager.StartOpenCloseTransaction()) //{ // SelectionSet acSSet = oEnt.Selection(doc, tr); // foreach (SelectedObject acSSObj in acSSet) // { // if (acSSObj != null) // { // } } [CommandMethod("RemoveProxiesFromBlocks", "RemoveProxiesFromBlocks", CommandFlags.Modal)] public void RemoveProxies() { Database db = HostApplicationServices.WorkingDatabase; using (Transaction tr = db.TransactionManager.StartOpenCloseTransaction()) { BlockTable bt = (BlockTable)tr.GetObject( db.BlockTableId, OpenMode.ForRead); foreach (ObjectId btrId in bt) { BlockTableRecord btr = (BlockTableRecord)tr.GetObject(btrId, OpenMode.ForRead); foreach (ObjectId entId in btr) { if (entId.ObjectClass.Name == "AcDbZombieEntity") { ProxyEntity ent = (ProxyEntity)tr.GetObject(entId, OpenMode.ForRead); ent.UpgradeOpen(); using (DBObject newEnt = new Line()) { ent.HandOverTo(newEnt, false, false); newEnt.Erase(); } } } } tr.Commit(); } } } public class ExplodeProxyMgd : IExtensionApplication { private static Editor editor = Application.DocumentManager.MdiActiveDocument.Editor; public void Initialize() { editor.WriteMessage("\nConvert Proxy->Block: Start with proxy-explode-to-block"); } public void Terminate() { } } }
7ee4bfd4777d5e85bb8ed4dfef0289eb5248a4b0
[ "C#" ]
2
C#
dirkrossger/ExplodeProxys
beb76172c854e85cbea989128cc68b319c041b56
b74ad8c45d55997298aa46e4f9a6651c3400e5a4
refs/heads/master
<repo_name>kaunas-coding-school/bootcamp-kurso-medziaga-la<file_sep>/pavyzdziai/paskaita-13/moviewish/resources/assets/js/calculator.js var C = {}; // C Object simplifies exporting the module C.isEven = function (num) { // enough to satisfy the test return true; // also passes JSLint }; module.exports = C; <file_sep>/pavyzdziai/paskaita-13/moviewish/tests/calculatorTest.js var assert = require('assert'); var C = require('../resources/assets/js/calculator.js'); describe('Calculator', function() { describe('isEven', function() { it('should return true', function() { assert.equal(true, C.isEven(2)); }); }); }); <file_sep>/pavyzdziai/paskaita-15/moviewish/resources/assets/js/calculator.js //// NODE BACKEND //// 1 var. Node module exported, needs to be compiled to Javascript to run in browser var Calculator = {}; Calculator.sum = function (number=true) { return number; }; module.exports = Calculator; //// Example of execution from app.js // var calculator = require('calculator.js'); // console.log(calculator.sum(2)); // ----------------------------------------------------------- // BROWSER FRONTEND // 2 var. Native Javascript Module pattern // var Calculator = (function () { // // var calc = {}; // calc.sum = function (number) { // if (number === undefined) { // number = true; // } // return number; // }; // return calc; // // })(); //// Example of execution from app.js //// index.html -> app.js + calculator.js // var calculator = new Calculator(); // console.log(calculator.sum(2)); <file_sep>/pavyzdziai/paskaita-15/moviewish/app/CalcStats.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class CalcStats extends Model { public function minArray($numbers = NULL, $numbers2 = NULL) { if (gettype($numbers) == "integer") { if ($numbers < $numbers2 || !$numbers2) { return $numbers; } else { return $numbers2; } } $min = $numbers[0]; $elements = $this->countArray($numbers); for ($i=0; $i < $elements; $i++) { if ($numbers[$i] < $min) { $min = $numbers[$i]; } } return $min; } public function maxArray($numbers) { return max($numbers); } public function countArray($numbers) { return sizeof($numbers); } public function averageArray($numbers) { if (gettype($numbers) == "integer") { return $numbers; } $elements = $this->countArray($numbers); $sum = 0; for ($i=0; $i < $elements; $i++) { $sum += $numbers[$i]; } $average = $sum / $elements; return round($average, 3); } public function allStats($numbers) { $min = $this->minArray($numbers); $max = $this->maxArray($numbers); $count = $this->countArray($numbers); $average = $this->averageArray($numbers); return $all = [$min, $max, $count, $average]; } } <file_sep>/pavyzdziai/paskaita-16/3-2-moviewish-laravel-app/app/Http/Controllers/SearchMoviesController.php <?php namespace App\Http\Controllers; use App\OMDB; use Illuminate\Http\Request; class SearchMoviesController extends Controller { public function index() { return view('search.index'); } public function send(Request $request) { $keyword = $request->keyword; $omdb = new OMDB; $response = $omdb->getSearch($keyword); $result = $omdb->getResults($response); return redirect()->route('search-results')->with('movies', $result); } public function results() { return view('search.results'); } } <file_sep>/pavyzdziai/paskaita-15/moviewish/resources/assets/js/harrypotter.js var HarryPotter = {}; // HarryPotter knygu kaina HarryPotter.price = 8; // [[1, 1, 1, 1, 1,], [1, 1, 1]] // // [5, 1]; // Galimybe pakeisti knygos kaina HarryPotter.setPrice = function(newPrice) { this.price = newPrice; }; // Metodas skaiciuoja kiek skirtingu knygu perkam // input Array // output Number HarryPotter.countBooks = function(books) { if (!books){ return 0; } return books.length; }; // Metodas skaiciuoja kokia nuolaida duoti pagal tai kiek knygu perkam // input Number // output Number HarryPotter.calcDiscount = function(differentBooks) { var discount = 0; switch (differentBooks) { case 2: discount = 5; break; case 3: discount = 10; break; case 4: discount = 20; break; case 5: discount = 25; break; } return discount; }; HarryPotter.applyDiscount = function(books) { var count = this.countBooks(books); return this.calcDiscount(count); }; HarryPotter.booksTotal = function(books) { var sum = 0; for (var i = 0; i < books.length; i++) { sum += books[i]; } return sum; }; HarryPotter.cartTotal = function(books) { if (typeof(books) === 'object') { return this.booksTotal(books) * this.price; } return books * this.price; }; HarryPotter.cartDiscount = function(books) { var discount = this.applyDiscount(books); // 10% var cartTotal = this.cartTotal(this.countBooks(books)); // books == [2, 1, 1] return cartTotal * discount / 100; // 10/100*72 }; HarryPotter.totalPrice = function(books) { var cartTotal = this.cartTotal(books); var booksTotal = this.countBooks(books); var discountSum = 0; var max = Math.max.apply(null, books); for (var i = 0; i < max; i++) { discountSum += this.cartDiscount(books); for (var j = 0; j < booksTotal; j++) { books[j] -= 1; if (books[j] === 0) { books.splice(j, 1); j--; booksTotal--; } } } return cartTotal - discountSum; }; module.exports = HarryPotter; <file_sep>/pavyzdziai/paskaita-16/3-2-moviewish-laravel-app/app/OMDB.php <?php namespace App; use Illuminate\Database\Eloquent\Model; use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; class OMDB extends Model { protected $url = 'https://api.themoviedb.org/3/'; protected $searchURL = ['GET', 'search/movie']; public function url() { return $this->url; } public function searchMethod() { return $this->searchURL[0]; } public function searchURL() { return $this->searchURL[1]; } public function getSearch($keyword=NULL) { // Prisijungimo API raktas $apikey = '<KEY>'; // Pilnas adresas $fullUrl = $this->searchURL().'?'.'api_key='.$apikey.'&query='.$keyword; // Susikuriu Guzzle Client client objekta $client = new Client(['base_uri' => $this->url()]); // Siunciu uzklausa i OMDB serveri try { $response = $client->request($this->searchMethod(), $fullUrl); } catch (RequestException $e) { $e->getRequest(); if ($e->hasResponse()) { $response = $e->getResponse(); } } // $code = $response->getStatusCode(); // // if ($code == 200) { // $results = $response->getBody(); // }; return $response; } public function getResults($response) { $body = $response->getBody(); $results = json_decode($body); return $results; } } <file_sep>/pavyzdziai/paskaita-12/moviewish/tests/Unit/FizzBuzzTest.php <?php namespace Tests\Unit; use App\FizzBuzz; use Tests\TestCase; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; class FizzBuzzTest extends TestCase { /** * A basic test example. * * @return void */ public function testFizzBuzzClassInitiation() { $fb = new FizzBuzz; } public function testFizzBuzzMethodResult() { $fb = new FizzBuzz; $fb->result(); } public function testFizzBuzzResult2() { $fb = new FizzBuzz; $result = $fb->result(2); $this->assertEquals(2, $result); // 2==2 } public function testFizzBuzzResult4() { $fb = new FizzBuzz; $result = $fb->result(4); $this->assertEquals(4, $result); // 2==2 } public function testFizzBuzzResult3() { $fb = new FizzBuzz; $result = $fb->result(3); $this->assertEquals("Fizz", $result); // 2==2 } public function testFizzBuzzResult5() { $fb = new FizzBuzz; $result = $fb->result(5); $this->assertEquals("Buzz", $result); // 2==2 } public function testFizzBuzzResult15() { $fb = new FizzBuzz; $result = $fb->result(15); $this->assertEquals("FizzBuzz", $result); // 2==  } public function testFizzBuzzResult6() { $fb = new FizzBuzz; $result = $fb->result(6); $this->assertEquals("Fizz", $result); // 2==2 } public function testFizzBuzzReturnsHundredNumbers() { $fb = new FizzBuzz; $result = $fb->hundred(); $this->assertCount(100, $result); } public function testFizzBuzzArrayFirst() { $fb = new FizzBuzz; $result = $fb->hundred(); $this->assertEquals(1, $result[0]); } public function testFizzBuzzArray90() { $fb = new FizzBuzz; $result = $fb->hundred(); $this->assertEquals("FizzBuzz", $result[89]); } public function testFizzBuzzArray99() { $fb = new FizzBuzz; $result = $fb->hundred(); $this->assertEquals("Fizz", $result[98]); } } <file_sep>/pavyzdziai/paskaita-16/3-2-moviewish-laravel-app/routes/web.php <?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ // Homepage for visitors Route::get('/', 'HomeController@index')->name('home'); Route::post('/', 'HomeController@feedback')->name('home'); // Authentication routes Auth::routes(); // Wishlist homepage for loggged in users Route::get('/wishlist', 'WishlistController@index')->name('wishlist'); // Search movies routes Route::get('/search', 'SearchMoviesController@index')->name('search'); Route::post('/search', 'SearchMoviesController@send')->name('search'); // Movie results route Route::get('/search/results', 'SearchMoviesController@results')->name('search-results'); // Movies Route::resource('movies', 'MovieController'); // Returns views without Controller Route::get('/cinemas', function () { return view('cinemas'); }); Route::get('/settings', function () { return view('settings'); }); <file_sep>/pavyzdziai/paskaita-12/moviewish/app/FizzBuzz.php <?php namespace App; use Illuminate\Database\Eloquent\Model; /** * */ class FizzBuzz extends Model { public function result($number = 0) { if ($number % 15 == 0) { $number = "FizzBuzz"; } else if ($number % 5 == 0) { $number = "Buzz"; } else if ($number % 3 == 0) { $number = "Fizz"; } return $number; } public function hundred() { $results = []; for ($i=1; $i <= 100; $i++) { array_push($results, $this->result($i)); } return $results; } } <file_sep>/pavyzdziai/paskaita-12/moviewish/tests/Unit/CalcStatsTest.php <?php namespace Tests\Unit; use App\CalcStats; use Tests\TestCase; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; class CalcStatsTest extends TestCase { /** * A basic test example. * * @return void */ public function testCalcStatsClassInitiations() { $cs = new CalcStats; } public function testCalcStatsMethodMinimum() { $cs = new CalcStats; $cs->minArray(); } public function testCalcStatsMinimum3() { $cs = new CalcStats; $result = $cs->minArray(3); $this->assertEquals(3, $result); } public function testCalcStatsMinimumTwoValues() { $cs = new CalcStats; $result = $cs->minArray(3, 2); $this->assertEquals(2, $result); } public function testCalcStatsMinimumTwoValuesArray() { $cs = new CalcStats; $result = $cs->minArray([3, 2]); $this->assertEquals(2, $result); } public function testCalcStatsMinimumFiveValuesArray() { $cs = new CalcStats; $result = $cs->minArray([3, 2, 100, -10, 0]); $this->assertEquals(-10, $result); } public function testCalcStatsMaximum() { $cs = new CalcStats; $result = $cs->maxArray([3, 2, 90, -10, 0]); $this->assertEquals(90, $result); } public function testCalcStatsElementsInEmptyArray() { $cs = new CalcStats; $result = $cs->countArray([]); $this->assertEquals(0, $result); } public function testCalcStatsElementsInArray() { $cs = new CalcStats; $result = $cs->countArray([3, 2, 90, -10, 0]); $this->assertEquals(5, $result); } public function testCalcStatsAverageSingle() { $cs = new CalcStats; $result = $cs->averageArray(3); $this->assertEquals(3, $result); } public function testCalcStatsAverageDoubleArray() { $cs = new CalcStats; $results = $cs->averageArray([2, 4]); $this->assertEquals(3, $results); } public function testCalcStatsAverageFloatArray() { $cs = new CalcStats; $results = $cs->averageArray([2, 4, 4]); $this->assertEquals(3.333, $results); } function testCalcStatsAllStatsArrayCount() { $cs = new CalcStats; $results = $cs->allStats([2, 4]); $this->assertCount(4, $results); } function testCalcStatsAllStatsArray() { $cs = new CalcStats; $results = $cs->allStats([2, 4, 4]); $this->assertEquals(2, $results[0]); $this->assertEquals(4, $results[1]); $this->assertEquals(3, $results[2]); $this->assertEquals(3.333, $results[3]); } } <file_sep>/pavyzdziai/paskaita-16/3-2-moviewish-laravel-app/tests/Unit/OMDBTest.php <?php namespace Tests\Unit; use App\OMDB; use Tests\TestCase; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; class OMDBTest extends TestCase { /** * Initiate the OMDB object from Class. * * @return void */ public function testOMDBClassInitiated() { $omdb = new OMDB; } /** * Test OMDB Url address. * * @return void */ public function testOMDBURL() { $omdb = new OMDB; $result = $omdb->url(); $this->assertEquals('https://api.themoviedb.org/3/', $result); } /** * A test Search method. * * @return void */ public function testOMDBSearchMethod() { $omdb = new OMDB; $result = $omdb->searchMethod(); $this->assertEquals('GET', $result); } /** * A test Search method address. * * @return void */ public function testOMDBSearchURL() { $omdb = new OMDB; $result = $omdb->searchUrl(); $this->assertEquals('search/movie', $result); } /** * A test Search method without parameters. * * @return void */ public function testOMDBSearchConnectionWithoutParameters() { $omdb = new OMDB; $result = $omdb->getSearch(); $this->assertEquals(422, $result->getStatusCode()); } /** * A test Search method with parameters. * * @return void */ public function testOMDBSearchConnectionWithParameters() { $omdb = new OMDB; $result = $omdb->getSearch('avengers'); $this->assertEquals(200, $result->getStatusCode()); } /** * A test Search no results. * * @return void */ public function testOMDBSearchResults() { $omdb = new OMDB; $response = $omdb->getSearch('akshfajkahskjf'); $result = $omdb->getResults($response); $this->assertEquals(0, $result->total_results); } /** * Test Search with results. * * @return void */ public function testOMDBSearchResultsMoreThan0() { $omdb = new OMDB; $response = $omdb->getSearch('avengers'); $result = $omdb->getResults($response); $this->assertGreaterThan(0, $result->total_results); } } <file_sep>/pavyzdziai/paskaita-15/moviewish/tests/HarryPotterTest.js var assert = require('assert'); var hp = require('../resources/assets/js/harrypotter.js'); describe('HarryPotter', function() { describe('countBooks()', function() { it('should return 0 if no parameters given', function() { assert.equal(0, hp.countBooks()); }); it('should return 1 if 1 parameter given', function() { assert.equal(0, hp.countBooks([])); }); it('should return 2 if 2 array values are given', function() { assert.equal(2, hp.countBooks([2, 3])); }); it('should return 5 if 5 array values are given', function() { assert.equal(5, hp.countBooks([2, 2, 2, 1, 1])); }); }); describe('calcDiscount()', function(){ it('should give no discount if one book is sold', function() { assert.equal(0, hp.calcDiscount(1)); }); it('should give 5% discount if two different books are sold', function() { assert.equal(5, hp.calcDiscount(2)); }); it('should give 10% discount if three different books are sold', function() { assert.equal(10, hp.calcDiscount(3)); }); it('should give 20% discount if four different books are sold', function() { assert.equal(20, hp.calcDiscount(4)); }); it('should give 25% discount if five different books are sold', function() { assert.equal(25, hp.calcDiscount(5)); }); }); describe('applyDiscount()', function(){ it('should give 25% discount if we buy 5 different books', function() { assert.equal(25, hp.applyDiscount([2, 2, 2, 1, 1])); }); }); describe('booksTotal()', function(){ it('should give 9 if we have an array of 9 books', function() { assert.equal(9, hp.booksTotal([3, 2, 2, 1, 1])); }); }); describe('cartTotal()', function(){ it('should give $72 total price of 9 if one book costs $8', function() { assert.equal(72, hp.cartTotal(9)); }); it('should give $72 total price of 9 if one book costs $8', function() { assert.equal(72, hp.cartTotal([3, 2, 2, 1, 1])); }); }); describe('cartDiscount()', function(){ it('should give $2.4 discount if we buy 3 different books ', function() { assert.equal(2.4, hp.cartDiscount([1, 1, 1])); }); it('should give $2.4 discount if we buy 3 different books but 4 in total', function() { assert.equal(2.4, hp.cartDiscount([2, 1, 1])); }); it('should give $6.4 discount if we buy 4 different books but 10 in total', function() { assert.equal(6.4, hp.cartDiscount([4, 3, 2, 1])); }); }); describe('totalPrice()', function(){ it('should give $30 total price if we buy 5 different books but 8 in total', function() { assert.equal(30, hp.totalPrice([1, 1, 1, 1, 1])); }); it('should give $60 total price if we buy 5 different books but 10 in total', function() { assert.equal(60, hp.totalPrice([2, 2, 2, 2, 2])); }); it('should give $51.6 total price if we buy 5 different books but 8 in total', function() { assert.equal(51.6, hp.totalPrice([2, 2, 2, 1, 1])); }); }); });
f6f54fbda642553c92916ef05b1505bd9972309d
[ "JavaScript", "PHP" ]
13
JavaScript
kaunas-coding-school/bootcamp-kurso-medziaga-la
6d8f1185cba123eb5edfcd2ca64ae0081f804ff9
96f4b10a61190fbd9c85182e3c73fd891e765f6c
refs/heads/master
<repo_name>NilsRethmeier/MoRTy<file_sep>/README.md # MoRTy: a simple tool for Zero-shot domain adaptation of embeddings MoRTy is a simple baseline method for **zero-shot domain adaptation** of embeddings that works especially well for **low-resource** applications, such as when *little pre-traing data is available*. It solves ... ### Problems In practice, one has to chose which embedding model (FastText, Glove, TransformerX) is optimal for a task. While most pre-training methods like BERT are optimized for *'high-pretraining-resource'* domains, they can not be directly applied to *'low-pre-training resource settings'* and incure substantial training costs. In practice, using a Multi-GPU model to fine tune on a sub 10 MB supervision task can seem counterintuitive and affords preparation and maintanance costs, which limits scalability of future use cases or during deployment. ### Acronym and architecture, model-code <p align="center"> <b>M</b>enu <b>o</b>f <b>r</b>econstructing <b>t</b>ransformations <b>y</b>ields domain (<i>de-</i>)adapted embeddings </p> <p align="center"> <img src="morty.png" width="700"> </p> ``` python # See parameter settings in #Recipe section below or in MoRTy.py example (pc=OrderedDict ...) class SparseOverCompleteAutoEncoder(torch.nn.Module): """ A sparse L1 autoencoder, that retrofits embeddings that are of the same (complete AE) or larger (overcomplete AE) dimension than the original embeddings. """ def __init__(self, emb_dim, hidden_size, bias=True): super(SparseOverCompleteAutoEncoder, self).__init__() self.lin_encoder = nn.Linear(emb_dim, hidden_size, bias=bias) # no bias works too self.lin_decoder = nn.Linear(hidden_size, emb_dim, bias=bias) self.feature_size = emb_dim self.hidden_size = hidden_size self.l1weight = params['l1'] # had little effect on SUM-of-18-tasks performance self.act = params['activation'] # linear was best for SUM-of-18-tasks score def forward(self, input): r = self.act(self.lin_encoder(input)) if self.l1weight is not None: # sparsity penalty x_ = self.lin_decoder(L1Penalty.apply(r, self.l1weight)) else: x_ = self.lin_decoder(r) # no sparsity penalty # x_ for training via loss, r are the new/retrofit embeddings after training (1-epoch) return x_, r ``` ### Recipe: :stew: 1. **pre-train**/ download **embeddings** `E_org` (using FastText is recommended for out-of-vocabulary abilities) 2. **Produce** `k` randomly autoencoded/ retro-fitted **versions** `E_r1 ... E_rk` of the original embedding `E_org` 3. **Chose** the **optimal** `E_ro` form the `k` `E_ri` according to: + **Embedding specialization**/ *Supervised use case:* a supervised end-task's develoment set (`E_ri` is now essentially a hyperparameter). To save computation, consider selecting the optimal embedding `E_ro` on a low-cost baseline such as logistic regression or FastText and then use the found `E_ro` in the more complex model. Also works to find optimal `E_ro` in multi-input/channel + multi-task settings. + **Embedding specialization**/ *Proxy supervised use case:* use the dev/test set of a related (benchmark) task to find optimal embeddings `E_ro`. *'Proxy-shot' setting*. + **Embedding generalization**/ *Zero-shot use case:* when training embeddings `E_ri` for 1 epoch on different pre-training corpora sizes (WikiText-2/-103, CommonCrawl) `E_org` we found MoRTy to always produce score improvements (between 1-9%) over the sum of 18 word-embedding benchmark tasks. This means that MoRTy *generalizes* embeddings 'blindly'. ### Properties/ use cases + Zero- to few/proxy-shot domain adaptation + train in seconds :clock1: + low RAM requirements, no GPU needed -- low carbon footprint, MoRTy :hearts: :earth_africa: + saves annotation + usable to train simpler models (lower model extension costs/time) + cheaply produce that last 5% performance increase for customers :smirk: + [MoRTy](https://en.wikipedia.org/wiki/Morty_Smith) is not a Muppet # Usage :wrench: `MoRTy.py` contains example code that takes a .vec file (e.g. `data/wikitext2_FastText_SG0.vec` in `#word\tembedding_values format`) of FastText or GloVe pretrained embeddings and produces new autoencoded versions of those embeddings. The parameters in the `pc` dictionary can be adjusted. Though the script supports hyper parameter exploration via extending the value list in the `pc` object, this should not be neccessary. </br> *Note:* To reproduce the papers 1-epoch results (below) MoRTy was trained for 1-epoch using the scripts defaults settings. Blue is FastText embedding baseline performance = 100% for 5x FastText baselines per corpus size. On each baseline 3 MoRTy (red, yellow, green) were trained for 1 epoch. <p align="center"> <img src="1epoch.png" width="490"> </p> The MT, ST results are best scores over multiple runs or MoRTy, so they indicate an upper bound that can approached on practical datasets using a development split for Mo*RT*y selection. In the paper experiments, the [word embdding benchmark](https://github.com/kudkudak/word-embeddings-benchmarks) by [<NAME> et al.](https://arxiv.org/abs/1702.02170) serves as evaluation set -- i.e., no dev set was used. Since for practical applications the method is intended as a postprocessing step, to get cheap score improvements on (m)any emebdding model, only relative (potential) score changes are reported in the paper. # Dependencies ``` python 3.6 # due to word embedding benchmark pandas 0.25.0 scikit-learn 0.21.2 pytorch 0.4.1 tdqm 4.32.1 ``` requirements.txt for the rest # Paper and bibtex Reference :scroll: [MoRTy: Unsupervised Learning of Task-specialized Word Embeddings by Autoencoding](https://www.aclweb.org/anthology/W19-4307), <NAME>, <NAME>, Repl4NLP@ACL, Italy, 2019 ``` @inproceedings{rethmeier-plank-2019-morty, title = "{M}o{RT}y: Unsupervised Learning of Task-specialized Word Embeddings by Autoencoding", author = "<NAME> and <NAME>", booktitle = "Proceedings of the 4th Workshop on Representation Learning for NLP (RepL4NLP-2019)", month = "august", year = "2019", address = "Florence, Italy", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/W19-4307", pages = "49--54", } ``` <file_sep>/MoRTy.py # %% #DONE: imports import torch import torch.nn as nn import torch.nn.functional as f import numpy as np import os # os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152 # os.environ["CUDA_VISIBLE_DEVICES"]="0" print(torch.cuda.device_count()) from collections import OrderedDict import os import sys if "evaluation/word-embeddings-benchmarks/" not in sys.path: # only add this once sys.path.append("evaluation/word-embeddings-benchmarks/") # add the Visualization package to python_path so we can use it here print(sys.path) import pickle import collections from pathlib import Path import pandas as pd from web.evaluate import evaluate_similarity, evaluate_on_all_no_logs from collections import defaultdict import copy from web.embedding import Embedding import warnings import itertools if not sys.warnoptions: warnings.simplefilter("ignore") device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print(device) #DONE: embedding loader # %% class LazyLoadEmbeddings(): """ Class that loads embeddings and the according word list lazyly with file path.vec as key. Expected input format is fasttext .vec file - i.e., 'word Emb_dim1 dim2 ... dimN' Useful, if for a task multiple embedding models (fasttext, glove etc.) will be tried out """ def __init__(self): self.loaded_embeddings = dict() def load_vec_file(self, path='../training_data/some_FT_File.ft.vec'): if path not in self.loaded_embeddings: print('read_embeddings', path) ft_vocab = list() ft_embeddings = list() with open(path, 'r', encoding="utf-8") as vecs: num_words, emb_dim = next(vecs).split() # skip count header print("loading", num_words, "words at dim", emb_dim) self.expected_tokens_per_line = int(emb_dim) + 1 for vec in vecs: data = vec.strip().split(' ') if len(data) == self.expected_tokens_per_line: ft_vocab.append(data[0]) # special case for broken data ft_embeddings.append(data[1:]) print(len(ft_vocab), 'words in fasttext vocab') self.loaded_embeddings[path] = dict(embs=ft_embeddings, vocab=ft_vocab) return self.loaded_embeddings[path]['embs'], self.loaded_embeddings[path]['vocab'] def give_words_batch(ft_embeddings, batch_size, nptype=np.float32): batch_num = int(len(ft_embeddings) / batch_size) for X_b in np.array_split(np.array(ft_embeddings, dtype=nptype), batch_num): yield X_b def linear(x): return x class L1Penalty(torch.autograd.Function): @staticmethod def forward(ctx, input, l1weight): ctx.save_for_backward(input) ctx.l1weight = l1weight return input @staticmethod def backward(ctx, grad_output): input, = ctx.saved_tensors grad_input = input.clone().sign().mul(ctx.l1weight) grad_input += grad_output return grad_input, None # %% #DONE: MoRTy models class SparseAutoEncoder(torch.nn.Module): def __init__(self, params): super(SparseAutoEncoder, self).__init__() emb_dim = params['emb_d'] hidden_size = params['rep_dim'] # default: same as original self.lin_encoder = nn.Linear(emb_dim, hidden_size) self.lin_decoder = nn.Linear(hidden_size, emb_dim) self.feature_size = emb_dim self.hidden_size = hidden_size # l1 for simple sparse AE, had little effect on SUM performance. self.l1weight = params['l1'] self.act = params['activation'] # linear was best for SUM score def forward(self, input): # encoder r = self.act(self.lin_encoder(input)) # decoder if self.l1weight is not None: # sparsity penalty x_ = self.lin_decoder(L1Penalty.apply(r, self.l1weight)) else: # no sparsity penalty x_ = self.lin_decoder(r) return x_, r #DONE: Morty main helper functions ############################################# # %% def relu1(x): # did not work # relu that restricts activations to 0-1 return x.clamp(min=0, max=1) # %% def MSE(pred, gold, reduce=torch.mean): # worked, but slightly worse than RMSE return reduce(((pred - gold) ** 2).mean(0)) # %% def RMSE(pred, gold, reduce=torch.mean): # works, but slower than MSE return torch.sqrt(MSE(pred, gold, reduce)) def get_AE_representations(embeddings, device, ptdtype, npdtype, model, batch_size=1000): # get model embeddings emb_list = [] # to use little memory, we batch for i in range(0, len(embeddings), batch_size): # to save memory embs = embeddings[i:i+batch_size] e = torch.tensor(np.asarray(embs, dtype=npdtype), requires_grad=False, device=device, dtype=ptdtype) a , representations = model.forward(e) emb_list.append(representations.cpu().data.numpy()) return np.concatenate(emb_list) def train_dev_split(embs, vocab, train_size_fraq=.9): df = pd.DataFrame() df['embs'] = embs df['vocab'] = vocab msk = np.random.rand(len(df)) < train_size_fraq train = df[msk] dev = df[~msk] return train['embs'].values.tolist(), train['vocab'].values.tolist(), dev['embs'].values.tolist(), dev['vocab'].values.tolist() def get_optimizer(hyper_conf, net): return hyper_conf['optim']['obj'](filter(lambda x: x.requires_grad, net.parameters()), # filter params that are non-tuneable (e.g. Embedding layer) lr=hyper_conf['lr'], **hyper_conf['optim']['params']) def num_morties_to_create(num_morties, epochs=1, original_embeddings_path="/tmp"): """ @param: num_morties how many Reconstructing Transformations to create. 1 epoch = default training. @param: epoch, creates one subvariation of the random transformation per epoch @param: creates a new path name for every variation """ return [original_embeddings_path + 'epoch:' + str(e) + 'rand:' + str(random_init) for random_init in range(num_morties) for e in range(epochs)] def filter_on_metric(scores, metric_we_care_about=''): #FIXME: define a sensible condition here. E.g. fires when a new max score is reached return True # makes no sense atm. == Placeholder def store_embeddings(path='MoRTy_embedding.', vocab=None, embs=None, store_as='.vec'): print(path) # vocab and embeddings are list and array, with the same sequence order # vocab[2] => embs[2] if vocab == None or embs == None: raise Exception("empty data dump") if store_as == '.pickle': with open(path+store_as,'wb') as f: pickle.dump({'vocab':vocab, 'embeddings':embs}, f) elif store_as == '.vec': with open(path+store_as,'w') as f: f.write(str(len(embs)) + ' ' + str(len(embs[vocab[0]])) + '\n') # header for token, emb in embs.items(): f.write(token + ' ' + ' '.join(str(x_i) for x_i in emb) + '\n') else: raise Exception('embedding output format not recognized') def loaded_embeddings(path='MoRTy_embedding.pkl', as_dict=False): """ Return vocab embedding dict. Vocab and and embeddings are mapped by order -- i.e. vocab[2] as assigned to embeddings[2] @params: as_dict=True returns a {vocab_i:embedding_i, ... } dict """ with open(path,'rb') as f: pickle.load(f) if as_dict: return dict(zip(f['vocab'], f['embeddings'])) return pickle.load(f) def parameter_combos_generator(param_lists_dict): """ Use to compare multiple embedders Usable for hyperparameter search, but not significantly beneficial. """ return (dict(zip(param_lists_dict, x)) for x in itertools.product(*param_lists_dict.values())) ## parameter setting def run_MoRTy_to_produce_specialized_embeddings(param_space, evaluate_word_embs=False): LLE = LazyLoadEmbeddings() # lazy embedding loader if used for multiple 'embs' ptdtype = torch.float if ptdtype == torch.float: npdtype = np.float32 # MoRTy ---------------- core of the MoRTy method '' for pc in parameter_combos_generator(param_space): # load data embs, vocab = LLE.load_vec_file(pc['embs']) train_embs, train_vocab, dev_embs, dev_vocab = train_dev_split(embs, vocab, train_size_fraq=pc['train_frac']) dev_embs = np.array(dev_embs, dtype=npdtype) # string array to float array pc['vocab_size'] = len(vocab) pc['emb_d'] = len(train_embs[0]) # train loop train_deque = collections.deque([], 5) # used for a 5-moving-average loss dev_deque = collections.deque([], 5) # used for a 5-moving-average loss model = pc['model'](pc) model = model.cuda() if torch.cuda.is_available() else model if not torch.cuda.is_available(): print("WARNING: running on CPUs") optimizer = get_optimizer(pc, model) # torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9) optimizer.zero_grad() for RT in num_morties_to_create(num_morties=7, epochs=pc['epochs'], original_embeddings_path=pc['embs']): for batch in give_words_batch(train_embs, pc['batch_size']): x_b = torch.tensor(batch, requires_grad=False, device=device, dtype=ptdtype) pred, _ = model.forward(x_b) loss = pc['loss'](pred, x_b, pc['reduce']) loss.backward() optimizer.step() # update parameters optimizer.zero_grad() ls = float(loss.cpu().data.numpy()) train_deque.append(ls) dev_deque.append(ls) # break # DONE: get the representations # print final losses print(np.mean(train_deque), pc['loss'].__name__, 'on train') # should fall, but not to 0 print(np.mean(dev_deque), pc['loss'].__name__, 'on') # should fall, but not to 0 representations = get_AE_representations(embs, device, ptdtype, npdtype, model) new_embeddings = dict(zip(vocab, representations)) #DONE: evlauate results if evaluate_word_embs: res = {k:v[0] for k, v in evaluate_on_all_no_logs(new_embeddings).to_dict().items()} print(res) # store the best RT embedding according to a proxy measure OR # store k MoRTy to select the optimal RT via a downstream tasks dev set if filter_on_metric: store_embeddings(path=RT + '.morty', vocab=vocab, embs=new_embeddings) if __name__ == "__main__": # parameter setting or exploration for MoRTy pc = OrderedDict([('model', [SparseAutoEncoder]), ('embs', ['data/wikitext2_FastText_SG0.vec'], # 'data/wikitext103_FastText_SG0.vec']# your original embedding ), ('vocab_size', ['added_on_the_fly']), ('batch_size', [128]), # ('activation', [linear]), # relu1, F.sigmoid ('epochs', [4]), # e.g. 5 can 5 new RT embeddings (1 per epoch) ('train_frac', [.999]), # to see hold out/ dev loss -- not needed ('l1', [None]), # 0.05, 0.001, 0.5 ('reduce', [torch.mean]), # or torch.sum: did not matter ('emb_d', ['added_on_the_fly']), # added by code ('loss', [RMSE]), # MSE works similarly well (faster) ('rep_dim', [40]), # overcomplete gives some boost # {"obj":torch.optim.SGD, "params":{"momentum":0.9}}]) ('optim', [{"obj":torch.optim.Adam, "params":{"eps":1e-08}}]), ('lr', [2e-02]) # ~ same as original (if annealed then ~1/2) ]) # produce MoRTy versions run_MoRTy_to_produce_specialized_embeddings(pc, evaluate_word_embs=False)
a3bf04296621b9427c3abc02122ddc897ce68379
[ "Markdown", "Python" ]
2
Markdown
NilsRethmeier/MoRTy
a1494423a48e6d00bafae316f4dcb246db5d7950
14d39f3411addf027899430e0d1f0c4e9bbd5e10
refs/heads/master
<file_sep># 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/. # # Copyright (c) 2013, <NAME> import sublime, sublime_plugin from threading import Timer, Lock from .complete.complete import find_uses, get_completions, get_diagnostics, get_definition, get_type, reparse, free_tu, free_all import os, re, sys, bisect, json, fnmatch def get_settings(): return sublime.load_settings("ClangComplete.sublime-settings") def get_setting(view, key, default=None): s = view.settings() if s.has("clangcomplete_%s" % key): return s.get("clangcomplete_%s" % key) return get_settings().get(key, default) def get_project_path(view): return view.window().folders()[0] def get_unsaved_buffer(view): buffer = None if view.is_dirty(): buffer = view.substr(sublime.Region(0, view.size())) return buffer def debug_print(*args): if get_settings().get("debug", False): print(*args) # # # Retrieve options from cmake # # def parse_flags(f): flags = [] for line in open(f).readlines(): if line.startswith('CXX_FLAGS') or line.startswith('CXX_DEFINES'): words = line[line.index('=')+1:].split() flags.extend([word for word in words if not word.startswith('-g')]) return flags def canonicalize_path(path, root): if path.startswith('-I'): return '-I'+os.path.normpath(os.path.join(root, path[2:])) # rel or abs path else: return path def parse_compile_commands(root, f): flags = [] compile_commands = json.load(open(os.path.join(root, f))) for obj in compile_commands: for key, value in obj.items(): if key == "command": for string in value.split()[1:]: if string.startswith(('-o', '-c')): break if not string.startswith('-g'): # ninja adds local paths as -I. and -I.. # make adds full paths as i flags flags.append(canonicalize_path(string, root)) return flags def merge_flags(flags, pflags): result = [] def append_result(f): if f.startswith(('-I', '-D', '-isystem', '-include', '-isysroot', '-W', '-std', '-pthread', '-arch')): if f not in pflags and f not in result: result.append(f) else: result.append(f) flags_to_merge = ['-isystem', '-include', '-isysroot', '-arch'] prev_flag = "" for f in flags: if len(prev_flag) > 0: append_result(prev_flag + ' ' + f) prev_flag = "" elif f in flags_to_merge: prev_flag = f else: append_result(f) return result def filter_flag(f): exclude_flags = ['-W*unused-but-set-variable', '-W*maybe-uninitialized', '-W*logical-op'] for pat in exclude_flags: if fnmatch.fnmatch(f, pat): return False return True def split_flags(flags): result = [] for f in flags: if filter_flag(f): result.extend(f.split()) return result def accumulate_options(path): flags = [] for root, dirs, filenames in os.walk(path): for f in filenames: if f.endswith('compile_commands.json'): flags.extend(merge_flags(parse_compile_commands(root, f), flags)) return split_flags(flags); if f.endswith('flags.make'): flags.extend(merge_flags(parse_flags(os.path.join(root, f)), flags)) return split_flags(flags) project_options = {} def clear_options(): global project_options project_options = {} def get_options(project_path, additional_options, build_dir, default_options): if project_path in project_options: return project_options[project_path] build_dir = os.path.join(project_path, build_dir) if os.path.exists(build_dir): project_options[project_path] = ['-x', 'c++'] + accumulate_options(build_dir) + additional_options else: project_options[project_path] = ['-x', 'c++'] + default_options + additional_options # debug_print(project_path, project_options[project_path]) return project_options[project_path] def get_args(view): project_path = get_project_path(view) additional_options = get_setting(view, "additional_options", []) build_dir = get_setting(view, "build_dir", "build") default_options = get_setting(view, "default_options", ["-std=c++11"]) # debug_print(get_options(project_path, additional_options, build_dir, default_options)) return get_options(project_path, additional_options, build_dir, default_options) # # # Retrieve include files # # def find_any_of(s, items): for item in items: i = s.find(item) if (i != -1): return i return -1 def bisect_right_prefix(a, x, lo=0, hi=None): if lo < 0: raise ValueError('lo must be non-negative') if hi is None: hi = len(a) while lo < hi: mid = (lo+hi)//2 if x < a[mid] and not a[mid].startswith(x): hi = mid else: lo = mid+1 return lo def find_prefix(items, prefix): return items[bisect.bisect_left(items, prefix): bisect_right_prefix(items, prefix)] project_includes = {} includes_lock = Lock() def clear_includes_impl(): global project_includes if includes_lock.acquire(timeout=10000): project_includes = {} includes_lock.release() else: debug_print("Can't clear includes") def clear_includes(): sublime.set_timeout(lambda:clear_includes_impl() , 1) def search_include(path): start = len(path) if path[-1] is not '/': start = start + 1 result = [] for root, dirs, filenames in os.walk(path): for f in filenames: full_name = os.path.join(root, f) result.append(full_name[start:]) return result def find_includes(view, project_path): result = set() is_path = False for option in get_args(view): if option.startswith('-I'): result.update(search_include(option[2:])) if is_path: result.update(search_include(option)) if option == '-isystem': is_path = True else: is_path = False for path in get_setting(view, "default_include_paths", ["/usr/include", "/usr/local/include"]): result.update(search_include(path)) return sorted(result) def get_includes(view): global project_includes if includes_lock.acquire(blocking=False): try: project_path = get_project_path(view) if project_path not in project_includes: project_includes[project_path] = find_includes(view, project_path) result = project_includes[project_path] finally: includes_lock.release() return result else: debug_print("Includes locked: return nothing") return [] def parse_slash(path, index): last = path.find('/', index) if last == -1: return path[index:] return path[index:last + 1] def complete_includes(view, prefix): slash_index = prefix.rfind('/') + 1 paths = find_prefix(get_includes(view), prefix) return sorted(set([parse_slash(path, slash_index) for path in paths])) # # # Error panel # # class ClangTogglePanel(sublime_plugin.WindowCommand): def run(self, **args): show = args["show"] if "show" in args else None if show or (show == None and not clang_error_panel.is_visible(self.window)): clang_error_panel.open(self.window) else: clang_error_panel.close() class ClangErrorPanelFlush(sublime_plugin.TextCommand): def run(self, edit, data): self.view.erase(edit, sublime.Region(0, self.view.size())) self.view.insert(edit, 0, data) def is_view_visible(view, window=None): ret = view != None and view.window() != None if ret and window: ret = view.window().id() == window.id() return ret class ClangErrorPanel(object): def __init__(self): self.view = None self.data = "" def set_data(self, data): self.data = data if self.is_visible(): self.flush() def get_view(self): return self.view def is_visible(self, window=None): return is_view_visible(self.view, window) def set_view(self, view): self.view = view def flush(self): self.view.set_read_only(False) self.view.set_scratch(True) self.view.run_command("clang_error_panel_flush", {"data": self.data}) self.view.set_read_only(True) def open(self, window=None): if window == None: window = sublime.active_window() if not self.is_visible(window): self.view = window.get_output_panel("clangcomplete") self.view.settings().set("result_file_regex", "^(..[^:\n]*):([0-9]+):?([0-9]+)?:? (.*)$") self.view.set_syntax_file('Packages/ClangComplete/ErrorPanel.tmLanguage') self.flush() window.run_command("show_panel", {"panel": "output.clangcomplete"}) def close(self): sublime.active_window().run_command("hide_panel", {"panel": "output.clangcomplete"}) clang_error_panel = ClangErrorPanel() # # # Get language from sublime # # language_regex = re.compile("(?<=source\.)[\w+#]+") def get_language(view): caret = view.sel()[0].a language = language_regex.search(view.scope_name(caret)) if language == None: return None return language.group(0) def is_supported_language(view): language = get_language(view) if language == None or (language != "c++" and language != "c" and language != "objc" and language != "objc++"): return False return True member_regex = re.compile(r"(([a-zA-Z_]+[0-9_]*)|([\)\]])+)((\.)|(->))$") not_code_regex = re.compile("(string.)|(comment.)") def convert_completion(x): if '\n' in x: c = x.split('\n', 1) return (c[0], c[1]) else: return (x, x) def convert_completions(completions): return [convert_completion(x) for x in completions] # def is_member_completion(view, caret): # line = view.substr(sublime.Region(view.line(caret).a, caret)) # if member_regex.search(line) != None: # return True # elif get_language(view).startswith("objc"): # return re.search(r"\[[\.\->\s\w\]]+\s+$", line) != None # return False class ClangCompleteClearCache(sublime_plugin.TextCommand): def run(self, edit): sublime.status_message("Clearing cache...") clear_includes() clear_options() free_all() class ClangCompleteFindUses(sublime_plugin.TextCommand): def run(self, edit): debug_print("Find Uses") filename = self.view.file_name() # The view hasnt finsished loading yet if (filename is None): return row, col = self.view.rowcol(self.view.sel()[0].begin()) uses = find_uses(filename, get_args(self.view), row+1, col+1, None) self.view.window().show_quick_panel(uses, self.on_done, sublime.MONOSPACE_FONT, 0, lambda index:self.quick_open(uses, index)) def quick_open(self, uses, index): self.view.window().open_file(uses[index], sublime.ENCODED_POSITION | sublime.TRANSIENT) def on_done(self): pass class ClangCompleteGotoDef(sublime_plugin.TextCommand): def run(self, edit): filename = self.view.file_name() # The view hasnt finsished loading yet if (filename is None): return reparse(filename, get_args(self.view), get_unsaved_buffer(self.view)) pos = self.view.sel()[0].begin() row, col = self.view.rowcol(pos) target = get_definition(filename, get_args(self.view), row+1, col+1) if (len(target) is 0): sublime.status_message("Cant find definition") else: self.view.window().open_file(target, sublime.ENCODED_POSITION) class ClangCompleteShowType(sublime_plugin.TextCommand): def run(self, edit): filename = self.view.file_name() # The view hasnt finsished loading yet if (filename is None): return reparse(filename, get_args(self.view), get_unsaved_buffer(self.view)) pos = self.view.sel()[0].begin() row, col = self.view.rowcol(pos) type = get_type(filename, get_args(self.view), row+1, col+1) sublime.status_message(type) class ClangCompleteComplete(sublime_plugin.TextCommand): def show_complete(self): self.view.run_command("hide_auto_complete") sublime.set_timeout(lambda: self.view.run_command("auto_complete"), 1) def run(self, edit, characters): debug_print("ClangCompleteComplete") regions = [a for a in self.view.sel()] self.view.sel().clear() for region in reversed(regions): pos = 0 region.end() + len(characters) if region.size() > 0: self.view.replace(edit, region, characters) pos = region.begin() + len(characters) else: self.view.insert(edit, region.end(), characters) pos = region.end() + len(characters) self.view.sel().add(sublime.Region(pos, pos)) caret = self.view.sel()[0].begin() word = self.view.substr(self.view.word(caret)).strip() debug_print("Complete", word) triggers = ['->', '::', '.'] if word in triggers: debug_print("Popup completions") self.show_complete() build_panel_window_id = None def is_build_panel_visible(window): return build_panel_window_id != None and window != None and window.id() == build_panel_window_id class ClangCompleteAutoComplete(sublime_plugin.EventListener): def complete_at(self, view, prefix, location, timeout): debug_print("complete_at", prefix) filename = view.file_name() # The view hasnt finsished loading yet if (filename is None): return [] if not is_supported_language(view): return [] completions = [] line = view.substr(view.line(location)) if line.startswith("#include") or line.startswith("# include"): row, col = view.rowcol(location - len(prefix)) start = find_any_of(line, ['<', '"']) if start != -1: completions = convert_completions(complete_includes(view, line[start+1:col] + prefix)) else: r = view.word(location - len(prefix)) word = view.substr(r) # Skip completions for single colon or dash, since we want to # optimize for completions after the `::` or `->` characters if word == ':' or word == '-': return [] p = 0 if re.match('^\w+$', word): p = r.begin() else: p = r.end() - 1 row, col = view.rowcol(p) # debug_print("complete: ", row, col, word) completions = convert_completions(get_completions(filename, get_args(view), row+1, col+1, "", timeout, get_unsaved_buffer(view))) return completions def diagnostics(self, view): filename = view.file_name() # The view hasnt finsished loading yet if (filename is None): return [] diagnostics = get_diagnostics(filename, get_args(view)) # If there are errors in the precompiled headers, then we will free # the tu, and reload the diagnostics for diag in diagnostics: if "has been modified since the precompiled header" in diag or "modified since it was first processed" in diag: free_tu(filename) diagnostics = get_diagnostics(filename, get_args(view)) break return [diag for diag in diagnostics if "#pragma once in main file" not in diag] def show_diagnostics(self, view): output = '\n'.join(self.diagnostics(view)) clang_error_panel.set_data(output) window = view.window() if not window is None and len(output) > 1: window.run_command("clang_toggle_panel", {"show": True}) def on_window_command(self, window, command_name, args): global build_panel_window_id debug_print(command_name, args) if command_name == 'show_panel' and args['panel'] == 'output.exec': if 'toggle' in args and args['toggle'] == True and build_panel_window_id != None: build_panel_window_id=None else: build_panel_window_id = window.id() if command_name == 'hide_panel': if build_panel_window_id != None or ('panel' in args and args['panel'] == 'output.exec'): build_panel_window_id = None return None def on_post_text_command(self, view, name, args): if not is_supported_language(view): return if 'delete' in name: return pos = view.sel()[0].begin() self.complete_at(view, "", pos, 0) def on_query_completions(self, view, prefix, locations): if not is_supported_language(view): return [] completions = self.complete_at(view, prefix, locations[0], get_setting(view, "timeout", 200)) debug_print("on_query_completions:", prefix, len(completions)) if (get_setting(view, "inhibit_sublime_completions", True)): return (completions, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS) else: return (completions) def on_activated_async(self, view): debug_print("on_activated_async") if not is_supported_language(view): return debug_print("on_activated_async: get_includes") get_includes(view) debug_print("on_activated_async: complete_at") self.complete_at(view, "", view.sel()[0].begin(), 0) def on_post_save_async(self, view): if not is_supported_language(view): return if not is_build_panel_visible(view.window()): self.show_diagnostics(view) pos = view.sel()[0].begin() self.complete_at(view, "", pos, 0) def on_close(self, view): if is_supported_language(view): free_tu(view.file_name()) def on_query_context(self, view, key, operator, operand, match_all): if key == "clangcomplete_supported_language": if view == None: view = sublime.active_window().active_view() return is_supported_language(view) elif key == "clangcomplete_is_code": return not_code_regex.search(view.scope_name(view.sel()[0].begin())) == None elif key == "clangcomplete_panel_visible": return clang_error_panel.is_visible() <file_sep>CXX=g++ CLANG_PREFIX=$(shell (cd /usr/local/include/clang-c/ && cd ../.. && pwd) 2> /dev/null || (cd /usr/lib/llvm-3.5/ && pwd) 2> /dev/null || (cd /usr/lib/llvm-3.4/ && pwd) 2> /dev/null || (cd /usr/lib/llvm-3.3/ && pwd) 2> /dev/null || (cd /usr/local/opt/llvm && pwd) 2> /dev/null) CLANG_FLAGS=-I$(CLANG_PREFIX)/include/ CLANG_LIBS=-L$(CLANG_PREFIX)/lib/ -lclang FLAGS=$(CLANG_FLAGS) LIBS=$(CLANG_LIBS) LIB_NAME=libcomplete SRC=complete UNAME_S := $(shell uname -s) ifeq ($(UNAME_S),Linux) LDFLAGS = -shared -Wl,-soname,$(LIB_NAME).so -o $(LIB_NAME).so $(SRC).o $(LIBS) -Wl,-rpath=$(CLANG_PREFIX)/lib endif ifeq ($(UNAME_S),Darwin) LDFLAGS = -dynamiclib -Wl,-install_name,$(LIB_NAME).dylib -o $(LIB_NAME).dylib $(SRC).o $(LIBS) endif all: $(CXX) -std=gnu++0x $(FLAGS) -DNDEBUG -Os -c -fPIC complete.cpp -o $(SRC).o $(CXX) $(LDFLAGS) debug: $(CXX) -std=gnu++0x $(FLAGS) -g -c -fPIC -DCLANG_COMPLETE_LOG $(SRC).cpp -o $(SRC).o $(CXX) $(LDFLAGS) log: $(CXX) -std=gnu++0x $(FLAGS) -Os -c -fPIC -DCLANG_COMPLETE_LOG $(SRC).cpp -o $(SRC).o $(CXX) $(LDFLAGS) <file_sep>// 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/. // // Copyright (c) 2013, <NAME> #ifndef CLANGCOMPLETE_COMPLETE_H #define CLANGCOMPLETE_COMPLETE_H extern "C" { typedef unsigned int clang_complete_string; const char * clang_complete_string_value(clang_complete_string s); void clang_complete_string_free(clang_complete_string s); typedef unsigned int clang_complete_string_list; void clang_complete_string_list_free(clang_complete_string_list list); int clang_complete_string_list_len(clang_complete_string_list list); const char * clang_complete_string_list_at(clang_complete_string_list list, int index); clang_complete_string_list clang_complete_get_completions( const char * filename, const char ** args, int argv, unsigned line, unsigned col, const char * prefix, int timeout, const char * buffer, unsigned len); clang_complete_string_list clang_complete_find_uses(const char * filename, const char ** args, int argv, unsigned line, unsigned col, const char * search); clang_complete_string_list clang_complete_get_diagnostics(const char * filename, const char ** args, int argv); // clang_complete_string_list clang_complete_get_usage(const char * filename, const char ** args, int argv); clang_complete_string clang_complete_get_definition(const char * filename, const char ** args, int argv, unsigned line, unsigned col); clang_complete_string clang_complete_get_type(const char * filename, const char ** args, int argv, unsigned line, unsigned col); void clang_complete_reparse(const char * filename, const char ** args, int argv, const char * buffer, unsigned len); void clang_complete_free_tu(const char * filename); void clang_complete_free_all(); } #endif<file_sep>ClangComplete ============= Description ----------- Clang completion for Sublime Text 3. Additionally, it provides diagnostics and some simple navigation capabilites. Installation ------------ First, clone this repo into your sublime packages folder(it doesn't use Package Control). Then cd into the `complete` directory and type: make This will build the `complete.so` binary. It requires the development version of Clang to build(the package `libclang-dev` on debian-based distros). To get the appropriate development package on OS X, install LLVM via Homebrew: brew install --with-clang --with-all-targets --with-rtti --universal --jit llvm Usage ----- ClangComplete provides code completion for C, C++, and Objective-C files. To figure out the compiler flags needed to parse the file, ClangComplete looks into the `build` directory in the project folder for the cmake build settings. If the build directory is placed somewhere else the `build_dir` can be set to the actual build directory. Also if cmake is not used, options can be manually set by setting the `default_options` setting. ClangComplete also shows diagnostics whenever a file is saved, and provides `Goto Definition` functionality. Here are the default shortcuts for ClangComplete: | Key | Action | |--------------|------------------| | alt+d, alt+d | Go to definition | | alt+d, alt+c | Clear cache | | alt+d, alt+t | Show type | Support ------- [Donate](https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=HMB5AGA7DQ9NS&lc=US&item_name=Donation%20to%20clang%20complete&button_subtype=services&currency_code=USD&bn=PP%2dBuyNowBF%3abtn_paynow_LG%2egif%3aNonHosted) <file_sep># 12.07.2015 Modified by <NAME> (<EMAIL>) #Metashell - Interactive C++ template metaprogramming shell # Copyright (C) 2013, <NAME> (<EMAIL>) # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Options for the module # CLANG_INCLUDEDIR Set this if the module can not find the Clang # headers # CLANG_LIBRARYDIR Set this if the module can not find the Clang # library # CLANG_BINARYDIR Set this if the module can not find the clang binary # CLANG_DEBUG Set this for verbose output # CLANG_STATIC Link staticly against libClang (not supported on Windows) # This module will define the following: # CLANG_FOUND # CLANG_INCLUDE_DIR # CLANG_LIBRARY # CLANG_DLL (only on Windows) # CLANG_HEADERS (the path to the headers used by clang) # CLANG_BINARY if (NOT $ENV{CLANG_INCLUDEDIR} STREQUAL "" ) set(CLANG_INCLUDEDIR $ENV{CLANG_INCLUDEDIR}) endif() if (NOT $ENV{CLANG_LIBRARYDIR} STREQUAL "" ) set(CLANG_LIBRARYDIR $ENV{CLANG_LIBRARYDIR}) endif() # Find clang on some Ubuntu versions foreach(V 3.5 3.4 3.3 3.2) set(CLANG_INCLUDEDIR "${CLANG_INCLUDEDIR};/usr/lib/llvm-${V}/include") set(CLANG_LIBRARYDIR "${CLANG_LIBRARYDIR};/usr/lib/llvm-${V}/lib") endforeach() # Find clang-c on Windows if (WIN32) set( CLANG_INCLUDEDIR "D:/llvm-3.4/llvm-3.4-mingw-w64-4.8.1-x64-posix-sjlj/include" ) set( CLANG_LIBRARYDIR "D:/llvm-3.4/llvm-3.4-mingw-w64-4.8.1-x64-posix-sjlj/bin" ) endif() find_path(CLANG_INCLUDE_DIR NAMES clang-c/Index.h HINTS ${CLANG_INCLUDEDIR}) if (WIN32) find_file(CLANG_LIBRARY NAMES libclang.dll HINTS ${CLANG_LIBRARYDIR}) find_file(CLANG_DLL NAMES libclang.dll HINTS ${CLANG_LIBRARYDIR}) endif() include(FindPackageHandleStandardArgs) # handle the QUIETLY and REQUIRED arguments and set CLANG_FOUND to TRUE # if all listed variables are TRUE find_package_handle_standard_args( CLANG DEFAULT_MSG CLANG_LIBRARY CLANG_INCLUDE_DIR ) mark_as_advanced(CLANG_INCLUDE_DIR CLANG_LIBRARY CLANG_DLL) if (CLANG_FOUND) message(STATUS "libclang found") message(STATUS " CLANG_INCLUDE_DIR = ${CLANG_INCLUDE_DIR}") message(STATUS " CLANG_LIBRARY = ${CLANG_LIBRARY}") if (WIN32) message(STATUS " CLANG_DLL = ${CLANG_DLL}") endif () else() message(STATUS "libclang not found") endif() <file_sep>// 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/. // // Copyright (c) 2013, <NAME> #ifndef CLANG_UTILS_TRANSLATION_UNIT_H #define CLANG_UTILS_TRANSLATION_UNIT_H // #include <Python.h> #include <clang-c/Index.h> #include <iostream> #include <fstream> #include <sstream> #include <set> #include <memory> #include <future> #include <mutex> #include <iterator> #include <algorithm> #include <unordered_map> #include <cstring> #include <cassert> #include <vector> #include "complete.h" #ifdef CLANG_COMPLETE_LOG std::ofstream dump_log("/home/paul/clang_log", std::ios_base::app); #define DUMP(x) dump_log << std::string(__PRETTY_FUNCTION__) << ": " << #x << " = " << x << std::endl #define TIMER() timer dump_log_timer(true); #define DUMP_TIMER() DUMP(dump_log_timer) #define DUMP_LOG_TIME(x) dump_log << x << ": " << dump_log_timer.reset().count() << std::endl #else #define DUMP(x) #define TIMER() #define DUMP_TIMER() #define DUMP_LOG_TIME(x) #endif namespace std { string& to_string(string& s) { return s; } const string& to_string(const string& s) { return s; } } class timer { typedef typename std::conditional<std::chrono::high_resolution_clock::is_steady, std::chrono::high_resolution_clock, std::chrono::steady_clock>::type clock_type; typedef std::chrono::milliseconds milliseconds; public: explicit timer(bool run = false) { if (run) this->reset(); } milliseconds reset() { milliseconds x = this->elapsed(); this->start = clock_type::now(); return x; } milliseconds elapsed() const { return std::chrono::duration_cast<milliseconds>(clock_type::now() - this->start); } template <typename Stream> friend Stream& operator<<(Stream& out, const timer& self) { return out << self.elapsed().count(); } private: clock_type::time_point start; }; // An improved async, that doesn't block template< class Function, class... Args> std::future<typename std::result_of<Function(Args...)>::type> detach_async( Function&& f, Args&&... args ) { typedef typename std::result_of<Function(Args...)>::type result_type; std::packaged_task<result_type(Args...)> task(std::forward<Function>(f)); auto fut = task.get_future(); std::thread(std::move(task)).detach(); return std::move(fut); } inline bool starts_with(const char *str, const char *pre) { size_t lenpre = strlen(pre), lenstr = strlen(str); return lenstr < lenpre ? false : strncmp(pre, str, lenpre) == 0; } inline bool istarts_with(const std::string& str, const std::string& pre) { return str.length() < pre.length() ? false : std::equal(pre.begin(), pre.end(), str.begin(), [](char a, char b) { return std::tolower(a) == std::tolower(b); }); } std::string get_line_at(const std::string& str, unsigned int line) { int n = 1; std::string::size_type pos = 0; std::string::size_type prev = 0; while ((pos = str.find('\n', prev)) != std::string::npos) { if (n == line) return str.substr(prev, pos - prev); prev = pos + 1; n++; } // To get the last line if (n == line) return str.substr(prev); else return ""; } CXIndex get_index(bool clear=false) { static std::shared_ptr<void> index = std::shared_ptr<void>(clang_createIndex(1, 1), &clang_disposeIndex); if (clear) index = std::shared_ptr<void>(clang_createIndex(1, 1), &clang_disposeIndex); return index.get(); } class translation_unit { // CXIndex index; CXTranslationUnit tu; std::string filename; std::timed_mutex m; CXUnsavedFile unsaved_buffer(const char * buffer, unsigned len) { CXUnsavedFile result; result.Filename = this->filename.c_str(); result.Contents = buffer; result.Length = len; return result; } static std::string to_std_string(CXString str) { std::string result; const char * s = clang_getCString(str); if (s != nullptr) result = s; clang_disposeString(str); return result; } struct completion_results { std::shared_ptr<CXCodeCompleteResults> results; typedef CXCompletionResult* iterator; completion_results(CXCodeCompleteResults* r) { this->results = std::shared_ptr<CXCodeCompleteResults>(r, &clang_disposeCodeCompleteResults); } std::size_t size() const { if (results == nullptr) return 0; else return results->NumResults; } iterator begin() { if (results == nullptr) return nullptr; else return results->Results; } iterator end() { if (results == nullptr) return nullptr; else return results->Results + results->NumResults; } }; template<class F> static void for_each_completion_string(CXCompletionResult& c, F f) { if ( clang_getCompletionAvailability( c.CompletionString ) == CXAvailability_Available ) { int num = clang_getNumCompletionChunks(c.CompletionString); for(int i=0;i<num;i++) { auto str = clang_getCompletionChunkText(c.CompletionString, i); auto kind = clang_getCompletionChunkKind(c.CompletionString, i); f(to_std_string(str), kind); } } } static std::string get_typed_text(CXCompletionResult& c) { if ( clang_getCompletionAvailability( c.CompletionString ) == CXAvailability_Available ) { int num = clang_getNumCompletionChunks(c.CompletionString); for(int i=0;i<num;i++) { auto str = clang_getCompletionChunkText(c.CompletionString, i); auto kind = clang_getCompletionChunkKind(c.CompletionString, i); if (kind == CXCompletionChunk_TypedText) return to_std_string(str); } } return {}; } static unsigned code_complete_options() { return CXCodeComplete_IncludeMacros | CXCodeComplete_IncludeCodePatterns | CXCodeComplete_IncludeBriefComments; } completion_results completions_at(unsigned line, unsigned col, const char * buffer, unsigned len) { if (buffer == nullptr) { return clang_codeCompleteAt(this->tu, this->filename.c_str(), line, col, nullptr, 0, code_complete_options()); } else { auto unsaved = this->unsaved_buffer(buffer, len); return clang_codeCompleteAt(this->tu, this->filename.c_str(), line, col, &unsaved, 1, code_complete_options()); } } static unsigned parse_options() { return CXTranslationUnit_DetailedPreprocessingRecord | CXTranslationUnit_IncludeBriefCommentsInCodeCompletion | CXTranslationUnit_Incomplete | CXTranslationUnit_PrecompiledPreamble | CXTranslationUnit_CacheCompletionResults; } void unsafe_reparse(const char * buffer=nullptr, unsigned len=0) { if (buffer == nullptr) clang_reparseTranslationUnit(this->tu, 0, nullptr, parse_options()); else { auto unsaved = this->unsaved_buffer(buffer, len); clang_reparseTranslationUnit(this->tu, 1, &unsaved, parse_options()); } } public: struct cursor { CXCursor c; CXTranslationUnit tu; cursor(CXCursor c, CXTranslationUnit tu) : c(c), tu(tu) {} CXCursorKind get_kind() { return clang_getCursorKind(this->c); } cursor get_reference() { return cursor(clang_getCursorReferenced(this->c), this->tu); } cursor get_definition() { return cursor(clang_getCursorDefinition(this->c), this->tu); } cursor get_type() { return cursor(clang_getTypeDeclaration(clang_getCanonicalType(clang_getCursorType(this->c))), this->tu); } std::string get_display_name() { return to_std_string(clang_getCursorDisplayName(this->c)); } std::string get_spelling() { return to_std_string(clang_getCursorSpelling(this->c)); } std::string get_type_name() { return to_std_string(clang_getTypeSpelling(clang_getCanonicalType(clang_getCursorType(this->c)))); } CXSourceLocation get_location() { return clang_getCursorLocation(this->c); } std::string get_location_path() { CXFile f; unsigned line, col, offset; clang_getSpellingLocation(this->get_location(), &f, &line, &col, &offset); return to_std_string(clang_getFileName(f)) + ":" + std::to_string(line) + ":" + std::to_string(col); } std::string get_include_file() { CXFile f = clang_getIncludedFile(this->c); return to_std_string(clang_getFileName(f)); } std::vector<cursor> get_overloaded_cursors() { std::vector<cursor> result = {*this}; if (clang_getCursorKind(this->c) == CXCursor_OverloadedDeclRef) { for(int i=0;i<clang_getNumOverloadedDecls(this->c);i++) { result.emplace_back(clang_getOverloadedDecl(this->c, i), this->tu); } } return result; } template<class F> struct find_references_trampoline { F f; cursor * self; find_references_trampoline(F f, cursor * self) : f(f), self(self) {} CXVisitorResult operator()(CXCursor c, CXSourceRange r) const { f(cursor(c, self->tu), r); return CXVisit_Continue; } }; template<class F> void find_references(const char* name, F f) { CXFile file = clang_getFile(this->tu, name); find_references_trampoline<F> trampoline(f, this); CXCursorAndRangeVisitor visitor = {}; visitor.context = &trampoline; visitor.visit = [](void *context, CXCursor c, CXSourceRange r) -> CXVisitorResult { return (*(reinterpret_cast<find_references_trampoline<F>*>(context)))(c, r); }; clang_findReferencesInFile(this->c, file, visitor); } bool is_null() { return clang_Cursor_isNull(this->c); } }; translation_unit(const char * filename, const char ** args, int argv) : filename(filename) { // this->index = clang_createIndex(1, 1); this->tu = clang_parseTranslationUnit(get_index(), filename, args, argv, NULL, 0, parse_options()); detach_async([=]() { this->reparse(); }); } translation_unit(const translation_unit&) = delete; cursor get_cursor_at(unsigned long line, unsigned long col, const char * name=nullptr) { if (name == nullptr) name = this->filename.c_str(); CXFile f = clang_getFile(this->tu, name); CXSourceLocation loc = clang_getLocation(this->tu, f, line, col); return cursor(clang_getCursor(this->tu, loc), this->tu); } void reparse(const char * buffer=nullptr, unsigned len=0) { std::lock_guard<std::timed_mutex> lock(this->m); this->unsafe_reparse(buffer, len); } struct usage { CXTUResourceUsage u; typedef CXTUResourceUsageEntry* iterator; usage(CXTUResourceUsage u) : u(u) {} usage(const usage&) = delete; iterator begin() { return u.entries; } iterator end() { return u.entries + u.numEntries; } ~usage() { clang_disposeCXTUResourceUsage(u); } }; std::unordered_map<std::string, unsigned long> get_usage() { std::lock_guard<std::timed_mutex> lock(this->m); std::unordered_map<std::string, unsigned long> result; auto u = std::make_shared<usage>(clang_getCXTUResourceUsage(this->tu)); for(CXTUResourceUsageEntry e:*u) { result.insert(std::make_pair(clang_getTUResourceUsageName(e.kind), e.amount)); } return result; } typedef std::tuple<std::size_t, std::string, std::string> completion; std::vector<completion> complete_at(unsigned line, unsigned col, const char * prefix, const char * buffer=nullptr, unsigned len=0) { std::lock_guard<std::timed_mutex> lock(this->m); TIMER(); std::vector<completion> results; std::string display; std::string replacement; std::string description; char buf[1024]; auto completions = this->completions_at(line, col, buffer, len); DUMP_LOG_TIME("Clang to complete"); results.reserve(completions.size()); for(auto& c:completions) { auto priority = clang_getCompletionPriority(c.CompletionString); auto ck = c.CursorKind; auto num = clang_getNumCompletionChunks(c.CompletionString); display.reserve(num*8); replacement.reserve(num*8); description.clear(); std::size_t idx = 1; for_each_completion_string(c, [&](const std::string& text, CXCompletionChunkKind kind) { switch (kind) { case CXCompletionChunk_LeftParen: case CXCompletionChunk_RightParen: case CXCompletionChunk_LeftBracket: case CXCompletionChunk_RightBracket: case CXCompletionChunk_LeftBrace: case CXCompletionChunk_RightBrace: case CXCompletionChunk_LeftAngle: case CXCompletionChunk_RightAngle: case CXCompletionChunk_CurrentParameter: case CXCompletionChunk_Colon: case CXCompletionChunk_Comma: case CXCompletionChunk_HorizontalSpace: case CXCompletionChunk_VerticalSpace: display += text; replacement += text; break; case CXCompletionChunk_TypedText: display += text; replacement += text; if (ck == CXCursor_Constructor) { std::snprintf(buf, 1024, "%lu", idx++); replacement.append(" ${").append(buf).append(":v}"); } break; case CXCompletionChunk_Placeholder: display += text; std::snprintf(buf, 1024, "%lu", idx++); replacement.append("${").append(buf).append(":").append(text).append("}"); break; case CXCompletionChunk_ResultType: case CXCompletionChunk_Text: case CXCompletionChunk_Informative: case CXCompletionChunk_Equal: description.append(text).append(" "); break; case CXCompletionChunk_Optional: case CXCompletionChunk_SemiColon: break; } }); display.append("\t").append(description); // Lower priority for completions that start with `operator` and `~` if (starts_with(display.c_str(), "operator") or starts_with(display.c_str(), "~")) priority = std::numeric_limits<decltype(priority)>::max(); if (not display.empty() and not replacement.empty() and starts_with(display.c_str(), prefix)) results.emplace_back(priority, std::move(display), std::move(replacement)); } std::sort(results.begin(), results.end()); // Perhaps a reparse can help rejuvenate clang? // if (results.size() == 0) this->unsafe_reparse(buffer, len); DUMP_LOG_TIME("Process completions"); DUMP(results.size()); return results; } std::vector<std::string> get_diagnostics(int timeout=-1) { std::unique_lock<std::timed_mutex> lock(this->m, std::defer_lock); if (timeout < 0) { lock.lock(); } else { if (!lock.try_lock_for(std::chrono::milliseconds(timeout))) return {}; } std::vector<std::string> result; auto n = clang_getNumDiagnostics(this->tu); for(int i=0;i<n;i++) { auto diag = std::shared_ptr<void>(clang_getDiagnostic(this->tu, i), &clang_disposeDiagnostic); if (diag != nullptr and clang_getDiagnosticSeverity(diag.get()) != CXDiagnostic_Ignored) { auto str = clang_formatDiagnostic(diag.get(), clang_defaultDiagnosticDisplayOptions()); result.push_back(to_std_string(str)); } } return result; } std::string get_definition(unsigned line, unsigned col) { std::lock_guard<std::timed_mutex> lock(this->m); std::string result; cursor c = this->get_cursor_at(line, col); DUMP(c.get_display_name()); cursor ref = c.get_reference(); DUMP(ref.is_null()); if (!ref.is_null()) { DUMP(ref.get_display_name()); result = ref.get_location_path(); } else if (c.get_kind() == CXCursor_InclusionDirective) { result = c.get_include_file(); } return result; } std::string get_type(unsigned line, unsigned col) { std::lock_guard<std::timed_mutex> lock(this->m); return this->get_cursor_at(line, col).get_type_name(); } std::set<std::string> find_uses_in(unsigned line, unsigned col, const char * name=nullptr) { std::lock_guard<std::timed_mutex> lock(this->m); std::set<std::string> result; if (name == nullptr) name = this->filename.c_str(); auto c = this->get_cursor_at(line, col); for(auto oc:c.get_overloaded_cursors()) { oc.find_references(name, [&](cursor ref, CXSourceRange r) { result.insert(ref.get_location_path()); }); } return result; } ~translation_unit() { std::lock_guard<std::timed_mutex> lock(this->m); clang_disposeTranslationUnit(this->tu); } }; class async_translation_unit : public translation_unit, public std::enable_shared_from_this<async_translation_unit> { struct query { std::future<std::vector<completion>> results_future; std::vector<completion> results; unsigned line; unsigned col; query() : line(0), col(0) {} std::pair<unsigned, unsigned> get_loc() { return std::make_pair(this->line, this->col); } void set(std::future<std::vector<completion>> && results_future, unsigned line, unsigned col) { this->results = {}; this->results_future = std::move(results_future); this->line = line; this->col = col; } std::vector<completion> get(int timeout) { if (results_future.valid() and this->ready(timeout)) { this->results = this->results_future.get(); // Force another query if completion results are empty if (this->results.size() == 0) std::tie(line, col) = std::make_pair(0, 0); } return this->results; } bool ready(int timeout = 10) { if (results_future.valid()) return (timeout > 0 and results_future.wait_for(std::chrono::milliseconds(timeout)) == std::future_status::ready); else return true; } }; std::timed_mutex async_mutex; query q; public: async_translation_unit(const char * filename, const char ** args, int argv) : translation_unit(filename, args, argv) {} std::vector<completion> async_complete_at(unsigned line, unsigned col, const char * prefix, int timeout, const char * buffer=nullptr, unsigned len=0) { std::unique_lock<std::timed_mutex> lock(this->async_mutex, std::defer_lock); if (!lock.try_lock_for(std::chrono::milliseconds(20))) return {}; if (std::make_pair(line, col) != q.get_loc()) { // If we are busy with a query, lets avoid making lots of new queries if (not this->q.ready()) return {}; auto self = this->shared_from_this(); std::string buffer_as_string(buffer, buffer+len); this->q.set(detach_async([=] { auto b = buffer_as_string.c_str(); if (buffer == nullptr) b = nullptr; // TODO: Should we always reparse? // else this->reparse(b, len); return self->complete_at(line, col, "", b, buffer_as_string.length()); }), line, col); } auto completions = q.get(timeout); if (prefix != nullptr and *prefix != 0) { std::string pre = prefix; std::vector<completion> results; std::copy_if(completions.begin(), completions.end(), inserter(results, results.begin()), [&](const completion& x) { return istarts_with(std::get<2>(x), pre); }); return std::move(results); } else { return std::move(completions); } } }; std::timed_mutex tus_mutex; std::unordered_map<std::string, std::shared_ptr<async_translation_unit>> tus; std::shared_ptr<async_translation_unit> get_tu(const char * filename, const char ** args, int argv, int timeout=-1) { std::unique_lock<std::timed_mutex> lock(tus_mutex, std::defer_lock); if (timeout < 0) lock.lock(); else if (!lock.try_lock_for(std::chrono::milliseconds(timeout))) return {}; if (tus.find(filename) == tus.end()) { tus[filename] = std::make_shared<async_translation_unit>(filename, args, argv); } return tus[filename]; } template<class T> std::mutex& get_allocations_mutex() { static std::mutex m; return m; } template<class T> std::unordered_map<unsigned int, T>& get_allocations() { static std::mutex m; static std::unordered_map<unsigned int, T> allocations; return allocations; }; template<class T> unsigned int new_wrapper() { std::unique_lock<std::mutex> lock(get_allocations_mutex<T>()); unsigned int id = (get_allocations<T>().size() * 8 + sizeof(T)) % std::numeric_limits<unsigned int>::max(); while (get_allocations<T>().count(id) > 0 and id < (std::numeric_limits<unsigned int>::max() - 1)) id++; assert(get_allocations<T>().count(id) == 0); get_allocations<T>().emplace(id, T()); return id; } template<class T> T& unwrap(unsigned int i) { assert(i > 0); std::unique_lock<std::mutex> lock(get_allocations_mutex<T>()); return get_allocations<T>().at(i); } template<class T> void free_wrapper(unsigned int i) { std::unique_lock<std::mutex> lock(get_allocations_mutex<T>()); get_allocations<T>().erase(i); } std::string& get_string(clang_complete_string s) { return unwrap<std::string>(s); } unsigned int new_string(const std::string& s) { auto i = new_wrapper<std::string>(); unwrap<std::string>(i) = std::string(s); return i; } typedef std::vector<std::string> slist; slist& get_slist(clang_complete_string_list list) { static slist empty_vec; assert(empty_vec.empty()); if (list == 0) return empty_vec; else return unwrap<slist>(list); } unsigned int new_slist() { return new_wrapper<slist>(); } unsigned int empty_slist() { return 0; } template<class Range> clang_complete_string_list export_slist(const Range& r) { auto id = new_slist(); auto& list = get_slist(id); for (const auto& s:r) { list.push_back(s); } return id; } template<class Range> clang_complete_string_list export_slist_completion(const Range& r) { auto id = new_slist(); auto& list = get_slist(id); for (const auto& s:r) { list.push_back(std::get<1>(s) + "\n" + std::get<2>(s)); } return id; } extern "C" { const char * clang_complete_string_value(clang_complete_string s) { return get_string(s).c_str(); } void clang_complete_string_free(clang_complete_string s) { free_wrapper<std::string>(s); } void clang_complete_string_list_free(clang_complete_string_list list) { free_wrapper<slist>(list); } int clang_complete_string_list_len(clang_complete_string_list list) { if (list == 0) return 0; else return get_slist(list).size(); } const char * clang_complete_string_list_at(clang_complete_string_list list, int index) { if (list == 0) return nullptr; else return get_slist(list).at(index).c_str(); } clang_complete_string_list clang_complete_get_completions( const char * filename, const char ** args, int argv, unsigned line, unsigned col, const char * prefix, int timeout, const char * buffer, unsigned len) { auto tu = get_tu(filename, args, argv, 200); if (tu == nullptr) return empty_slist(); else return export_slist_completion(tu->async_complete_at(line, col, prefix, timeout, buffer, len)); } clang_complete_string_list clang_complete_find_uses(const char * filename, const char ** args, int argv, unsigned line, unsigned col, const char * search) { auto tu = get_tu(filename, args, argv); return export_slist(tu->find_uses_in(line, col, search)); } clang_complete_string_list clang_complete_get_diagnostics(const char * filename, const char ** args, int argv) { auto tu = get_tu(filename, args, argv, 200); if (tu == nullptr) return empty_slist(); else { tu->reparse(nullptr, 0); return export_slist(tu->get_diagnostics(250)); } } clang_complete_string clang_complete_get_definition(const char * filename, const char ** args, int argv, unsigned line, unsigned col) { auto tu = get_tu(filename, args, argv); return new_string(tu->get_definition(line, col)); } clang_complete_string clang_complete_get_type(const char * filename, const char ** args, int argv, unsigned line, unsigned col) { auto tu = get_tu(filename, args, argv); return new_string(tu->get_type(line, col)); } void clang_complete_reparse(const char * filename, const char ** args, int argv, const char * buffer, unsigned len) { auto tu = get_tu(filename, args, argv); tu->reparse(); } void clang_complete_free_tu(const char * filename) { std::string name = filename; detach_async([=] { std::lock_guard<std::timed_mutex> lock(tus_mutex); if (tus.find(name) != tus.end()) { tus.erase(name); } }); } void clang_complete_free_all() { std::lock_guard<std::timed_mutex> lock(tus_mutex); tus.clear(); get_index(true); } } #endif<file_sep>PROJECT(CLANG_COMPLETE) set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}") SET(CMAKE_CXX_COMPILER "g++") SET(CMAKE_C_COMPILER "gcc") SET(CLANG_COMPLETE_ROOT_DIR .) set( CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/ ) set(CMAKE_VERBOSE_MAKEFILE 1) SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -DNDEBUG -Os -c -fPIC") find_package(Clang) include_directories( . ${CLANG_INCLUDE_DIR} ) add_library(complete MODULE complete.cpp) target_link_libraries(complete ${CLANG_DLL} ) <file_sep># 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/. # # Copyright (c) 2013, <NAME> from ctypes import cdll from ctypes import c_int from ctypes import c_char_p from ctypes import c_void_p from ctypes import c_uint from ctypes import py_object from copy import copy import os import platform current_path = os.path.dirname(os.path.abspath(__file__)) suffix = 'so' if platform.system() == 'Darwin': suffix = 'dylib' elif platform.system() == 'Windows': suffix = 'dll' complete = cdll.LoadLibrary('%s/libcomplete.%s' % (current_path, suffix)) # # # Clang c api wrapper # # complete.clang_complete_string_list_len.restype = c_int complete.clang_complete_string_list_at.restype = c_char_p complete.clang_complete_string_value.restype = c_char_p complete.clang_complete_find_uses.restype = c_uint complete.clang_complete_get_completions.restype = c_uint complete.clang_complete_get_diagnostics.restype = c_uint complete.clang_complete_get_definition.restype = c_uint complete.clang_complete_get_type.restype = c_uint def convert_to_c_string_array(a): result = (c_char_p * len(a))() result[:] = [x.encode('utf-8') for x in a] return result def convert_string_list(l): result = [complete.clang_complete_string_list_at(l, i).decode('utf-8') for i in range(complete.clang_complete_string_list_len(l))] complete.clang_complete_string_list_free(l) return result def convert_string(s): result = complete.clang_complete_string_value(s).decode('utf-8') complete.clang_complete_string_free(s) return result def find_uses(filename, args, line, col, file_to_search): search = None if file_to_search is not None: search = file_to_search.encode('utf-8') return convert_string_list(complete.clang_complete_find_uses(filename.encode('utf-8'), convert_to_c_string_array(args), len(args), line, col, search)) def get_completions(filename, args, line, col, prefix, timeout, unsaved_buffer): if unsaved_buffer is None and not os.path.exists(filename): return [] buffer = None if (unsaved_buffer is not None): buffer = unsaved_buffer.encode("utf-8") buffer_len = 0 if (buffer is not None): buffer_len = len(buffer) return convert_string_list(complete.clang_complete_get_completions(filename.encode('utf-8'), convert_to_c_string_array(args), len(args), line, col, prefix.encode('utf-8'), timeout, buffer, buffer_len)) def get_diagnostics(filename, args): return convert_string_list(complete.clang_complete_get_diagnostics(filename.encode('utf-8'), convert_to_c_string_array(args), len(args))) def get_definition(filename, args, line, col): return convert_string(complete.clang_complete_get_definition(filename.encode('utf-8'), convert_to_c_string_array(args), len(args), line, col)) def get_type(filename, args, line, col): return convert_string(complete.clang_complete_get_type(filename.encode('utf-8'), convert_to_c_string_array(args), len(args), line, col)) def reparse(filename, args, unsaved_buffer): buffer = None if (unsaved_buffer is not None): buffer = unsaved_buffer.encode("utf-8") buffer_len = 0 if (buffer is not None): buffer_len = len(buffer) complete.clang_complete_reparse(filename.encode('utf-8'), convert_to_c_string_array(args), len(args), buffer, buffer_len) def free_tu(filename): complete.clang_complete_free_tu(filename.encode('utf-8')) def free_all(): complete.clang_complete_free_all()
cf7e95157c90460d53b7031b1e97a21fd4fecd0e
[ "CMake", "Markdown", "Makefile", "Python", "C", "C++" ]
8
Python
shaurya0/ClangComplete
74140f17663c4f1d0f14963cdb49b0ae0475d804
a139f22a131d87b8911262604dd4431d36058140
refs/heads/master
<repo_name>reddyprasad481/angular-app<file_sep>/app/scripts/controllers/contact.js 'use strict'; /** * @ngdoc function * @name lmsApp.controller:ContactCtrl * @description * # ContactCtrl * Controller of the lmsApp */ angular.module('lmsApp') .controller('ContactCtrl', function (contactsService) { this.awesomeThings = [ 'HTML5 Boilerplate', 'AngularJS', 'Karma' ]; this.contacts =contactsService.getContacts(); console.log(this.contacts); }); <file_sep>/test/spec/services/appservice.js 'use strict'; /*describe('Service: appService', function () { // load the service's module beforeEach(module('commonServices')); // instantiate service var appService; beforeEach(inject(function (_appService_) { appService = _appService_; })); it('should do something', function () { expect(!!appService).toBe(true); }); });*/ describe('Service: appService', function () { beforeEach(module('commonServices')); describe('appService', function () { var service, $httpBackend; var phones; /* beforeEach(inject(function (_appService_) { service = _appService_; }));*/ beforeEach(inject(function($injector) { service = $injector.get('appService'); $httpBackend = $injector.get('$httpBackend'); $httpBackend.when('GET', 'http://localhost:8080/spring_rest_services/service/customers/getCustomers').respond(['Toyota', 'Honda', 'Tesla']); $httpBackend.whenPOST('http://localhost:8080/spring_rest_services/service/customers/phones').respond(function(method, url, data, headers){ console.log('Received these data:', method, url, data, headers); phones.push(angular.fromJson(data)); return [200, {}, {}]; }); })); afterEach(function() { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); it('should do something', function () { expect(!!service).toBe(true); }); it('getCustomers - should return 3 car manufacturers', function () { var opts ={method:'GET', endpoint: 'customers/getCustomers', data: {} }; service.make(opts).then(function(response) { console.log(response); expect(response.data.length).toEqual(3); //the response is null //expect(response.data.length).toEqual(3); }); $httpBackend.flush(); }); it('savePhones - should save 4 phone numbers of manufacturers', function () { var inputData =[1234567890, 9989367612, 9583095830,7089654312]; phones =[]; var opts ={method:'POST', endpoint: 'customers/phones', data: inputData }; service.make(opts).then(function(response) { console.log(response); console.log(phones); expect(phones[0].length).toEqual(4); //the response is null //expect(response.data.length).toEqual(3); expect(phones[0]).toEqual(inputData); }); $httpBackend.flush(); }); }); });<file_sep>/app/scripts/main/main.component.js 'use strict' angular.module('main',['ngStorage']); angular.module('main') .component('mainComponent',{ template:'<div>Hi {{$ctrl.userName}} </div> <div>{{$ctrl.pdfData}}</div>', controller:MainController }); function MainController(appService,$sessionStorage) { var self = this; this.awesomeThings = [ 'AngularJS', 'Karma', 'jasmine', 'HTML5', 'CSS3', 'bootstrap' ]; console.log($sessionStorage); this.userName = $sessionStorage.Uname ; self.customers = null; this.sum = function(input1,input2){ var result = input1+input2; console.log("===========result: "+result+" ========="); console.log($sessionStorage); console.log("===========result: "+this.userName+" ========="); return result; }; this.getCustomers = function(){ appService.make({endpoint:'customers/getCustomers',method:'GET', data:{}}) .then(function(response){ console.log("=========response From Service======"); console.log(response); self.customers = response.data; //self.pdfData = response; //console.log(self.pdfData); // var pdfUrl = URL.createObjectURL(response); // var printwWindow = $window.open(pdfUrl); // printwWindow.print(); },function(error){ console.log(error); }); }; } //MainController.$inject = ['appService','$sessionStorage']; //MainController.$inject = ['$sessionStorage'];<file_sep>/test/spec/controllers/maincmp.js 'use strict'; describe('Controller: MainController', function () { // load the controller's module beforeEach(module('main')); var $componentController,$sessionStorage,$httpBackend; var appService; // Initialize the controller and a mock scope /*beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); MainCont = $controller('MainController', { $scope: scope // place here mocked dependencies }); }));*/ beforeEach(module('commonServices')); // instantiate service var appService; beforeEach(inject(function (_appService_,_$sessionStorage_) { appService = _appService_; $sessionStorage = _$sessionStorage_; })); beforeEach(inject(function(_$componentController_) { $componentController = _$componentController_; })); beforeEach(inject(function($injector) { // service = $injector.get('appService'); $httpBackend = $injector.get('$httpBackend'); $httpBackend.when('GET', 'http://localhost:8080/spring_rest_services/service/customers/getCustomers').respond(['Toyota', 'Honda', 'Tesla']); $httpBackend.whenPOST('http://localhost:8080/spring_rest_services/service/customers/phones').respond(function(method, url, data, headers){ console.log('Received these data:', method, url, data, headers); phones.push(angular.fromJson(data)); return [200, {}, {}]; }); })); afterEach(function() { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); /*it('should attach a list of awesomeThings to the scope', function () { expect(MainCont.awesomeThings.length).toBe(6); });*/ it('should attach a list of awesomeThings to the scope', function() { //var onDeleteSpy = jasmine.createSpy('onDelete'); // var bindings = {hero: {}, onDelete: onDeleteSpy}; $sessionStorage.Uname ="Prasad"; var ctrl = $componentController('mainComponent', {appService:appService,$sessionStorage:$sessionStorage},null); //ctrl.delete(); //expect(onDeleteSpy).toHaveBeenCalledWith({hero: ctrl.hero}); expect(ctrl.awesomeThings.length).toBe(6); expect(ctrl.sum(5,6)).toBe(11); }); it('should calculate sum of two digits', function() { //var onDeleteSpy = jasmine.createSpy('onDelete'); // var bindings = {hero: {}, onDelete: onDeleteSpy}; var ctrl = $componentController('mainComponent', null,appService); //ctrl.delete(); //expect(onDeleteSpy).toHaveBeenCalledWith({hero: ctrl.hero}); // expect(ctrl.awesomeThings.length).toBe(6); expect(ctrl.sum(5,8)).toBe(13); }); it('test session storage data', function() { //var onDeleteSpy = jasmine.createSpy('onDelete'); // var bindings = {hero: {}, onDelete: onDeleteSpy}; $sessionStorage.Uname ="<NAME>"; var ctrl = $componentController('mainComponent', {appService:appService,$sessionStorage:$sessionStorage},null); //ctrl.delete(); //expect(onDeleteSpy).toHaveBeenCalledWith({hero: ctrl.hero}); // expect(ctrl.awesomeThings.length).toBe(6); expect(ctrl.userName).toBe("<NAME>"); }); it('getCustomers - should return 3 car manufacturers', function () { $sessionStorage.Uname ="Reddy" var ctrl = $componentController('mainComponent', {appService:appService,$sessionStorage:$sessionStorage},null); expect(ctrl.userName).toBe("Reddy"); expect(ctrl.customers).toEqual(null); ctrl.getCustomers(); $httpBackend.flush(); expect(ctrl.customers.length).toEqual(3); expect(ctrl.customers).toEqual(['Toyota', 'Honda', 'Tesla']); }); }); <file_sep>/app/scripts/common/services/common.serive.module.js angular.module('commonServices',['ngResource']);<file_sep>/app/scripts/services/contactsservice.js 'use strict'; /** * @ngdoc service * @name lmsApp.contactsService * @description * # contactsService * Service in the lmsApp. */ angular.module('lmsApp') .service('contactsService', function () { // AngularJS will instantiate a singleton by calling "new" on this function this.getContacts=function(){ var contacts=[ {name:'Reddy' ,des:'owner'}, {name:'Prasad', des:'AVP'}, {name:'Sathya', des:'CEO'} ]; return contacts; }; });
6ccd44bda3e662c7dafbb10ea4f5dd2ace1781f7
[ "JavaScript" ]
6
JavaScript
reddyprasad481/angular-app
14dbe25c9d1c9b9dbe5d4b074ea706a598ddef6d
58ae45c20735a4e5f08262d5173d3ebd18001141
refs/heads/master
<repo_name>aayush-p/zync<file_sep>/README.md zync ==== simple utility to synchronize directories over internet. created to sync my folder with one on my friends pc containing common pics. <file_sep>/src/tp/zync/old/SyncSend.java package tp.zync.old; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import javax.swing.JTextArea; import tp.zync.Packet; import tp.zync.SendWorker; public class SyncSend { static ObjectOutputStream oOut; static ObjectInputStream oIn; static JTextArea tf; //static BufferedReader br; static Socket clientSocket; static SendWorker sendWorker; static HashMap<String, Long> fileMap = new HashMap<String, Long>(); public static void mainStartFn(String currentFolder, String ip, String port, SendWorker sw) throws InterruptedException, ClassNotFoundException{ sendWorker = sw; // sendWorker.publish(); // tf = tf4; //select folder //String folderName = "C:\\Users\\Aayush\\Desktop\\Datafiction"; // String folderName = "F:\\00 xtra OS data\\Downloads\\test_dt"; // String folderName = "F:\\The.Other.Woman.2014.HDRip.XViD.juggs[ETRG]"; String folderName = currentFolder; // File f = new File(folderName); // FileInputStream fIn; //send // int portNumber = 27022; // String hostIP = "127.0.0.1"; String hostIP = ip; int portNumber = Integer.parseInt(port); //s = null; boolean flag = true; while(flag){ try { clientSocket = new Socket(hostIP, portNumber); oOut = new ObjectOutputStream(clientSocket.getOutputStream()); oIn = new ObjectInputStream(clientSocket.getInputStream()); startSending(folderName); flag = false; } catch (IOException e) { flag = false; //repeat until complete or die trying e.printStackTrace(); System.out.println("repeatingggggg.."); Thread.sleep(5000); } } } private static void startSending(String folderName) throws IOException, ClassNotFoundException { //start send Packet p = new Packet(); p.pcktType = "start"; p.fileName = folderName; SyncSend.oOut.writeObject(p); SyncSend.oOut.reset(); Path root = Paths.get(folderName); Files.walkFileTree(root, new VisitNSave()); //now we have all files list //check with reciever what files to send p = new Packet(); p.pcktType = "check"; p.fileMap = fileMap; // System.out.println("Sending Check"); tf.append("Sending Check"); SyncSend.oOut.writeObject(p); SyncSend.oOut.reset(); //receive req files map Packet pRead = (Packet) SyncSend.oIn.readObject(); fileMap = pRead.fileMap; //now send only these files... Iterator it = fileMap.entrySet().iterator(); while(it.hasNext()){ Map.Entry entry = (Map.Entry) it.next(); //send this file sendFile(entry.getKey().toString()); it.remove(); } //end p = new Packet(); p.pcktType = "end"; System.out.println("end"); SyncSend.oOut.writeObject(p); SyncSend.oOut.reset(); //last read pRead = (Packet) oIn.readObject(); //send end start //start recv //end } private static void sendFile(String file) throws IOException { System.out.println("sending file: " + file.toString()); Packet p = new Packet(); p.pcktType = "fileStart"; p.fileName = file.toString(); // p.fileType = "file"; SyncSend.oOut.writeObject(p); SyncSend.oOut.reset(); //now send data p.pcktType = "data"; p.fileName = file.toString(); // p.fileType = "file"; FileInputStream fIn = new FileInputStream(new File(file)); // System.out.println("data"); int res = 0; byte[] buf = new byte[1024*1024]; while((res = fIn.read(buf)) != -1 ){ // res = fIn.read(buf); //write output to packet and send // System.out.println(Arrays.toString(buf)); // System.out.println(new String(buf)); // System.out.println(buf.toString() + " ... " + res); p.bArray = buf; p.size = res; // System.out.println(pData.bArray); SyncSend.oOut.writeObject(p); SyncSend.oOut.reset(); } fIn.close(); p.pcktType = "fileEnd"; p.fileName = file.toString(); // p.fileType = "file"; SyncSend.oOut.writeObject(p); SyncSend.oOut.reset(); } } class VisitNSave extends SimpleFileVisitor<Path> { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attr) throws IOException { if (attr.isSymbolicLink()) { System.out.format("Symbolic link: %s ", file); } else if (attr.isRegularFile()) { System.out.format("Regular file: %s ", file); } else { System.out.format("Other: %s ", file); } System.out.println("(" + attr.size() + "bytes)"); //add each file to the map SyncSend.fileMap.put(file.toString(), attr.size()); return FileVisitResult.CONTINUE; } // Print each directory visited. //@Override //public FileVisitResult preVisitDirectory(Path dir, // BasicFileAttributes attr) throws IOException { // System.out.format("Directory: %s%n", dir); // // Packet p = new Packet(); // p.pcktType = "dirName"; // p.fileName = dir.toString(); // p.fileType = "dir"; // // SyncSend.oOut.writeObject(p); // SyncSend.oOut.reset(); // // return FileVisitResult.CONTINUE; //} // If there is some error accessing // the file, let the user know. // If you don't override this method // and an error occurs, an IOException // is thrown. @Override public FileVisitResult visitFileFailed(Path file, IOException exc) { System.err.println(exc); return FileVisitResult.CONTINUE; } }<file_sep>/src/tp/zync/old/DTReciever.java package tp.zync.old; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.ServerSocket; import java.net.Socket; import tp.zync.Packet; public class DTReciever { public static void main(String[] args) { // TODO Auto-generated method stub int portNumber = 27000; ServerSocket serverSocket; try { serverSocket = new ServerSocket(portNumber); Socket clientSocket = serverSocket.accept(); // PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); // BufferedReader in = new BufferedReader( // new InputStreamReader(clientSocket.getInputStream())); ObjectInputStream oIn = new ObjectInputStream(clientSocket.getInputStream()); ObjectOutputStream oOut = new ObjectOutputStream(clientSocket.getOutputStream()); // PrintWriter bw = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()) ); String folderName = "C:\\Users\\Aayush\\Desktop\\test\\"; Packet p = (Packet) oIn.readObject(); Packet pWrite = new Packet(); if (p.pcktType.equals("start")){ // String fileName = p.bArray.toString(); String fileName = p.fileName; System.out.println(fileName); FileOutputStream fOut = new FileOutputStream(new File(folderName+fileName)); while(true){ // bw.write("a"); // bw.flush(); oOut.writeObject(pWrite); p = (Packet) oIn.readObject(); if (p.pcktType.equals("end")){ oOut.writeObject(pWrite); break; } System.out.println(p.pcktType); System.out.println(p.bArray.toString()); fOut.write(p.bArray, 0, p.size); } //if end fOut.close(); } } catch (IOException e) { // TODO Auto-generated catch block System.out.println("Exception caught when trying to listen on port " + portNumber + " or listening for a connection"); //System.out.println(e.getMessage()); e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>/src/tp/zync/Packet.java package tp.zync; import java.io.Serializable; import java.util.HashMap; public class Packet implements Serializable{ /** * */ private static final long serialVersionUID = 1L; public String pcktType; public String fileName; // public String fileType; public int size; public long fileSize; public byte bArray[]; public HashMap<String, Long> fileMap; } <file_sep>/src/tp/zync/RecvWorker.java package tp.zync; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.swing.JTextArea; import javax.swing.SwingWorker; /** * Searches the text files under the given directory and counts the number of instances a given word is found in these * file. * * @author <NAME> */ public class RecvWorker extends SwingWorker<Integer, String> { static ObjectOutputStream oOut; static ObjectInputStream oIn; // static BufferedReader br; static ServerSocket serverSocket; static HashMap<String, Long> fileMap; static String recvSrcFolder; static String senderSrcFolder; static RecvWorker recvWorker; private static void failIfInterrupted() throws InterruptedException { if (Thread.currentThread().isInterrupted()) { throw new InterruptedException("Interrupted while searching files"); } } /** The text area where messages are written. */ private final JTextArea messagesTextArea; private String currentFolder; //private String ip; private String port; public static void mainRecvFn(String currentFolder, String port, RecvWorker rw) throws InterruptedException, ClassNotFoundException, IOException{ recvWorker = rw; recvWorker.publish("in main start recv"); //select folder // recvSrcFolder = "F:\\00 xtra OS data\\Downloads\\test2"; // String folderName = "C:\\Users\\Aayush\\Desktop\\t2"; // String folderName = "F:\\Fotus\\NYC Naagu"; recvSrcFolder = currentFolder; // File f = new File(folderName); // FileInputStream fIn; //recv // int portNumber = 27022; int portNumber = Integer.parseInt(port); serverSocket = null; serverSocket = new ServerSocket(portNumber); Socket clientSocket = serverSocket.accept(); recvWorker.publish(((InetSocketAddress)clientSocket.getRemoteSocketAddress()).getPort() + "" ); recvWorker.publish(((InetSocketAddress)clientSocket.getRemoteSocketAddress()).getAddress() + ""); oIn = new ObjectInputStream(clientSocket.getInputStream()); oOut = new ObjectOutputStream(clientSocket.getOutputStream()); // PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); // BufferedReader in = new BufferedReader( // new InputStreamReader(clientSocket.getInputStream())); //start recv Packet p = (Packet) oIn.readObject(); senderSrcFolder = p.fileName; String destFileName = null; FileOutputStream fOut = null; recvWorker.publish(p.pcktType + "\t" + p.fileName); if (p.pcktType.equals("start")){ p = (Packet) oIn.readObject(); while(!p.pcktType.equals("end")){ //System.out.println(p.pcktType); if(p.pcktType.equals("check")){ fileMap = new HashMap<String, Long>(p.fileMap); System.out.println(fileMap.size()); //check in folder what files are needed Path root = Paths.get(recvSrcFolder); Files.walkFileTree(root, new VisitNEditWorkerRecvClass()); Packet pCheckWrite = new Packet(); pCheckWrite.pcktType = "check"; pCheckWrite.fileMap = (HashMap<String, Long>) fileMap.clone(); System.out.println(pCheckWrite.fileMap.size()); oOut.writeObject(pCheckWrite); oOut.reset(); }else if(p.pcktType.equals("fileStart")){ String srcName = p.fileName; String newFile = srcName.substring( senderSrcFolder.length() ); // recvWorker.publish("file name" + newFile); destFileName = recvSrcFolder + newFile; recvWorker.publish("receiving file: " + destFileName); System.out.println("receiving file: " + destFileName); // recvWorker.publish("name---" + p.pcktType + "\t" + p.fileType + "\t" + p.fileName); File newFileFile = new File(destFileName); //create folder if not exists String destParent = newFileFile.getParent(); new File(destParent).mkdirs(); fOut = new FileOutputStream(newFileFile, false); } else if(p.pcktType.equals("data")){ System.out.println("data aya"); fOut.write(p.bArray, 0, p.size); }else if(p.pcktType.equals("dirName")){ String src = p.fileName; String newFile = src.substring( senderSrcFolder.length() ); destFileName = recvSrcFolder + newFile; recvWorker.publish(destFileName); recvWorker.publish("dir name" + newFile); (new File(destFileName)).mkdirs(); }else if(p.pcktType.equals("fileEnd")){ // recvWorker.publish("file end"); fOut.close(); // oOut.writeObject(p); // oOut.reset(); } p = (Packet) oIn.readObject(); } } recvWorker.publish("End sab kuch"); oOut.writeObject(p); oOut.reset(); Thread.sleep(888); } /** * Creates an instance of the worker * * @param word * The word to search * @param directory * the directory under which the search will occur. All text files found under the given directory are * searched * @param messagesTextArea * The text area where messages are written */ public RecvWorker(final String currentFolder, String port, final JTextArea messagesTextArea) { publish("in constrtr send"); this.currentFolder = currentFolder; this .port = port; this.messagesTextArea = messagesTextArea; } @Override protected Integer doInBackground() { publish("in backgnd send"); boolean flag = true; while(flag){ try { mainRecvFn(currentFolder, port, this); mainSendFn(); flag = false; } catch (Exception e) { flag = true; publish(e.getMessage()); publish("repeating after exception in 3s.."); if(oOut != null){ try { oOut.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } if (oIn != null){ try { oIn.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } if (serverSocket != null){ try { serverSocket.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } fileMap = new HashMap<String, Long>(); try { Thread.sleep(3000); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // TODO Auto-generated catch block e.printStackTrace(); } } // SendWorker.failIfInterrupted(); // publish("Listing all text files under the directory: " + directory); // Return the number of matches found return 0; } public static void mainSendFn() throws InterruptedException, ClassNotFoundException, IOException{ recvWorker.publish("in main start send"); // tf = tf4; //select folder //String folderName = "C:\\Users\\Aayush\\Desktop\\Datafiction"; // String folderName = "F:\\00 xtra OS data\\Downloads\\test_dt"; // String folderName = "F:\\The.Other.Woman.2014.HDRip.XViD.juggs[ETRG]"; String folderName = recvSrcFolder; // senderSrcFolder = folderName; // File f = new File(folderName); // FileInputStream fIn; //send // int portNumber = 27022; // String hostIP = "127.0.0.1"; // String hostIP = ip; // int portNumber = Integer.parseInt(port); //s = null; // clientSocket = new Socket(hostIP, portNumber); // // oOut = new ObjectOutputStream(clientSocket.getOutputStream()); // oIn = new ObjectInputStream(clientSocket.getInputStream()); startSending(folderName); } private static void startSending(String folderName) throws IOException, ClassNotFoundException { recvWorker.publish("in main -> startSending send"); //start send Packet p = new Packet(); p.pcktType = "start"; p.fileName = folderName; RecvWorker.oOut.writeObject(p); RecvWorker.oOut.reset(); Path root = Paths.get(folderName); Files.walkFileTree(root, new VisitNSaveWorkerRecvClass ()); //now we have all files list //check with reciever what files to send p = new Packet(); p.pcktType = "check"; p.fileMap = fileMap; // System.out.println("Sending Check"); // tf.append("Sending Check"); RecvWorker.oOut.writeObject(p); RecvWorker.oOut.reset(); //receive req files map Packet pRead = (Packet) RecvWorker.oIn.readObject(); fileMap = pRead.fileMap; //now send only these files... @SuppressWarnings("rawtypes") Iterator it = fileMap.entrySet().iterator(); while(it.hasNext()){ @SuppressWarnings("rawtypes") Map.Entry entry = (Map.Entry) it.next(); //send this file sendFile(entry.getKey().toString()); it.remove(); } //end p = new Packet(); p.pcktType = "end"; recvWorker.publish("end"); RecvWorker.oOut.writeObject(p); RecvWorker.oOut.reset(); //last read pRead = (Packet) oIn.readObject(); } private static void sendFile(String file) throws IOException { recvWorker.publish("sending file: " + file.toString()); System.out.println("sending file: " + file.toString()); Packet p = new Packet(); p.pcktType = "fileStart"; p.fileName = file.toString(); // p.fileType = "file"; RecvWorker.oOut.writeObject(p); RecvWorker.oOut.reset(); //now send data p.pcktType = "data"; p.fileName = file.toString(); // p.fileType = "file"; FileInputStream fIn = new FileInputStream(new File(file)); // System.out.println("data"); int res = 0; byte[] buf = new byte[1024*1024]; while((res = fIn.read(buf)) != -1 ){ // res = fIn.read(buf); //write output to packet and send // System.out.println(Arrays.toString(buf)); // System.out.println(new String(buf)); // System.out.println(buf.toString() + " ... " + res); p.bArray = buf; p.size = res; // System.out.println(pData.bArray); RecvWorker.oOut.writeObject(p); RecvWorker.oOut.reset(); } fIn.close(); p.pcktType = "fileEnd"; p.fileName = file.toString(); // p.fileType = "file"; RecvWorker.oOut.writeObject(p); RecvWorker.oOut.reset(); } @Override protected void process(final List<String> chunks) { // Updates the messages text area for (final String string : chunks) { messagesTextArea.append(string); messagesTextArea.append("\n"); } } } class VisitNEditWorkerRecvClass extends SimpleFileVisitor<Path> { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attr) throws IOException { if (attr.isSymbolicLink()) { System.out.format("Symbolic link: %s ", file); } else if (attr.isRegularFile()) { System.out.format("Regular file: %s ", file); } else { System.out.format("Other: %s ", file); } System.out.println("(" + attr.size() + "bytes)"); String onlyFileName = file.toString().substring(RecvWorker.recvSrcFolder.length()); String nameOnSender = RecvWorker.senderSrcFolder + onlyFileName; //check if this is present in map... if yes then remove it if (RecvWorker.fileMap.containsKey(nameOnSender) && RecvWorker.fileMap.get(nameOnSender) == attr.size()){ System.out.println("same found: " + nameOnSender); RecvWorker.fileMap.remove(nameOnSender); } return FileVisitResult.CONTINUE; } // If there is some error accessing // the file, let the user know. // If you don't override this method // and an error occurs, an IOException // is thrown. @Override public FileVisitResult visitFileFailed(Path file, IOException exc) { System.err.println(exc); return FileVisitResult.CONTINUE; } } class VisitNSaveWorkerRecvClass extends SimpleFileVisitor<Path> { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attr) throws IOException { if (attr.isSymbolicLink()) { System.out.format("Symbolic link: %s ", file); } else if (attr.isRegularFile()) { System.out.format("Regular file: %s ", file); } else { System.out.format("Other: %s ", file); } System.out.println("(" + attr.size() + "bytes)"); //add each file to the map RecvWorker.fileMap.put(file.toString(), attr.size()); return FileVisitResult.CONTINUE; } // If there is some error accessing // the file, let the user know. // If you don't override this method // and an error occurs, an IOException // is thrown. @Override public FileVisitResult visitFileFailed(Path file, IOException exc) { System.err.println(exc); return FileVisitResult.CONTINUE; } }
dad6a5e3c6630d3002eb44df75d5833265b645de
[ "Markdown", "Java" ]
5
Markdown
aayush-p/zync
e6e02e525c49315997ac01a9c56dc9533319f838
42881bd6412b2ae575bc32cbd5c419e85fdd277d
refs/heads/master
<file_sep>{\rtf1\ansi\ansicpg1252\cocoartf1671 {\fonttbl\f0\fnil\fcharset0 HelveticaNeue-Bold;\f1\fnil\fcharset0 HelveticaNeue;\f2\froman\fcharset0 Times-Bold; \f3\froman\fcharset0 Times-Roman;\f4\fnil\fcharset0 HelveticaNeue-Italic;} {\colortbl;\red255\green255\blue255;\red56\green56\blue56;\red255\green255\blue255;\red0\green0\blue0; } {\*\expandedcolortbl;;\cssrgb\c28235\c28235\c28235;\cssrgb\c100000\c100000\c100000;\cssrgb\c0\c0\c0; } \margl1440\margr1440\vieww10800\viewh8400\viewkind0 \deftab720 \pard\pardeftab720\sl300\partightenfactor0 \f0\b\fs24 \cf2 \cb3 \expnd0\expndtw0\kerning0 /* 1. \f1\b0\fs26\fsmilli13200 How many campaigns and sources does CoolTShirts use? Which source is used for each campaign?*/\ \ SELECT COUNT(DISTINCT utm_campaign )\ FROM page_visits;\ \ SELECT COUNT(DISTINCT utm_source )\ FROM page_visits;\ \ SELECT DISTINCT utm_source, \ utm_campaign\ FROM page_visits\ GROUP BY 1;\cb1 \ \ \f0\b\fs24 \cb3 /* 2. \f1\b0 \fs26\fsmilli13200 What pages are on the CoolTShirts website?*/\cb1 \ \ \ SELECT DISTINCT page_name\ FROM page_visits;\ \ \pard\pardeftab720\sl280\partightenfactor0 \f2\b\fs24 \cf4 /* 3. \f3\b0 \f1\fs35\fsmilli17600 \cf2 \cb3 How many first touches is each campaign responsible for?*/\ \pard\pardeftab720\sl300\partightenfactor0 \fs26\fsmilli13200 \cf2 \cb1 \ WITH first_touch AS (\ SELECT user_id,\ MIN(timestamp) as first_touch_at\ FROM page_visits\ GROUP BY user_id)\ SELECT COUNT(*) AS 'number of touches', \ pv.utm_source,\ pv.utm_campaign\ FROM first_touch AS 'ft'\ JOIN page_visits AS 'pv'\ ON ft.user_id = pv.user_id\ AND ft.first_touch_at = pv.timestamp\ GROUP BY 3\ ORDER BY 1 DESC;\ \ /* \f0\b\fs24 \cb3 4. \f1\b0 \fs26\fsmilli13200 How many last touches is each campaign responsible for?*/\cb1 \ \ WITH last_touch AS (\ SELECT user_id,\ MAX(timestamp) as last_touch_at\ FROM page_visits\ GROUP BY user_id)\ SELECT COUNT(*) AS number_of_last_touches, \ pv.utm_source,\ pv.utm_campaign\ FROM last_touch AS 'lt'\ JOIN page_visits AS 'pv'\ ON lt.user_id = pv.user_id\ AND lt.last_touch_at = pv.timestamp\ GROUP BY 3\ ORDER BY 1 DESC;\ \ /* \f0\b\fs24 \cb3 5. \f1\b0 \fs26\fsmilli13200 How many visitors make a purchase?*/\ \ SELECT COUNT(*), page_name\ FROM page_visits\ WHERE page_name = '4 - purchase'\ GROUP BY page_name;\ \cb1 \ \f0\b\fs24 \cb3 /*6. \f1\b0\fs26\fsmilli13200 How many last touches\'a0 \f4\i on the purchase page \f1\i0 \'a0is each campaign responsible for?*/\cb1 \ \ WITH last_touch AS (\ SELECT user_id,\ MAX(timestamp) as last_touch_at\ FROM page_visits\ GROUP BY user_id)\ SELECT COUNT(*) AS number_of_last_touches, \ pv.utm_source,\ pv.utm_campaign\ FROM last_touch AS 'lt'\ JOIN page_visits AS 'pv'\ ON lt.user_id = pv.user_id\ AND lt.last_touch_at = pv.timestamp\ WHERE pv.page_name = '4 - purchase' \ GROUP BY 3\ ORDER BY 1 DESC;\ \ \ \ \ \ \ \ \ }<file_sep># Codecademy Codecademy projects This repository contains projects from the Codecademy intensive courses: 'Data Visualization with Python' and 'Learn SQL from scratch' The two capstone projects were: Analyzing Netflix stock prices for 2017 using Python. Analyzing CoolTshirts.com touch attribution data to recommend a marketing strategy using SQL.
de935c83f736d13c1e61627ebef8eae9f40e4934
[ "Markdown", "SQL" ]
2
SQL
am-willmore/Codecademy
00e02b6c4c56c7ace46e6da658cfafc7e0d13839
32c630599166584805017ea61e7d01cd69bc7bff
refs/heads/master
<repo_name>pitagoras3/CircularQueue<file_sep>/tests/QueueTest.java import org.junit.Before; import static org.junit.Assert.*; public class QueueTest { private Queue<Integer> queue; private int size; @Before public void setQueue(){ size = 10; queue = new Queue(size); } /* Create queue filled with Integers from 0 to size-1 and check if Circular Queue works as it should */ @org.junit.Test public void testEnqueueAndDequeue() throws Exception { for(int i = 0;i<size;i++) queue.enqueue(i); for(int i = 0;i<size;i++){ assertTrue(queue.first() == i); queue.dequeue(); } } @org.junit.Test public void testFirst1() throws Exception { queue.enqueue(0); assertTrue(queue.first() == 0); } @org.junit.Test (expected = EmptyException.class) public void testIsEmpty() throws Exception { queue.first(); } //Fill with too many elements (size+1) @org.junit.Test (expected = FullException.class) public void testIsFull1() throws Exception { for(int i = 0;i<size+1;i++) queue.enqueue(i); } //Fill with equivalent amount of elements @org.junit.Test public void testIsFull2() throws Exception { for(int i = 0;i<size;i++) queue.enqueue(i); } }<file_sep>/README.md #Circular Queue Implementation of Circular Queue in Java, using ArrayList of generic type. Implementation has own declared Exceptions, and JUnit tests. <i>Project ready for IntelliJ.<br> .java files are in 'src' package, JUnit 'tests' are in tests package</i>
87708ce8dd85cebe5aafea0826e51cee59312b6d
[ "Markdown", "Java" ]
2
Java
pitagoras3/CircularQueue
fc0f1536ffb49451479b33a253987e31e8d5908f
2b4e87a9a7cb5e8aba44c0adafd3550bc7e7c0ea
refs/heads/master
<file_sep>import { SAVE_ANSWER, SAVE_ANSWER_STATUS, CHANGE_ANSWER_LOADING } from '../constants/constants.js' const initialState = { answerData: '', answerStatus: null, answerIsLoading: false } export default function interactionAnswer(state = initialState, action) { switch (action.type) { case SAVE_ANSWER: return { ...state, answerData: JSON.stringify(JSON.parse(action.payload), null, 2) } case SAVE_ANSWER_STATUS: return { ...state, answerStatus: action.payload } case CHANGE_ANSWER_LOADING: return { ...state, answerIsLoading: action.payload } default: return state } }<file_sep>export const CHANGE_AUTHORIZAION = 'CHANGE_AUTHORIZAION' export const CHANGE_FULLSCREEN = 'CHANGE_FULLSCREEN' export const SAVE_ANSWER = 'SAVE_ANSWER' export const SAVE_ANSWER_STATUS = 'SAVE_ANSWER_STATUS' export const CHANGE_ANSWER_LOADING = 'CHANGE_ANSWER_LOADING' export const SAVE_REQUEST = 'SAVE_REQUEST' export const CHANGE_REQUEST_STATUS = 'CHANGE_REQUEST_STATUS' export const SEND_REQUEST = 'SEND_REQUEST' export const SEND_ACCOUNT_REQUEST = 'SEND_ACCOUNT_REQUEST' export const SAVE_ACCOUNT_INFO = 'SAVE_ACCOUNT_INFO' export const SAVE_REQUEST_HISTORY = 'SAVE_REQUEST_HISTORY' export const DELETE_REQUEST_HISTORY = 'DELETE_REQUEST_HISTORY' export const ERASE_REQUESTS_HISTORY = 'ERASE_REQUESTS_HISTORY' export const SAVE_REQUEST_HISTORY_INITIAL = 'SAVE_REQUEST_HISTORY_INITIAL' export const CHANGE_FORM_VALUE = 'CHANGE_FORM_VALUE' export const CHANGE_INPUTS_VALIDATE = 'CHANGE_INPUTS_VALIDATE' export const CHANGE_FORM_VALIDATE = 'CHANGE_FORM_VALIDATE' export const CHANGE_SUBMIT_STATUS = 'CHANGE_SUBMIT_STATUS' export const CHANGE_INVALID_STATUS = 'CHANGE_INVALID_STATUS' export const CHANGE_FORM_ERROR_STATUS = 'CHANGE_FORM_ERROR_STATUS' export const CHANGE_FORM_LOADING_STATUS = 'CHANGE_FORM_LOADING_STATUS' export const SEND_AUTH_FORM = 'SEND_AUTH_FORM'<file_sep>import React, { useEffect } from 'react' import { useDispatch, useSelector } from 'react-redux' import './AuthorizationForm.scss' import Logo from '../../assets/svg/logo.svg' import FormError from '../FormError' import Input from '../Input/Input' import Button from '../Button' import GitHubLink from '../GitHubLink' import { changeFormValue, changeInputsValidate, changeFormValidate, changeSubmitStatus, changeInvalidStatus, sendAuthForm } from '../../actions/authorization' import { logIn } from '../../actions/app' import { getCookie } from '../../helpers/helpers' function AuthorizationForm() { const dispatch = useDispatch() const { login, subLogin, password, loginValid, passwordValid, isSubmitDisabled, isFormAnswerLoading, isPasswordInvalid, isLoginInvalid, formError, allFormValid, } = useSelector(store => store.authorizationForm) useEffect(() => { const token = getCookie('token') if (token) { dispatch(logIn(true)) } }, [dispatch]) useEffect(() => { if (loginValid && passwordValid) { dispatch(changeFormValidate(true)) dispatch(changeSubmitStatus(false)) } else if (!loginValid && !passwordValid) { dispatch(changeFormValidate(false)) } if (loginValid) { dispatch(changeInvalidStatus({ isLoginInvalid: false })) } if (passwordValid) { dispatch(changeInvalidStatus({ isPasswordInvalid: false })) } }, [dispatch, loginValid, passwordValid]) const handleSubmit = e => { e.preventDefault() if (allFormValid) { doAuthorization() } else { dispatch(changeSubmitStatus(true)) } if (!loginValid) { dispatch(changeInvalidStatus({ isLoginInvalid: true })) } if (!passwordValid) { dispatch(changeInvalidStatus({ isPasswordInvalid: true })) } } const doAuthorization = () => { localStorage.setItem(`login`, `${login}`) localStorage.setItem(`subLogin`, `${subLogin}`) localStorage.setItem(`password`, `${password}`) dispatch(sendAuthForm()) } const validateField = e => { const { name, value } = e.target switch (name) { case 'login': let isLoginValid = Boolean( value.match(/^[-\w.]+@([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}$/) || value.match(/^(?=.*[A-Za-z0-9]$)[A-Za-z_][A-Za-z\d.-]{0,19}$/)) dispatch(changeFormValue({ name: name, value: value })) dispatch(changeInputsValidate({ loginValid: isLoginValid })) if (!isLoginValid) { dispatch(changeInvalidStatus(true)) } break case 'subLogin': dispatch(changeFormValue({ name: name, value: value })) break case 'password': let isPasswordValid = Boolean(value.match('^[a-zA-Z0-9 ]+$')) dispatch(changeInputsValidate({ passwordValid: isPasswordValid })) dispatch(changeFormValue({ name: name, value: value })) if (!isPasswordValid) { dispatch(changeInvalidStatus(true)) } break default: break } } return ( <div className="login"> <img className="login-logo" src={Logo} alt="Logo" /> <form className="login-form" onSubmit={handleSubmit}> <span className="login-form__title">API-консолька</span> <FormError formError={formError} /> <Input type={"text"} name={"login"} title={"Логин"} value={login} onChange={validateField} titleсlass={"login-form__label"} wrapсlass={`login-form__group ${isLoginInvalid ? "input_invalid" : ""}`} /> <div className="login-form__wrap"> <Input type={"text"} name={"subLogin"} title={"Сублогин"} titleclass={"login-form__label"} value={subLogin} onChange={validateField} titleсlass={"login-form__label"} wrapсlass={"login-form__group"} /> <span className="login-form__option-text">Опционально</span> </div> <Input type={"password"} name={"password"} title={"Пароль"} titleclass={"login-form__label"} value={password} onChange={validateField} titleсlass={"login-form__label"} wrapсlass={`login-form__group ${isPasswordInvalid ? "input_invalid" : ""}`} /> <Button title={"Войти"} className={"btn_standart login-form__submit"} disabled={isSubmitDisabled} loading={isFormAnswerLoading} /> </form> <GitHubLink /> </div> ) } export default AuthorizationForm<file_sep>import React, { useMemo } from 'react' import { useSelector, useDispatch } from 'react-redux' import './HistoryPanel.scss' import Button from '../Button' import Request from '../Request' import { ReactComponent as ClearIcon } from '../../assets/svg/clear.svg' import { eraseAllRequestsHistory } from '../../actions/requestHistory' function HistoryPanel() { const dispatch = useDispatch() const requestHistory = useSelector(store => store.requestHistory.requestHistory) const generateHistoryItems = useMemo(() => { if (requestHistory.length === 0) { return } return requestHistory.map((item, i) => { return ( <Request {...item} key={i} data={item} /> ) }) }, [requestHistory]) const eraseRequestsHistory = () => { dispatch(eraseAllRequestsHistory()) } const toScrollBlock = e => { let target = e.target.closest('.history-panel__requests') if (target.clientWidth !== target.scrollWidth) { target.scrollLeft -= (e.nativeEvent.wheelDelta * 40) } } return ( <div className="history-panel"> <div className="history-panel__requests" onWheel={toScrollBlock}> {generateHistoryItems} </div> <div className="history-panel__wrap-btn"> <Button className={"btn_transparent"} action={eraseRequestsHistory} left={<ClearIcon aria-hidden="true" />} arialabel="Очистить"> </Button> </div> </div> ) } export default HistoryPanel<file_sep>import React from 'react' import './GitHubLink.scss' function GitHubLink() { return ( <a href="https://github.com/krobik" className="github-link" target="_blank" rel="noopener noreferrer">github.com/krobik </a> ) } export default GitHubLink<file_sep>import { SAVE_REQUEST_HISTORY, ERASE_REQUESTS_HISTORY, DELETE_REQUEST_HISTORY, SAVE_REQUEST_HISTORY_INITIAL } from '../constants/constants.js' export function saveRequestHistory(data) { return { type: SAVE_REQUEST_HISTORY, payload: data, } } export function eraseAllRequestsHistory() { return { type: ERASE_REQUESTS_HISTORY } } export function deleteRequestHistory(request) { return { type: DELETE_REQUEST_HISTORY, payload: request, } } export function saveRequestHistoryInitial(initialData) { return { type: SAVE_REQUEST_HISTORY_INITIAL, payload: initialData, } }<file_sep>import React, { useState, useRef, useEffect, useCallback } from 'react' import { useDispatch } from 'react-redux' import './Request.scss' import { deleteRequestHistory } from '../../actions/requestHistory' import { sendRequest } from '../../actions/sendRequest' import { saveRequest } from '../../actions/request' import { writeToBufer } from '../../helpers/helpers' import Portal from "../Portal" import TooltipPopover from "../TooltipPopover" function Request({ actionName, status, data }) { const dispatch = useDispatch() const [dropDownStatus, setDropDownToggle] = useState(false) const [animateCopy, setCopyAnimate] = useState(false) const [coords, setCoords] = useState({}) const wrapperRef = useRef(null) const textInput = useRef(null) const btnRef = useRef(null) const options = ['Выполнить', 'Скопировать', 'Удалить'] const handleClickOutside = useCallback(e => { if (dropDownStatus) { if (wrapperRef.current && !wrapperRef.current.contains(e.target)) { setDropDownToggle(false) } } }, [dropDownStatus]) useEffect(() => { document.addEventListener("keydown", handleHideDropdown, true) document.addEventListener("click", handleClickOutside, false) return () => { document.removeEventListener("keydown", handleHideDropdown, true) document.removeEventListener("click", handleClickOutside, false) } }, [handleClickOutside]) const toggleDropDown = e => { e.stopPropagation() setDropDownToggle(!dropDownStatus) } const handleHideDropdown = e => { if (e.key === "Escape") { e.target.blur() setDropDownToggle(false) } } const handleClickToDropdown = e => { e.stopPropagation() if (e.target.innerHTML === options[1]) { setCopyAnimate(!animateCopy) if (navigator.clipboard) { writeToBufer(JSON.stringify(data.request)) } setDropDownToggle(false) } else if (e.target.innerHTML === options[2]) { dispatch(deleteRequestHistory(data)) setDropDownToggle(false) } else if (e.target.innerHTML === options[0]) { dispatch(saveRequest(JSON.stringify(data.request))) dispatch(sendRequest()) setDropDownToggle(false) } } const handleClick = () => { dispatch(saveRequest((JSON.stringify(data.request, null, 2)))) } const renderDropdownOptions = () => { if (!options) { return } return options.map((option, i) => { return ( <li className="request-dropdown__item" key={i}> <button className="request-dropdown__btn" onClick={handleClickToDropdown}>{option} </button> </li> ) }) } const updateTooltipCoords = el => { let dropdown = textInput.current.getBoundingClientRect() let dropDownWidth = dropdown.width const rect = el.getBoundingClientRect() // Если слева места недостаточно if (dropDownWidth > rect.right) { setCoords({ left: rect.x, top: rect.y + rect.height }) } else { setCoords({ left: (rect.x + rect.width) - dropDownWidth, top: rect.y + rect.height }) } } return ( <div className="request" ref={wrapperRef} onClick={handleClick} > <div className="request__inner" ref={btnRef}> <span className={`request__status request__status_${status || "error"}`}></span> <div className="request__wrap-name"> <span className="request__name">{actionName || "action is wrong"}</span> <span className={"request-copied " + (animateCopy ? "request-copied_animated" : "")} onAnimationEnd={() => setCopyAnimate(!animateCopy)} > Скопировано </span> </div> <button className="request-dots" onClick={(e) => { toggleDropDown(e) updateTooltipCoords(e.target.closest('.request__inner')) }} aria-haspopup="true" > <span className="request-dots__dot"></span> <span className="request-dots__dot"></span> <span className="request-dots__dot"></span> <Portal> <TooltipPopover coords={coords} updateTooltipCoords={() => updateTooltipCoords(btnRef.current)}> <ul className={`request-dropdown ${dropDownStatus ? "request-dropdown_active" : ""}`} ref={textInput} aria-label="submenu"> {renderDropdownOptions()} </ul> </TooltipPopover> </Portal> </button> </div> </div> ) } export default Request<file_sep>import { createStore, compose, applyMiddleware } from 'redux' import createSagaMiddleware from 'redux-saga' import { rootReducer } from '../reducers' import { watchLoadAccountInfo, } from '../sagas/sagaLoadInfo' import { watchLoadData } from '../sagas/sagaLoadRequest' import { watchLoadAuthorization } from '../sagas/sagaAuth' const sagaMiddleware = createSagaMiddleware() const middleware = [ applyMiddleware(sagaMiddleware), ...(window.__REDUX_DEVTOOLS_EXTENSION__ ? [window.__REDUX_DEVTOOLS_EXTENSION__()] : []) ] export const store = createStore(rootReducer, compose(...middleware)) sagaMiddleware.run(watchLoadData) sagaMiddleware.run(watchLoadAccountInfo) sagaMiddleware.run(watchLoadAuthorization)<file_sep>import React from "react" function TextArea(props) { const { lang, value, name, onChange, placeholder, className, readOnly } = props return ( <textarea lang={lang} className={className} name={name} value={value} onChange={onChange} placeholder={placeholder} readOnly={readOnly} /> ) } export default TextArea<file_sep>import { CHANGE_AUTHORIZAION, CHANGE_FULLSCREEN } from '../constants/constants.js' export function logIn(data) { return { type: CHANGE_AUTHORIZAION, payload: data, } } export function toggleFullscreen(bool) { return { type: CHANGE_FULLSCREEN, payload: bool, } }<file_sep>import React, { useEffect } from "react" import debounce from "lodash/debounce" import './TooltipPopover.scss' const TooltipPopover = ({ children, coords, updateTooltipCoords }) => { const updateCoords = debounce(updateTooltipCoords, 100) useEffect(() => { window.addEventListener("resize", updateCoords) return () => window.removeEventListener("resize", updateCoords) }, [updateCoords]) return ( <div className="popover" style={{ ...coords }} > <div className="popover__inner">{children}</div> </div> ) } export default TooltipPopover<file_sep>import RequestResponse from './RequestResponse' export default RequestResponse<file_sep># Sendsay API Console The Sendsay API Console provides a web interface for requests to the Sendsay API. ## О проекте Тестовое задание Sendsay. API-консоль состоит из формы авторизации и интерфейса консоли. Она используется, чтобы выполнять запросы к Sendsay API. ## Где смотреть Пройти по ссылке https://krobik.github.io/api-console/ ## Использовал - React - React Router - Redux - Redux-saga - Sendsay-api - SCSS - React-use-gesture - lodash.debounce ## Почему использовал Scss - использовал в связи с тем, что наименование классов производится по BEM, удобно использовать вложенность. Валидацию формы сделал вручную, так как тестовое, но для реальной задачи использовал бы какую-нибуть готовую библиотеку ## Авторизация Логин: <EMAIL> Пароль: <PASSWORD> ## Примеры запросов - {"action":"pong"} - {"action":"sys.settings.get"} ## Что можно сделать? / Что есть в проекте Форма авторизации: - Авторизация сохраняется при перезагрузке страницы Интерфейс консоли: Консоль состоит из набора панелей, которые занимают всё свободное пространство окна: - Заголовка - Полей запроса-ответа - Истории запросов - Панели с действиям ### Заголовок - Заголовок показывает `account` и `sublogin` из ответа «понга». Если авторизовывались без саблогина, `sublogin` не отображается. - Кнопка «Выйти» делает логаут и переносит пользователя на форму авторизации. - Кнопка перехода в полноэкранный режим — разворачивает окно «на все деньги», подобно YouTube или Vimeo. ### Поля запроса-ответа - Горизонтальный размер полей регулируется - Размеры (пропорции) сохраняются при закрытии браузера ### Отправка запросов к серверу - Запрос к серверу — это валидный JSON. Если в поле ввода невалидно, то подсвечивается поле ввода. Если поле ввода запроса валидно: - отправляется запрос и отображается ответ сервера - если запрос уникальный, он добавляется в историю запросов - если запрос не уникальный, то в истории запросов перемещяется в начало - При нажатии «Форматировать» происходит форматирование текста запроса ### История запросов - Приложение хранит до 15 последних уникальных валидных запросов и умеет отображать их в обратном хронологическом порядке. - Если запрос валиден (с точки зрения валидатора JSON), но при выполнении произошла ошибка, то запрос сохраняется в истории, но так же сохраняется информация об ошибке. - При закрытии вкладки браузера история не пропадает. - Список элементов истории запросов умеет прокручиваться горизонтально с помощью колеса мыши. ### Элемент истории запросов Элемент истории умеет: - Показывать статус выполнения запроса — без ошибок отмечаются зеленым цветом, с ошибками — красным - Выводить значение свойства `action` из запроса, например `track.get` - При нажатии на элемент, подставлять в поле ввода запроса *отформатированный* сохраненный запрос Элемент истории содержит в себе «дропдаун». Дропдаун элемента истории запросов содержит действия: - Выполнить — в поле запроса вставляется сохраненный запрос и выполняется (без физического нажатия кнопки «отправить») - Скопировать — запрос копируется в буфер обмена, и показывается визуальный отклик этого действия - Удалить — безвозвратно удаляет запрос из истории запросов, без диалоговых окон. <file_sep>import React from 'react' import { useSelector, useDispatch } from 'react-redux' import './ActionPanels.scss' import { saveRequest, changeRequestStatus } from '../../actions/request' import { sendRequest } from '../../actions/sendRequest' import { ReactComponent as FormatIcon } from '../../assets/svg/format.svg' import GitHubLink from '../GitHubLink' import Button from '../Button' import { isJsonString } from '../../helpers/helpers.js' function ActionPanels() { const requestData = useSelector(store => store.requestData.savedRequest) const answerIsLoading = useSelector(store => store.answerData.answerIsLoading) const dispatch = useDispatch() const sendRequestFunction = () => { if (isJsonString(requestData)) { dispatch(sendRequest()) } else { dispatch(changeRequestStatus('error')) } } const formatRequest = () => { if (isJsonString(requestData)) { dispatch(saveRequest(JSON.stringify(JSON.parse(requestData), null, 2))) } } return ( <div className="action-panels"> <Button title={"Отправить"} action={sendRequestFunction} className={"btn_standart"} loading={answerIsLoading} /> <GitHubLink /> <Button title={"Форматировать"} action={formatRequest} className={"btn_transparent"} left={<FormatIcon className="action-panels__format-icon" aria-hidden="true"/>}> </Button > </div> ) } export default ActionPanels<file_sep>export function getCookie(name) { let matches = document.cookie.match(new RegExp( '(?:^|\\s)' + name.replace(/([.$?*+\\\\/{}|()\\[\]^])/g, '\\$1') + '=(.*?)(?:;|$)')) return matches ? matches[1] : undefined } export function isJsonString(str) { try { JSON.parse(str) } catch (e) { return false } return true } export function getAuthLocalStorageData() { let login = localStorage.getItem(`login`) let subLogin = localStorage.getItem(`subLogin`) let password = localStorage.getItem(`password`) let obj = { login, subLogin, password } return obj } export function writeToBufer(data) { navigator.clipboard.writeText(data) .then(() => { navigator.clipboard.readText() }) .catch(err => { console.log('Something went wrong', err) }) } export function openFullscreen(elem) { if (elem.requestFullscreen) { elem.requestFullscreen() } else if (elem.mozRequestFullScreen) { elem.mozRequestFullScreen() } else if (elem.webkitRequestFullscreen) { elem.webkitRequestFullscreen() } else if (elem.msRequestFullscreen) { elem.msRequestFullscreen() } } export function closeFullscreen() { if (document.exitFullscreen) { document.exitFullscreen() } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen() } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen() } else if (document.msExitFullscreen) { document.msExitFullscreen() } }<file_sep>import React, { useEffect, useMemo } from 'react' import { useSelector, useDispatch } from 'react-redux' import { Link } from 'react-router-dom' import './Header.scss' import Logo from '../../assets/svg/logo.svg' import { ReactComponent as LogOutIcon } from '../../assets/svg/log-out.svg' import { ReactComponent as FullScreenIcon } from '../../assets/svg/to-full-screen.svg' import { ReactComponent as ExitFullScreenIcon } from '../../assets/svg/exit-full-screen.svg' import { toggleFullscreen, logIn } from '../../actions/app' import { saveRequestHistoryInitial } from '../../actions/requestHistory' import Button from '../Button' import AccountInfo from '../AccountInfo' import { openFullscreen, closeFullscreen } from '../../helpers/helpers' function Header() { const requestHistory = useSelector(store => store.requestHistory.requestHistory) const isFullScreen = useSelector(store => store.app.isFullScreen) const dispatch = useDispatch() useEffect(() => { window.addEventListener('beforeunload', handleWindowBeforeUnload) return () => { window.removeEventListener("beforeunload", handleWindowBeforeUnload) } }) useEffect(() => { if (localStorage.getItem('requestsHistory') !== null) { dispatch(saveRequestHistoryInitial(JSON.parse(localStorage.getItem('requestsHistory')))) } }, [dispatch]) const handleWindowBeforeUnload = () => { localStorage.setItem('requestsHistory', `${JSON.stringify(requestHistory)}`) } const changeFullScreen = () => { let elem = document.documentElement if (isFullScreen) { closeFullscreen() dispatch(toggleFullscreen(false)) } else { openFullscreen(elem) dispatch(toggleFullscreen(true)) } } const logOut = () => { dispatch(logIn(false)) document.cookie = 'token=; expires=-1' localStorage.clear() } const memoizedAccountInfo = useMemo(() => { return <AccountInfo /> }, []) return ( <header className="header"> <div className="header__inner"> <div className='header-company'> <Link to="/main"><img className="header__logo" src={Logo} alt="Logo" /></Link> <span className="header__name">API-консолька</span> </div> <div className="header-detail"> {memoizedAccountInfo} <Button title={"Выйти"} action={logOut} className={"btn_transparent-with-icon header-detail__logout"} right={<LogOutIcon aria-hidden="true" className="i i-logout" />} /> <Button action={changeFullScreen} className={"btn_transparent"} left={isFullScreen ? <ExitFullScreenIcon aria-hidden="true" /> : <FullScreenIcon className="i i-fullscreen" aria-hidden="true" />} arialabel={"Изменить полноэкранный режим"}> </Button> </div> </div> </header > ) } export default Header<file_sep>import React from "react" import meh from '../../assets/svg/meh.svg' import './FormError.scss' function FormError({ formError }) { if (formError !== null && formError.length > 0) { return ( <div className="auth-form-error"> <img className="auth-form-error__icon" src={meh} alt="Sad icon" /> <div className="auth-form-error__block"> <span className="auth-form-error__title">Вход не вышел</span> <span className="auth-form-error__info">{formError}</span> </div> </div> ) } else { return "" } } export default FormError<file_sep>import React from "react" import './Button.scss' import Loader from '../Loader' const Button = props => { const { title, action, className, disabled, loading, arialabel } = props return ( <button className={`btn ${className}`} onClick={action} disabled={disabled} aria-label={arialabel} > {props.left} <span className={`btn__text ${loading ? "btn__text_hidden" : ""}`}>{title}</span> {loading && <Loader />} {props.right} </button> ) } export default Button<file_sep>import { CHANGE_FORM_VALUE, CHANGE_INPUTS_VALIDATE, CHANGE_FORM_VALIDATE, CHANGE_SUBMIT_STATUS, CHANGE_INVALID_STATUS, CHANGE_FORM_ERROR_STATUS, CHANGE_FORM_LOADING_STATUS, SEND_AUTH_FORM } from '../constants/constants.js' export function changeFormValue(value) { return { type: CHANGE_FORM_VALUE, payload: value, } } export function changeInputsValidate(data) { return { type: CHANGE_INPUTS_VALIDATE, payload: data, } } export function changeFormValidate(data) { return { type: CHANGE_FORM_VALIDATE, payload: data, } } export function changeSubmitStatus(status) { return { type: CHANGE_SUBMIT_STATUS, payload: status, } } export function changeInvalidStatus(data) { return { type: CHANGE_INVALID_STATUS, payload: data, } } export function changeFormErrorStatus(data) { return { type: CHANGE_FORM_ERROR_STATUS, payload: data, } } export function changeFormLoadingStatus(data) { return { type: CHANGE_FORM_LOADING_STATUS, payload: data, } } export function sendAuthForm() { return { type: SEND_AUTH_FORM, } }<file_sep>import Sendsay from 'sendsay-api' import { getAuthLocalStorageData } from '../helpers/helpers' export function fetchData(requestData) { let localStorageData = getAuthLocalStorageData() const sendsay = new Sendsay({ auth: { login: localStorageData.login, subLogin: localStorageData.subLogin, password: <PASSWORD> } }) return sendsay.request(requestData) }<file_sep>import ActionPanels from './ActionPanels' export default ActionPanels<file_sep>import React from "react" import './Input.scss' const Input = props => { const { type, name, title, value, placeholder, onChange, wrapсlass, titleсlass } = props return ( <div className={`input ${wrapсlass}`}> <label className={titleсlass} htmlFor={name}> {title} </label> <input className={`input__field`} id={name} name={name} type={type} value={value} onChange={onChange} placeholder={placeholder} {...props} /> </div> ) } export default Input<file_sep>import React, { useEffect } from 'react' import { useDispatch, useSelector } from 'react-redux' import { sendAccountRequest } from '../../actions/account' import './AccountInfo.scss' function AccountInfo() { const dispatch = useDispatch() const { account, sublogin } = useSelector(store => store.account) const authFormSubloginValue = localStorage.getItem('subLogin') useEffect(() => { dispatch(sendAccountRequest('{"action":"pong"}')) }, [dispatch]) return ( <div className="account-info"> <span>{account}</span> {authFormSubloginValue && <> <span className="account-info__separ">:</span> <span>{sublogin}</span> </> } </div> ) } export default AccountInfo<file_sep>import { takeEvery, put, call } from 'redux-saga/effects' import { saveAccountInfo } from '../actions/account' import { SEND_ACCOUNT_REQUEST } from '../constants/constants.js' import { fetchData } from './sagas' function* workerLoadAccountInfo(action) { const requestData = action.payload let requestDataObject = JSON.parse(requestData) try { let res = yield call(fetchData, requestDataObject) let obj = { status: 'success', account: res.account, sublogin: res.sublogin } yield put(saveAccountInfo(obj)) } catch (error) { let obj = { status: 'error', errorInfo: error } yield put(saveAccountInfo(obj)) } } export function* watchLoadAccountInfo() { yield takeEvery(SEND_ACCOUNT_REQUEST, workerLoadAccountInfo) } <file_sep>import { SAVE_REQUEST, CHANGE_REQUEST_STATUS } from '../constants/constants.js' const initialState = { savedRequest: '', isValid: null } export default function interactionRequest(state = initialState, action) { switch (action.type) { case SAVE_REQUEST: return { ...state, savedRequest: action.payload } case CHANGE_REQUEST_STATUS: return { ...state, isValid: action.payload } default: return state } }<file_sep>import React from 'react' import { Link } from 'react-router-dom' import './NotFound.scss' function NotFound(){ return( <div className="not-found"> <Link to="/main" className="not-found__link">Go to Main Page</Link> </div> ) } export default NotFound<file_sep>import { SAVE_ACCOUNT_INFO } from '../constants/constants.js' const initialState = { account: null, sublogin: null, errorInfo: null } export default function account(state = initialState, action) { switch (action.type) { case SAVE_ACCOUNT_INFO: return { ...state, ...action.payload } default: return state } }<file_sep>import { combineReducers } from 'redux' import interactionRequest from './interactionRequest' import interactionAnswer from './interactionAnswer' import interactionRequestHistory from './interactionRequestHistory' import app from './app' import account from './account' import authorization from './authorization' export const rootReducer = combineReducers({ app, authorizationForm: authorization, account, requestData: interactionRequest, answerData: interactionAnswer, requestHistory: interactionRequestHistory, })<file_sep>import { SAVE_REQUEST_HISTORY, ERASE_REQUESTS_HISTORY, DELETE_REQUEST_HISTORY, SAVE_REQUEST_HISTORY_INITIAL } from '../constants/constants.js' const initialState = { maxCountRequests: 15, requestHistory: [] } export default function interactionRequestHistory(state = initialState, action) { switch (action.type) { case SAVE_REQUEST_HISTORY: if (state.requestHistory.length < state.maxCountRequests) { if (isUnic(action.payload.actionName)) { return { ...state, requestHistory: [...state.requestHistory, action.payload].reverse() } } else { state.requestHistory.unshift(...state.requestHistory.splice(findIndex(action.payload.actionName), 1)) return { ...state, requestHistory: [...state.requestHistory] } } } return { ...state } case DELETE_REQUEST_HISTORY: state.requestHistory.splice(findIndex(action.payload.actionName), 1) return { ...state, requestHistory: [...state.requestHistory] } case ERASE_REQUESTS_HISTORY: return { ...state, requestHistory: [] } case SAVE_REQUEST_HISTORY_INITIAL: return { ...state, requestHistory: [...action.payload] } default: return state } function isUnic(actionName) { return !state.requestHistory.some(item => item.actionName === actionName) } function findIndex(actionName) { return state.requestHistory.findIndex(item => item.actionName === actionName) } }<file_sep>import React from 'react' import { useSelector } from 'react-redux' import { Route, Redirect, Switch } from 'react-router-dom' import './App.css' import Header from '../Header' import HistoryPanel from '../HistoryPanel/HistoryPanel' import RequestResponse from '../RequestResponse' import ActionPanels from '../ActionPanels' import AuthorizationForm from '../AuthorizationForm' import NotFound from '../NotFound' function App() { const isLogged = useSelector(store => store.app.isLogged) return ( <div className="App"> <Switch> <Route exact path="/"> {isLogged ? <Redirect to="/main" /> : <AuthorizationForm />} </Route> <Route path="/main"> {isLogged ? <> <Header /> <HistoryPanel /> <RequestResponse /> <ActionPanels /> </> : <Redirect to="/" /> } </Route> <Route path="*"> <NotFound /> </Route> </Switch> </div> ) } export default App<file_sep>import { SEND_ACCOUNT_REQUEST, SAVE_ACCOUNT_INFO } from '../constants/constants.js' export function sendAccountRequest(data) { return { type: SEND_ACCOUNT_REQUEST, payload: data, } } export function saveAccountInfo(data) { return { type: SAVE_ACCOUNT_INFO, payload: data, } } <file_sep>import { CHANGE_AUTHORIZAION, CHANGE_FULLSCREEN } from '../constants/constants.js' const initialState = { isLogged: false, isFullScreen: false, } export default function appReduces(state = initialState, action) { switch (action.type) { case CHANGE_AUTHORIZAION: return { ...state, isLogged: action.payload } case CHANGE_FULLSCREEN: return { ...state, isFullScreen: action.payload } default: return state } }<file_sep>import HistoryPanel from './HistoryPanel' export default HistoryPanel<file_sep>export const requestData = (state) => state.requestData.savedRequest export const authorizationFormData = (state) => state.authorizationForm<file_sep>import React from 'react' import './Loader.scss' function Loader() { return ( <div className="loader"> <div className="loader__inner"> <div className="loader__part"></div> <div className="loader__part"></div> <div className="loader__part"></div> <div className="loader__part"></div> <div className="loader__part"></div> <div className="loader__part"></div> <div className="loader__part"></div> <div className="loader__part"></div> </div> </div> ) } export default Loader<file_sep>import { takeEvery, put, call, select } from 'redux-saga/effects' import * as selectors from '../selectors/selectors' import { saveAnswer, saveAnswerStatus, changeAnswerLoading } from '../actions/answer' import { saveRequestHistory } from '../actions/requestHistory' import { SEND_REQUEST } from '../constants/constants.js' import {fetchData} from './sagas' function* workerLoadData() { const requestData = yield select(selectors.requestData) let requestDataObject = JSON.parse(requestData) yield put(changeAnswerLoading(true)) try { yield call(fetchData, requestDataObject) let obj = { status: 'success', actionName: requestDataObject.action, request: requestDataObject } yield put(saveAnswer(JSON.stringify(obj))) yield put(saveAnswerStatus('')) yield put(saveRequestHistory(obj)) } catch (error) { let obj = { status: 'error', actionName: requestDataObject.action, request: requestDataObject, errorInfo: error } yield put(saveAnswer(JSON.stringify(obj))) yield put(saveAnswerStatus('error')) yield put(saveRequestHistory(obj)) } yield put(changeAnswerLoading(false)) } export function* watchLoadData() { yield takeEvery(SEND_REQUEST, workerLoadData) }<file_sep>import { SEND_REQUEST } from '../constants/constants.js' export function sendRequest(request) { return { type: SEND_REQUEST, payload: request } }
53657c9ef308dcb9c93fedacd8b6a698fddc302c
[ "JavaScript", "Markdown" ]
37
JavaScript
krobik/api-cons
de27c17cb373214a73a331d7ab32e9f269619723
54408a86816bcc12596b5713b31c0bd1a26dfca5
refs/heads/master
<repo_name>aavnsh/tasks4all-django<file_sep>/tasklist/urls.py from django.conf.urls import url from django.contrib import admin from tasklist import views urlpatterns = [ url(r'^mine/$', views.view_list, {'filter_type': 'mine'}, name="list-mine"), url(r'^task/(?P<task_id>\d{1,6})$', views.view_task, name='task_detail'), url(r'^incomplete/$', views.view_list, {'filter_type': 'incomplete'}, name='incomplete_tasks'), url(r'^completed/$', views.view_list, {'view_completed': True}, name='completed_tasks'), url(r'^recent/added/$', views.view_list, {'filter_type': 'recent-add'}, name="recently_added"), url(r'^recent/completed/$', views.view_list, {'filter_type': 'recent-complete'}, name="recently_completed"), url(r'^admin/', admin.site.urls), ]<file_sep>/readme.md It's a "task management" web application, primarily designed for the phone. ##Current: - can enter a task with description, target date, priority (high, medium, low) - can edit a task description, target date, priority - can move the task to completed - can view the task list - can sort the task list by target date and priority - can view the complete task list - please set up the database on the backend to house the task data. ##Future: - Search - Purge/Archive - Assign Tasks - Group Tasks into Lists - Notification and Alarms (so scheduled tasks) - Rest/API layer ##Technical Choices: - Django/Python for backend - bootstrap for css, js - jquery-ui for ui widgets<file_sep>/tasklist/utils.py import datetime from django.contrib import messages from tasklist.models import Item def mark_done(request, done_items): for item in done_items: i = Item.objects.get(id=item) i.completed = True i.completed_date = datetime.datetime.now() i.save() messages.success(request, "Item \"{i}\" marked complete.".format(i=i.title)) def undo_completed_task(request, undone_items): for item in undone_items: i = Item.objects.get(id=item) i.completed = False i.save() messages.success(request, "Previously completed task \"{i}\" marked incomplete.".format(i=i.title)) <file_sep>/tasklist/admin.py from django.contrib import admin from tasklist.models import Item class ItemAdmin(admin.ModelAdmin): list_display = ('title', 'due_date', 'priority') ordering = ('due_date', 'priority', 'title') search_fields = ('name',) admin.site.register(Item, ItemAdmin)<file_sep>/tasklist/models.py from __future__ import unicode_literals import datetime from django.db import models from django.contrib.auth.models import User from django_enumfield import enum from django.utils.encoding import python_2_unicode_compatible class PriorityType(enum.Enum): LOW = 0 MEDIUM = 1 HIGH = 2 labels = { LOW: 'Low', MEDIUM: 'Medium', HIGH: 'High' } @python_2_unicode_compatible class Item(models.Model): title = models.CharField(max_length=140) created_date = models.DateField(auto_now=True) due_date = models.DateField(blank=True, null=True, ) completed = models.BooleanField(default=False) completed_date = models.DateField(blank=True, null=True) created_by = models.ForeignKey(User) priority = enum.EnumField(PriorityType, default=PriorityType.MEDIUM) note = models.TextField(blank=True, null=True) def overdue_status(self): if self.due_date and datetime.date.today() > self.due_date: return True else: return False def priority_label(self): if self.priority: return PriorityType.get(self.priority).label else: return '' def __str__(self): return self.title def save(self): if self.completed: self.completed_date = datetime.datetime.now() super(Item, self).save() class Meta: ordering = ["-due_date", "-priority"] <file_sep>/requirements.txt Django==1.9 django-enumfield==1.3b2 <file_sep>/tasklist/tests.py from django.test import TestCase from tasklist.forms import AddItemForm from tasklist.models import Item class ItemMethodTests(TestCase): def test_new_item_is_incomplete(self): new_item = Item() self.assertIs(new_item.completed, False) def test_new_item_is_not_overdue(self): new_item = Item() self.assertIs(new_item.overdue_status(), False) def test_add_form_blank_is_invalid(self): form_data = {} form = AddItemForm(data=form_data) self.assertFalse(form.is_valid()) <file_sep>/tasklist/forms.py from django import forms from django.forms import ModelForm from tasklist.models import Item class AddItemForm(ModelForm): def __init__(self, *args, **kwargs): super(AddItemForm, self).__init__(*args, **kwargs) due_date = forms.DateField( required=False, widget=forms.DateTimeInput(attrs={'class': 'due_date_picker'}) ) title = forms.CharField( widget=forms.widgets.TextInput(attrs={'size': 35}) ) note = forms.CharField(widget=forms.Textarea(), required=False) class Meta: model = Item exclude = [] class EditItemForm(ModelForm): def __init__(self, *args, **kwargs): super(EditItemForm, self).__init__(*args, **kwargs) class Meta: model = Item exclude = ('created_date', 'created_by',) <file_sep>/tasklist/views.py import datetime from django.contrib import messages from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render from tasklist.forms import AddItemForm, EditItemForm from tasklist.models import Item from tasklist.utils import mark_done, undo_completed_task @login_required() def view_list(request, filter_type='mine', view_completed=False): mark_done(request, request.POST.getlist('mark_done')) undo_completed_task(request, request.POST.getlist('undo_completed_task')) thedate = datetime.datetime.now() created_date = "%s-%s-%s" % (thedate.year, thedate.month, thedate.day) if filter_type == "mine": task_list = Item.objects.filter(created_by=request.user, completed=False).order_by('due_date', '-priority') completed_list = Item.objects.filter(created_by=request.user, completed=True).order_by('due_date', '-priority') elif filter_type == "recent-add": task_list = Item.objects.filter( created_by=request.user, completed=False).order_by('-created_date')[:50] elif filter_type == "recent-complete": task_list = Item.objects.filter( created_by=request.user, completed=True).order_by('-completed_date')[:50] else: task_list = Item.objects.filter(created_by=request.user, completed=False).order_by('due_date', '-priority') completed_list = Item.objects.filter(created_by=request.user, completed=True).order_by('due_date', '-priority') if request.POST.getlist('add_task'): form = AddItemForm(request.POST, initial={ 'created_by': request.user.id }) if form.is_valid(): new_task = form.save() messages.success(request, "New task \"{t}\" has been added.".format(t=new_task.title)) return HttpResponseRedirect(request.path) else: if filter_type != "mine" and filter_type != "recent-add" and filter_type != "recent-complete": form = AddItemForm(initial={ 'created_by': request.user.id, }) return render(request, 'tasklist/view_list.html', locals()) @login_required() def view_task(request, task_id): task = get_object_or_404(Item, pk=task_id) if task.created_by == request.user: if request.POST: form = EditItemForm(request.POST, instance=task) if form.is_valid(): form.save() messages.success(request, "The task has been edited.") return HttpResponseRedirect(reverse('incomplete_tasks')) else: form = EditItemForm(instance=task) if task.due_date: thedate = task.due_date else: thedate = datetime.datetime.now() else: messages.info(request, "You do not have permission to view/edit this task.") return render(request, 'tasklist/view_task.html', locals())
2e84a4e627192322c92e2c27a674b031ce68c05e
[ "Markdown", "Python", "Text" ]
9
Python
aavnsh/tasks4all-django
dd2767971c27b1988b59dd0276a700a6fcde572e
14c9c651ff986f15332fc92eca61277256a48964
refs/heads/master
<repo_name>kenlyau/pwa-example<file_sep>/src/app.js export default function () { console.log('app is runing') }<file_sep>/README.md # pwa-example Progressive Web Apps Example ### step 1 ``` # parcel index.html ```
81123247e06bcb81d54a7caeb92debf48aa77635
[ "JavaScript", "Markdown" ]
2
JavaScript
kenlyau/pwa-example
db66effa606983bc94546a3f4881a65480525cc8
259852347c4e11c0e161746976d2afeccf95e06d
refs/heads/master
<repo_name>swamitsk/socket_io_chat<file_sep>/app.js var express = require('express'); app = express(); var server = require('http').createServer(app); var io = require('socket.io').listen(server); server.listen(3000, function(req,res){ console.log("listening....."); }); app.use(express.static(__dirname + '/public')); app.use(express.static(__dirname + '/bower_components')); io.sockets.on('connection',function(socket){ console.log("client connected.."); socket.on('send msg', function(data){ console.log(data); io.sockets.emit('get msg',data); }) })
af2a284837a6caee1693107f4b969d0440d54dd9
[ "JavaScript" ]
1
JavaScript
swamitsk/socket_io_chat
63d3b05b61ef007c0cac2cf9d9556870e22ddb2f
3437f33a3d74d654ae298f557fad87406e1efb63
refs/heads/master
<file_sep>import unittest, matrix as m """ class initialize(unittest.TestCase): def test_initialize(self): """ class compare(unittest.TestCase): def test_equals(self): a = m.Matrix([[1, 2], [3, 4]]) b = m.Matrix([[1, 2], [3, 4]]) self.assertEqual(a,b) def test_not_equals(self): a = m.Matrix([[1, 3], [2, 4]]) b = m.Matrix([[1, 2], [3, 4]]) c = m.Matrix([[1]]) self.assertNotEqual(a,b) self.assertNotEqual(a,c) class ops(unittest.TestCase): def test_sum(self): a = m.Matrix([[1, 3], [2, 4]]) b = m.Matrix([[1, 2], [3, 4]]) res = m.Matrix([[2,5],[5,8]]) self.assertEqual(a+b,res) def test_scal_mul(self): a = m.Matrix([[1, 3], [2, 4]]) res = m.Matrix([[4,12],[8,16]]) self.assertEqual(a*4,res) def test_matmul(self): a = m.Matrix([[1, 3], [2, 4]]) i = m.Matrix([[1,0],[0,1]]) self.assertEqual(a@i,a) class checkBadInput(unittest.TestCase): def test_badlist_in_constructor(self): self.assertRaises(ValueError, m.Matrix,[[1],[8,5],[78,5]]) class checkSums(unittest.TestCase): def test_sum_by_row(self): self.assertEqual(m.Matrix([[1, 2], [3, 4]]).sum_by_row(), [3,7]) def test_sum_by_column(self): self.assertEqual(m.Matrix([[1, 2], [3, 4]]).sum_by_column(), [4,6]) class squareConstructor(unittest.TestCase): def test_constructor_makes_identity(self): self.assertEqual(m.SquareMatrix(2), m.Matrix([[1,0],[0,1]])) if __name__ == '__main__': unittest.main() <file_sep>"""Provides a Matrix class""" class Matrix: def __init__(self, l): x = map(len, l) if len(set(x))!=1: raise ValueError("List lenghts aren't consistent!") self.l = l def __eq__(self, other): if isinstance(other, self.__class__): return self.l == other.l def copy(self): return Matrix([row.copy() for row in self.l]) def __str__(self): return str(self.l) def __add__(a, b): if len(a.l) != len(b.l): raise ValueError("Matrices dimensions don't match!") return Matrix([[a.l[i][j] + b.l[i][j] for j in range(len(a.l[i]))] for i in range(len(a.l))]) def __mul__(self, n): return Matrix([[self.l[i][j] * n for j in range(len(self.l[i]))] for i in range(len(self.l))]) def __matmul__(a,b): n = len(a.l) # righe di a m = len(b.l[0]) #colonne di b p = len(b.l) #dimensione comune alle due matrici if (p != len(a.l[0])): raise ValueError("Matrices dimensions don't match!") newm = [] for i in range(n): newline = [] for j in range(m): newcell = 0 for h in range(p): newcell += a.l[i][h] * b.l[h][j] newline.append(newcell) newm.append(newline) return Matrix(newm) def transpose(self): newm = [[self.l[j][i] for j in range(len(self.l[i]))] for i in range(len(self.l))] return Matrix(newm) def norm(self): tr = self.transpose() return max([sum(map(abs, col)) for col in tr.l]) if __name__ == "__main__": a = Matrix([[1, 2], [3, 4]]) b = Matrix([[1, 2], [3, 4]]) print(a != b) a = Matrix([[1, 3], [2, 4]]) print(a != b) c = Matrix([[1]]) print(a == c) print(a != c) print("Proviamo la copy") b = a print (b is a) b = a.copy() print (b is a) print(b==a) print("proviamo la somma") a = Matrix([[1, 2], [3, 4]]) print(a) print(b) c = a+b print(c) print(a) print(b) print("proviamo la mul scalare") print(a*4) print("proviamo la matmul") i = Matrix([[1,0],[0,1]]) print(a@i) print(a@b) print("proviamo transpose") print(a.transpose()) <file_sep>"""This module contains the Euler Accelerator for series. It also implements two generators for series converging to pi and e.""" def pi_series(): sum = 4 div = 1 while True: yield sum div += 2 sum -= 4 / div yield sum div += 2 sum += 4 / div def e_series(): s = 1 i = 0 fact = 1 while True: yield s i += 1 fact *= i s += 1 / fact def firstn(g, n): for i in range(n): yield next(g) def euler_accelerator(g): a = next(g) b = next(g) c = next(g) while True: yield c - ((c - b) ** 2) / (a - 2 * b + c) a = b b = c c = next(g) if __name__ == '__main__': print("exact value for pi :- {0:.16}".format(3.14159265358979)) print("old(pi) :-", list(firstn(pi_series(), 7))) print("new(pi) :-", list(firstn(euler_accelerator(pi_series()), 7))) print("exact value for e :- {0:.16}".format(2.71828182845904)) print("old(e) :-", list(firstn(e_series(), 7))) print("new(e) :-", list(firstn(euler_accelerator(e_series()), 7))) <file_sep>"""Useful decorators""" def logging(F): def logegr (*args): with open('decoratedlog.txt', 'a') as log: log.write(F.__name__ + str(args) + '\n') return F(*args) return logger def memoization(F): """Accelerate function execution by caching values. Useful for recursive functions.""" F.memory = dict() def wrapper(*args): if args not in F.memory: F.memory[args] = F(*args) return F.memory[args] return wrapper def decorator(F): def wrapper(*args): print("executing {0}{1}".format(F.__name__,args)) return F(*args) return wrapper @memoization def f(a,b): print(a,b) @memoization def fact(n): if n == 1: return 1 return n*fact(n-1) if __name__=="__main__": print(fact(5)) print(fact(10)) <file_sep>"""Implements a metaclass (AutoInit) that detects the names of the constructor's arguments and automatically initializes the corresponding fields with the actual values passed to the constructor.""" from inspect import signature class AutoInit(type): def __init__(Class, classname, bases, attr): par = iter(signature(Class.__init__).parameters) def newinit(self, *args): next(par) # discard the 'self' name for arg in args: kw = next(par) setattr(self, kw, arg) Class.__init__ = newinit if __name__ == '__main__': class Person(metaclass=AutoInit): def __init__(self, name, age): pass class Circle(metaclass=AutoInit): def __init__(self, x, y, ray): pass class Car(metaclass=AutoInit): def __init__(self, model, color, plate, year):pass a_person = Person('John', 25) a_circle = Circle(0, 0, 3.14) a_car = Car('Ford Ka', 'Blue', 'AF329SZ', 1999) print("A Person of name :- {}, and age :- {}." .format(a_person.name,a_person.age)) print("A Circle centered in <{},{}>, and ray {}." .format(a_circle.x,a_circle.y, a_circle.ray)) print("A {} {} whose plate is {} and was registered in {}." .format(a_car.color,a_car.model,a_car.plate,a_car.year)) <file_sep>"""Extending the Polynomial class from 'polynomials' module by using a metaclass. The extension leave the module 'polynomials' untouched. This extension add to Polynomial methods to calculate possible rational roots, to get the effective roots and to get all the polynomials that factorize 'self'""" from polynomials import * from functools import reduce def proots(self): a0 = self.c[-1] an = self.c[0] # p = list of integer divisors of a0 p = list(filter(lambda x: a0 % x == 0, range(1, abs(a0)+1))) q = list(filter(lambda x: an % x == 0, range(1, abs(an)+1))) r = list(set(x//y for x in p for y in q)) # r = [int(x) for x in r if int(x)-x==0] r += [-x for x in r] return r def roots(self): return list(filter(lambda x: self % Polynomial(1, -x) == 0, self.proots())) def pfactors(self): res = list(map(lambda r: Polynomial(1, -r), self.roots())) remainder = reduce(Polynomial.__truediv__, [self] + res) if not (len(remainder.c) == 1 and remainder.c[0] == 1): res += [remainder] return res class ExtendedPolynomial(type): def __init__(meta, classname, supers, attr): meta.proots = proots meta.roots = roots meta.pfactors = pfactors Polynomial = ExtendedPolynomial('Polynomial', (), dict(Polynomial.__dict__)) if __name__=='__main__': import functools p = Polynomial(1, 2, -1, -2) print('Potential roots for {} are :- {}'.format(p, p.proots())) print('Rational roots for {} are :- {}'.format(p, p.roots())) print('The factors for {} are:'.format(p)) for q in p.pfactors(): print(" · {}".format(q)) print('Counterprove: {} = '.format(p), end='') print(functools.reduce(Polynomial.__mul__, p.pfactors())) p = Polynomial(2,-3,1,-2,-8) print('Potential roots for {} are :- {}'.format(p, p.proots())) print('Rational roots for {} are :- {}'.format(p, p.roots())) print('The factors for {} are:'.format(p)) for q in p.pfactors(): print(" · {}".format(q)) print('Counterprove: {} = '.format(p), end='') print(functools.reduce(Polynomial.__mul__, p.pfactors())) <file_sep>from itertools import zip_longest from functools import reduce class TooHighOrderDivisorException(Exception): pass def superscript(s): input = '0123456789' output = u'\u2070\u00b9\u00b2\u00b3\u2074\u2075\u2076\u2077\u2078\u2079' #input = '2' #output = '\N{SUPERSCRIPT TWO}' #print('\N{SUPERSCRIPT TWO}') return s.translate(str.maketrans(input, output)) class Polynomial: def __init__(self, *c): self.c = c def __repr__(self): s = '' for i in range(len(self.c)): exp = len(self.c) - 1 - i a = self.c[i] if a != 0: if a > 0: s += '+' if a == -1 and exp != 0: s += '-' elif a == 1 and exp != 0: pass else: s += str(a) if exp > 0: s += 'x' if exp > 1: s += (superscript(str(exp))) return s def __add__(a, b): return Polynomial(*list(reversed([x + y for x,y in zip_longest(reversed(a.c), reversed(b.c), fillvalue=0)]))) def __sub__(a, b): b = Polynomial(*list(map(lambda x: -x, b.c))) return a + b def monomials(self): res = [] for i in range(len(self.c)): if self.c[i] != 0: res.append(Polynomial(*([self.c[i]] + [0]*(len(self.c) -1-i)))) return res def __lshift__(self, mon): b = mon.c[0] m = len(mon.c) - 1 return Polynomial(*(list(map(lambda x: x*b, self.c)) + [0] * m)) def __mul__(a, b): return reduce(lambda x,y: x+y, list(map(lambda x: b<<x, a.monomials()))) def ruffini(self, other): if len(other.c) > 2: raise TooHighOrderDivisorException("ERROR!!! The divisor {} is too high order! It should be one!".format(other)) r = -other.c[-1]//other.c[0] q = [self.c[0]] for a in self.c[1:]: q += [q[-1] * r+a] quotient = Polynomial(*q[:-1]) remainder = q[-1] *other.c[0] return (quotient, remainder) def __truediv__(self, other): return self.ruffini(other)[0] def __mod__(self, other): return self.ruffini(other)[1] if __name__ == "__main__": p = Polynomial(7, 0, 2, 0, -1) q = Polynomial(-1,0,42) r = Polynomial(3.2, 15, 0, 1, 4, 2, 0) print("p :- {}\nq :- {}\nr :- {}".format(p,q,r)) z = p + q + r print("z :- {}".format(z)) print("Monomials of z:", z.monomials() ) print("z-r :- {}".format(z-r)) print('The polynomials generated by q×p are:') for p1 in p.monomials(): print(" · {}".format(q<<p1)) print('p·q :- {} \nq·p :- {}'.format(p*q, q*p)) r = Polynomial(2,-5,-1,6).ruffini(Polynomial(1,1)) print('2x³-5x²-x+6/x+1 :- {} with remainder :- {} '.format(r[0],r[1])) p1 = Polynomial(2,3,0,-4) p2 = Polynomial(1,1) print('2x³+3x²-4/x+1 :- {} with remainder :- {} '.format((p1/p2),p1%p2)) print("Let's try some impossible operations") try: print(" · Can I do {}/{}? ".format(q,p), end='') q/p except TooHighOrderDivisorException as e: print(e) try: print(" · Can I do {}%{}? ".format(q,p), end='') q%p except TooHighOrderDivisorException as e: print(e) try: print(" · Can I do {}.ruffini({})? ".format(q,p), end='') q.ruffini(p) except TooHighOrderDivisorException as e: print(e) <file_sep>"""Provides a translate function that convert markdown syntax into HTML.""" import re rules = ( (r'^([^#\*\d-].+$)',r'<p>\1</p>'), (r'_(.+)_', r'<em>\1</em>'), (r'\*\*(.+)\*\*',r'<strong>\1</strong>'), (r'`(.+)`', r'<code>\1</code>')) line_rules =((r'((^\* .+$\n)+)', r'<ul>\n\1</ul>'), (r'((^\d+\. .+$\n)+)', r'<ol>\n\1</ol>'), (r'^\* (.+)', r'\t<li>\1</li>'), (r'^\d+\. (.+)', r'\t<li>\1</li>'), (r'^###(.+)', r'<h1>\1</h1>'), (r'^##(.+)', r'<h2>\1</h2>'), (r'^#(.+)', r'<h3>\1</h3>'), (r'^---$', r'<hr />')) def translate(fn): file = open(fn) result = "<html>\n" for line in file: for pattern, repl in rules: line = re.sub(pattern, repl, line) result += line for pattern, repl in line_rules: result = re.sub(pattern, repl, result, flags = re.MULTILINE) result+= "\n</html>" return result if __name__ == "__main__": for fn in sys.argv[1:]: print(translate(fn))
ec70ba9bcba44c1577ea71d428f77cf07bd77734
[ "Python" ]
8
Python
FedericoPicetti/adv-python-exercises
2a8e5cc7d0a6b66f78587556af64ec044751c1f0
25c02892f34d9fadd9f5120819a20c199176df2f
refs/heads/master
<file_sep>package by.academy.library.service.impl; import java.util.Date; import java.util.List; import by.academy.library.dao.LibraryDao; import by.academy.library.dao.collection.LibraryDaoCollectionImple; import by.academy.library.ds.Library; import by.academy.library.entity.Author; import by.academy.library.entity.Book; import by.academy.library.service.CatalogService; public class RegularCatalogServiceImpl implements CatalogService { private LibraryDao libraryDao; public RegularCatalogServiceImpl(Library library) { this.libraryDao = new LibraryDaoCollectionImple(library); } @Override public List<Book> listBooks() { List<Book> books = libraryDao.getBooks(); return books; } @Override public List<Author> listAuthors() { List<Author> authors = libraryDao.getAuthors(); return authors; } @Override public void addBook(String author, String title) { libraryDao.addBook(author, title); } }
110c9a3fad609788f2aebaadf7a69c4a5f878306
[ "Java" ]
1
Java
RomanJav/Library
edace03f128ec0ce5ce805d6aa64caf087add328
41af708b97b62cc02d95bb3c58ea4e77f2756d9e
refs/heads/master
<repo_name>cmocha/joomla-t3-template-gulp-tasks<file_sep>/gulpfile.js var gulp = require('gulp'); // PLUGINS var browserSync = require('browser-sync'); // BROWSER SYNC TASK // gulp browserSync // Either proxy setting worked for the Joomla-Tools Vagrant Box // Note I added these lines below in the Vagrantfile to expose the ports for Browsersync // config.vm.network "forwarded_port", guest: 3000, host: 3000 // config.vm.network "forwarded_port", guest: 3001, host: 3001 // // Enable public network // config.vm.network "public_network" // // run ifconfig inside vagrant box to see the appropriate address available to connect via the network from external device. gulp.task('browserSync', function() { browserSync({ //proxy: "joomla.box/mysite/" proxy: "172.16.17.32:80" // View browser sync at - http://172.16.17.32:3000/mysite/ // View browsersync control at http://localhost:3001/ }); }); // WATCH TASK // gulp watch // This task starts browsersync and watches our files. gulp.task('watch', ['browserSync'], function(){ var watchLess = gulp.watch(['./less/*.less', './less/**/*.less'], browserSync.reload); watchLess.on('change', function (event) { console.log('Event type: ' + event.type); // added, changed, or deleted console.log('Event path: ' + event.path); // The path of the modified file }); gulp.watch(['*.php', './html/**/*.php'] , browserSync.reload); gulp.watch('./js/**/*.js', browserSync.reload); }); <file_sep>/README.md # T3 Joomla Gulp Tasks T3 Joomla Gulp Tasks is a collection of gulp tasks for use with the free T3 Joomla Framework blank T3 Template with Bootstrap 3. ## Gulp Tasks Watch Task ```sh gulp watch ``` - Starts browserSync and watches the less, js and php files in the template. Upon changes it reloads browserSync. >T3 Joomla Gulp Tasks is a work in progess. I created this because I wanted to use browserSync however with all of the nice features baked into the T3 Framework for some reason this is left out or at least I didn't find it. For now this is all I needed to get started with BrowserSync and the current T3 Framework and T3 Blank Bootstrap 3 Template. Requires environment running node >= 0.12.
14756d5f0fd1fc9af7fa576e3cbb6fabf20e2fbf
[ "JavaScript", "Markdown" ]
2
JavaScript
cmocha/joomla-t3-template-gulp-tasks
4ab27eee377ef01d715e2b39e693c8fbc9a4ad8d
34f929f9f53b1f11be330636b50221cca262123e
refs/heads/master
<repo_name>yafimsva/teamMac<file_sep>/classes/student.php <?php /** * Created by PhpStorm. * User: Brandon * Date: 4/26/2019 * Time: 2:04 PM */ // class Student // { // } <file_sep>/index.php <?php /* * <NAME> * April 23, 2019 * 355/teamMac/index.php */ //Turn on error reporting ini_set('display_errors', 1); error_reporting(E_ALL); //Require autoload require_once('vendor/autoload.php'); require_once('model/database.php'); session_start(); //Create an instance of the Base class $f3 = Base::instance(); //Turn of Fat-Free error reporting $f3->set('DEBUG', 3); $f3->route('GET|POST /home', function ($f3) { if (!isset($_SESSION['teacherLogin'])) { $f3->reroute('/'); } $db = new Database(); $db->connect(); $f3->set("currentDate", date("Y-m-d")); $students = $db->getStudentsByID($_SESSION['classid']); $dates = $db->getDates(); $attendances = $db->viewAttendance($_SESSION['classid']); $mySchedule = $db->getMySchedule($_SESSION['teacherid']); $getHelpers = $db->getHelpersForClass(($_SESSION['classid'])); $f3->set('students', $students); $f3->set('datesArray', $dates); $f3->set('attendances', $attendances); $f3->set('mySchedule', $mySchedule); $f3->set('helpers', $getHelpers); if(isset($_POST['updateAttendance'])) { $db->teacherUpdateAttendanceToAbsent($_SESSION['classid'], $_POST['date']); $classid = $_SESSION['classid']; $date =$_POST['date']; foreach ($_POST['updateAttendance'] as $sid) { $db->teacherUpdateAttendance($_SESSION['classid'], $_POST['date'], $sid); // $taken = $db->checkIfAttedanceTaken($_POST['date'], $sid); // if(sizeof($taken) == 0) // { // $db->takeAttendance($_POST['date'], $sid); // } // else // { // echo("<script>alert('ERROR: Duplicate attendance entires')</script>"); // } } $f3->reroute('home#calendar'); } if (isset($_POST['attendance'])) { $duplicate = false; foreach ($_POST['attendance'] as $sid) { $check = $db->checkIfAttedanceTaken($_POST['date'], $sid); if (sizeof($check) != 0) { $duplicate = true; break; } } if (!$duplicate) { foreach ($students as $student) { $db->takeAttendance($_POST['date'], $student['sid'], 0); } foreach ($_POST['attendance'] as $sid) { $db->updateAttendance($sid, 1, $_POST['date']); // $taken = $db->checkIfAttedanceTaken($_POST['date'], $sid); // if(sizeof($taken) == 0) // { // $db->takeAttendance($_POST['date'], $sid); // } // else // { // echo("<script>alert('ERROR: Duplicate attendance entires')</script>"); // } } $f3->reroute('home'); } else { $f3->reroute('home#calendar'); } } $template = new Template(); echo $template->render('views/index.html'); }); $f3->route('GET|POST /', function ($f3) { $db = new Database(); $db->connect(); if (isset($_SESSION['teacherLogin'])) { $f3->reroute('home'); } else if (isset($_SESSION['adminLogin'])) { $f3->reroute('admin'); } if (isset($_POST['username'], $_POST['password'])) { if (strtolower($_POST['username']) == "admin" && $_POST['password'] == "<PASSWORD>") { $_SESSION['adminLogin'] = true; $f3->reroute('admin'); } $usernameExists = $db->usernameExists($_POST['username']); $_SESSION['username'] = $_POST['username']; $_SESSION['password'] = $_POST['<PASSWORD>']; if($_POST['username'] == "admin") { $usernameExists = true; } if($usernameExists) { $results = $db->checkLogin($_POST['username'], $_POST['password']); if($_POST['password'] == "<PASSWORD>") { $f3->reroute('admin'); } if (isset($results['teacherid'])) { $_SESSION['teacherLogin'] = true; $_SESSION['teacherid'] = $results['teacherid']; $_SESSION['name'] = $results['name']; $_SESSION['username'] = $results['username']; $_SESSION['classid'] = $results['classid']; $_SESSION['class'] = $results['className']; $_SESSION['daysLeft'] = $results['daysLeft']; $f3->reroute('home'); } else { $_SESSION['usernameError'] = "valid"; $_SESSION['loginError'] = "invalid"; $f3->reroute('/'); } } else { $_SESSION['loginError'] = "valid"; $_SESSION['usernameError'] = "invalid"; $f3->reroute('/'); } } $template = new Template(); echo $template->render('views/login.html'); }); $f3->route('GET|POST /admin', function ($f3) { if (!isset($_SESSION['adminLogin'])) { $f3->reroute('/'); } $db = new Database(); $db->connect(); $first_day_this_month = date('Y-m-01'); $this_month = date('m'); $last_day_next_month = date('Y-m-t', strtotime(" +1 months")); $next_month = date('m', strtotime(" +1 months")); $this_month_name = date("F", mktime(0, 0, 0, $this_month, 10)); $next_month_name = date("F", mktime(0, 0, 0, $next_month, 10)); $datesForTeachers = $db->getDatesForTeachers($first_day_this_month, $last_day_next_month); $students = $db->getStudents(); $teachers = $db->getTeachers(); $classes = $db->getClasses(); $helpers = $db->getHelpers(); $scheduleDates = $db->getScheduleDates(); $viewSchedules = $db->viewSchedule(); $f3->set('students', $students); $f3->set('teachers', $teachers); $f3->set('classes', $classes); $f3->set('helpers', $helpers); $f3->set('scheduleDates', $scheduleDates); $f3->set('viewSchedules', $viewSchedules); $f3->set('datesForTeachers', $datesForTeachers); $f3->set('this_month_name', $this_month_name); $f3->set('next_month_name', $next_month_name); // post student into database if (isset($_POST['firstName'], $_POST['lastName'], $_POST['email'], $_POST['dob'])) { if ($_POST['studentClass'] != 0) { $firstName = $_POST['firstName']; $lastName = $_POST['lastName']; $email = $_POST['email']; $dob = $_POST['dob']; $studentClass = $_POST['studentClass']; $db->insertStudent($firstName, $lastName, $dob, $email, $studentClass); $f3->reroute('admin#students'); } else { $f3->set("errors['studentClass']", "You did not pick a class for your student, student was not added"); } } // post teacher into database if (isset($_POST['teacherName'], $_POST['teacherUsername'], $_POST['password'], $_POST['confirmPassword'], $_POST['teacherClass'])) { if ($_POST['password'] == $_POST['confirmPassword']) { if ($_POST['teacherClass'] != 0) { if ($_POST['endDate'] != '') { $teacherEndDate = $_POST['endDate']; } else { $teacherEndDate = NULL; } $teacherName = $_POST['teacherName']; $teacherUsername = $_POST['teacherUsername']; $teacherPassword = ($_POST['password']); $teacherClass = $_POST['teacherClass']; $db->insertTeacher($teacherName, $teacherUsername, $teacherPassword, $teacherClass, $teacherEndDate); $f3->reroute('admin#teachers'); } else { $f3->set("errors['teacherClass']", "You did not pick a class for your teacher, teacher was not added"); } } else { $f3->set("errors['nomatch']", "Passwords did not match, teacher was not added"); } } //post classes into database if ($_POST['className']) { $db->insertClass($_POST['className']); $f3->reroute('admin#classes'); } // post student into database if (isset($_POST['updateFirstName'], $_POST['updateLastName'], $_POST['updateEmail'], $_POST['updateDob'], $_POST['updateStudentClass'])) { $updateFirstName = $_POST['updateFirstName']; $updateLastName = $_POST['updateLastName']; $updateEmail = $_POST['updateEmail']; $updateDob = $_POST['updateDob']; $updateStudentClass = $_POST['updateStudentClass']; $sid = $_POST['sid']; $db->updateStudent($sid, $updateFirstName, $updateLastName, $updateDob, $updateEmail, $updateStudentClass); $f3->reroute('admin#students'); } //deletes a student if (isset($_POST['deleteStudent'])) { $db->deleteStudent($_POST['deleteStudent']); $f3->reroute('admin#students'); } //updates a class name if (isset($_POST['updateClassName'], $_POST['updateClassNameID'])) { $newClassName = $_POST['updateClassName']; $updateClassNameID = $_POST['updateClassNameID']; $db->updateClass($newClassName, $updateClassNameID); $f3->reroute('admin#classes'); } //updates a teacher if (isset($_POST['updateTeacherName'], $_POST['updateTeacherUsername'])) { if ($_POST['updatePassword'] == $_POST['updateConfirmPassword']) { if ($_POST['endDateUpdate'] != '') { $updateTeacherEndDate = $_POST['endDateUpdate']; } else { $updateTeacherEndDate = NULL; } $updateTeacherName = $_POST['updateTeacherName']; $updateTeacherUsername = $_POST['updateTeacherUsername']; $updatePassword = $_POST['updatePassword']; $updateTeacherClass = $_POST['updateTeacherClass']; $updateTeacherId = $_POST['teacherid']; $db->updateTeacher($updateTeacherId, $updateTeacherName, $updateTeacherUsername, $updatePassword, $updateTeacherClass, $updateTeacherEndDate); if (isset($_POST['onStudentsPage'])) { $f3->reroute('admin#students'); } else { $f3->reroute('admin#teachers'); } } else { $f3->set("errors['updateNoMatch']", "Passwords did not match, teacher was not updated"); } } //deletes a student if (isset($_POST['deleteTeacher'])) { $db->deleteTeacher($_POST['deleteTeacher']); if (isset($_POST['onStudentsPage'])) { $f3->reroute('admin#students'); } else { $f3->reroute('admin#teachers'); } } //insert a helper if (isset($_POST['helperName'], $_POST['helperClass'])) { if ($_POST['helperClass'] != 0) { $db->insertHelper($_POST['helperName'], $_POST['helperClass']); if (isset($_POST['onStudentsPage'])) { $f3->reroute('admin#students'); } else { $f3->reroute('admin#teachers'); } } else { $f3->set("errors['noClassHelper']", "You did not pick a class for your helper, helper was not added"); } } //updates a helper if (isset($_POST['updateHelperName'], $_POST['updateHelperClass'])) { $updateHelperName = $_POST['updateHelperName']; $updateHelperClass = $_POST['updateHelperClass']; $helperid = $_POST['helperid']; $db->updateHelper($updateHelperName, $updateHelperClass, $helperid); if (isset($_POST['onStudentsPage'])) { $f3->reroute('admin#students'); } else { $f3->reroute('admin#teachers'); } } //deletes a helper if (isset($_POST['deleteHelper'])) { $db->deleteHelper($_POST['deleteHelper']); if (isset($_POST['onStudentsPage'])) { $f3->reroute('admin#students'); } else { $f3->reroute('admin#teachers'); } } //Set schedule if (isset($_POST['schedule'])) { $duplicate = false; foreach ($_POST['schedule'] as $teacherid) { $check = $db->checkIfScheduleSet($_POST['scheduleDate'], $teacherid); if (sizeof($check) != 0) { $duplicate = true; break; } } if (!$duplicate) { foreach ($teachers as $teacher) { $db->setSchedule($_POST['scheduleDate'], $teacher['teacherid'], 0); } foreach ($_POST['schedule'] as $teacherid) { $db->updateSchedule($_POST['scheduleDate'], $teacherid, 1); } $f3->reroute('admin#schedule'); } else { $f3->reroute('admin#schedule'); } } //delete schedule for one date if (isset($_POST['deleteSchedule'])) { $db->deleteScheduleForOneDate($_POST['deleteSchedule']); $f3->reroute('admin#schedule'); } $template = new Template(); echo $template->render('views/admin.html'); }); $f3->route('GET|POST /upload', function($f3) { $target_dir = $_POST['location'] . '/'; $currentLocation = str_replace(' ', '%20', $target_dir); $currentLocation = str_replace('/', '%2F', $currentLocation); $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION)); if(isset($_POST['submit'])) { // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats // if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" // && $imageFileType != "gif" ) { // echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; // $uploadOk = 0; // } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { $f3->reroute('admin#files'); // $f3->reroute('admin#files' . $currentLocation); } else { echo "<h1>SORRY</h1>"; } } } }); $f3->route('GET|POST /add_directory', function ($f3) { $target_dir = $_POST['location'] . '/'; $currentLocation = str_replace(' ', '%20', $target_dir); $currentLocation = str_replace('/', '%2F', $currentLocation); mkdir($target_dir . $_POST['folder_name']); $f3->reroute('admin#files'); // $f3->reroute('admin#' . $currentLocation); }); $f3->route('GET|POST /delete/files/*', function ($f3, $params) { $dir = 'files/' . $params['*']; if(is_file($dir)) { unlink($dir); } else { $it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS); $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST); foreach($files as $file) { if ($file->isDir()){ rmdir($file->getRealPath()); } else { unlink($file->getRealPath()); } } rmdir($dir); } $f3->reroute('admin#files'); }); $f3->route('GET|POST /logout', function ($f3) { session_destroy(); $f3->reroute('/'); $template = new Template(); echo $template->reroute('admin#files'); }); //Run fat free $f3->run();<file_sep>/sql/attendance.sql -- phpMyAdmin SQL Dump -- version 4.8.3 -- https://www.phpmyadmin.net/ -- -- Host: localhost:3306 -- Generation Time: May 09, 2019 at 01:29 PM -- Server version: 10.1.40-MariaDB -- PHP Version: 7.2.7 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `yvainilo_grc` -- -- -------------------------------------------------------- -- -- Table structure for table `attendance` -- CREATE TABLE `attendance` ( `date` date NOT NULL, `sid` int(255) NOT NULL, `present` tinyint(1) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `attendance` -- INSERT INTO `attendance` (`date`, `sid`, `present`) VALUES ('2019-05-08', 1, 1), ('2019-05-08', 2, 1), ('2019-05-08', 3, 1), ('2019-05-08', 4, 1), ('2019-05-08', 5, 1), ('2019-05-08', 6, 0), ('2019-05-08', 7, 0), ('2019-05-08', 10, 1), ('2019-05-09', 1, 1), ('2019-05-09', 2, 1), ('2019-05-09', 3, 1), ('2019-05-09', 4, 1), ('2019-05-09', 5, 0), ('2019-05-09', 6, 0), ('2019-05-09', 7, 0), ('2019-05-09', 10, 0), ('2019-05-09', 11, 0), ('2019-05-09', 12, 0), ('2019-05-08', 11, 1), ('2019-05-08', 12, 0); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/model/database.php <?php if ($_SERVER['USER'] == 'yvainilo') { require_once('/home/yvainilo/config.php'); } else if ($_SERVER['USER'] == 'bskargre') { require_once '/home/bskargre/config.php'; } else if ($_SERVER['USER'] == 'nalexand') { require_once '/home/nalexand/config.php'; } else if ($_SERVER['USER'] == 'dkovalev') { require_once '/home/dkovalev/config.php'; } /** * Class Database database class to insert and get information */ class Database { public function connect() { try { //instantiate a database object $GLOBALS['dbh'] = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD); } catch (PDOException $e) { echo $e->getMessage(); } } function insertStudent($first, $last, $dob, $parents_email, $studentClass) { global $dbh; $sql = "INSERT INTO students (first, last, dob, parents_email, classid) VALUES(:fname, :lname, :dob, :parents_email, :classid);"; $statement = $dbh->prepare($sql); $statement->bindValue(':fname', $first, PDO::PARAM_STR); $statement->bindValue(':lname', $last, PDO::PARAM_STR); $statement->bindValue(':dob', $dob, PDO::PARAM_STR); $statement->bindValue(':parents_email', $parents_email, PDO::PARAM_STR); $statement->bindValue(':classid', $studentClass, PDO::PARAM_INT); $statement->execute(); $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } } public function getStudents() { global $dbh; $sql = "SELECT students.*, classes.className FROM students INNER JOIN classes ON students.classid = classes.classid ORDER BY classid ASC, last ASC"; $statement = $dbh->prepare($sql); $statement->execute(); $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } $results = $statement->fetchAll(PDO::FETCH_ASSOC); // // $posts = array(); // // foreach($results as $result) { // $sid = $result['sid']; // $first = $result['first']; // $last = $result['last']; // } return $results; } public function getStudentsByID($classid) { global $dbh; $sql = "SELECT * FROM `students` WHERE classid = :classid ORDER BY last ASC;"; $statement = $dbh->prepare($sql); $statement->bindValue(':classid', $classid, PDO::PARAM_STR); $statement->execute(); $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } $results = $statement->fetchAll(PDO::FETCH_ASSOC); return $results; } function takeAttendance($date, $sid, $present) { global $dbh; $sql = "INSERT INTO attendance (date, sid, present) VALUES(:date, :sid, :present);"; $statement = $dbh->prepare($sql); $statement->bindValue(':date', $date, PDO::PARAM_STR); $statement->bindValue(':sid', $sid, PDO::PARAM_STR); $statement->bindValue(':present', $present, PDO::PARAM_STR); $statement->execute(); $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } } function teacherUpdateAttendanceToAbsent($classid, $date) { global $dbh; $sql = "UPDATE attendance INNER JOIN students ON students.sid = attendance.sid SET present = 0 WHERE students.classid = :classid AND attendance.date = :date;"; $statement = $dbh->prepare($sql); $statement->bindValue(':classid', $classid, PDO::PARAM_STR); $statement->bindValue(':date', $date, PDO::PARAM_STR); $statement->execute(); $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } } function teacherUpdateAttendance($classid, $date, $sid) { global $dbh; $sql = "UPDATE attendance INNER JOIN students ON students.sid = attendance.sid SET present = 1 WHERE students.classid = :classid AND attendance.date = :date AND attendance.sid = :sid;"; $statement = $dbh->prepare($sql); $statement->bindValue(':classid', $classid, PDO::PARAM_STR); $statement->bindValue(':date', $date, PDO::PARAM_STR); $statement->bindValue(':sid', $sid, PDO::PARAM_STR); $statement->execute(); $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } } function updateAttendance($sid, $present, $date) { global $dbh; $sql = "UPDATE attendance SET present = :present WHERE sid = :sid AND date = :date;"; $statement = $dbh->prepare($sql); $statement->bindValue(':date', $date, PDO::PARAM_STR); $statement->bindValue(':sid', $sid, PDO::PARAM_STR); $statement->bindValue(':present', $present, PDO::PARAM_STR); $statement->execute(); $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } } public function viewAttendance($classid) { global $dbh; $sql = "SELECT students.first, students.last, attendance.date, attendance.sid, attendance.present, classes.classid FROM students INNER JOIN attendance ON students.sid = attendance.sid INNER JOIN classes ON students.classid = classes.classid WHERE students.classid = :classid;"; $statement = $dbh->prepare($sql); $statement->bindValue(':classid', $classid, PDO::PARAM_STR); $statement->execute(); $results = $statement->fetchAll(PDO::FETCH_ASSOC); return $results; } public function viewSchedule() { global $dbh; $sql = "SELECT teachers.name, schedule.date, schedule.teacherid, schedule.scheduled, classes.classid FROM teachers INNER JOIN schedule ON teachers.teacherid = schedule.teacherid INNER JOIN classes ON teachers.classid = classes.classid ORDER by name ASC;"; $statement = $dbh->prepare($sql); $statement->execute(); $results = $statement->fetchAll(PDO::FETCH_ASSOC); return $results; } public function getAttendanceCount($date, $sid) { global $dbh; $sql = "SELECT date, sid FROM attendance WHERE date = :date AND sid = :sid"; $statement = $dbh->prepare($sql); $statement->bindValue(':date', $date, PDO::PARAM_STR); $statement->bindValue(':sid', $sid, PDO::PARAM_STR); // $statement->bindValue(':present', $present, PDO::PARAM_STR); $statement->execute(); $results = $statement->rowCount(); return $results; } public function getDates() { global $dbh; $sql = "SELECT DISTINCT date, DATE_FORMAT(date,'%b %d, %Y') as niceDate FROM attendance ORDER BY date DESC"; $statement = $dbh->prepare($sql); $statement->execute(); $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } $results = $statement->fetchAll(PDO::FETCH_ASSOC); return $results; } public function getDatesForTeachers($start, $end) { global $dbh; $sql = "SELECT *, DATE_FORMAT(date,'%b %d, %Y') as niceDate, DATE_FORMAT(date,'%a') as dayName, DATE_FORMAT(date,'%M') as monthName from (select adddate('1970-01-01',t4*10000 + t3*1000 + t2*100 + t1*10 + t0) date from (select 0 t0 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0, (select 0 t1 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1, (select 0 t2 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2, (select 0 t3 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3, (select 0 t4 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v where date between :start and :end"; $statement = $dbh->prepare($sql); $statement->bindValue(':start', $start, PDO::PARAM_STR); $statement->bindValue(':end', $end, PDO::PARAM_STR); $statement->execute(); $results = $statement->fetchAll(PDO::FETCH_ASSOC); return $results; } public function setSchedule($date, $teacherid, $scheduled) { global $dbh; $sql = "INSERT INTO schedule (date, teacherid, scheduled) VALUES (:date, :teacherid, :scheduled);"; $statement = $dbh->prepare($sql); $statement->bindValue(':date', $date, PDO::PARAM_STR); $statement->bindValue(':teacherid', $teacherid, PDO::PARAM_STR); $statement->bindValue(':scheduled', $scheduled, PDO::PARAM_STR); $statement->execute(); } public function updateSchedule($date, $teacherid, $scheduled) { global $dbh; $sql = "UPDATE schedule SET scheduled = :scheduled WHERE teacherid = :teacherid AND date = :date;"; $statement = $dbh->prepare($sql); $statement->bindValue(':date', $date, PDO::PARAM_STR); $statement->bindValue(':teacherid', $teacherid, PDO::PARAM_STR); $statement->bindValue(':scheduled', $scheduled, PDO::PARAM_STR); $statement->execute(); } function insertTeacher($teacherName, $teacherUsername, $teacherPassword, $teacherClass, $endDate) { global $dbh; $sql = "INSERT INTO teachers (name, username, password, classid, endDate) VALUES(:name, :username, :password, :classid, :endDate);"; $statement = $dbh->prepare($sql); $statement->bindValue(':name', $teacherName, PDO::PARAM_STR); $statement->bindValue(':username', $teacherUsername, PDO::PARAM_STR); $statement->bindValue(':password', $<PASSWORD>, PDO::PARAM_STR); $statement->bindValue(':classid', $teacherClass, PDO::PARAM_STR); $statement->bindValue(':endDate', $endDate, PDO::PARAM_STR); $statement->execute(); $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } } function insertClass($className) { global $dbh; $sql = "INSERT INTO classes (className) VALUES(:className);"; $statement = $dbh->prepare($sql); $statement->bindValue(':className', $className, PDO::PARAM_STR); $statement->execute(); $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } } function insertHelper($helperName, $classid) { global $dbh; $sql = "INSERT INTO helpers(name, classid) VALUES (:helperName, :classid)"; $statement = $dbh->prepare($sql); $statement->bindValue(':helperName', $helperName, PDO::PARAM_STR); $statement->bindValue(':classid', $classid, PDO::PARAM_STR); $statement->execute(); $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } } public function getHelpers() { global $dbh; $sql = "SELECT helpers.*, classes.className FROM helpers INNER JOIN classes ON helpers.classid = classes.classid ORDER BY name ASC;"; $statement = $dbh->prepare($sql); $statement->execute(); $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } $results = $statement->fetchAll(PDO::FETCH_ASSOC); return $results; } public function getHelpersForClass($classid) { global $dbh; $sql = "SELECT helpers.*, classes.className FROM helpers INNER JOIN classes ON helpers.classid = classes.classid WHERE helpers.classid = :classid ORDER BY name ASC;"; $statement = $dbh->prepare($sql); $statement->bindValue(':classid', $classid, PDO::PARAM_STR); $statement->execute(); $results = $statement->fetchAll(PDO::FETCH_ASSOC); return $results; } public function getTeachers() { global $dbh; $sql = "SELECT DATEDIFF(teachers.endDate ,CURRENT_DATE()) daysLeft, teachers.*, classes.className FROM teachers INNER JOIN classes ON teachers.classid = classes.classid ORDER BY name ASC"; $statement = $dbh->prepare($sql); $statement->execute(); $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } $results = $statement->fetchAll(PDO::FETCH_ASSOC); return $results; } public function getClasses() { global $dbh; $sql = "SELECT * FROM classes SORT ORDER BY className ASC"; $statement = $dbh->prepare($sql); $statement->execute(); $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } $results = $statement->fetchAll(PDO::FETCH_ASSOC); return $results; } function updateStudent($sid, $first, $last, $dob, $parents_email, $studentClass) { global $dbh; $sql = "UPDATE students SET first = :fname, last = :lname, dob = :dob, parents_email = :parents_email, classid = :classid WHERE sid = :sid"; $statement = $dbh->prepare($sql); $statement->bindValue(':fname', $first, PDO::PARAM_STR); $statement->bindValue(':lname', $last, PDO::PARAM_STR); $statement->bindValue(':dob', $dob, PDO::PARAM_STR); $statement->bindValue(':parents_email', $parents_email, PDO::PARAM_STR); $statement->bindValue(':classid', $studentClass, PDO::PARAM_INT); $statement->bindValue(':sid', $sid, PDO::PARAM_INT); $statement->execute(); $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } } function updateTeacher($teacherid, $name, $username, $password, $classid, $endDate) { global $dbh; $sql = "UPDATE teachers SET name = :name, username = :username, password = :<PASSWORD>, classid = :classid, endDate = :endDate WHERE teacherid = :teacherid"; $statement = $dbh->prepare($sql); $statement->bindValue(':teacherid', $teacherid, PDO::PARAM_STR); $statement->bindValue(':name', $name, PDO::PARAM_STR); $statement->bindValue(':username', $username, PDO::PARAM_STR); $statement->bindValue(':password', $password, PDO::PARAM_STR); $statement->bindValue(':endDate', $endDate, PDO::PARAM_STR); $statement->bindValue(':classid', $classid, PDO::PARAM_INT); $statement->execute(); $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } } function updateClass($className, $classid) { global $dbh; $sql = "UPDATE classes SET className = :className WHERE classid = :classid"; $statement = $dbh->prepare($sql); $statement->bindValue(':className', $className, PDO::PARAM_STR); $statement->bindValue(':classid', $classid, PDO::PARAM_STR); $statement->execute(); $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } } function updateHelper($name, $classid, $helperid) { global $dbh; $sql = "UPDATE helpers SET name = :name, classid = :classid WHERE helperid = :helperid"; $statement = $dbh->prepare($sql); $statement->bindValue(':name', $name, PDO::PARAM_STR); $statement->bindValue(':classid', $classid, PDO::PARAM_STR); $statement->bindValue(':helperid', $helperid, PDO::PARAM_STR); $statement->execute(); $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } } function deleteHelper($helperid) { global $dbh; $sql = "DELETE FROM helpers WHERE helperid = :helperid"; $statement = $dbh->prepare($sql); $statement->bindValue(':helperid', $helperid, PDO::PARAM_STR); $statement->execute(); $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } } function deleteStudent($sid) { global $dbh; $sql = "DELETE FROM students WHERE sid = :sid"; $statement = $dbh->prepare($sql); $statement->bindValue(':sid', $sid, PDO::PARAM_INT); $statement->execute(); $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } } function deleteTeacher($teacherid) { global $dbh; $sql = "DELETE FROM teachers WHERE teacherid = :teacherid"; $statement = $dbh->prepare($sql); $statement->bindValue(':teacherid', $teacherid, PDO::PARAM_INT); $statement->execute(); $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } } public function usernameExists($username) { global $dbh; $sql = "SELECT * FROM `teachers` WHERE username = :username"; $statement = $dbh->prepare($sql); $statement->bindValue(':username', $username, PDO::PARAM_STR); $statement->execute(); $results = $statement->fetchAll(PDO::FETCH_ASSOC); if(sizeof($results) > 0) { return true; } else { return false; } $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } } public function checkLogin($username, $password) { global $dbh; $sql = "SELECT DATEDIFF(teachers.endDate ,CURRENT_DATE()) daysLeft, teachers.*, classes.className FROM teachers INNER JOIN classes ON teachers.classid = classes.classid WHERE username = :username AND password = :password;"; $statement = $dbh->prepare($sql); $statement->bindValue(':username', $username, PDO::PARAM_STR); $statement->bindValue(':password', $password, PDO::PARAM_STR); $statement->execute(); $results = $statement->fetch(PDO::FETCH_ASSOC); $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } return $results; } public function checkIfAttedanceTaken($date, $sid) { global $dbh; $sql = "SELECT * FROM attendance WHERE date = :date AND sid = :sid"; $statement = $dbh->prepare($sql); $statement->bindValue(':date', $date, PDO::PARAM_STR); $statement->bindValue(':sid', $sid, PDO::PARAM_STR); $statement->execute(); $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } $results = $statement->fetchAll(PDO::FETCH_ASSOC); return $results; } public function checkIfScheduleSet($date, $teacherid) { global $dbh; $sql = "SELECT * FROM schedule WHERE date = :date AND teacherid = :teacherid"; $statement = $dbh->prepare($sql); $statement->bindValue(':date', $date, PDO::PARAM_STR); $statement->bindValue(':teacherid', $teacherid, PDO::PARAM_STR); $statement->execute(); $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } $results = $statement->fetchAll(PDO::FETCH_ASSOC); return $results; } public function getMySchedule($teacherid) { global $dbh; $sql = "SELECT *, DATE_FORMAT(date,'%b %d, %Y') as niceDate FROM schedule where teacherid = :teacherid ORDER BY date DESC LIMIT 15"; $statement = $dbh->prepare($sql); $statement->bindValue(':teacherid', $teacherid, PDO::PARAM_STR); $statement->execute(); $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } $results = $statement->fetchAll(PDO::FETCH_ASSOC); return $results; } public function deleteScheduleForOneDate($date) { global $dbh; $sql = "DELETE FROM schedule WHERE date = :date;"; $statement = $dbh->prepare($sql); $statement->bindValue(':date', $date, PDO::PARAM_STR); $statement->execute(); } public function getScheduleDates() { global $dbh; $sql = "SELECT DISTINCT date FROM schedule ORDER BY date DESC"; $statement = $dbh->prepare($sql); $statement->execute(); $arr = $statement->errorInfo(); if (isset($arr[2])) { print_r($arr[2]); } $results = $statement->fetchAll(PDO::FETCH_ASSOC); return $results; } } <file_sep>/sql/students.sql -- phpMyAdmin SQL Dump -- version 4.8.3 -- https://www.phpmyadmin.net/ -- -- Host: localhost:3306 -- Generation Time: May 09, 2019 at 01:27 PM -- Server version: 10.1.40-MariaDB -- PHP Version: 7.2.7 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `yvainilo_grc` -- -- -------------------------------------------------------- -- -- Table structure for table `students` -- CREATE TABLE `students` ( `sid` int(11) NOT NULL, `first` varchar(50) NOT NULL, `last` varchar(50) NOT NULL, `dob` date NOT NULL, `parents_email` varchar(50) NOT NULL, `classid` int(11) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `students` -- INSERT INTO `students` (`sid`, `first`, `last`, `dob`, `parents_email`, `classid`) VALUES (1, 'YafimCH', 'Vainilovich', '2019-01-01', '<EMAIL>', 1), (2, 'David', 'koval', '2000-01-01', '<EMAIL>', 2), (3, 'Brandon', 'Scar', '2019-05-08', '<EMAIL>', 3), (4, 'Nic', 'Alex', '2019-05-01', '<EMAIL>', 4), (5, 'Alex', 'Bykovich', '2019-05-12', '<EMAIL>', 5), (7, 'Peter', 'Pan', '1999-03-22', '<EMAIL>', 2), (11, 'check', 'check', '9999-03-22', '<EMAIL>', 5), (13, 'Someone', 'Unknown', '2014-03-11', '<EMAIL>', 4), (14, 'Arthur ', 'Bek', '1999-03-22', '<EMAIL>', 2); -- -- Indexes for dumped tables -- -- -- Indexes for table `students` -- ALTER TABLE `students` ADD PRIMARY KEY (`sid`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `students` -- ALTER TABLE `students` MODIFY `sid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/tdd/databaseTest.php <?php /** * Created by PhpStorm. * User: Brandon * Date: 5/14/2019 * Time: 1:44 PM */ use PHPUnit\Framework\TestCase as TestCase; class DatabaseTest extends TestCase { private $database; public function setUp() { $this->database = new Database(); $this->database->connect(); } public function tearDown() { unset($this->database); } public function testDatabaseGetStudents() { $entries = $this->database->getStudents(); $this->assertInternalType('array', $entries); $this->assertTrue(count($entries) > 0); } }<file_sep>/sql/teachers.sql -- phpMyAdmin SQL Dump -- version 4.8.3 -- https://www.phpmyadmin.net/ -- -- Host: localhost:3306 -- Generation Time: May 25, 2019 at 06:21 PM -- Server version: 10.1.40-MariaDB -- PHP Version: 7.2.7 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `yvainilo_grc` -- -- -------------------------------------------------------- -- -- Table structure for table `teachers` -- CREATE TABLE `teachers` ( `teacherid` int(11) NOT NULL, `name` varchar(50) NOT NULL, `username` varchar(50) NOT NULL, `password` varchar(80) NOT NULL, `classid` int(11) NOT NULL, `endDate` date DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `teachers` -- INSERT INTO `teachers` (`teacherid`, `name`, `username`, `password`, `classid`, `endDate`) VALUES (3, '<NAME>', 'yafimsva', '123', 1, '2019-08-08'), (6, '<NAME>', 'sasha', '123', 2, '0000-00-00'), (7, 'Angela', 'agie', '123', 4, NULL), (8, '<NAME>', 'alina', '123', 3, '0000-00-00'), (31, 'Koval', 'koval1', '123', 3, '2019-05-28'), (32, 'KOVAL2', 'koval2', '123', 4, NULL), (29, 'koval30', 'koval30', '123', 3, NULL), (33, 'Koval4', 'koval4', '123', 2, '2019-05-17'); -- -- Indexes for dumped tables -- -- -- Indexes for table `teachers` -- ALTER TABLE `teachers` ADD PRIMARY KEY (`teacherid`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `teachers` -- ALTER TABLE `teachers` MODIFY `teacherid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=34; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/sql/schedule.sql -- phpMyAdmin SQL Dump -- version 4.8.3 -- https://www.phpmyadmin.net/ -- -- Host: localhost:3306 -- Generation Time: Jun 01, 2019 at 03:04 AM -- Server version: 10.1.40-MariaDB -- PHP Version: 7.2.7 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `yvainilo_grc` -- -- -------------------------------------------------------- -- -- Table structure for table `schedule` -- CREATE TABLE `schedule` ( `date` date NOT NULL, `teacherid` int(11) NOT NULL, `scheduled` int(11) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `schedule` -- INSERT INTO `schedule` (`date`, `teacherid`, `scheduled`) VALUES ('2019-06-02', 8, 1), ('2019-06-02', 7, 1), ('2019-06-02', 32, 1), ('2019-06-02', 33, 0), ('2019-06-02', 6, 0), ('2019-06-02', 3, 0), ('2019-06-09', 8, 1), ('2019-06-09', 7, 1), ('2019-06-09', 32, 1), ('2019-06-09', 33, 1), ('2019-06-09', 6, 1), ('2019-06-09', 3, 0), ('2019-07-07', 8, 1), ('2019-07-07', 7, 1), ('2019-07-07', 32, 0), ('2019-07-07', 33, 1), ('2019-07-07', 6, 0), ('2019-07-07', 3, 1), ('2019-06-30', 8, 1), ('2019-06-30', 7, 0), ('2019-06-30', 32, 1), ('2019-06-30', 33, 0), ('2019-06-30', 6, 1), ('2019-06-30', 3, 1), ('2019-07-21', 8, 1), ('2019-07-21', 7, 1), ('2019-07-21', 32, 0), ('2019-07-21', 33, 1), ('2019-07-21', 6, 0), ('2019-07-21', 3, 1), ('2019-06-16', 8, 1), ('2019-06-16', 7, 0), ('2019-06-16', 32, 0), ('2019-06-16', 33, 1), ('2019-06-16', 6, 1), ('2019-06-16', 3, 0), ('2019-06-23', 8, 1), ('2019-06-23', 7, 1), ('2019-06-23', 32, 0), ('2019-06-23', 33, 0), ('2019-06-23', 6, 1), ('2019-06-23', 3, 1), ('2019-07-14', 8, 0), ('2019-07-14', 7, 1), ('2019-07-14', 32, 0), ('2019-07-14', 33, 1), ('2019-07-14', 6, 1), ('2019-07-14', 3, 0), ('2019-07-28', 8, 0), ('2019-07-28', 7, 1), ('2019-07-28', 32, 0), ('2019-07-28', 33, 1), ('2019-07-28', 6, 1), ('2019-07-28', 3, 0); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
c5265d2abc752c68a5537bda6a1ec6641f7fa8ad
[ "SQL", "PHP" ]
8
PHP
yafimsva/teamMac
eb29756ece129c3cc8832e25dbccc1329a6bd9cd
89204e7c83ca8c1f110ee15879e19f4a9803ea60
refs/heads/master
<file_sep> class Genetics { constructor(popSz, chromoSz, minGene, maxGene, crossRate, mutRate, anomRate) { this.popSz = popSz; this.chromoSz = chromoSz; this.minGene = minGene; this.maxGene = maxGene; this.crossRate = crossRate; this.mutRate = mutRate; this.anomRate = anomRate; this.fitnesses = []; this.population = this.newPopulation(); this.maxFit = 0; this.generation = 1; this.muts = 0; this.crosses = 0; this.anoms = 0; this.mutsTotal = 0; this.crossesTotal = 0; this.anomsTotal = 0; this.mutsRate = 0.0; this.crossesRate = 0.0; this.anomsRate = 0.0; } newPopulation() { var pop = []; for(var i = 0; i < this.popSz; ++i) { pop[i] = this.newChromosome(); } return pop; } newChromosome() { var chromo = []; for(var i = 0; i < this.chromoSz; ++i) { chromo[i] = this.newGene(); } return chromo; } newGene() { var x = random(this.minGene, this.maxGene); var y = random(this.minGene, this.maxGene); var force = createVector(x, y); return force; } repopulate() { var newPop = []; this.muts = 0; this.crosses = 0; this.anoms = 0; this.mutsTotal = 0; this.crossesTotal = 0; this.anomsTotal = 0; // Calculate max fitness this.maxFit = 0; for(var i = 0; i < this.fitnesses.length; ++i) { if(this.fitnesses[i] > this.maxFit) this.maxFit = this.fitnesses[i]; } if(this.maxFit <= 0) return; while(newPop.length < this.population.length) { var prob = random(0, 1); this.anomsTotal++; if(prob < this.anomRate) { this.anoms++; var c1 = this.newChromosome(); var c2 = this.newChromosome(); } else { var c1 = this.choose(); var c2 = this.choose(); this.crossover(c1, c2); this.mutate(c1); this.mutate(c2); } newPop.push(c1); newPop.push(c2); } this.population = newPop; this.generation++; this.mutsRate = (this.muts / this.mutsTotal) * 100; this.crossesRate = (this.crosses / this.crossesTotal) * 100; this.anomsRate = (this.anoms / this.anomsTotal) * 100; } choose() { while(true) { var index = round(random(0, this.popSz - 1)); var prob = random(0, this.maxFit); if(prob < this.fitnesses[index]) return this.population[index].slice(); } } crossover(c1, c2) { var prob = random(0, 1); this.crossesTotal++; if(prob < this.crossRate) { this.crosses++; var crossPoint = round(random(0, this.chromoSz - 1)); for(var i = 0; i < this.chromoSz; ++i) { if(i < crossPoint) c2[i] = c1[i]; else c1[i] = c2[i]; } } } mutate(c) { for(var i = 0; i < this.chromoSz; ++i) { var prob = random(0, 1); this.mutsTotal++; if(prob < this.mutRate) { this.muts++; c[i] = this.newGene(); } } } } <file_sep># Smart Rockets Genetic algorithms simulation in JavaScript using the P5 library. View the simulation at the project's [GitHub Pages site](https://ggolish.github.io/SmartRocketsP5/). ## Sources Inspiration comes from the original [Smart Rockets](http://www.blprnt.com/smartrockets/) project and [<NAME>'s video series](https://www.youtube.com/playlist?list=PLRqwX-V7Uu6bJM3VgzjNV5YxVxUwzALHV) about genetic algorithms. ## Author Written by <NAME>. ## License This project is licensed under the [MIT license](https://github.com/ggolish/SmartRocketsP5/blob/master/LICENSE.md). <file_sep>function rotatePointX(x, y, point, a) { return (x - point.x) * cos(a) - (y - point.y) * sin(a); } function rotatePointY(x, y, point, a) { return (x - point.x) * sin(a) + (y - point.y) * cos(a); } class Boundary { constructor(x, y, w, h, a) { //a *= -(PI / 180); this.center = createVector(x, y); this.vertices = []; this.vertices.push(createVector(rotatePointX(x, y, this.center, a), rotatePointY(x, y, this.center, a))); this.vertices.push(createVector(rotatePointX(x + w, y, this.center, a), rotatePointY(x + w, y, this.center, a))) this.vertices.push(createVector(rotatePointX(x + w, y + h, this.center, a), rotatePointY(x + w, y + h, this.center, a))); this.vertices.push(createVector(rotatePointX(x, y + h, this.center, a), rotatePointY(x, y + h, this.center, a))); this.vertices.map(v => v.add(this.center)); this.reward = 0.1; } show() { fill(255); noStroke(); beginShape(QUADS); for(var i = 0; i < this.vertices.length; ++i) { vertex(this.vertices[i].x, this.vertices[i].y); } endShape(CLOSE); } collidesWith(x, y) { return collidePointPoly(x, y, this.vertices); } } class Target extends Boundary { constructor(x, y, w, h) { super(x, y, w, h, 0); this.reward = 10; } } <file_sep>var canvas; var lifeSpanSlider; var anomsSlider; var crossesSlider; var mutsSlider; var nrockets = 500; var lifeTime; var maxLifeTime; var forceLimit = 0.15; var crossRate = 0.7; var mutRate = 0.01; var anomRate = 0.1; var targetSize = 15; var boundIntersection = 30; var rockets = []; var genetics; var bestRocket = 0; var boundaries = []; var from; function setup() { canvas = createCanvas(800, 600); canvas.parent('canvasDiv'); lifeTime = height; maxLifeTime = 4 * height; lifeSpanSlider = createSlider(10, maxLifeTime, lifeTime, 10); anomsSlider = createSlider(0, 1, anomRate, 0.01); crossesSlider = createSlider(0, 1, crossRate, 0.1); mutsSlider = createSlider(0, 0.5, mutRate, 0.01); lifeSpanSlider.parent('lifeSpanSlider'); anomsSlider.parent('anomsSlider'); crossesSlider.parent('crossesSlider'); mutsSlider.parent('mutsSlider'); genetics = new Genetics(nrockets, maxLifeTime, -forceLimit, forceLimit, crossRate, mutRate, anomRate); newRockets(); boundaries[0] = new Target(width / 2 - 5, height * 0.1, targetSize, targetSize); } function draw() { background(0); for(var i = 0; i < rockets.length; ++i) { rockets[i].update(); for(var j = 0; j < boundaries.length; ++j) { rockets[i].collides(boundaries[j]); } rockets[i].show(rockets[bestRocket].fitness); } for(var i = 0; i < boundaries.length; ++i) { boundaries[i].show(); } if(mouseIsPressed) { stroke(255); line(from.x, from.y, mouseX, mouseY); } calcFitnesses(); displayStatus(); if(frameCount % lifeTime == 0) { lifeTime = lifeSpanSlider.value(); anomRate = genetics.anomRate = anomsSlider.value(); crossRate = genetics.crossRate = crossesSlider.value(); mutRate = genetics.mutRate = mutsSlider.value(); genetics.repopulate(); newRockets(); } } function displayStatus() { fill(255); textFont("Monospace"); text(" Generation: " + genetics.generation, 10, 20); text(" Anomalies: " + genetics.anomsRate.toFixed(2) + "%", 10, 35); text(" Crossovers: " + genetics.crossesRate.toFixed(2) + "%", 10, 50); text(" Mutations: " + genetics.mutsRate.toFixed(2) + "%", 10, 65); text("Frames Left: " + (lifeTime - (frameCount % lifeTime)), 10, 80); } function newRockets() { rockets = [] for(var i = 0; i < nrockets; ++i) rockets.push(new Rocket(width / 2, height - 50, genetics.population[i])) } function calcFitnesses() { genetics.fitnesses = []; var maxFit = 0; for(var i = 0; i < rockets.length; ++i) { if(!rockets[i].crashed && !rockets[i].finished) { var distance = rockets[i].pos.dist(boundaries[0].center); rockets[i].fitness = 1 / distance; if(rockets[i].fitness > maxFit) { maxFit = rockets[i].fitness; bestRocket = i; } } } rockets.map(function(e) { if(!e.crashed && !e.finished) { e.fitness /= maxFit; } }); for(var i = 0; i < rockets.length; ++i) { genetics.fitnesses.push(rockets[i].fitness); } } function keyTyped() { if(key == ' ') { genetics = new Genetics(nrockets, maxLifeTime, -forceLimit, forceLimit, crossRate, mutRate, anomRate); newRockets(); } } function mousePressed() { from = createVector(mouseX, mouseY); } function mouseReleased() { to = createVector(mouseX, mouseY); fromTo = createVector(to.x - from.x, to.y - from.y); d = fromTo.mag(); boundaries.push(new Boundary(from.x, from.y, d, 10, fromTo.heading())); }
0391d0d3f83fcbde8df401be87229525fc538f26
[ "JavaScript", "Markdown" ]
4
JavaScript
ggolish/SmartRocketsP5
3f20625b336905fd878b3bb942dbe0acc0e34e50
ffe1780115be78b9ebc7fbe45c3df417c9760204
refs/heads/master
<repo_name>SaurabhThakre/Ball-EatUp<file_sep>/README.md # Ball_EatUp A Fun to play 2D animated survival intuitive game made with "p5.js" library in Javascript. <img src="./Assets/demo.gif" alt="animated" /> Play Game by using this Link: "https://saurabhthakre.github.io/Ball-EatUp/." <file_sep>/Javascript/sketch.js var c1 = { x: 100, y: 250, diameter: 50, speedx: 5, speedy: 5, flag: 0, flagx: 0 }; var c2 = { x: 200, y: 350, diameter: 90, speedx: 6, speedy: 6, flag: 0, flagx: 0 }; var c3 = { x: 300, y: 450, diameter: 50, speedx: 7, speedy: 7, flag: 0, flagx: 0 }; var c4 = { x: 400, y: 550, diameter: 50, speedx: 8, speedy: 8, flag: 0, flagx: 0 }; var c5 = { x: 500, y: 650, diameter: 90, speedx: 9, speedy: 9, flag: 0, flagx: 0 }; var c6 = { x: 600, y: 150, diameter: 50, speedx: 10, speedy: 10, flag: 0, flagx: 0 }; var c7 = { x: 700, y: 250, diameter: 50, speedx: 7, speedy: 7, flag: 0, flagx: 0 }; var c8 = { x: 800, y: 350, diameter: 90, speedx: 8, speedy: 8, flag: 0, flagx: 0 }; var c9 = { x: 900, y: 450, diameter: 90, speedx: 9, speedy: 9, flag: 0, flagx: 0 }; var c10 = { x: 1000, y: 550, diameter: 50, speedx: 10, speedy: 10, flag: 0, flagx: 0 }; var p1 = { x: 250, y: 250, diameter: 50 }; ////pause variable var pauseStatus = true; var playerdied = 0; var signs = [-1, 1]; var windowx = 1100; var windowy = 660; var timerValue = 0; var foodx = []; var foody = []; var flag_food = 0; var flag_fooddraw = 0; food_distance = 100; let eat; let gameover; let win; var foodCount = 0; var foodCountFlag = 0; var foodAddCount = 0; //start = 0 (game has not started) //start = 1 (game is running) var start = 0; var pauseString = ""; pauseX = mouseX; pauseY = mouseY; ppf = 1; var restart = 1; var stopStatus = 0; var timerClock = 10; // variable list over //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// function reinitializeAll() { c1.x = 100; c1.y = 250; c1.diameter = 50; c1.speedx = 5; c1.speedy = 5; c1.flag = 0; c1.flagx = 0; c2.x = 200; c2.y = 350; c2.diameter = 90; c2.speedx = 6; c2.speedy = 6; c2.flag = 0; c2.flagx = 0; c3.x = 300; c3.y = 450; c3.diameter = 50; c3.speedx = 7; c3.speedy = 7; c3.flag = 0; c3.flagx = 0; c4.x = 400; c4.y = 550; c4.diameter = 50; c4.speedx = 8; c4.speedy = 8; c4.flag = 0; c4.flagx = 0; c5.x = 500; c5.y = 650; c5.diameter = 90; c5.speedx = 9; c5.speedy = 9; c5.flag = 0; c5.flagx = 0; c6.x = 600; c6.y = 150; c6.diameter = 5; c6.speedx = 10; c6.speedy = 10; c6.flag = 0; c6.flagx = 0; c7.x = 700; c7.y = 250; c7.diameter = 50; c7.speedx = 7; c7.speedy = 7; c7.flag = 0; c7.flagx = 0; c8.x = 800; c8.y = 350; c8.diameter = 90; c8.speedx = 8; c8.speedy = 8; c8.flag = 0; c8.flagx = 0; c9.x = 900; c9.y = 450; c9.diameter = 90; c9.speedx = 9; c9.speedy = 9; c9.flag = 0; c9.flagx = 0; c10.x = 1000; c10.y = 550; c10.diameter = 50; c10.speedx = 10; c10.speedy = 10; c10.flag = 0; c10.flagx = 0; p1.x = 250; p1.y = 250; p1.diameter = 50; ////pause variable pauseStatus = true; playerdied = 0; signs = [-1, 1]; windowx = 1100; windowy = 660; timerValue = 0; foodx = []; foody = []; flag_food = 0; flag_fooddraw = 0; food_distance = 100; foodCount = 0; foodCountFlag = 0; foodAddCount = 0; //start = 0 (game has not started) //start = 1 (game is running) start = 0; pauseString = ""; pauseX = mouseX; pauseY = mouseY; ppf = 1; timerClock = 10; pauseString = ""; draw(); } function preload() { eat = loadSound("../Audio/eat_food.mp3"); gameover = loadSound("../Audio/game_over.mp3"); win = loadSound("../Audio/win.mp3"); } // pauseStatus==0 ( game pause) // pauseStatus==1 (game running) ///for puase game function pauseFunction() { pauseStatus = 0; pauseX = mouseX; pauseY = mouseY; } function setup() { var cnv = createCanvas(windowx, windowy); setInterval(timeIt, 1000); var x = 30; var y = (windowHeight - height) / 2; cnv.position(x, y); } var startStatus = -1; var newVar = null; var flagDied = 0; // function displayScorePlayer() { // return timerClock; // } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////// function draw() { if (pauseStatus == 1) { timerClock += 10; console.log(timerClock + " aaaaaaaaaa"); } background(22); noStroke(); if (foodCountFlag == 1 && foodx.length >= foodCount / 1.5) { if (foodAddCount == 0) { var remove = random(foodx.length); foodx.splice(remove, 1); foody.splice(remove, 1); } if (foodAddCount >= 10) { foodAddCount = 0; } else { foodAddCount += 5; } } food(); foodCountFlag = 1; // if (pauseStatus == 1) { enemy(c1, 400, 200, pauseStatus); enemy(c2, 500, 100, pauseStatus); enemy(c3, 600, 300, pauseStatus); enemy(c4, 700, 180, pauseStatus); enemy(c5, 800, 250, pauseStatus); enemy(c6, 450, 220, pauseStatus); enemy(c7, 550, 200, pauseStatus); enemy(c8, 650, 150, pauseStatus); enemy(c9, 750, 230, pauseStatus); enemy(c10, 850, 300, pauseStatus); if (pauseStatus == 1) { player(p1, pauseStatus); ppf = 1; } else { if (ppf == 1) { pauseX = mouseX; pauseY = mouseY; } ppf = 0; fill(0, 0, 255); ellipse(pauseX, pauseY, p1.diameter, p1.diameter); // arc(obj.x, obj.y, smileDiam, smileDiam, startAng, endAng); console.log("v"); console.log(pauseX, pauseY); } playerVsenemy(p1, c1); playerVsenemy(p1, c2); playerVsenemy(p1, c3); playerVsenemy(p1, c4); playerVsenemy(p1, c5); playerVsenemy(p1, c6); playerVsenemy(p1, c7); playerVsenemy(p1, c8); playerVsenemy(p1, c9); playerVsenemy(p1, c10); // last two parameter for enemy are introduced // for randomizing there movement from one another // for best output take select values from specified range // for 2nd parameter between 300 to 1000 // for 3nd parameter between 100 to 300 // } textSize(32); textAlign(CENTER, CENTER); fill(255, 242, 0); text(pauseString, 0, windowy / 2, width); //lose condition if (playerdied == 1) { if (isNaN(timerClock)) { pauseString = "GAME OVER!!!!\n Click to play again\n" + "Your score: " + "950"; playerscore = 950; } else { pauseString = "GAME OVER!!!!\n Click to play again\n" + "Your score: " + timerClock; playerscore = timerClock; } playerdied = 2; } //win condition if ( c1.diameter < 10 && c2.diameter < 10 && c3.diameter < 10 && c4.diameter < 10 && c5.diameter < 10 && c6.diameter < 10 && c7.diameter < 10 && c8.diameter < 10 && c9.diameter < 10 && c10.diameter < 10 ) { if (playerdied != 2) { pauseString = "YOU WIN!!!\n Click to play again\n" + "Your score: " + timerClock; } playerdied = 2; } } // pauseStatus==0 ( game pause) // pauseStatus==1 (game running) function mousePressed() { if (mouseX > 0 && mouseX <= 1100 && mouseY > 0 && mouseY < 650) { if (playerdied == 2) { reinitializeAll(); resetSketch(); } } if (mouseX > 0 && mouseX <= 1100 && mouseY > 0 && mouseY < 650) { if (pauseStatus == 0) { console.log(pauseX, pauseY); if ( mouseX > pauseX - p1.diameter / 2 && mouseX < pauseX + p1.diameter / 2 && mouseY > pauseY - p1.diameter / 2 && mouseY < pauseY + p1.diameter / 2 ) { console.log( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" ); pauseStatus = 1; pauseString = ""; console.log(pauseStatus); } } else if (pauseStatus == 1) { pauseStatus = 0; pauseString = "Game Paused \n Click inside player to play."; pauseX = mouseX; pauseY = mouseX; // ellipse(pauseX, pauseY, obj.diameter, obj.diameter); } } } function player(obj, pauseFlag) { //setInterval(food(), 10000); noStroke(); fill(0, 0, 255); playerMovement(obj, pauseFlag); console.log(mouseX, mouseY); p1.x = mouseX; p1.y = mouseY; eatFood(obj, 1); } function enemy(obj, random1, random2, pauseFlag) { stroke(255); fill(255, 0, 0); ellipse(obj.x, obj.y, obj.diameter, obj.diameter); var startAng = 0.01 * PI; var endAng = 1 * PI; var smileDiam = 0.6 * obj.diameter; fill(255); arc(obj.x, obj.y, smileDiam, smileDiam, startAng, endAng); // line(obj.x-10, obj.y+10,obj.x+20,obj.y+10); // Eyes var offset = 0.5 * obj.diameter; var eyeDiam = 0.3 * obj.diameter; fill(255); ellipse(obj.x - offset, obj.y - offset, eyeDiam, eyeDiam); ellipse(obj.x + offset, obj.y - offset, eyeDiam, eyeDiam); var offset1 = 0.2 * obj.diameter; var eyeDiam1 = 0.2 * obj.diameter; ellipse(obj.x - offset1, obj.y - offset1, eyeDiam1, eyeDiam1); ellipse(obj.x + offset1, obj.y - offset1, eyeDiam1, eyeDiam1); moveRandom(obj, random1, random2, pauseFlag); eatFood(obj, 0); } function playerMovement(obj, pauseFlag) { if (obj.x > windowx - obj.diameter / 2) { obj.x = windowx - obj.diameter / 2; if (pauseFlag == 1) { ellipse(obj.x, mouseY, obj.diameter, obj.diameter); } else { ellipse(pauseX, pauseY, obj.diameter, obj.diameter); } fill(0); var startAng = 0.01 * PI; var endAng = 1 * PI; var smileDiam = 0.6 * obj.diameter; arc(obj.x, mouseY, smileDiam, smileDiam, startAng, endAng); // Eyes var offset = 0.2 * obj.diameter; var eyeDiam = 0.1 * obj.diameter; fill(0); if (pauseFlag == 1) { ellipse(obj.x - offset, mouseY - offset, eyeDiam, eyeDiam); ellipse(obj.x + offset, mouseY - offset, eyeDiam, eyeDiam); } else { ellipse(pauseX, pauseY, eyeDiam, eyeDiam); ellipse(pauseX, pauseY, eyeDiam, eyeDiam); } } else if (obj.x < obj.diameter / 2) { obj.x = obj.diameter / 2; if (pauseFlag == 1) { ellipse(obj.x, mouseY, obj.diameter, obj.diameter); } else { ellipse(pauseX, pauseY, obj.diameter, obj.diameter); } fill(0); var startAng = 0.01 * PI; var endAng = 1 * PI; var smileDiam = 0.6 * obj.diameter; arc(obj.x, mouseY, smileDiam, smileDiam, startAng, endAng); // Eyes var offset = 0.2 * obj.diameter; var eyeDiam = 0.1 * obj.diameter; fill(0); if (pauseFlag == 1) { ellipse(obj.x - offset, mouseY - offset, eyeDiam, eyeDiam); ellipse(obj.x + offset, mouseY - offset, eyeDiam, eyeDiam); } else { ellipse(pauseX, pauseY, eyeDiam, eyeDiam); ellipse(pauseX, pauseY, eyeDiam, eyeDiam); } } else if (obj.y > windowy - obj.diameter / 2) { obj.y = windowy - obj.diameter / 2; ellipse(mouseX, obj.y, obj.diameter, obj.diameter); fill(0); var startAng = 0.01 * PI; var endAng = 1 * PI; var smileDiam = 0.6 * obj.diameter; arc(mouseX, obj.y, smileDiam, smileDiam, startAng, endAng); // Eyes var offset = 0.2 * obj.diameter; var eyeDiam = 0.1 * obj.diameter; fill(0); ellipse(mouseX - offset, obj.y - offset, eyeDiam, eyeDiam); ellipse(mouseX + offset, obj.y - offset, eyeDiam, eyeDiam); } else if (obj.y < obj.diameter / 2) { obj.y = windowy - obj.diameter / 2; ellipse(mouseX, obj.y, obj.diameter, obj.diameter); fill(0); var startAng = 0.01 * PI; var endAng = 1 * PI; var smileDiam = 0.6 * obj.diameter; arc(mouseX, obj.y, smileDiam, smileDiam, startAng, endAng); // Eyes var offset = 0.2 * obj.diameter; var eyeDiam = 0.1 * obj.diameter; fill(0); ellipse(mouseX - offset, obj.y - offset, eyeDiam, eyeDiam); ellipse(mouseX + offset, obj.y - offset, eyeDiam, eyeDiam); } else { if (pauseFlag == 1) { ellipse(mouseX, mouseY, obj.diameter, obj.diameter); } else { ellipse(pauseX, pauseY, obj.diameter, obj.diameter); } fill(0); var startAng = 0.01 * PI; var endAng = 1 * PI; var smileDiam = 0.6 * obj.diameter; arc(mouseX, mouseY, smileDiam, smileDiam, startAng, endAng); // Eyes var offset = 0.2 * obj.diameter; var eyeDiam = 0.1 * obj.diameter; fill(0); if (pauseFlag == 1) { ellipse(mouseX - offset, mouseY - offset, eyeDiam, eyeDiam); ellipse(mouseX + offset, mouseY - offset, eyeDiam, eyeDiam); } else { ellipse(pauseX, pauseY, eyeDiam, eyeDiam); ellipse(pauseX, pauseY, eyeDiam, eyeDiam); } } } function playerVsenemy(obj1, obj2) { if (obj1.diameter == 0 || obj2.diameter == 0) { //do nothing } else { if ( sqrt(sq(obj1.x - obj2.x) + sq(obj1.y - obj2.y)) <= obj1.diameter / 2 + obj2.diameter / 2 ) { if (obj1.diameter <= obj2.diameter) { gameover.play(); obj2.diameter = obj2.diameter + 8; obj1.diameter = 0; playerdied = 1; } else { win.play(); obj1.diameter = obj1.diameter + obj2.diameter / 8; obj2.diameter = 0; } } } } function food() { noStroke(); fill(0, 0, 255); for (let i = food_distance; i <= windowx; i = i + food_distance) { for (let j = food_distance; j < windowy; j = j + food_distance) { if (foodCountFlag == 0) { foodCount++; } if (foodx.length == 0) { ellipse(i, j, 8, 8); } else { for (let k = 0; k < foodx.length; k++) { if (foodx[k] == i && foody[k] == j) { flag_fooddraw = 1; } } if (flag_fooddraw == 1) { flag_fooddraw = 0; } else { ellipse(i, j, 8, 8); } } } } } function timeIt() { if (timerValue < 11) { timerValue++; } else { timerValue = 0; } } function eatFood(obj, x) { for (let i = food_distance; i <= windowx; i = i + food_distance) { for (let j = food_distance; j < windowy; j = j + food_distance) { if ( i <= obj.x + obj.diameter / 2 && i >= obj.x - obj.diameter / 2 && j <= obj.y + obj.diameter / 2 && j >= obj.y - obj.diameter / 2 ) { if (foodx.length == 0) { foodx.push(i); foody.push(j); eat.play(); if (x == 0) obj.diameter = obj.diameter + 4; else obj.diameter = obj.diameter + 1.0; if (obj.diameter > 175 && x == 0) { fill(200, 200, 0); obj.diameter = 175; } } else { for (let k = 0; k < foodx.length; k++) { if (foodx[k] == i && foody[k] == j) { flag_food = 1; } } if (flag_food == 0) { foodx.push(i); foody.push(j); eat.play(); if (x == 0) obj.diameter = obj.diameter + 4; else obj.diameter = obj.diameter + 1.0; if (obj.diameter > 175 && x == 0) { fill(200, 200, 0); obj.diameter = 175; } } else { flag_food = 0; } } } } } } function moveRandom(obj, randomize, change, pauseFlag) { if (pauseFlag == 1) { if (obj.flag == change) { obj.speedx = random(signs) * obj.speedx; obj.speedy = random(signs) * obj.speedy; obj.flag = 0; } else { obj.flag++; } if (obj.flagx == randomize) { obj.flagx = 0; } else { obj.flagx++; } if (obj.flagx < randomize / 3) { obj.x = obj.x + obj.speedx; } else if (obj.flagx < (2 * randomize) / 3 && obj.flagx >= randomize / 3) { obj.y = obj.y + obj.speedy; } else { obj.x = obj.x + obj.speedx; obj.y = obj.y + obj.speedy; } var limit = abs(obj.speedx); if (obj.x >= windowx - obj.diameter / 2 - limit) { obj.x = windowx - obj.diameter / 2 - 2 * limit; obj.speedx = -obj.speedx; } else if (obj.x <= obj.diameter / 2 + limit) { obj.x = obj.diameter / 2 + 2 * limit; obj.speedx = -obj.speedx; } if (obj.y >= windowy - obj.diameter / 2 - limit) { obj.y = windowy - obj.diameter / 2 - 2 * limit; obj.speedy = -obj.speedy; } else if (obj.y <= obj.diameter / 2 + limit) { obj.y = obj.diameter / 2 + 2 * limit; obj.speedy = -obj.speedy; } } }
3eff9f6b7416589aec397c7607aa8b87470b64dd
[ "Markdown", "JavaScript" ]
2
Markdown
SaurabhThakre/Ball-EatUp
1220e35725ef6f99183ef7de79b3ae407a1d9506
6e4e80d4862a8863c8b7e0cc2a698170371b6d5b
refs/heads/master
<file_sep>from __future__ import unicode_literals from django.db import models from datetime import date, datetime from django.utils import timezone import bcrypt import re NAME_REGEX =re.compile('^[A-z]+$') EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$') # Create your models here. class UserValidation(models.Manager): # validate data obtained from register form def register(self,postdata): errors =[] if len(postdata['name']) <2: errors.append("User name must be at least 2 characters") elif not NAME_REGEX.match(postdata['name']): errors.append("User name must only contain alphabet") if not EMAIL_REGEX.match(postdata['email']): errors.append('Email format is incorrect') # if len(postdata['password']) < 8: errors.append('Password must be at least 8 characters') elif postdata["password"] != postdata['confirmpassword']: errors.append('Password do not match') if postdata["date_birth"] == "" or len(postdata["date_birth"]) < 1: errors.append("Date field can not be empty") elif postdata["date_birth"] >= unicode(date.today()): errors.append("You can't be born in the future!") if len(errors) == 0: # generate new salt salt = bcrypt.gensalt() # encode the password obtained from form password = postdata['password'].encode() # hash password and salt together hashed_pw = bcrypt.hashpw(password, salt) # add the new users to database User.objects.create(name=postdata['name'], email= postdata['email'], password=hashed_pw, date_birth = postdata['date_birth']) print User.objects.all() return errors def login(self,postdata): errors=[] # check if the email in the database or not print User.objects.filter(email=postdata['email']) if User.objects.filter(email=postdata['email']): # encode the password to a specific format since the about email is registered form_pw = postdata['password'].encode() # encode the registered user's password fro database to a specific format db_pw = User.objects.get(email=postdata['email']).password.encode() # compare the password with the password in database if not bcrypt.checkpw(form_pw, db_pw): errors.append('Incorrect password') else: errors.append("User name has not been registered") return errors class User(models.Model): name = models.CharField(max_length=45) email = models.CharField(max_length=45) password = models.CharField(max_length=100) date_birth = models.DateField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # secrets_liked - this is a method on user object that is available through the related name objects = UserValidation() def __unicode__(self): return "user_id: " + str(self.id) + ", name: " + self.name + ", date_birth: " + str(self.date_birth) class appointManager(models.Manager): def appointval(self, postdata, id): errors = [] # print str(datetime.today()).split()[1]-> to see just the time in datetime print datetime.now().strftime("%H:%M") if not postdata['date']: errors.append("Date, time, and task can not be empty!") elif postdata['date']: if not postdata["date"] >= unicode(date.today()): errors.append("Date must be set in future!") if len(postdata["date"]) < 1: errors.append("Date field can not be empty") print "got to appointment post Data:", postdata['date'] if len(Appointment.objects.filter(date = postdata['date'] ,time= postdata['time'])) > 0: errors.append("Can Not create an appointment on existing date and time") if len(postdata['task'])<2: errors.append("Please insert take, must be more than 2 characters") if len(errors)==0: makeappoint= Appointment.objects.create(user=User.objects.get(id=id), task= postdata['task'],date= str(postdata['date']),time= postdata['time']) print ("ELVA!!!!!!") return(True, makeappoint) else: return(False, errors) def edit_appointment(self, postdata, app_id): errors = [] print errors # if postdata['edit_date']: if not postdata["edit_date"] >= unicode(date.today()): errors.append("Appointment date can't be in the past!") print "appoint date can't be past" if postdata["edit_date"] == "" or len(postdata["edit_tasks"]) < 1: errors.append("All fields must be filled out!") print "all fields must fill out pop out" if errors == []: update_time= self.filter(id = app_id).update(task = postdata['edit_tasks'], status = postdata['edit_status'], time = postdata['edit_time'], date = postdata['edit_date']) return (True, update_time) else: return (False, errors) class Appointment(models.Model): user= models.ForeignKey(User, related_name="onrecord", blank=True, null=True) task= models.CharField(max_length=255) status= models.CharField(max_length=255) date= models.DateField(blank=True, null=True); time= models.TimeField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now=True, blank=True, null=True) objects= appointManager() <file_sep>from django.shortcuts import render, redirect from .models import User, Appointment from django.contrib import messages from django.db.models import Count from datetime import date # Create your views here. def index(request): return render(request, 'exam_app/index.html') def register(request): postdata= { "name": request.POST['name'], 'email': request.POST['email'], 'password': request.POST['password'], 'confirmpassword': request.POST['confirmpassword'], 'date_birth': request.POST['date_birth'] } # get data from register form, now validate in models.Manager # the resultfromvalidation is just a variable store the result from validation in models.Manager register_error = User.objects.register(request.POST) print register_error if len(register_error) == 0: request.session['id'] = User.objects.filter(email=postdata['email'])[0].id request.session['name'] = postdata['name'] return redirect('/appointment') else: for error in register_error: messages.info(request, error) return redirect('/') def login(request): postdata= { 'email': request.POST['email'], 'password': request.POST['<PASSWORD>'], } login_error = User.objects.login(postdata) if len(login_error) == 0: request.session['id'] = User.objects.filter(email=postdata['email'])[0].id request.session['name'] = User.objects.filter(email=postdata['email'])[0].email return redirect('/appointment') for error in login_error: messages.info(request, error) return redirect('/') def appointment(request): if 'id' not in request.session: return redirect ("/") appointments= Appointment.objects.filter(user__id=request.session['id']).exclude(date=date.today()) user= User.objects.get(id=request.session['id']) # others = User.objects.all().exclude(appoint__id=request.session['id']) context = { "user": user, 'time': date.today(), "today_appoint": Appointment.objects.filter(user__id = request.session['id']).filter(date = date.today()), "appointments": appointments } return render(request, 'exam_app/appointment.html', context) def add(request): if request.method != "POST": messages.error(request,"Can't add like that!") return redirect('/') else: add_appoint= Appointment.objects.appointval(request.POST, request.session['id']) if add_appoint[0] == False: for each in add_appoint[1]: messages.error(request, each) #for each error in the list, make a message for each one. return redirect('/appointment') if add_appoint[0] == True: messages.success(request, 'Appointment Successfully Added') return redirect('/appointment') def update(request, appoint_id): try: appointment= Appointment.objects.get(id=appoint_id) except Appointment.DoesNotExist: messages.info(request,"appointment Not Found") return redirect('/appointment') context={ "appointment": appointment, # "others": User.objects.filter(joiner__id=appoint.id).exclude(id=appoint.creator.id), } return render(request, 'exam_app/update.html', context) def edit_appoint(request, appoint_id): if 'id' not in request.session: return redirect ('/') if request.method != 'POST': messages.info(request, "Cannot edit like this!") return redirect('/update'+ appoint_id) try: print("/"*50) update_app = Appointment.objects.edit_appointment(request.POST, appoint_id) print "got to edit_appoint Try" except Appointment.DoesNotExist: messages.info(request,"appointment Not Found") return redirect('/update/'+appoint_id) if update_app[0]==False: messages.info(request, "Please fill in all the spaces and make sure it's valid!") return redirect('/update/'+appoint_id) else: messages.success(request, "successfuly updated information") return redirect('/appointment') def add(request): if request.method != "POST": messages.error(request,"Can't add like that!") return redirect('/') else: add_appoint= Appointment.objects.appointval(request.POST, request.session['id']) if add_appoint[0] == False: for each in add_appoint[1]: messages.error(request, each) #for each error in the list, make a message for each one. return redirect('/appointment') if add_appoint[0] == True: messages.success(request, 'Appointment Successfully Added') return redirect('/appointment') # def delete(request, appoint_id): try: target= Appointment.objects.get(id=appoint_id) except Appointment.DoesNotExist: messages.info(request,"Message Not Found") return redirect('/appointment') target.delete() return redirect('/appointment') # # def logout(request): if 'id' not in request.session: return redirect('/') print "*******" print request.session['id'] del request.session['id'] return redirect('/')
07bb91348e6772ee4c698b7884a6abad95354c9a
[ "Python" ]
2
Python
elva316/django_exam
acc0501b8a37e6930ff1bb261e57e78366e06bb9
0a69ebca335512b2781599da12c0f42e41406ec1
refs/heads/master
<repo_name>romerotron/AXRUITextField<file_sep>/AXRUITextField.swift // // AXRUITextField.swift // // // Created by <NAME> // Copyright © 2017 <NAME>. All rights reserved. // import Foundation import UIKit class AXRUITextField: UITextField, UITextFieldDelegate { // Override the required initializers required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! delegate = self setProperties() } required override init(frame: CGRect) { super.init(frame: frame) delegate = self setProperties() } // Convenience initializer with BOOL for AutoLayout convenience init(frame: CGRect, autoLayout: ObjCBool){ self.init(frame: frame) if autoLayout.boolValue { self.translatesAutoresizingMaskIntoConstraints = false } } override func textRect(forBounds bounds: CGRect) -> CGRect { return UIEdgeInsetsInsetRect(bounds, edgeInsets()) } override func editingRect(forBounds bounds: CGRect) -> CGRect { return UIEdgeInsetsInsetRect(bounds, edgeInsets()) } override func placeholderRect(forBounds bounds: CGRect) -> CGRect { return UIEdgeInsetsInsetRect(bounds, edgeInsets()) } func edgeInsets() -> UIEdgeInsets { return UIEdgeInsets(top:4, left:15, bottom:4, right:15) } func setProperties(){ // Set the border color and border width self.layer.borderColor = UIColor.blueHighlight().cgColor self.layer.borderWidth = 2 // Set the corner radius self.layer.cornerRadius = 3 // Turn off auto-correct self.autocorrectionType = .no // Set default keyboard to dark self.keyboardAppearance = .dark } } <file_sep>/README.md ## AXRUITextField I wanted to create a generic UITextField class for [Hang Local](https://hanglocal.us) that I could use through out the app that I felt was generally much easier to interface with from a UX perspective. ### Features 1. Includes a UITextField border to more clearly highlight the text field. 2. Ensures the newer darker iOS keyboard is displayed. 3. Enables AutoLayout to programmatically create constraints. You can see an example of what it looks like here ![AXRUITextField](AXRUITextFieldScreenshot.png)
8bf49b479e6b22ee11c4f8e928cb9aafd434494a
[ "Swift", "Markdown" ]
2
Swift
romerotron/AXRUITextField
5f9f0bb34c0bf6d69787a28de185cc6e1d5ed4f5
6ae14fe5596fe188d10b987d75c3c75da8b411fc
refs/heads/master
<repo_name>star-finder/gaia<file_sep>/src/peers/gaia/JPF_gaia_SymbolicVariable.java package gaia; import gaia.variable.Domain; import gaia.variable.GlobalVariables; import gov.nasa.jpf.annotation.MJI; import gov.nasa.jpf.symbc.numeric.IntegerExpression; import gov.nasa.jpf.vm.MJIEnv; import gov.nasa.jpf.vm.NativePeer; public class JPF_gaia_SymbolicVariable extends NativePeer { @MJI public static void setMinMax__III__V(MJIEnv env, int objRef, int var, int min, int max){ Object [] attrs = env.getArgAttributes(); IntegerExpression sym_arg = (IntegerExpression)attrs[0]; if (sym_arg !=null){ GlobalVariables.domains.put(attrs[0].toString(), new Domain(min,max)); } } } <file_sep>/src/classes/gaia/SymbolicVariable.java package gaia; public class SymbolicVariable { native public static void setMinMax(int var, int min, int max); } <file_sep>/INSTALL.md `Gaia` requires either (`Latte` + `Omega`) or `barvinok` to count models of linear constraints. Here are the instructions to install all the tools to `/home/qsphan/programs/bin`. ## 1. Install barvinok Get barvinok ``` $ cd /home/qsphan/programs/src $ wget http://barvinok.gforge.inria.fr/barvinok-0.41.tar.gz $ tar xf barvinok-0.41.tar.gz ``` Instructions to install the library can be found in `README`. The following instructions are for the impatient. barvinok requires GMP and NTL ### Install GMP ``` $ cd /home/qsphan/programs/src $ wget https://gmplib.org/download/gmp/gmp-6.1.0.tar.xz $ tar xf gmp-6.1.0.tar.xz $ cd gmp-6.1.0 $ ./configure --prefix=/home/qsphan/programs/bin ``` If `m4` is missing, install it `sudo apt-get install m4`. Then ``` $ make $ make check $ make install ``` ### Install NTL ``` $ cd /home/qsphan/programs/src $ wget https://shoup.net/ntl/ntl-11.4.1.tar.gz $ tar xf ntl-11.4.1.tar.gz $ cd ntl-11.4.1/src $ ./configure NTL_GMP_LIP=on NTL_STD_CXX11=on PREFIX=/home/qsphan/programs/bin GMP_PREFIX=/home/qsphan/programs/bin $ make $ make install ``` ### Install barvinok ``` $ cd /home/qsphan/programs/src/barvinok-0.41 $ ./configure --prefix=/home/qsphan/programs/bin --with-gmp-prefix=/home/qsphan/programs/bin --with-ntl-prefix=/home/qsphan/programs/bin $ make $ make check $ make install ```
d23629685eadeb3a01b49d1d3939dbb15357d3e7
[ "Markdown", "Java" ]
3
Java
star-finder/gaia
92433494fd7a15645e1516b34ad26a3594142cd0
6ee925aa2896456bf69b43e49ff8c78256c23eb6
refs/heads/master
<repo_name>chenman/selfAnalysis<file_sep>/web/js/NLComponent/table/com.newland.table.NLTreeTable.js /* 树表格 @author lwj */ (function($) { $.addTreeFlex = function(t, p) { if (t.grid) return false; //如果Grid已经存在则返回 $(t) .show() //show if hidden .attr({ cellPadding: 0, cellSpacing: 0, border: 0 }) //remove padding and spacing .removeAttr('width') //remove width properties ; //create grid class var g = { hset: {}, rePosDrag: function() { var cdleft = 0 - this.hDiv.scrollLeft; if (this.hDiv.scrollLeft > 0) cdleft -= Math.floor(p.cgwidth / 2); $(g.cDrag).css({ top: g.hDiv.offsetTop + 1 }); var cdpad = this.cdpad; $('div', g.cDrag).hide(); $('thead tr:first th:visible', this.hDiv).each(function() { if ($(this).css("display") == "none") { return; } var n = $('thead tr:first th:visible', g.hDiv).index(this); var cdpos = parseInt($('div', this).width()); var ppos = cdpos; if (cdleft == 0) cdleft -= Math.floor(p.cgwidth / 2); cdpos = cdpos + cdleft + cdpad; $('div:eq(' + n + ')', g.cDrag).css({ 'left': cdpos + 'px' }).show(); cdleft = cdpos; } ); }, fixHeight: function(newH) { newH = false; if (!newH) newH = $(g.bDiv).height(); var hdHeight = $(this.hDiv).height(); $('div', this.cDrag).each( function() { $(this).height(newH + hdHeight); } ); var nd = parseInt($(g.nDiv).height()); if (nd > newH) $(g.nDiv).height(newH).width(200); else $(g.nDiv).height('auto').width('auto'); $(g.block).css({ height: newH, marginBottom: (newH * -1) }); var hrH = g.bDiv.offsetTop + newH; if (p.height != 'auto' && p.resizable) hrH = g.vDiv.offsetTop; $(g.rDiv).css({ height: hrH }); }, dragStart: function(dragtype, e, obj) { //default drag function start if (dragtype == 'colresize') //column resize { $(g.nDiv).hide(); $(g.nBtn).hide(); var n = $('div', this.cDrag).index(obj); var ow = $('th:visible div:eq(' + n + ')', this.hDiv).width(); //var ow = $('th:visible:eq(' + n + ') div', this.hDiv).width(); $(obj).addClass('dragging').siblings().hide(); //$(obj).prev().addClass('dragging').show();//modify by lwj 10.12.06 不显示前一个拖拽线条样式 this.colresize = { startX: e.pageX, ol: parseInt(obj.style.left), ow: ow, n: n }; $('body').css('cursor', 'col-resize'); } else if (dragtype == 'vresize') //table resize { var hgo = false; $('body').css('cursor', 'row-resize'); if (obj) { hgo = true; $('body').css('cursor', 'col-resize'); } this.vresize = { h: p.height, sy: e.pageY, w: p.width, sx: e.pageX, hgo: hgo }; } else if (dragtype == 'colMove') //column header drag { $(g.nDiv).hide(); $(g.nBtn).hide(); this.hset = $(this.hDiv).offset(); this.hset.right = this.hset.left + $('table', this.hDiv).width(); this.hset.bottom = this.hset.top + $('table', this.hDiv).height(); this.dcol = obj; this.dcoln = $('th', this.hDiv).index(obj); this.colCopy = document.createElement("div"); this.colCopy.className = "colCopy"; this.colCopy.innerHTML = obj.innerHTML; if ($.browser.msie) { this.colCopy.className = "colCopy ie"; } $(this.colCopy).css({ position: 'absolute', 'float': 'left', display: 'none', textAlign: obj.align }); $('body').append(this.colCopy); $(this.cDrag).hide(); } $('body').noSelect(); }, reSize: function() { //---------------modify by lwj 11.6.8-------------------// //--------------------start------------------// /* this.gDiv.style.width = p.width; this.bDiv.style.height = p.height; */ $(this.gDiv).width(p.width); $(this.bDiv).height(p.height); //--------------------end------------------// }, dragMove: function(e) { if (this.colresize) //column resize { var n = this.colresize.n; var diff = e.pageX - this.colresize.startX; var nleft = this.colresize.ol + diff; var nw = this.colresize.ow + diff; if (nw > p.minwidth) { $('div:eq(' + n + ')', this.cDrag).css('left', nleft); this.colresize.nw = nw; } } else if (this.vresize) //table resize { var v = this.vresize; var y = e.pageY; var diff = y - v.sy; if (!p.defwidth) p.defwidth = p.width; if (p.width != 'auto' && !p.nohresize && v.hgo) { var x = e.pageX; var xdiff = x - v.sx; var newW = v.w + xdiff; if (newW > p.defwidth) { this.gDiv.style.width = newW + 'px'; p.width = newW; } } var newH = v.h + diff; if ((newH > p.minheight || p.height < p.minheight) && !v.hgo) { this.bDiv.style.height = newH + 'px'; p.height = newH; this.fixHeight(newH); } v = null; } /*--------------------start-------------------*/ // by lwj 10.12.06 屏蔽列头拖拽 样式 /* the old code else if (this.colCopy) { $(this.dcol).addClass('thMove').removeClass('thOver'); if (e.pageX > this.hset.right || e.pageX < this.hset.left || e.pageY > this.hset.bottom || e.pageY < this.hset.top) { //this.dragEnd(); $('body').css('cursor', 'move'); } else $('body').css('cursor', 'pointer'); $(this.colCopy).css({ top: e.pageY + 10, left: e.pageX + 20, display: 'block' }); } */ /*--------------------end-------------------*/ }, dragEnd: function() { if (this.colresize) { var n = this.colresize.n; var nw = this.colresize.nw; $('th:visible div:eq(' + n + ')', this.hDiv).css('width', nw); //$('th:visible:eq(' + n + ') div', this.hDiv).css('width', nw); $('tr', this.bDiv).each( function() { /*-----------start------------*/ //modify by lwj 10.12.06 避免拖拽时,列自定义插入DIV时,解析出错 $("td:visible div[candrag='true']:eq(" + n + ")", this).css('width', nw); /*-----------end------------*/ /* the old code $('td:visible div:eq(' + n + ')', this).css('width', nw); //$('td:visible:eq(' + n + ') div', this).css('width', nw); */ } ); this.hDiv.scrollLeft = this.bDiv.scrollLeft; $('div:eq(' + n + ')', this.cDrag).siblings().show(); $('.dragging', this.cDrag).removeClass('dragging'); this.rePosDrag(); this.fixHeight(); this.colresize = false; } else if (this.vresize) { this.vresize = false; } else if (this.colCopy) { $(this.colCopy).remove(); if (this.dcolt != null) { /*------------------start-----------------*/ // by lwj 10.9.13 屏蔽列头拖拽 /* the old code if (this.dcoln > this.dcolt) { $('th:eq(' + this.dcolt + ')', this.hDiv).before(this.dcol); } else { $('th:eq(' + this.dcolt + ')', this.hDiv).after(this.dcol); } this.switchCol(this.dcoln, this.dcolt); */ /*------------------end-----------------*/ $(this.cdropleft).remove(); $(this.cdropright).remove(); this.rePosDrag(); } this.dcol = null; this.hset = null; this.dcoln = null; this.dcolt = null; this.colCopy = null; $('.thMove', this.hDiv).removeClass('thMove'); $(this.cDrag).show(); } $('body').css('cursor', 'default'); $('body').noSelect(false); }, toggleCol: function(cid, visible) { var ncol = $("th[axis='col" + cid + "']", this.hDiv)[0]; var n = $('thead th', g.hDiv).index(ncol); var cb = $('input[value=' + cid + ']', g.nDiv)[0]; if (visible == null) { visible = ncol.hide; } if ($('input:checked', g.nDiv).length < p.minColToggle && !visible) return false; if (visible) { ncol.hide = false; $(ncol).show(); cb.checked = true; } else { ncol.hide = true; $(ncol).hide(); cb.checked = false; } //modify by lwj 11.8.30为了防止colModel配置中fireEvent里有自定义TR TD。 //--------------------start-------------------// /* $('tbody tr', t).each ( function() { if (visible) $('td:eq(' + n + ')', this).show(); else $('td:eq(' + n + ')', this).hide(); } ); */ $("tbody tr[id^='"+p.table_id+"_row_']", t).each( function() { var _tds = $(this).children("td"); if (visible){ $(_tds[n]).show(); }else{ $(_tds[n]).hide(); } } ); //--------------------end-------------------// this.rePosDrag(); if (p.onToggleCol) p.onToggleCol(cid, visible); return visible; }, switchCol: function(cdrag, cdrop) { //switch columns //modify by chw 12.04.01 //防止内嵌table导致获取tr集合不正确 //$('tbody tr', t).each $("tbody tr[id^='"+p.table_id+"_row_']", t).each ( function() { if (cdrag > cdrop) $('td:eq(' + cdrop + ')', this).before($('td:eq(' + cdrag + ')', this)); else $('td:eq(' + cdrop + ')', this).after($('td:eq(' + cdrag + ')', this)); } ); //switch order in nDiv if (cdrag > cdrop) $('tr:eq(' + cdrop + ')', this.nDiv).before($('tr:eq(' + cdrag + ')', this.nDiv)); else $('tr:eq(' + cdrop + ')', this.nDiv).after($('tr:eq(' + cdrag + ')', this.nDiv)); if ($.browser.msie && $.browser.version < 7.0) $('tr:eq(' + cdrop + ') input', this.nDiv)[0].checked = true; this.hDiv.scrollLeft = this.bDiv.scrollLeft; }, scroll: function() { this.hDiv.scrollLeft = this.bDiv.scrollLeft; this.rePosDrag(); }, hideLoading: function() { $('.pReload', this.pDiv).removeClass('loading'); if (p.hideOnSubmit){ /* modify by lwj 10.4.19 $(g.block).remove(); */ g.doMask('unmask'); } //modify by lwj 10.7.16 /* $('.pPageStat', this.pDiv).html(p.errormsg); */ if(p.usepager){ $('.pPageStat', this.pDiv).html(p.errormsg); } this.loading = false; }, /*----------------start---------------*/ //add by lwj 10.8.10 //把addData方法中的代码剥离成独立方法 parseData: function(data){ var ths = $('thead tr:first th', g.hDiv); var thsdivs = $('thead tr:first th div', g.hDiv); var tbhtml = []; if (p.dataType == 'json') { if (data.rows != null) { $.each(data.rows, function(i, row) { /*----------------start---------------*/ //add by lwj 10.8.4 if(row.parentId && row.id){ if(row.parentId.toUpperCase()!="NULL" && row.id!=row.parentId){//说明是孩子 tbhtml.push("<tbody id="+p.table_id+"_tbody_"+row.id+ " name="+p.table_id+"_tbody_"+row.parentId+" style='display: none;'>"); }else{//说明是父亲或者无父子关系 tbhtml.push("<tbody id="+p.table_id+"_tbody_"+row.id+">"); } } /*----------------end---------------*/ tbhtml.push("<tr id='", p.table_id+"_row_", row.id, "'"); if (i % 2 && p.striped) { tbhtml.push(" class='erow'"); } if (p.rowbinddata) { /* the old code tbhtml.push("chd='", row.cell.join("_FG$SP_"), "'"); */ //-------------start--------------// // add by lwj 11.2.23 过滤特殊字符 var chstr = ""; for(var i=0; i<row.cell.length; i++){ if(typeof(row.cell[i]) == "string"){//modify by lwj 11.6.9 chstr = chstr + row.cell[i].replace(/\</g,"&lt;") .replace(/\>/g,"&gt;") //.replace("\"","\&quot;"); .replaceAll("\"","\&quot;");//modiby lwj 11.6.14 }else{ chstr = chstr + row.cell[i]; } if(i < row.cell.length-1){ chstr = chstr + "_FG$SP_"; } } tbhtml.push("chd=\"" + chstr + "\""); //-------------end--------------// } tbhtml.push(">"); var trid = row.id; $(ths).each(function(j) { var tddata = ""; var tdclass = ""; var ver_align = p.colModel[j]&&p.colModel[j]["vertical-align"] != undefined? p.colModel[j]["vertical-align"]: "middle"; tbhtml.push("<td align='", this.align, "'"); var idx = $(this).attr('axis').substr(3); if (p.sortname && p.sortname == $(this).attr('abbr')) { tdclass = 'sorted'; } if (this.hide) { tbhtml.push(" style='display:none; vertical-align:"+ver_align+";"); }else{ tbhtml.push(" style='vertical-align:"+ver_align+";'"); } var width = thsdivs[j].style.width; var div = []; var divInner = row.cell[idx] || ""; //-------------start--------------// // add by lwj 11.2.23 过滤特殊字符 if(typeof divInner == "string"){//modify by lwj 11.6.9 divInner = divInner.replace(/\</g,"&lt;") .replace(/\</g,"&lt;") //.replace("\"","&quot;"); .replaceAll("\"","\&quot;");//modiby lwj 11.6.14 } //-------------end--------------// /*-------------start---------*/ // modify by lwj 10.12.06 DIV加入candrag属性。防止列自定义嵌入DIV时,拖拽解析DIV出错. div.push("<div candrag='true' title='"+divInner+"' style='text-align:", this.align, ";width:"+width, ";line-height: 16px;"); /*-------------end---------*/ /* the old code //div.push("<div title='"+divInner+"' style='text-align:", this.align, ";width:", width, ";"); //div.push("<div style='text-align:", this.align, ";width:", width, ";"); */ /*----------------start---------------*/ //add by lwj 10.8.9 添加数据行的行高 //div.push("height:17px; line-height:17px;"); /*----------------end---------------*/ if (p.nowrap == false) { div.push("white-space:normal;word-break:break-all;"); } /* the old code //modiby by lwj 10.12.06 div.push("'>"); */ if(p.showcheckbox){ div.push(" padding:2px 4px 0px 4px; float:left;'>");//modiby by lwj 10.12.06 }else{ div.push(" padding:2px 4px 3px 4px; float:left;'>");//modiby by lwj 10.12.06 } if (idx == "-1") { //checkbox div.push("<input type='checkbox' id='", p.table_id, "_chk_", row.id, "' name='", p.table_id, "_chk_", row.parentId, "' class='itemchk' value='", row.id, "'/>"); if (tdclass != "") { tdclass += " chboxtd"; } else { tdclass += "chboxtd"; } } /*----------------start---------------*/ //add by lwj 10.8.4 /* else if (idx == "-2") { //image var times = (row.id+"").split("_").length-1; for(var m=0; m<times; m++){ div.push("<div class='treegrid_row_link_front_leaf_pic_div'></div>"); } var cls = "treegrid_row_link_leaf_pic_div"; //---------------start---------------------// //modify by chw 12.04.26 //添加自定义叶子节点样式 if(p.linkPicClass && p.linkPicClass.leafClass){ cls += " " + p.linkPicClass.leafClass; } //---------------------end------------------------// var f = row.parentId && row.id && row.parentId.toUpperCase()!="NULL" && row.hasChild; if(f){//说明有孩子 cls = "treegrid_row_link_plus_close_pic_div"; //---------------start---------------------// //modify by chw 12.04.26 //添加自定义关闭节点样式 if(p.linkPicClass && p.linkPicClass.closeClass){ cls += " " + p.linkPicClass.closeClass; } //---------------------end------------------------// } div.push("<div ",(f?" title='展开子数据' ":"")," id='", p.table_id, "_row_link_div_", row.id, "' class='", cls, "'></div>"); }*/ /*----------------end---------------*/ else { //var divInner = row.cell[idx] || ""; /*-------------start---------------*/ /* 这是原先的自有代码 if (this.format) { divInner = this.format(divInner, trid); } /*-------------end---------------*/ if((p.showcheckbox && j==1) || j==0){ div.push("<a class='a'>"); var times = (row.id+"").split("_").length-1; for(var m=0; m<times; m++){ div.push("<ins></ins>"); } var cls = "treegrid_row_link_leaf_pic_div"; //---------------start---------------------// //modify by chw 12.04.26 //添加自定义叶子节点样式 if(p.linkPicClass && p.linkPicClass.leafClass){ cls += " " + p.linkPicClass.leafClass; } //---------------------end------------------------// var f = row.parentId && row.id && row.parentId.toUpperCase()!="NULL" && row.hasChild; if(f){//说明有孩子 cls = "treegrid_row_link_plus_close_pic_div"; //---------------start---------------------// //modify by chw 12.04.26 //添加自定义关闭节点样式 if(p.linkPicClass && p.linkPicClass.closeClass){ cls += " " + p.linkPicClass.closeClass; } //---------------------end------------------------// } div.push("<ins ",(f?" title='展开子数据' ":"")," id='", p.table_id, "_row_link_div_", row.id, "' class='", cls, "' style='vertical-align:", ver_align , "'></ins>"); } div.push(divInner); div.push("</a>"); } div.push("</div>"); if (tdclass != "") { tbhtml.push(" class='", tdclass, "'"); } tbhtml.push(">", div.join(""), "</td>"); }); tbhtml.push("</tr>"); /*----------------start---------------*/ //add by lwj 10.8.4 //if(row.parentId && row.id && row.parentId.toUpperCase()!="NULL" && row.id!=row.parentId){//说明是孩子 tbhtml.push("</tbody>"); //} /*----------------end---------------*/ }); } } else if (p.dataType == 'xml') { i = 1; $("rows row", data).each(function() { i++; var robj = this; var arrdata = new Array(); $("cell", robj).each(function() { arrdata.push($(this).text()); }); var nid = $(this).attr('id'); tbhtml.push("<tr id='", "row", nid, "'"); if (i % 2 && p.striped) { tbhtml.push(" class='erow'"); } if (p.rowbinddata) { tbhtml.push("chd='", arrdata.join("_FG$SP_"), "'"); } tbhtml.push(">"); var trid = nid; $(ths).each(function(j) { tbhtml.push("<td align='", this.align, "'"); if (this.hide) { tbhtml.push(" style='display:none;'"); } var tdclass = ""; var tddata = ""; var idx = $(this).attr('axis').substr(3); if (p.sortname && p.sortname == $(this).attr('abbr')) { tdclass = 'sorted'; } var width = thsdivs[j].style.width; var div = []; div.push("<div style='text-align:", this.align, ";width:", width, ";"); if (p.nowrap == false) { div.push("white-space:normal"); } div.push("'>"); if (idx == "-1") { //checkbox div.push("<input type='checkbox' id='", p.table_id, "_chk_", nid, "' class='itemchk' value='", nid, "'/>"); if (tdclass != "") { tdclass += " chboxtd"; } else { tdclass += "chboxtd"; } } else { var divInner = arrdata[idx] || "&nbsp;"; if (p.rowbinddata) { tddata = arrdata[idx] || ""; } /*-------------start---------------*/ /* 这是原先的自有代码 if (this.format) { divInner = this.format(divInner, trid); } /*-------------end---------------*/ div.push(divInner); } div.push("</div>"); if (tdclass != "") { tbhtml.push(" class='", tdclass, "'"); } tbhtml.push(" axis='", tddata, "'", ">", div.join(""), "</td>"); }); tbhtml.push("</tr>"); }); } return tbhtml; }, /*----------------end---------------*/ /*-----------------start---------------*/ //modify by chw 12.10.17 //可以上下移动数据,包括孩子数据,只限制没有配置勾选框的情况下 adjustOrder: function(_param){ var selectTrObj = $(g.bDiv).find("tbody tr[id^="+p.table_id+"_row_].trSelected"); if(selectTrObj.length){ var flag = false; if(p.showcheckbox){ var count = 0; for(var i=0; i<selectTrObj.length; i++){ var chkobj = $(selectTrObj[i]).children().children().children(); //input checkbox if(chkobj.attr("disabled") == false || chkobj.attr("disabled") == "false"){ count++; } } if(count > 1){ flag = true; } } if(!flag){ if(selectTrObj != undefined){ var trPrefix = selectTrObj.attr("id").substr(0, selectTrObj.attr("id").lastIndexOf("_")); var selectTodyObj = selectTrObj.parent("tbody"); //当前选中节点的元素的父元素,即tbody var tbodyId = selectTodyObj.attr("id"); //获得btody的Id var tbodyPrefix = tbodyId.substr(0, tbodyId.lastIndexOf("_")); var index = tbodyId.substr(tbodyId.lastIndexOf("_") + 1, tbodyId.length); if(_param.order == "up"){ index = index - 1; var preTbodyObjForSel = $(g.bDiv).find("tbody[id="+(tbodyPrefix+"_"+index)+"]");//获取当前选中行对应的同级相邻前一行的行tbody对象 if(preTbodyObjForSel.length == 0){ alert("行数据为当前层级的顶级,无法继续向上移动"); return false; } preTbodyObjForSel.before(selectTodyObj); var preChildren = (p.showcheckbox && preTbodyObjForSel.length>1)?preTbodyObjForSel: this.getChildren(tbodyPrefix+"_"+index); //var preChildren = this.getChildren(tbodyPrefix+"_"+index); if(!p.showcheckbox || (p.showcheckbox && preTbodyObjForSel.length==1)){ for(var i=preChildren.length-1; i>=0; i--){ preTbodyObjForSel.after(preChildren[i]); } preChildren.push(preTbodyObjForSel[0]); } selectChildren = (p.showcheckbox && selectTodyObj.length>1)?selectTodyObj: this.getChildren(tbodyPrefix+"_"+(index+1)); //selectChildren = this.getChildren(tbodyPrefix+"_"+(index+1)); if(!p.showcheckbox || (p.showcheckbox && selectTodyObj.length==1)){ for(var i=selectChildren.length-1; i>=0; i--){ selectTodyObj.after(selectChildren[i]); } selectChildren.push(selectTodyObj[0]); } var oldSelectTbodyId = selectTodyObj.attr("id"); var oldPreTbodyId = preTbodyObjForSel.attr("id"); this.changeChildrenId({ oldId: tbodyId, newId: oldPreTbodyId, data: selectChildren, tbodyPrefix: tbodyPrefix, trPrefix: trPrefix }); this.changeChildrenId({ oldId: oldPreTbodyId, newId: tbodyId, data: preChildren, tbodyPrefix: tbodyPrefix, trPrefix: trPrefix }); }else if(_param.order == "down"){ index = parseInt(index) + 1; var nextTbodyObjForSel = $(g.bDiv).find("tbody[id="+(tbodyPrefix+"_"+index)+"]");//获取当前选中行对应的同级相邻前一行的行tbody对象 if(nextTbodyObjForSel.length == 0){ alert("当前节点处于当前层级的最后一个节点,无法继续往下移"); return false; } nextTbodyObjForSel.after(selectTodyObj); //var nextChildren = nextTbodyObjForSel; var nextChildren = (p.showcheckbox && nextTbodyObjForSel.length>1)? nextTbodyObjForSel: this.getChildren(tbodyPrefix+"_"+index); //var nextChildren = this.getChildren(tbodyPrefix+"_"+index); if(!p.showcheckbox || (p.showcheckbox && nextTbodyObjForSel.length==1)){ for(var i=nextChildren.length-1; i>=0; i--){ nextTbodyObjForSel.after(nextChildren[i]); } nextChildren.push(nextTbodyObjForSel[0]); } var selectChildren = (p.showcheckbox && selectTodyObj.length>1)?selectTodyObj: this.getChildren(tbodyPrefix+"_"+(index+1)); //selectChildren = this.getChildren(tbodyPrefix+"_"+(index+1)); if(!p.showcheckbox || (p.showcheckbox && selectTodyObj.length == 1)){ for(var i=selectChildren.length-1; i>=0; i--){ selectTodyObj.after(selectChildren[i]); } selectChildren.push(selectTodyObj[0]); } var oldSelectTbodyId = selectTodyObj.attr("id"); var oldNextTbodyId = nextTbodyObjForSel.attr("id"); this.changeChildrenId({ oldId: tbodyId, newId: oldNextTbodyId, data: selectChildren, tbodyPrefix: tbodyPrefix, trPrefix: trPrefix }); this.changeChildrenId({ oldId: oldNextTbodyId, newId: tbodyId, data: nextChildren, tbodyPrefix: tbodyPrefix, trPrefix: trPrefix }); } }else{ alert("请先选中一行数据进行移动"); } }else{ alert("只能针对一行数据进行移动"); } }else{ alert("只能针对一行数据进行移动"); } //this.firePicColumnEvent(); }, /*----------------end-------------------*/ getChildren: function(id){ var childrenIdPrefix = id+"_"; var allChildrenObjs = $(g.bDiv).find("tbody[id^="+childrenIdPrefix+"]"); return allChildrenObjs; }, changeChildrenId: function(__param){ var childrenIdPrefix = __param.oldId; //var allChildrenObjs = $(g.bDiv).find("tbody[id^="+childrenIdPrefix+"]"); for(var i=0; i<__param.data.length; i++){ var _id = $(__param.data[i]).attr("id"); var flag = false; if(_id == __param.oldId){//如果当前循环的对象是跟选中的节点对象是同一级的,则不需要修改name的值 flag = true; } var newChildrenId = _id.replace(__param.oldId, __param.newId); //将节点ID修改为新的 var newName = newChildrenId.substr(0, newChildrenId.lastIndexOf("_")); //获取前一个循环对象的ID,作为当前节点的name属性的值。 $(__param.data[i]).attr("id", newChildrenId); //将替换后的ID设置到当前循环的对象中去。 var prefix = p.table_id+"_tbody_"; var suffix = newChildrenId.substr(prefix.length, newChildrenId.length); var insObj = null; if(p.showcheckbox){ insObj = $(__param.data[i]).children("tr").children("td.chboxtd").next().children("div").children("a").find("ins[id^='test_row_link_div_']"); var chboxObj = $(__param.data[i]).children("tr").children("td.chboxtd").children("div").find("input[id^='test_chk_']"); if(chboxObj != undefined){ chboxObj.attr("id", p.table_id+"_chk_" + suffix); chboxObj.attr("name", p.table_id+"_chk_" + newName.substr(prefix.length, newName.length)); } }else{ insObj = $(__param.data[i]).children("tr").children("td").first().children("div").children("a").find("ins[id^='test_row_link_div_']"); } if(insObj != undefined){ insObj.attr("id", "test_row_link_div_" + suffix); } var trId = __param.trPrefix + newChildrenId.substr(__param.tbodyPrefix.length, newChildrenId.length); $(__param.data[i]).children("tr").attr("id", trId); //设置tr的id if(!flag){ //说明当前循环的对象不是跟选中的行对象同一级的,需要重新设置name属性 if(newName == undefined){ //如果没值,则直接设置为__param.newId $(__param.data[i]).attr("name", __param.newId); }else{ $(__param.data[i]).attr("name", newName); } } } this.firePicColumnEvent(); if(p.showcheckbox && p.cbLinked){//modify by lwj 12.5.14 加上钩选框是否关联孩子属性 this.fireLinkRowsChkEvent(); } }, addData: function(data) { //parse data //alert(JSON.encode(data)); if (p.preProcess) { data = p.preProcess(data); } $('.pReload', this.pDiv).removeClass('loading'); this.loading = false; if (!data) { //modify by lwj 10.7.16 /* $('.pPageStat', this.pDiv).html(p.errormsg); */ //alert("tmd"); if(p.usepager){ $('.pPageStat', this.pDiv).html(p.errormsg); } return false; } var temp = p.total; if (p.dataType == 'xml') { p.total = +$('rows total', data).text(); } else { p.total = data.total; } if (p.total < 0) { p.total = temp; } if (p.total == 0) { $('tr, a, td, div', t).unbind(); $(t).empty(); p.pages = 1; p.page = 1; /*----------------start---------------*/ //modify by lwj 10.6.21 //如果两个表格联动,后面的表格usepager属性为false,即不显示"页面操作菜单栏", //这时,当第一个表格点击查询第二个表格时,相关状态会在第一个表格的"页面操作菜单栏"中体现 if(p.usepager){ this.buildpager(); $('.pPageStat', this.pDiv).html(p.nomsg); } /*----------------end---------------*/ if (p.hideOnSubmit){ /* modify by lwj 10.4.19 $(g.block).remove(); */ g.doMask('unmask'); } return false; } p.pages = Math.ceil(p.total / p.rp); if (p.dataType == 'xml') { p.page = +$('rows page', data).text(); } else { p.page = data.page; } /*----------------start---------------*/ //modify by lwj 10.6.21 //如果两个表格联动,后面的表格usepager属性为false,即不显示"页面操作菜单栏", //这时,当第一个表格点击查询第二个表格时,相关状态会在第一个表格的"页面操作菜单栏"中体现 if(p.usepager){ this.buildpager(); } /*----------------end---------------*/ var tbhtml = this.parseData(data); tbhtml.unshift("<tbody>"); tbhtml.push("</tbody>"); $(t).html(tbhtml.join("")); //alert($(t).html()); this.rePosDrag(); /*----------------start---------------*/ //add by lwj 10.8.6 //对第二列的图标添加事件 this.firePicColumnEvent(); //对各行数据中的钩选框,添加儿子的钩选事件 //if(p.showcheckbox){ if(p.showcheckbox && p.cbLinked){//modify by lwj 12.5.14 加上钩选框是否关联孩子属性 this.fireLinkRowsChkEvent(); } /*----------------end---------------*/ this.addRowProp(); this.applyEvent();//add by lwj 10.3.15 if (p.onSuccess) p.onSuccess(); if (p.hideOnSubmit){ /* modify by lwj 10.4.19 $(g.block).remove();//$(t).show(); */ g.doMask('unmask'); } this.hDiv.scrollLeft = this.bDiv.scrollLeft; if ($.browser.opera) $(t).css('visibility', 'visible'); }, /* //---------------start---------------// //add by lwj 10.8.11 //对第二列的图标添加事件 firePicEvent: function(){ $(this).click(function(){ //function doChildHide(id){ function doChildHide(id, c){ var dObj = $("#"+p.table_id+"_row_link_div_"+id); //if(dObj.hasClass("treegrid_row_link_plus_open_pic_div")){ if(!c && dObj.hasClass("treegrid_row_link_plus_open_pic_div")){ dObj.removeClass("treegrid_row_link_plus_open_pic_div") .addClass("treegrid_row_link_plus_close_pic_div"); dObj.attr("title", "展开子数据"); } $("tbody[name$='"+p.table_id+"_tbody_"+id+"']", g.bDiv).each(function(){ this.style.display = "none"; var tid = $(this).attr("id"); tid = tid.substring((p.table_id+"_tbody_").length, tid.length); //doChildHide(tid); doChildHide(tid, true); }); } function doChildShow(id, c){ var dObj = $("#"+p.table_id+"_row_link_div_"+id); //if(dObj.hasClass("treegrid_row_link_plus_open_pic_div")){ if(!c && dObj.hasClass("treegrid_row_link_plus_close_pic_div")){ dObj.removeClass("treegrid_row_link_plus_close_pic_div") .addClass("treegrid_row_link_plus_open_pic_div"); dObj.attr("title", "隐藏子数据"); } $("tbody[name$='"+p.table_id+"_tbody_"+id+"']", g.bDiv).each(function(){ this.style.display = ""; var tid = $(this).attr("id"); tid = tid.substring((p.table_id+"_tbody_").length, tid.length); //doChildHide(tid); doChildShow(tid, true); }); } var id = $(this).attr("id"); id = id.substring((p.table_id+"_row_link_div_").length, id.length); var divObj = $(this); if(divObj.hasClass("treegrid_row_link_plus_close_pic_div")){ //if(p.url){ // this.ajaxChildData({param: {opType: "getChildren"}, parentId: id}); //}else if(p.onAppendChild){ var trObj = $("#"+p.table_id+"_row_"+id); var parentData = g.getRowData(trObj[0]); var pa = {"parentId": id, "parentData": parentData[0]}; p.onAppendChild.call(this, pa); }else{ doChildShow(id); } }else if(divObj.hasClass("treegrid_row_link_plus_open_pic_div")){ doChildHide(id); } }); //-----------------start-------------------------// //add by chw 12.04.01 //给第二列图标添加mouseover事件 if(p.picColuMouseoverEvent){ $(this).hover(function(){ if($(this).hasClass("treegrid_row_link_plus_close_pic_div")){ $(this).trigger("click"); } },function(){}); } }, //----------------end---------------// */ doChildShow: function (id, c){ var dObj = $("#"+p.table_id+"_row_link_div_"+id); //if(dObj.hasClass("treegrid_row_link_plus_open_pic_div")){ if(!c && dObj.hasClass("treegrid_row_link_plus_close_pic_div")){ dObj.removeClass("treegrid_row_link_plus_close_pic_div"); //---------------start---------------------// //modify by chw 12.04.26 //如果设置了自定义的关闭样式,需要在打开状态下,移除自定义的关闭样式 if(p.linkPicClass && p.linkPicClass.closeClass){ dObj.removeClass(p.linkPicClass.closeClass); } dObj.addClass("treegrid_row_link_plus_open_pic_div"); //modify by chw 12.04.26 //如果有设置自定义的打开样式,需要添加自定义的打开样式 if(p.linkPicClass && p.linkPicClass.openClass){ dObj.addClass(p.linkPicClass.openClass); } //-----------------end---------------------------// dObj.attr("title", "隐藏子数据"); } $("tbody[name$='"+p.table_id+"_tbody_"+id+"']", g.bDiv).each(function(){ var chi_tid = $(this).attr("id"); chi_tid = chi_tid.substring((p.table_id+"_tbody_").length, chi_tid.length); this.style.display = ""; if($("#"+p.table_id+"_row_link_div_"+chi_tid).hasClass("treegrid_row_link_plus_open_pic_div")){ var tid = $(this).attr("id"); tid = tid.substring((p.table_id+"_tbody_").length, tid.length); g.doChildShow(tid, true); } }); }, doChildHide: function(id, c){ var dObj = $("#"+p.table_id+"_row_link_div_"+id); if(!c && dObj.hasClass("treegrid_row_link_plus_open_pic_div")){ dObj.removeClass("treegrid_row_link_plus_open_pic_div"); //---------------start---------------------// //modify by chw 12.04.26 //如果设置了自定义的打开样式,需要在打开状态下,移除自定义的打开样式 if(p.linkPicClass && p.linkPicClass.openClass){ dObj.removeClass(p.linkPicClass.openClass); } dObj.addClass("treegrid_row_link_plus_close_pic_div"); //modify by chw 12.04.26 //如果有设置自定义的关闭样式,需要添加自定义的关闭样式 if(p.linkPicClass && p.linkPicClass.closeClass){ dObj.addClass(p.linkPicClass.closeClass); } //---------------------end---------------------// dObj.attr("title", "展开子数据"); } $("tbody[name$='"+p.table_id+"_tbody_"+id+"']", g.bDiv).each(function(){ this.style.display = "none"; var tid = $(this).attr("id"); tid = tid.substring((p.table_id+"_tbody_").length, tid.length); g.doChildHide(tid, true); }); }, /*--------------start-----------------*/ stopPropagation: function(e){ if (e && e.stopPropagation){ e.stopPropagation(); }else{ window.event.cancelBubble = true; } }, /*---------------end------------------*/ /*----------------start---------------*/ //add by lwj 10.8.11 //对第二列的图标添加事件 firePicEvent: function(){ $(this).click(function(e){ /* function doChildHide(id, c){ var dObj = $("#"+p.table_id+"_row_link_div_"+id); if(!c && dObj.hasClass("treegrid_row_link_plus_open_pic_div")){ dObj.removeClass("treegrid_row_link_plus_open_pic_div") .addClass("treegrid_row_link_plus_close_pic_div"); dObj.attr("title", "展开子数据"); } $("tbody[name$='"+p.table_id+"_tbody_"+id+"']", g.bDiv).each(function(){ this.style.display = "none"; var tid = $(this).attr("id"); tid = tid.substring((p.table_id+"_tbody_").length, tid.length); doChildHide(tid, true); }); } */ var id = $(this).attr("id"); id = id.substring((p.table_id+"_row_link_div_").length, id.length); var divObj = $(this); if(divObj.hasClass("treegrid_row_link_plus_close_pic_div")){ if(p.onAppendChild){ var trObj = $("#"+p.table_id+"_row_"+id); var parentData = g.getRowData(trObj[0]); var pa = {"parentId": id, "parentData": parentData[0]}; p.onAppendChild.call(this, pa); }else{ /* var cObj = $("tbody[name$='_tbody_"+id+"']", g.bDiv); cObj.each(function(){ //this.style.display = "block"; this.style.display = "";// modify by lwj 10.12.07 block在火狐下会错位 divObj.removeClass("treegrid_row_link_plus_close_pic_div") .addClass("treegrid_row_link_plus_open_pic_div"); divObj.attr("title", "隐藏子数据"); });*/ g.doChildShow(id); } }else if(divObj.hasClass("treegrid_row_link_plus_open_pic_div")){ g.doChildHide(id); } g.stopPropagation(e); }); /*-----------------start-------------------------*/ //add by chw 12.04.01 //给第二列图标添加mouseover事件 if(p.picOnMouseover){ $(this).hover(function(){ if($(this).hasClass("treegrid_row_link_plus_close_pic_div")){ $(this).trigger("click"); } },function(){}); } }, /*----------------end---------------*/ /* //----------------start--------------// //add by lwj 10.8.11 //对第二列的图标添加事件 firePicEvent: function(){ $(this).click(function(){ function doChildHide(id){ var dObj = $("#"+p.table_id+"_row_link_div_"+id); if(dObj.hasClass("treegrid_row_link_plus_open_pic_div")){ dObj.removeClass("treegrid_row_link_plus_open_pic_div") .addClass("treegrid_row_link_plus_close_pic_div"); dObj.attr("title", "展开子数据"); } $("tbody[name$='"+p.table_id+"_tbody_"+id+"']", g.bDiv).each(function(){ this.style.display = "none"; var tid = $(this).attr("id"); tid = tid.substring((p.table_id+"_tbody_").length, tid.length); doChildHide(tid); }); } var id = $(this).attr("id"); id = id.substring((p.table_id+"_row_link_div_").length, id.length); var divObj = $(this); if(divObj.hasClass("treegrid_row_link_plus_close_pic_div")){ //if(p.url){ // this.ajaxChildData({param: {opType: "getChildren"}, parentId: id}); //}else if(p.onAppendChild){ var trObj = $("#"+p.table_id+"_row_"+id); var parentData = g.getRowData(trObj[0]); var pa = {"parentId": id, "parentData": parentData[0]}; p.onAppendChild.call(this, pa); }else{ var cObj = $("tbody[name$='_tbody_"+id+"']", g.bDiv); cObj.each(function(){ //this.style.display = "block";// this.style.display = "";// modify by lwj 10.12.07 block在火狐下会错位 divObj.removeClass("treegrid_row_link_plus_close_pic_div") .addClass("treegrid_row_link_plus_open_pic_div"); divObj.attr("title", "隐藏子数据"); }); } }else if(divObj.hasClass("treegrid_row_link_plus_open_pic_div")){ doChildHide(id); } }); //-----------------start-------------------------// //add by chw 12.04.01 //给第二列图标添加mouseover事件 if(p.picColuMouseoverEvent){ $(this).hover(function(){ if($(this).hasClass("treegrid_row_link_plus_close_pic_div")){ $(this).trigger("click"); } },function(){}); } }, //----------------end---------------// */ /*----------------start---------------*/ //add by lwj 10.8.11 //对第二列的图标添加事件 ajaxChildData: function(paramObj){ if(!paramObj){ return false; } if(!paramObj.param){ return false; } if (p.hideOnSubmit){ g.doMask('mask'); } if (p.extParam) { for (var pi = 0; pi < p.extParam.length; pi++) paramObj.param[paramObj.param.length] = p.extParam[pi]; } $.ajax({ type: p.method, url: p.url, data: paramObj.param, dataType: p.dataType, success: function(data) { //alert(JSON.encode(data)); if (data != null && data.error != null) { if (p.onError) { p.onError(data); g.hideLoading(); } } else { var pa = {"parentId": paramObj.parentId+""}; var d = this.changeJsonObject(data, pa); //alert(JSON.encode(d)); if(d){ this.appendChild(d[0], pa); } } }, error: function(data) { try { if (p.onError) { p.onError(data); } else { alert("获取数据发生异常"); } g.hideLoading(); } catch (e) { } } }); }, /*----------------end---------------*/ /*----------------start---------------*/ //add by lwj 10.8.11 //对钩选框,添加儿子的钩选事件 fireChkEvent: function(){ function doChildChk(obj, ischeck){ if (ischeck) { obj.parent().parent().parent().addClass("trSelected"); } else { obj.parent().parent().parent().removeClass("trSelected"); } var id = obj.attr("id"); id = id.substring((p.table_id+"_chk_").length, id.length); //对钩选框ID对应的TBODY下的钩选框(儿子钩选框)进行关联操作 /* $("tbody[name='"+p.table_id+"_tbody_"+id+"']", g.bDiv).each(function(){ $(":checkbox.itemchk", this).each(function(){ if(this.name == (p.table_id+"_chk_"+id)){ this.checked = ischeck; doChildChk($(this), ischeck); } }); }); */ //对钩选框ID对应的TBODY下的钩选框(儿子钩选框)进行关联操作 $("tbody[name='"+p.table_id+"_tbody_"+id+"']", g.bDiv).each(function(){ var _parent = $(this).children("tr"); $(":checkbox.itemchk", this).each(function(){ if(this.name == (p.table_id+"_chk_"+id)){ this.checked = ischeck; if(this.checked){ $(this).attr("disabled", "disabled"); $(_parent).attr("trcheckboxDis", this.checked); }else{ $(this).attr("disabled", ""); $(_parent).removeAttr("trcheckboxDis"); } doChildChk($(this), ischeck); } }); }); } $(this).click(function(){ var ischeck = $(this).attr("checked"); doChildChk($(this), ischeck); }); }, /*----------------end---------------*/ /*----------------start---------------*/ //add by lwj 10.8.6 //对第二列的图标添加事件 firePicColumnEvent: function(){ var fn = this.firePicEvent; $("tbody tr ins[class^='treegrid_row_link_plus_']", g.bDiv).each(function(i){ fn.call(this); }); }, /*----------------end---------------*/ /*----------------start---------------*/ //add by lwj 10.8.6 //对各行数据中的钩选框,添加儿子的钩选事件 fireLinkRowsChkEvent: function(){ var fn = this.fireChkEvent; $(":checkbox.itemchk", g.bDiv).each(function(){ fn.call(this); }); }, /*----------------end---------------*/ /*----------------start---------------*/ //添加clearAllRows方法 add by lwj 10.3.15 //清空所有的表格数据 clearAllRows: function(){ //$(t).html(""); $(t).empty();//modify by lwj 11.8.17 if(p.showcheckbox){ $("input:first", g.hDiv).attr("checked", ""); } g.doUsePager(); p.isSuccessSearch = false; }, /*----------------end---------------*/ /*----------------start---------------*/ //添加applyEvent方法 add by lwj 10.3.15 //处理各列注册的事件 applyEvent: function(row){ if(p.colModel){ var tr_object, td_object, div_object; //-------------start-------------// // modify by chw 12.1.14 var o = $("tbody tr", t); if(row && row.length){ o = row; } //$("tbody tr", t).each(function(i){ //-------------end-------------// o.each(function(i){ tr_object = this; $(p.colModel).each(function(j) { if(this.fireEvent){ /*td_object = $(tr_object).children()[p.showcheckbox ? (j+1) : j];*/ /*---------------start---------------*/ //加了一列图片,索引要加1 //td_object = $(tr_object).children()[p.showcheckbox ? (j+2) : (j+1)]; td_object = $(tr_object).children()[p.showcheckbox ? (j+1) : j]; /*---------------end---------------*/ div_object = $(td_object).children()[0]; /* //原来没传g this.fireEvent(tr_object, div_object); */ this.fireEvent({"tr_object": tr_object, "div_object": div_object, "grid": g}); } }); }); } }, /*----------------end---------------*/ /*----------------start---------------*/ //添加dealData方法 add by lwj 10.3.15 dealData: function(jsonObject){ //alert(JSON.encode(jsonObject)); try{ var resultID = jsonObject.resultID; var resultMsg = jsonObject.resultMsg; if(resultID){ if(resultID == p.successResultID){ return true; }else{ if(p.showErrorMsg){ alert(resultMsg); } return false; } }else{//alert(resultID); alert(p.errormsg); return false; } }catch(_error){ throw _error; } }, /*----------------end---------------*/ /*----------------start---------------*/ //代码独立出来,添加getDataArr方法 //add by lwj 10.8.4 /* getDataArr: function(o){ var size = p.colModel.length; var temp_name, tmp = "",arr = new Array(size); for(var j=0; j<size; j++){ temp_name = p.colModel[j].name; tmp = eval("o."+temp_name); if(typeof(tmp)=="number"){ tmp = tmp==0 ? "0" : tmp; }else{ tmp = tmp ? tmp : ""; } arr[j] = tmp; } return arr; }, */ getDataArr: function(list){ var size = p.colModel.length; var temp_name, tmp = "",arr = new Array(size); for(var j=0; j<size; j++){ temp_name = p.colModel[j].name; /* the old code tmp = eval("list."+temp_name); */ //---------------start--------------// // modify by lwj 11.2.23 if(temp_name.indexOf("\.") != -1){ var arrs = temp_name.split("\."); tmp = list[arrs[0]]; for(var m=1; m<arrs.length; m++){ //modify by chw 12.05.09 //防止出现传递多级数据时,数据为空的情况 //tmp = tmp[arrs[m]]; if(tmp && tmp[arrs[m]] != undefined && tmp[arrs[m]] != null){ tmp = tmp[arrs[m]]; }else{ tmp = ""; } } }else{ tmp = list[temp_name]; } //---------------end--------------// if(typeof(tmp)=="number"){ tmp = tmp==0 ? "0" : tmp; }else{ tmp = tmp ? tmp : ""; } arr[j] = tmp; } return arr; }, /*----------------end---------------*/ /*----------------start---------------*/ //添加changeJsonObject方法 add by lwj 10.3.8 // modify by lwj 10.4.13 // modify by lwj 10.8.4 parentId=id,说明有孩子,如果="null",说明没有孩子,如果=父亲的ID,说明是父亲的孩子 changeJsonObject: function(jsonObject, param){ try{ var temp_object; //var temp_name; var o = [{}]; o[0].total = jsonObject.total; o[0].page = jsonObject.page; o[0].rows = []; //var size = p.colModel.length; //var tmp = ""; var list, cList, rD; /*--------------start-----------*/ //对行的ID,根据记录数进行赋值 var index = 0; if(o[0].page){ index = p.rp * (parseInt(o[0].page)-1); index = index>=0 ? index : 0; } /*--------------end-----------*/ function appendC(list, parentId){ if(list.children){ for(var k=0; k<list.children.length; k++){ cList = list.children[k]; if(cList){ //rD = {"id": (parentId+"_"+k), "cell": g.getDataArr(cList), parentId: parentId+"", hasChild: false, tbody: (k==0 ? true : false), _tbody: (k==list.children.length-1 ? true : false)}; rD = { "id": (parentId+"_"+k), "cell": g.getDataArr(cList), parentId: parentId+"", hasChild: false }; if(cList.children){ rD.hasChild = true; } o[0].rows.push(rD); } appendC(cList, (parentId+"_"+k)); } } } var rowNum = 0; if(param.noDel != undefined && param.noDel){ var trs = $("tbody[name='"+p.table_id+"_tbody_"+param.parentId+"']", g.bDiv); rowNum = trs.length; } if(jsonObject && jsonObject.resultList){ for(var i=0; i<jsonObject.resultList.length; i++){ list = jsonObject.resultList[i]; if(list){ //rD = {"id": (index+i)+"", "cell": this.getDataArr(list), parentId: "null", hasChild: false, tbody: false, _tbody: false}; rD = { //"id": ((param&&param.parentId)?(param.parentId+"_"+i)):(index+i)+""),//(index+i)+"", "id": ((param&&param.parentId)?(param.parentId+"_"+(rowNum+i)):(index+rowNum+i)+""),//(index+i)+"", "cell": this.getDataArr(list), parentId: (param.parentId?param.parentId:"null"), hasChild: false }; if(list.children){ rD.parentId = (param&&param.parentId) ? param.parentId : (index+i)+""; rD.hasChild = true; } o[0].rows.push(rD); appendC(list, rD.id); } } } return o; }catch(_error){ throw _error; } }, /*----------------end---------------*/ /*----------------start---------------*/ //添加freshParam方法 add by lwj 10.3.11 //如果表格重载或者重新查询时,要对参数进行重新初始化之类的处理 freshParam: function(param){ $.extend(p, param); }, /*----------------end---------------*/ /*----------------start---------------*/ //add by lwj 10.3.9 //添加getRowData方法,根据传入的TR对象,获取TR中的CH属性,并返回封装后的JSON对象 //如果row_object即TR对象为空,则根据表格中 有选中样式的 TR进行操作 //该方法只适用于 表格各行数据无钩选框的情况 getRowData: function(row_object){ var row_objects = []; var chd = null; if(row_object){ chd = $(row_object).attr("chd"); }else{ if(!p.showcheckbox){ /*-------------start----------------*/ //modify by chw 12.04.01 //防止内嵌table导致获取不到正确的tr行 //var trs = $(g.bDiv).find("tr"); var trs = $(g.bDiv).find("tbody tr[id^="+p.table_id+"_row_]"); /*-------------end----------------*/ for(var i=0; i<trs.length; i++){ if($(trs[i]).hasClass("trSelected")){ chd = $(trs[i]).attr("chd"); break; } } } } if(chd){ row_objects.push({}); g.generalObject(row_objects, chd, 0); } return row_objects; }, /*----------------end---------------*/ changeSort: function(th) { //change sortorder if (this.loading) return true; $(g.nDiv).hide(); $(g.nBtn).hide(); if (p.sortname == $(th).attr('abbr')) { if (p.sortorder == 'asc') p.sortorder = 'desc'; else p.sortorder = 'asc'; } $(th).addClass('sorted').siblings().removeClass('sorted'); $('.sdesc', this.hDiv).removeClass('sdesc'); $('.sasc', this.hDiv).removeClass('sasc'); $('div', th).addClass('s' + p.sortorder); p.sortname = $(th).attr('abbr'); if (p.onChangeSort) p.onChangeSort(p.sortname, p.sortorder); else this.populate(); }, buildpager: function() { //rebuild pager based on new properties $('.pcontrol input', this.pDiv).val(p.page); $('.pcontrol span', this.pDiv).html(p.pages); /* the old code var r1 = (p.page - 1) * p.rp + 1; var r2 = r1 + p.rp - 1; */ /*---------start----------*/ //防止字符串 modify by lwj 10.12.03 var r1 = (parseInt(p.page) - 1) * parseInt(p.rp) + 1; var r2 = r1 + parseInt(p.rp) - 1; /*---------end----------*/ if (p.total < r2) r2 = p.total; var stat = p.pagestat; stat = stat.replace(/{from}/, r1); stat = stat.replace(/{to}/, r2); stat = stat.replace(/{total}/, p.total); /*modify by lwj 10.7.16*/ /* $('.pPageStat', this.pDiv).html(stat); */ if(p.usepager){ $('.pPageStat', this.pDiv).html(stat); } }, /* populate: function() { //get latest data //log.trace("开始访问数据源"); if (this.loading) return true; if (p.onSubmit) { var gh = p.onSubmit(); if (!gh) return false; } this.loading = true; if (!p.url) return false; $('.pPageStat', this.pDiv).html(p.procmsg); $('.pReload', this.pDiv).addClass('loading'); $(g.block).css({ top: g.bDiv.offsetTop }); if (p.hideOnSubmit) $(this.gDiv).prepend(g.block); //$(t).hide(); if ($.browser.opera) $(t).css('visibility', 'hidden'); if (!p.newp) p.newp = 1; if (p.page > p.pages) p.page = p.pages; //var param = {page:p.newp, rp: p.rp, sortname: p.sortname, sortorder: p.sortorder, query: p.query, qtype: p.qtype}; var param = [ { name: 'pageNumber', value: p.newp } , { name: 'pageSize', value: p.usepager ? p.rp : 1000} , { name: 'sortname', value: p.sortname } , { name: 'sortorder', value: p.sortorder } , { name: 'query', value: p.query } , { name: 'qtype', value: p.qtype } , { name: 'qop', value: p.qop } ]; //param = jQuery.extend(param, p.extParam); if (p.extParam) { for (var pi = 0; pi < p.extParam.length; pi++) param[param.length] = p.extParam[pi]; } $.ajax({ type: p.method, url: p.url, data: param, dataType: p.dataType, success: function(data) { if (data != null && data.error != null) { if (p.onError) { p.onError(data); g.hideLoading(); } } else { //g.addData(data); // modify by lwj 10.3.12 if(g.dealData(data)){ g.addData(g.changeJsonObject(data, {'pageNumber': p.newp, 'pageSize': p.rp})[0]); p.isSuccessSearch = true; }else{ g.hideLoading(); } } }, error: function(data) { try { if (p.onError) { p.onError(data); } else { alert("获取数据发生异常;") } g.hideLoading(); } catch (e) { } } }); }, */ /* 对表格进行遮罩操作 //add by lwj 10.4.19 modify by lwj 10.6.27 */ doMask: function(type){ //var o = document.getElementById(p.container_id); var o = g.gDiv;//modify by lwj 11.6.9 if(p.maskObject){ if(typeof(p.maskObject) == "string"){ o = document.getElementById(p.maskObject); }else if(typeof(p.maskObject) == "object"){ o = p.maskObject; } } if(!g.maskDiv){ g.maskDiv = document.createElement('div'); //creat blocker g.maskDiv.setAttribute("id", p.container_id+"_maskDiv"); g.maskDiv.className = 'gBlock'; $(g.maskDiv).fadeTo(0, p.blockOpacity); var innerIframe = " <iframe style=\"display: block; z-index: -1; filter: alpha(Opacity='0'); left: -1px;" +" left: expression(((parseInt(document.getElementById('"+p.container_id+"_maskDiv').currentStyle.borderLeftWidth)||0)*-1)+'px'); " +" width: expression(document.getElementById('"+p.container_id+"_maskDiv').offsetWidth+'px'); " +" position: absolute; top: -1px; " +" top: expression(((parseInt(document.getElementById('"+p.container_id+"_maskDiv').currentStyle.borderTopWidth)||0)*-1)+'px'); " +" height: expression(document.getElementById('"+p.container_id+"_maskDiv').offsetHeight+'px');\"" +" tabIndex=-1 src=\"\" frameBorder=0>" +" </iframe>"; $(g.maskDiv).prepend(innerIframe); } var gh = $(o).height(); //var gw = $(o).width(); var gw = $(o).width()+2;//modify by lwj 11.6.16 不然IE6右边会露一点遮不到 //var gtop = o.offsetTop; var gtop = 0;//modify by lwj 11.6.9 $(g.maskDiv).css({ width: gw, height: gh, //position: 'relative', position: 'absolute', //marginBottom: (gh * -1), marginBottom: 0,//modify by lwj 11.6.9 zIndex: 1//, //top: gtop,//modify by lwj 11.6.15 //left: '0px'//modify by lwj 11.6.15 }); if(!g.maskMsgDiv){ g.maskMsgDiv = document.createElement('div'); //creat blocker g.maskMsgDiv.className = 'grid-mask-msg'; $(g.maskMsgDiv).html("<div>请稍候...</div>"); } if(type == 'mask'){ if(!g.tmpDiv){ g.tmpDiv = document.createElement('div'); //creat blocker g.tmpDiv.className = p.gridClass; } $(g.tmpDiv).append(g.maskDiv); $(g.tmpDiv).append(g.maskMsgDiv); if(p.maskObject){ $(o).prepend(g.tmpDiv); }else{ $(this.gDiv).prepend(g.tmpDiv); } //---------------start----------------------// // modify by lwj 11.6.16 //var t = Math.round($(o).height() / 2 - ($(g.maskMsgDiv).height() - parseInt($(g.maskMsgDiv).css("padding-top")) - parseInt($(g.maskMsgDiv).css("padding-bottom"))) / 2)+"px"; //var l = Math.round($(o).width() / 2 - ($(g.maskMsgDiv).width() - parseInt($(g.maskMsgDiv).css("padding-left")) - parseInt($(g.maskMsgDiv).css("padding-right"))) / 2)+"px"; var t = Math.round($(o).height() / 2 - ($(g.maskMsgDiv).height() - parseInt($(g.maskMsgDiv).css("padding-top")) - parseInt($(g.maskMsgDiv).css("padding-bottom"))) / 2); var l = Math.round($(o).width() / 2 - ($(g.maskMsgDiv).width() - parseInt($(g.maskMsgDiv).css("padding-left")) - parseInt($(g.maskMsgDiv).css("padding-right"))) / 2); l = l - 4;//减4是因为DIV 样式 padding: 2px; var _top, _left; if(p.maskObject){ _top = $(o).offset().top + t + "px"; _left = $(o).offset().left + l + "px"; }else{ _top = t + "px"; _left = l + "px"; } //$(g.maskMsgDiv).css("top", t); //$(g.maskMsgDiv).css("left", l); $(g.maskMsgDiv).css("top", _top); $(g.maskMsgDiv).css("left", _left); //---------------end----------------------// }else if(type == 'unmask'){ $(g.maskMsgDiv).remove(); $(g.maskDiv).remove(); $(g.tmpDiv).remove(); } }, getParentId: function(_param){ var keyValue = _param.keyValue; var tr = null; for(var i=0; i<p.colModel.length; i++){ if(p.colModel[i].name == _param.keyId){//说明是关键属性列 var $trs = $("tbody tr[id^="+p.table_id+"_row_]", g.bDiv); for(var j=0; j<$trs.length; j++){ var _tds = $($trs[j]).children("td"); //--------------start-------------------// //modify by chw 12.05.02 //i的值就是关键属性列所在的td的下标(分有勾选框跟无勾选框状态)。 //alert($("div", $(_tds[(p.showcheckbox ? i+1 : i)])).html()); var text = $("div", $(_tds[(p.showcheckbox ? i+1 : i)])).attr("title");//text(); //alert(text); if(text == _param.keyValue){ tr = $trs[j]; break; } //--------------end-------------------// } } } if(tr!=null){ var tbodyPrefix = p.table_id + "_tbody_"; var parentId = $(tr).parent("tbody").attr("id"); _param.parentId = parentId.substr(tbodyPrefix.length, parentId.length); } /* var tbodyPrefix = p.table_id + "_tbody_"; for(var i=0; i<trs.length; i++){ var tr = $(trs[i]); if(tr.attr("chd").indexOf(keyValue) > -1){ parentId = tr.parent("tbody").attr("id"); _param.parentId = parentId.substr(tbodyPrefix.length, parentId.length); break; } } */ return _param.parentId; }, getChildrenLen: function(_param){ var keyValue = _param.keyValue; var trs = $("tbody tr[id^="+p.table_id+"_row_]", g.bDiv); var tbodyPrefix = p.table_id + "_tbody_"; for(var i=0; i<trs.length; i++){ var tr = $(trs[i]); if(tr.attr("chd").indexOf(keyValue) > -1){ parentId = tr.parent("tbody").attr("id"); _param.parentId = parentId.substr(tbodyPrefix.length, parentId.length); break; } } return _param.parentId; }, /*----------------start---------------*/ //add by lwj 10.8.10 添加孩子行 appendChild: function(data, param){ //alert("aa:"+JSON.encode(data)); if (!data) { if(p.usepager){ $('.pPageStat', this.pDiv).html(p.errormsg); } return false; } function doChildChk(parentId){ //对钩选框ID对应的TBODY下的钩选框(儿子钩选框)进行关联操作 $("tbody[name='"+p.table_id+"_tbody_"+parentId+"']", g.bDiv).each(function(){ $(":checkbox.itemchk", this).each(function(){ if(this.name == (p.table_id+"_chk_"+parentId)){ chkFn.call(this); var id = this.id.substring((p.table_id+"_chk_").length, this.id.length); doChildChk(id); } }); }); } function doChildPic(parentId){ var cObj = $("tbody[name='"+p.table_id+"_tbody_"+parentId+"']", g.bDiv); if(cObj.length){ //-----------------------start-------------------------------// //modify chw 12.04.26 //添加文件夹打开或者关闭样式 //父亲文件夹图标换成打开状态 $("#"+p.table_id+"_row_link_div_"+parentId).removeClass("treegrid_row_link_plus_close_pic_div"); if(p.linkPicClass && p.linkPicClass.closeClass){ $("#"+p.table_id+"_row_link_div_"+parentId).removeClass(p.linkPicClass.closeClass); } $("#"+p.table_id+"_row_link_div_"+parentId).addClass("treegrid_row_link_plus_open_pic_div"); if(p.linkPicClass && p.linkPicClass.openClass){ $("#"+p.table_id+"_row_link_div_"+parentId).addClass(p.linkPicClass.openClass); } //-----------------------------------end--------------------------// $("#"+p.table_id+"_row_link_div_"+parentId).attr("title", "隐藏子数据"); cObj.each(function(){ /*this.style.display = "block";*/ this.style.display = "";// modify by lwj 10.12.07 block在火狐下会错位 //modify by chw 12.10.16 //结构改变,将div改为ins //$("tr div[class^='treegrid_row_link_plus_']", this).each(function(){ $("tr ins[class^='treegrid_row_link_plus_']", this).each(function(){ //modify by chw 12.11.06 //如果插入数据时没有删除原先的数据,则因为是使用bind方法绑定事件,导致原先的对象会绑定多次事件 //所以需要判断当前对象是否有绑定了某个事件 if(!$(this).data("events") || !$(this).data("events")["click"]) { picFn.call(this); var id = this.id.substring((p.table_id+"_row_link_div_").length, this.id.length); doChildPic(id); } }); }); } } function removeChild(parentId){ $("tbody[name='"+p.table_id+"_tbody_"+parentId+"']", g.bDiv).each(function(){ var id = this.id.substring((p.table_id+"_tbody_").length, this.id.length); removeChild(id); $(this).remove(); }); } function fireChildRowsEvent(parentId){ var cObj = $("tbody[name='"+p.table_id+"_tbody_"+parentId+"']", g.bDiv); cObj.each(function(){ var r = $("tr", this)[0]; g.rowProp.call(r); var id = this.id.substring((p.table_id+"_tbody_").length, this.id.length); fireChildRowsEvent(id); }); } function recuChild(parentId){ var obj = null; var child = $("tbody[name='"+parentId+"']", g.bDiv); if(child.length > 0){ obj = recuChild($(child[child.length-1]).attr("id")); }else{ obj = $("tbody[id='"+parentId+"']", g.bDiv); } return obj; } //如果调用appendChild方法允许删除原先的孩子数据 if(param.noDel != undefined && !param.noDel){ //将父亲行下的所有子行删除 removeChild(param.parentId); } var tbhtml = this.parseData(data); var parentObj = $("#"+p.table_id+"_tbody_"+param.parentId); //再将孩子加入父亲行下面 //$(tbhtml.join("")).insertAfter(parentObj); var c = $(tbhtml.join(""));// modify by chw 12.1.14 //modify by chw 12.11.06 //如果调用appendChild方法时,不允许删除原先的孩子数据,则直接插入到当前孩子节点的后面。 if(param.noDel != undefined && param.noDel){ var childTrs = $("tbody[name='"+p.table_id+"_tbody_"+param.parentId+"']", g.bDiv); if(childTrs.length > 0){//如果当前父亲数据有孩子行,则需要递归到最后一个孩子节点那边,保证新插入的数据在最后一行 var child = recuChild($(childTrs[childTrs.length-1]).attr("id")); //c.insertAfter($(childTrs[childTrs.length-1])); c.insertAfter(child); }else{//如果没有孩子节点,则直接插入到当前父亲行后面 c.insertAfter(parentObj); } }else{ c.insertAfter(parentObj);// modify by chw 12.1.14 } //对加入的孩子行添加行事件 fireChildRowsEvent(param.parentId); this.applyEvent($("tr", c));// add by chw 12.1.14 var picFn = this.firePicEvent; var chkFn = this.fireChkEvent; doChildPic(param.parentId); //if(p.showcheckbox){ if(p.showcheckbox && p.cbLinked){//modify by lwj 12.5.14 加上钩选框是否关联孩子属性 doChildChk(param.parentId); //如果父亲行勾选框有勾选,则需要级联勾选孩子节点 alert($("tbody tr[id="+p.table_id+"_row_"+param.parentId+"]", g.bDiv).children("td.chboxtd").length); alert($("tbody tr[id="+p.table_id+"_row_"+param.parentId+"]", g.bDiv).children("td.chboxtd").children().children("input.itemchk").length); var checked = $("tbody tr[id="+p.table_id+"_row_"+param.parentId+"]", g.bDiv).children("td.chboxtd").children().children("input.itemchk")[0].checked; $("tbody tr[id^="+p.table_id+"_row_"+param.parentId+"_]", g.bDiv).each( function() { $("input.itemchk", this).each(function() { var ptr = $(this).parent().parent().parent(); if (checked) { this.checked = checked; ptr.addClass("trSelected"); $(this).attr("disabled", "disabled"); } else { this.checked = checked; ptr.removeClass("trSelected"); $(this).attr("disabled", ""); } if (p.onrowchecked) { p.onrowchecked.call(this); } g.freshCheckboxState(); }); } ); } }, /*----------------end---------------*/ populate: function() { //get latest data //log.trace("开始访问数据源"); if (this.loading) return true; if (p.onSubmit) { var gh = p.onSubmit(); if (!gh) return false; } this.loading = true; //if (!p.url) return false; /*----------------start---------------*/ //modify by lwj 10.6.21 //如果两个表格联动,后面的表格usepager属性为false,即不显示"页面操作菜单栏", //这时,当第一个表格点击查询第二个表格时,相关状态会在第一个表格的"页面操作菜单栏"中体现 if(p.usepager){ $('.pPageStat', this.pDiv).html(p.procmsg); $('.pReload', this.pDiv).addClass('loading'); } /*----------------end---------------*/ $(g.block).css({ top: g.bDiv.offsetTop }); if (p.hideOnSubmit){ /* modify by lwj 10.4.19 $(this.gDiv).prepend(g.block); //$(t).hide(); */ g.doMask('mask'); } if ($.browser.opera) $(t).css('visibility', 'hidden'); if (!p.newp){ p.newp = 1; } if (p.page > p.pages) p.page = p.pages; //var param = {page:p.newp, rp: p.rp, sortname: p.sortname, sortorder: p.sortorder, query: p.query, qtype: p.qtype}; var param = [ { name: 'pageNumber', value: p.newp } , { name: 'pageSize', value: p.usepager ? p.rp : 1000} , { name: 'sortname', value: p.sortname } , { name: 'sortorder', value: p.sortorder } , { name: 'query', value: p.query } , { name: 'qtype', value: p.qtype } , { name: 'qop', value: p.qop } ]; //param = jQuery.extend(param, p.extParam); if (p.extParam) { for (var pi = 0; pi < p.extParam.length; pi++) param[param.length] = p.extParam[pi]; } function doData(){ if(g.dealData(p.tableData)){ g.addData(g.changeJsonObject(p.tableData, {'pageNumber': p.newp, 'pageSize': p.rp})[0]); p.isSuccessSearch = true; }else{ g.hideLoading(); } } //alert(JSON.encode(p.tableData)); if(p.tableData && !p.url){ doData(); }else if(p.url){ $.ajax({ type: p.method, url: p.url, data: param, dataType: p.dataType, success: function(data) { //alert(JSON.encode(data)); if (data != null && data.error != null) { if (p.onError) { p.onError(data); g.hideLoading(); } } else { p.tableData = data; doData(); } }, error: function(data) { try { if (p.onError) { p.onError(data); } else { alert("获取数据发生异常"); } g.hideLoading(); } catch (e) { } } }); } }, doSearch: function() { var queryType = $('select[name=qtype]', g.sDiv).val(); var qArrType = queryType.split("$"); var index = -1; if (qArrType.length != 3) { p.qop = "Eq"; p.qtype = queryType; } else { p.qop = qArrType[1]; p.qtype = qArrType[0]; index = parseInt(qArrType[2]); } p.query = $('input[name=q]', g.sDiv).val(); //添加验证代码 if (p.query != "" && p.searchitems && index >= 0 && p.searchitems.length > index) { if (p.searchitems[index].reg) { if (!p.searchitems[index].reg.test(p.query)) { alert("你的输入不符合要求!"); return; } } } p.newp = 1; this.populate(); }, changePage: function(ctype) { //change page if (this.loading) return true; switch (ctype) { case 'first': p.newp = 1; break; case 'prev': if (p.page > 1) p.newp = parseInt(p.page) - 1; break; //modify by chw 12.04.05 //到达最后一页之后,因为p.newp被设置为1,导致点击下一页的按钮,会跑到第一页去 //case 'next': if (p.page < p.pages) p.newp = parseInt(p.page) + 1; break; case 'next': if (p.page < p.pages){ p.newp = parseInt(p.page) + 1; }else{ p.newp = p.pages; } break; case 'last': p.newp = p.pages; break; case 'input': var nv = parseInt($('.pcontrol input', this.pDiv).val()); if (isNaN(nv)) nv = 1; if (nv < 1) nv = 1; else if (nv > p.pages) nv = p.pages; $('.pcontrol input', this.pDiv).val(nv); p.newp = nv; break; } /* if (p.newp==p.page) return false; */ if (p.newp==p.page){ if(ctype!='reload' && ctype!='change'){ return false; } } /* if (p.onChangePage) p.onChangePage(p.newp); else this.populate(); */ if (p.onChangePage){ p.onChangePage(p.newp, p.rp); }else{ this.populate(); } }, cellProp: function(n, ptr, pth) { var tdDiv = document.createElement('div'); if (pth != null) { if (p.sortname == $(pth).attr('abbr') && p.sortname) { this.className = 'sorted'; } $(tdDiv).css({ textAlign: pth.align, width: $('div:first', pth)[0].style.width }); if (pth.hide) $(this).css('display', 'none'); } if (p.nowrap == false) $(tdDiv).css('white-space', 'normal'); if (this.innerHTML == '') this.innerHTML = '&nbsp;'; //tdDiv.value = this.innerHTML; //store preprocess value tdDiv.innerHTML = this.innerHTML; var prnt = $(this).parent()[0]; var pid = false; if (prnt.id) pid = prnt.id.substr(3); if (pth != null) { if (pth.format){ pth.format(tdDiv, pid); } } $("input.itemchk", tdDiv).each(function() { /*-------------start---------------*/ /* 这是原先的自有代码 $(this).click(function() { if (this.checked) { $(ptr).addClass("trSelected"); } else { $(ptr).removeClass("trSelected"); } if (p.onrowchecked) { p.onrowchecked.call(this); } }); */ /*-------------end---------------*/ /*----------------start---------------*/ //modify by lwj 10.3.9 $(this).bind('click', function() { if (this.checked) { $(ptr).addClass("trSelected"); } else { $(ptr).removeClass("trSelected"); } if (p.onrowchecked) { p.onrowchecked.call(this); } }); /*----------------end---------------*/ }); $(this).empty().append(tdDiv).removeAttr('width'); //wrap content //add editable event here 'dblclick',如果需要可编辑在这里添加可编辑代码 }, addCellProp: function() { var $gF = this.cellProp; //moidfy by chw 12.04.01 //$('tbody tr td', g.bDiv).each $("tbody tr[id^="+p.table_id+"_row_] td", g.bDiv).each ( function() { var n = $('td', $(this).parent()).index(this); var pth = $('th:eq(' + n + ')', g.hDiv).get(0); var ptr = $(this).parent(); $gF.call(this, n, ptr, pth); } ); $gF = null; }, /*-------------start---------------*/ /* 这是原先的自有代码 getCheckedRows: function() { var ids = []; $(":checkbox:checked", g.bDiv).each(function() { ids.push($(this).val()); }); return ids; }, */ /*-------------start---------------*/ /*----------------start---------------*/ //add by lwj 10.3.11 //添加getRowsData方法,获取所有钩选的行数据 封装后的JSON对象 //该方法只适用于 表格各行数据有钩选框的情况 getRowsData: function() { //var arr = $(":checkbox:checked", g.bDiv); /*----------------start---------------*/ //modify by lwj 10.7.7 //为了防止列中有别的钩选框 表格的钩选框有样式 itemchk var arr = $(":checkbox:checked.itemchk", g.bDiv); /*----------------end---------------*/ var len = arr.length; /* the old code var temp = ""; for(var i=0; i<len; i++){ temp = temp + "{},"; } temp = "["+temp.substr(0, temp.length-1)+"]"; var row_objects = eval(temp); */ //-----------------start----------------// // modify by lwj 11.2.23 var row_objects = []; for(var i=0; i<len; i++){ row_objects.push({}); } //-----------------end----------------// var chd = null; for(var i=0; i<len; i++){ chd = $(arr[i]).parent().parent().parent().attr("chd"); g.generalObject(row_objects, chd, i); } return row_objects; }, /*----------------end---------------*/ /*-----------------start----------------*/ openRow: function(_param){ if(_param && _param.identityColumn && _param.value){ var identityColumn = _param.identityColumn; var value = _param.value; var $trs = $("tbody tr[id^="+p.table_id+"_row_]", g.bDiv); for(var i=0, len=$trs.length; i<len; i++){ var rowData = g.getRowData($trs[i]); if(rowData[0][identityColumn] && rowData[0][identityColumn] == value){ var flag = true; var tr_id, id, divObj; var tBodyName = $($trs[i]).parent().attr("name"); var parentTbody = $("#"+tBodyName, g.bDiv); //如果$trs[i]是子行 if(tBodyName){ id = tBodyName.substr((p.table_id + "_tbody_").length, tBodyName.length); divObj = $("#"+p.table_id+"_row_link_div_"+id); if(divObj.hasClass("treegrid_row_link_plus_close_pic_div")){ flag = false; } } if(flag){ tr_id = $($trs[i]).attr("id"); id = tr_id.substr((p.table_id+"_row_").length, tr_id.length); g.doChildShow(id); } } } } }, closeRow: function(_param){ if(_param && _param.identityColumn && _param.value){ var identityColumn = _param.identityColumn; var value = _param.value; var $trs = $("tbody tr[id^="+p.table_id+"_row_]", g.bDiv); for(var i=0, len=$trs.length; i<len; i++){ var rowData = g.getRowData($trs[i]); if(rowData[0][identityColumn] && rowData[0][identityColumn] == value){ var flag = true; var tr_id, id, divObj; var tBodyName = $($trs[i]).parent().attr("name"); var parentTbody = $("#"+tBodyName, g.bDiv); //如果$trs[i]是子行 if(tBodyName){ id = tBodyName.substr((p.table_id + "_tbody_").length, tBodyName.length); divObj = $("#"+p.table_id+"_row_link_div_"+id); if(divObj.hasClass("treegrid_row_link_plus_close_pic_div")){ flag = false; } } if(flag){ tr_id = $($trs[i]).attr("id"); id = tr_id.substr((p.table_id+"_row_").length, tr_id.length); g.doChildHide(id); } } } } }, /*-----------------end---------------------*/ deleteRow: function(param){ var arr = []; if(param && param.rowNum){ var array = param.rowNum.split(",") str = ""; for(var i=0; i<array.length; i++){ if(!isNaN(parseInt(array[i]))){ if(str.indexOf(array[i]) == -1){ str = str + array[i] + ";"; arr[arr.length] = $("tbody tr[id^="+p.table_id+"_row_]:eq("+(parseInt(array[i]))+")", g.bDiv); } } } for(var i=0; i<arr.length; i++){ arr[i].remove(); } }else{ if(p.showcheckbox){ arr = $(":checkbox:checked.itemchk", g.bDiv).parent().parent().parent().filter(function(){ return $(this).parent().attr("noDel") != true || $(this).parent().attr("noDel") != "true"; }); }else{ //arr = $("tbody tr[id^="+p.table_id+"_row_].trSelected", g.bDiv); function circleAddObj(tbodyId){ var children = $("tbody[name^="+tbodyId+"]", g.bDiv).filter(function(){ return $(this).attr("noDel") != true || $(this).attr("noDel") != "true"; });; for(var j=0; j<children.length; j++){ //arr.push(children[j]); $(children[j]).remove(); circleAddObj($(children[j]).attr("id")); } } var selectTr = $("tbody tr[id^="+p.table_id+"_row_].trSelected", g.bDiv).filter(function(){ return $(this).parent().attr("noDel") != true || $(this).parent().attr("noDel") != "true"; });; if(selectTr.length > 0){ //arr.push(selectTr[0]); var tbodyId = selectTr.parent().attr("id"); circleAddObj(tbodyId); selectTr.remove(); } } if(arr && arr.length > 0){ arr.each(function(){ if(param.isNotDelTopRow){ if($(this).parent().attr("name") != undefined){ $(this).parent().remove(); } }else{ $(this).parent().remove(); } }); } } //如果用户将表格数据删除,则需要更新标题头的勾选框状态 g.freshCheckboxState(); }, getAllData: function(param){ if(!param.isList){ var $trs = $("tbody tr[id^="+p.table_id+"_row_]", g.bDiv).filter(function(){ return $(this).parent("tbody").attr("name") == undefined; });//获取顶级的行对象 var len = $trs.length; var row_objects = []; for(var i=0; i<len; i++){ row_objects.push({}); } //var tbodyPre = p.table_id+"_tbody_"; function circleAddData(row_object, tbodyId){ var childrenTbody = $("tbody[name='"+tbodyId+"']", g.bDiv); if(childrenTbody.length > 0){ row_object.children = []; var len = childrenTbody.length; for(var i=0; i<len; i++){ row_object.children.push({}); } for(var i=0; i<len; i++){ var $tr = $(childrenTbody[i]).children("tr"); var chd = $tr.attr("chd"); g.generalObject(row_object.children, chd, i); circleAddData(row_object.children[i], $(childrenTbody[i]).attr("id")); } }else{ row_object.children = null; } } for(var i=0; i<len; i++){ var chd = $($trs[i]).attr("chd"); //var parent = $($trs[i]).parent().attr("name"); g.generalObject(row_objects, chd, i); circleAddData(row_objects[i], $($trs[i]).parent("tbody").attr("id")); } return row_objects; }else{ var $trs = $("tbody tr[id^="+p.table_id+"_row_]", g.bDiv);//获取顶级的行对象 var len = $trs.length; var row_objects = []; for(var i=0; i<len; i++){ row_objects.push({}); } for(var i=0; i<len; i++){ var chd = $($trs[i]).attr("chd"); g.generalObject(row_objects, chd, i); } return row_objects; } }, /*----------------start---------------*/ //add by lwj 11.7.14 //增加freshCheckboxState方法,刷新钩选框的状态 freshCheckboxState: function(){ // if($("tbody tr", g.bDiv).length>0 && $("tbody tr input[type='checkbox'][disabled='']:not(:checked).itemchk", g.bDiv).length==0){ if($("tbody tr", g.bDiv).length>0 && $("tbody tr input[type='checkbox']:not(:disabled):not(:checked).itemchk", g.bDiv).length==0){ if($("tbody tr input[type='checkbox']:not(:disabled)", g.bDiv).length==0){ //当用户配置了disCheckbox属性为true,如果表格当中多有的数据都是disabled的话,则要将表头的勾选框去钩。 g.doUncheck(); }else{ g.doCheck(); } }else{ g.doUncheck(); } }, //增加doUncheck方法,列头栏的钩选框恢复去钩 doUncheck: function(){ $("th div input[type='checkbox']", g.hDiv).filter(function(){ return $(this).hasClass("noborder"); }).attr("checked", false); }, //增加doUncheck方法,列头栏的钩选框打钩 doCheck: function(){ $("th div input[type='checkbox']", g.hDiv).filter(function(){ return $(this).hasClass("noborder"); }).attr("checked", true); }, /*----------------end---------------*/ /*----------------start---------------*/ //add by lwj 10.3.11 //增加cancelAllSelectState方法,取消所有选中行的状态 cancelAllSelectState: function() { //modify by chw 12.04.01 //$("tbody tr", g.bDiv).each(function() { $("tbody tr[id^="+p.table_id+"_row_]", g.bDiv).each(function() { if($(this).attr("class").indexOf("trSelected") != -1){ $(this).removeClass("trSelected"); if(p.showcheckbox){ $("input:checkbox", this).attr("checked", false); } } }); g.freshCheckboxState(); }, /*----------------end---------------*/ /*----------------start---------------*/ //add by lwj 10.3.10 //增加generalObject方法 //根据处理对象 //@param row_objects JSON数组 //@param chd TR中的CH属性值 //@param index 行数据要存放在JSON数组中的索引 generalObject: function(row_objects, chd, index){ var data_array = chd.split("_FG$SP_"); var col_model = p.colModel; var col_name = "", col_value = ""; for(var i=0; i<col_model.length; i++){ col_name = col_model[i].name; col_value = data_array[i]; /* the old code execute({ 'col_name': col_name, 'object_str': "row_objects["+index+"]", 'col_value': col_value }); */ //---------------start--------------// // modify by lwj 11.2.23 execute({ col_name: col_name, row_object: row_objects[index], col_value: col_value }); //---------------end--------------// } function execute(param){ var col_name = param.col_name; var flag = col_name.indexOf("\."); //var object_str = param.object_str; var row_object = param.row_object;// modify by lwj 11.2.23 var col_value = param.col_value; if(flag == -1){ //eval(object_str+"."+col_name+"='"+col_value+"'"); row_object[col_name] = col_value;// modify by lwj 11.2.22 }else{ var front_str = col_name.substr(0, flag); var end_str = col_name.substr(flag+1, col_name.length); /* the old code if(!eval(object_str+"."+front_str)){ eval(object_str+"."+front_str+"={}"); } execute({ 'col_name': end_str, 'object_str': object_str+"."+front_str, 'col_value': col_value }); */ //---------------start--------------// // modify by lwj 11.2.23 if(!row_object[front_str]){ row_object[front_str] = {}; } execute({ col_name: end_str, row_object: row_object[front_str], col_value: col_value }); //---------------end--------------// } } }, /*----------------end---------------*/ getCellDim: function(obj) // get cell prop for editable event { var ht = parseInt($(obj).height()); var pht = parseInt($(obj).parent().height()); var wt = parseInt(obj.style.width); var pwt = parseInt($(obj).parent().width()); var top = obj.offsetParent.offsetTop; var left = obj.offsetParent.offsetLeft; var pdl = parseInt($(obj).css('paddingLeft')); var pdt = parseInt($(obj).css('paddingTop')); return { ht: ht, wt: wt, top: top, left: left, pdl: pdl, pdt: pdt, pht: pht, pwt: pwt }; }, rowProp: function() { if (p.rowhandler) { p.rowhandler(this); } if ($.browser.msie && $.browser.version < 7.0) { $(this).hover(function() { $(this).addClass('trOver'); }, function() { $(this).removeClass('trOver'); }); } /*----------------start----------------*/ /*add by lwj 增加行选中事件处理,只有不显示钩选框的情况下才生效*/ if(!p.showcheckbox){ $(this).click(function(){ if($(this).attr("class").indexOf("trSelected") == -1){ //$(g.bDiv).find("tr").each(function(){ // $(this).removeClass('trSelected'); //}); /*-------------start----------------*/ //modify by chw 12.04.01 //防止内嵌table导致获取不到正确的tr行 //var trs = $(g.bDiv).find("tr"); $(g.bDiv).find("tbody tr[id^="+p.table_id+"_row_]").each(function(){ $(this).removeClass('trSelected'); }); /*-------------end----------------*/ $(this).addClass('trSelected'); }else{ if(p.onRowSelectedChangeClass){ $(this).removeClass('trSelected'); } } }); } /*----------------end----------------*/ }, //---------------------start---------------------// //add by chw 12.11.09 //遍历判断tbody,添加属性noDel,用于调用删除行数据接口的时候,判断是否选中的行是否能删除 circleParent: function(parentId){ var parentObj = $("tbody[id='"+parentId+"']", g.bDiv); if(parentObj && parentObj.length >=1){ var childrenObj = $("tbody[name='"+parentId+"']", g.bDiv); var count = 0; for(var i=0; i<childrenObj.length; i++){ var chkObj = $("input:checkbox.itemchk", $(childrenObj[i])); if(chkObj[0] && chkObj[0].checked && ($(childrenObj[i]).attr("noDel") == undefined || $(childrenObj[i]).attr("noDel") == false || $(childrenObj[i]).attr("noDel") == "false")){ count++; } } if(count == childrenObj.length){ parentObj.attr("noDel", "false"); }else{ parentObj.attr("noDel", "true"); } g.circleParent(parentObj.attr("name")); } }, //---------------------end---------------------// addRowProp: function() { var $gF = this.rowProp; //$('tbody tr', g.bDiv).each( $("tbody tr[id^="+p.table_id+"_row_]", g.bDiv).each( function() { $("input.itemchk", this).each(function() { var ptr = $(this).parent().parent().parent(); $(this).click(function() { if (this.checked) { ptr.addClass("trSelected"); } else { ptr.removeClass("trSelected"); } g.circleParent($(this).parent().parent().parent().parent().attr("name")); if (p.onrowchecked) { p.onrowchecked.call(this); } g.freshCheckboxState(); }); }); $gF.call(this); } ); $gF = null; }, checkAllOrNot: function(parent) { var ischeck = $(this).attr("checked"); //$('tbody tr', g.bDiv).each(function() { $("tbody tr[id^="+p.table_id+"_row_]", g.bDiv).each(function() { if (ischeck) { $(this).addClass("trSelected"); } else { $(this).removeClass("trSelected"); } }); $("input.itemchk", g.bDiv).each(function() { this.checked = ischeck; if(!ischeck){ $(this).attr("disabled", ""); } //Raise Event if (p.onrowchecked) { p.onrowchecked.call(this); } }); }, pager: 0 }; //create model if any if (p.colModel) { thead = document.createElement('thead'); tr = document.createElement('tr'); //p.showcheckbox ==true; if (p.showcheckbox) { var cth = jQuery('<th/>'); var cthch = jQuery('<input type="checkbox"/>'); cthch.addClass("noborder") cth.addClass("cth").attr({ 'axis': "col-1", width: "22", "isch": true }).append(cthch); $(tr).append(cth); } /*------------start-----------------*/ //add by lwj 10.8.6 //增加图标列。 //modify by chw 12.10.16 //去掉图标列,合并到第一列数据 /* var cth = jQuery('<th/>'); var cthpic = jQuery('<input type="hidden"/>'); cth.attr({ 'axis': "col-2", width: p.linkPicColumnWidth, "ispic": true }).append(cthpic); $(tr).append(cth); */ /*------------end-----------------*/ for (i = 0; i < p.colModel.length; i++) { var cm = p.colModel[i]; var th = document.createElement('th'); th.innerHTML = cm.display; if (cm.name && cm.sortable) $(th).attr('abbr', cm.name); //th.idx = i; $(th).attr('axis', 'col' + i); if (cm.align) th.align = cm.align; if (cm.width) $(th).attr('width', cm.width); if (cm.hide) { th.hide = true; } if (cm.toggle != undefined) { th.toggle = cm.toggle } if (cm.format) { th.format = cm.format; } if(cm.isKey){ th.isKey = cm.isKey; } if(cm.title_align){ th.title_align = cm.title_align; }else{ th.title_align = "center"; } $(tr).append(th); } $(thead).append(tr); $(t).prepend(thead); } // end if p.colmodel //init divs g.gDiv = document.createElement('div'); //create global container g.mDiv = document.createElement('div'); //create title container g.hDiv = document.createElement('div'); //create header container g.bDiv = document.createElement('div'); //create body container g.vDiv = document.createElement('div'); //create grip g.rDiv = document.createElement('div'); //create horizontal resizer g.cDrag = document.createElement('div'); //create column drag g.block = document.createElement('div'); //creat blocker g.nDiv = document.createElement('div'); //create column show/hide popup g.nBtn = document.createElement('div'); //create column show/hide button g.iDiv = document.createElement('div'); //create editable layer g.tDiv = document.createElement('div'); //create toolbar g.sDiv = document.createElement('div'); if (p.usepager) g.pDiv = document.createElement('div'); //create pager container g.hTable = document.createElement('table'); //set gDiv g.gDiv.className = p.gridClass; /*----------------start---------------*/ //modify by lwj 10.6.27 //当没有注册表格遮罩对象时,须对gDiv层添加样式 //if(!p.maskObject){//modify by lwj 11.6.15 $(g.gDiv).css({ position: "relative" }); //} /*----------------end---------------*/ //if (p.width != 'auto') g.gDiv.style.width = p.width + 'px'; //modify by lwj 10.3.1 使其支持百分比显示 if (p.width != 'auto') g.gDiv.style.width = p.width + ((p.width+"").indexOf("%")?"":'px'); //add conditional classes if ($.browser.msie) $(g.gDiv).addClass('ie'); if (p.novstripe) $(g.gDiv).addClass('novstripe'); $(t).before(g.gDiv); $(g.gDiv) .append(t) ; //set toolbar if (p.buttons) { g.tDiv.className = 'tDiv'; var tDiv2 = document.createElement('div'); tDiv2.className = 'tDiv2'; for (i = 0; i < p.buttons.length; i++) { var btn = p.buttons[i]; if (!btn.separator) { var btnDiv = document.createElement('div'); btnDiv.className = 'fbutton'; btnDiv.innerHTML = "<div><span style='padding-top: 3px;'>" + btn.displayname + "</span></div>"; btnDiv.disabled = btn.disabled; if (btn.title) { btnDiv.title = btn.title; } if (btn.bclass) $('span', btnDiv) .addClass(btn.bclass) .css({paddingLeft:20});//add by lwj 10.12.06; btnDiv.onpress = btn.onpress; btnDiv.name = btn.name; if (btn.onpress) { $(btnDiv).click ( function() { //this.onpress(this.name, g.gDiv); this.onpress(); } ); } $(tDiv2).append(btnDiv); if ($.browser.msie && $.browser.version < 7.0) { $(btnDiv).hover(function() { $(this).addClass('fbOver'); }, function() { $(this).removeClass('fbOver'); }); } } else { $(tDiv2).append("<div class='btnseparator'></div>"); } } $(g.tDiv).append(tDiv2); $(g.tDiv).append("<div style='clear:both'></div>"); $(g.gDiv).prepend(g.tDiv); } //set hDiv g.hDiv.className = 'hDiv'; $(t).before(g.hDiv); //set hTable g.hTable.cellPadding = 0; g.hTable.cellSpacing = 0; $(g.hDiv).append('<div class="hDivBox"></div>'); $('div', g.hDiv).append(g.hTable); var thead = $("thead:first", t).get(0); if (thead) $(g.hTable).append(thead); thead = null; if (!p.colmodel) var ci = 0; //setup thead $('thead tr:first th', g.hDiv).each ( function() { var thdiv = document.createElement('div'); if ($(this).attr('abbr')) { $(this).click( function(e) { if (!$(this).hasClass('thOver')) return false; var obj = (e.target || e.srcElement); if (obj.href || obj.type) return true; g.changeSort(this); } ); if ($(this).attr('abbr') == p.sortname) { this.className = 'sorted'; thdiv.className = 's' + p.sortorder; } } if (this.hide) $(this).hide(); /*if (!p.colmodel && !$(this).attr("isch")) {*/ if (!p.colmodel && !$(this).attr("isch") && !$(this).attr("ispic")) {//modify by lwj 10.8.6 $(this).attr('axis', 'col' + ci++); } /*---------start-------------*/ //add by lwj 10.8.9 列头加图标 if($(this).attr("ispic")){ $(thdiv).addClass("treegrid_row_link_head_pic_div"); } /*---------end-------------*/ //modify by chw 12.04.28 //新增表头文本对齐方式 //$(thdiv).css({ textAlign: this.align, width: this.width + 'px' }); $(thdiv).css({ textAlign: this.title_align, width: this.width + 'px' }); thdiv.innerHTML = this.innerHTML; $(this).empty().append(thdiv).removeAttr('width'); /*if (!$(this).attr("isch")) {*/ if (!$(this).attr("isch") && !$(this).attr("ispic")) {//modify by lwj 10.8.6 $(this).mousedown(function(e) { g.dragStart('colMove', e, this); }) .hover( function() { if (!g.colresize && !$(this).hasClass('thMove') && !g.colCopy) $(this).addClass('thOver'); if ($(this).attr('abbr') != p.sortname && !g.colCopy && !g.colresize && $(this).attr('abbr')) $('div', this).addClass('s' + p.sortorder); else if ($(this).attr('abbr') == p.sortname && !g.colCopy && !g.colresize && $(this).attr('abbr')) { var no = ''; if (p.sortorder == 'asc') no = 'desc'; else no = 'asc'; $('div', this).removeClass('s' + p.sortorder).addClass('s' + no); } if (g.colCopy) { var n = $('th', g.hDiv).index(this); if (n == g.dcoln) return false; if (n < g.dcoln) $(this).append(g.cdropleft); else $(this).append(g.cdropright); g.dcolt = n; } else if (!g.colresize) { var thsa = $('th:visible', g.hDiv); var nv = -1; for (var i = 0, j = 0, l = thsa.length; i < l; i++) { if ($(thsa[i]).css("display") != "none") { if (thsa[i] == this) { nv = j; break; } j++; } } var nv = $('th:visible', g.hDiv).index(this); var onl = parseInt($('div:eq(' + nv + ')', g.cDrag).css('left')); var nw = parseInt($(g.nBtn).width()) + parseInt($(g.nBtn).css('borderLeftWidth')); nl = onl - nw + Math.floor(p.cgwidth / 2); $(g.nDiv).hide(); $(g.nBtn).hide(); $(g.nBtn).css({ 'left': nl, top: g.hDiv.offsetTop }).show(); var ndw = parseInt($(g.nDiv).width()); $(g.nDiv).css({ top: g.bDiv.offsetTop }); if ((nl + ndw) > $(g.gDiv).width()) $(g.nDiv).css('left', onl - ndw + 1); else $(g.nDiv).css('left', nl); if ($(this).hasClass('sorted')) $(g.nBtn).addClass('srtd'); else $(g.nBtn).removeClass('srtd'); } }, function() { $(this).removeClass('thOver'); if ($(this).attr('abbr') != p.sortname) $('div', this).removeClass('s' + p.sortorder); else if ($(this).attr('abbr') == p.sortname) { var no = ''; if (p.sortorder == 'asc') no = 'desc'; else no = 'asc'; $('div', this).addClass('s' + p.sortorder).removeClass('s' + no); } if (g.colCopy) { $(g.cdropleft).remove(); $(g.cdropright).remove(); g.dcolt = null; } }) ; //wrap content } } ); //set bDiv g.bDiv.className = 'bDiv'; $(t).before(g.bDiv); $(g.bDiv) .css({ height: (p.height == 'auto') ? 'auto' : p.height + "px" }) .scroll(function(e) { g.scroll() }) .append(t) ; if (p.height == 'auto') { $('table', g.bDiv).addClass('autoht'); } //add td properties if (p.url == false || p.url == "") { g.addCellProp(); //add row properties g.addRowProp(); } //set cDrag var cdcol = $('thead tr:first th:first', g.hDiv).get(0); if (cdcol != null) { g.cDrag.className = 'cDrag'; g.cdpad = 0; g.cdpad += (isNaN(parseInt($('div', cdcol).css('borderLeftWidth'))) ? 0 : parseInt($('div', cdcol).css('borderLeftWidth'))); g.cdpad += (isNaN(parseInt($('div', cdcol).css('borderRightWidth'))) ? 0 : parseInt($('div', cdcol).css('borderRightWidth'))); g.cdpad += (isNaN(parseInt($('div', cdcol).css('paddingLeft'))) ? 0 : parseInt($('div', cdcol).css('paddingLeft'))); g.cdpad += (isNaN(parseInt($('div', cdcol).css('paddingRight'))) ? 0 : parseInt($('div', cdcol).css('paddingRight'))); g.cdpad += (isNaN(parseInt($(cdcol).css('borderLeftWidth'))) ? 0 : parseInt($(cdcol).css('borderLeftWidth'))); g.cdpad += (isNaN(parseInt($(cdcol).css('borderRightWidth'))) ? 0 : parseInt($(cdcol).css('borderRightWidth'))); g.cdpad += (isNaN(parseInt($(cdcol).css('paddingLeft'))) ? 0 : parseInt($(cdcol).css('paddingLeft'))); g.cdpad += (isNaN(parseInt($(cdcol).css('paddingRight'))) ? 0 : parseInt($(cdcol).css('paddingRight'))); $(g.bDiv).before(g.cDrag); var cdheight = $(g.bDiv).height(); var hdheight = $(g.hDiv).height(); $(g.cDrag).css({ top: -hdheight + 'px' }); /* 屏蔽拖动相关功能 modify by lwj 10.7.16*/ $('thead tr:first th', g.hDiv).each ( function() { var cgDiv = document.createElement('div'); $(g.cDrag).append(cgDiv); if (!p.cgwidth) p.cgwidth = $(cgDiv).width(); /* the old code $(cgDiv).css({ height: cdheight + hdheight }) .mousedown(function(e) { g.dragStart('colresize', e, this); })//屏蔽 by lwj 10.7.16 ; */ //modify by lwj 10.12.06 钩选框排除 /*-----------start------------*/ var isch = $(this).attr("isch"); var ispic = $(this).attr("ispic"); $(cgDiv).css({ height: cdheight + hdheight }); if(!isch){ $(cgDiv).mousedown(function(e) { g.dragStart('colresize', e, this); })//屏蔽 by lwj 10.7.16 open by lwj 10.12.06 ; } /*-----------end------------*/ //if ($.browser.msie && $.browser.version < 7.0) { g.fixHeight($(g.gDiv).height()); /*屏蔽 by lwj 10.7.16 open by lwj 10.12.06 */ $(cgDiv).hover( function() { g.fixHeight(); /* the old code $(this).addClass('dragging'); */ //modify by lwj 10.12.06 钩选框排除 if(!isch){ $(this).addClass('dragging'); } /*-----------end------------*/ }, function() { if (!g.colresize) $(this).removeClass('dragging') } ); //} } ); g.rePosDrag(); } //add strip if (p.striped) //$('tbody tr:odd', g.bDiv).addClass('erow'); $("tbody tr[id^='"+p.table_id+"_row_']:odd", g.bDiv).addClass('erow'); if (p.resizable && p.height != 'auto') { g.vDiv.className = 'vGrip'; $(g.vDiv) .mousedown(function(e) { g.dragStart('vresize', e) }) .html('<span></span>'); $(g.bDiv).after(g.vDiv); } if (p.resizable && p.width != 'auto' && !p.nohresize) { g.rDiv.className = 'hGrip'; $(g.rDiv) .mousedown(function(e) { g.dragStart('vresize', e, true); }) .html('<span></span>') .css('height', $(g.gDiv).height()) ; if ($.browser.msie && $.browser.version < 7.0) { $(g.rDiv).hover(function() { $(this).addClass('hgOver'); }, function() { $(this).removeClass('hgOver'); }); } $(g.gDiv).append(g.rDiv); } /*-------------start---------------*/ // modify by lwj 10.3.16 g.doUsePager = function(){ if (p.usepager) { g.pDiv.className = 'pDiv'; g.pDiv.innerHTML = '<div class="pDiv2"></div>'; $(g.bDiv).after(g.pDiv); var html = '<div class="pGroup"><div class="pFirst pButton" title="转到第一页"><span></span></div><div class="pPrev pButton" title="转到上一页"><span></span></div> </div><div class="btnseparator"></div> <div class="pGroup"><span class="pcontrol">当前第 <input type="text" size="1" value="1" />页,总页数 <span> 1 </span></span></div><div class="btnseparator"></div><div class="pGroup"> <div class="pNext pButton" title="转到下一页"><span></span></div><div class="pLast pButton" title="转到最后一页"><span></span></div></div><div class="btnseparator"></div><div class="pGroup"> <div class="pReload pButton" title="刷新"><span></span></div> </div> <div class="btnseparator"></div><div class="pGroup"><span class="pPageStat"></span></div>'; $('div', g.pDiv).html(html); $('.pReload', g.pDiv).click(function() { if(p.isSuccessSearch){ //g.populate(); g.changePage('reload'); } }); $('.pFirst', g.pDiv).click(function() { if(p.isSuccessSearch){ g.changePage('first'); } }); $('.pPrev', g.pDiv).click(function() { if(p.isSuccessSearch){ g.changePage('prev'); } }); $('.pNext', g.pDiv).click(function() { if(p.isSuccessSearch){ g.changePage('next'); } }); $('.pLast', g.pDiv).click(function() { if(p.isSuccessSearch){ g.changePage('last'); } }); $('.pcontrol input', g.pDiv).keydown(function(e) { if (e.keyCode==13 && p.isSuccessSearch){ g.changePage('input'); } }); if ($.browser.msie && $.browser.version < 7) $('.pButton', g.pDiv).hover(function() { $(this).addClass('pBtnOver'); }, function() { $(this).removeClass('pBtnOver'); }); if (p.useRp) { var opt = ""; for (var nx = 0; nx < p.rpOptions.length; nx++) { if (p.rp == p.rpOptions[nx]) sel = 'selected="selected"'; else sel = ''; opt += "<option value='" + p.rpOptions[nx] + "' " + sel + " >" + p.rpOptions[nx] + "&nbsp;&nbsp;</option>"; }; $('.pDiv2', g.pDiv).prepend("<div class='pGroup'>每页 <select name='rp'>" + opt + "</select>条</div> <div class='btnseparator'></div>"); $('select', g.pDiv).change( function() { if (p.onRpChange){ p.onRpChange(+this.value); } else { p.newp = 1; p.rp = this.value; if(p.isSuccessSearch){ //g.populate(); g.changePage('change'); } } } ); } //add search button if (p.searchitems) { $('.pDiv2', g.pDiv).prepend("<div class='pGroup'> <div class='pSearch pButton'><span></span></div> </div> <div class='btnseparator'></div>"); $('.pSearch', g.pDiv).click(function() { $(g.sDiv).slideToggle('fast', function() { $('.sDiv:visible input:first', g.gDiv).trigger('focus'); }); }); //add search box g.sDiv.className = 'sDiv'; sitems = p.searchitems; var sopt = ""; var op = "Eq"; for (var s = 0; s < sitems.length; s++) { if (p.qtype == '' && sitems[s].isdefault == true) { p.qtype = sitems[s].name; sel = 'selected="selected"'; } else sel = ''; if (sitems[s].operater == "Like") { op = "Like"; } else { op = "Eq"; } sopt += "<option value='" + sitems[s].name + "$" + op + "$" + s + "' " + sel + " >" + sitems[s].display + "&nbsp;&nbsp;</option>"; } if (p.qtype == '') p.qtype = sitems[0].name; $(g.sDiv).append("<div class='sDiv2'>快速检索:<input type='text' size='30' name='q' class='qsbox' /> <select name='qtype'>" + sopt + "</select> <input type='button' name='qclearbtn' value='清空' /></div>"); $('input[name=q],select[name=qtype]', g.sDiv).keydown(function(e) { if (e.keyCode == 13) g.doSearch() }); $('input[name=qclearbtn]', g.sDiv).click(function() { $('input[name=q]', g.sDiv).val(''); p.query = ''; g.doSearch(); }); $(g.bDiv).after(g.sDiv); } } } g.doUsePager(); /*-------------end---------------*/ /*-------------start---------------*/ /* 这是原先的自有代码 // add pager if (p.usepager) { g.pDiv.className = 'pDiv'; g.pDiv.innerHTML = '<div class="pDiv2"></div>'; $(g.bDiv).after(g.pDiv); var html = '<div class="pGroup"><div class="pFirst pButton" title="转到第一页"><span></span></div><div class="pPrev pButton" title="转到上一页"><span></span></div> </div><div class="btnseparator"></div> <div class="pGroup"><span class="pcontrol">当前第 <input type="text" size="1" value="1" />页,总页数 <span> 1 </span></span></div><div class="btnseparator"></div><div class="pGroup"> <div class="pNext pButton" title="转到下一页"><span></span></div><div class="pLast pButton" title="转到最后一页"><span></span></div></div><div class="btnseparator"></div><div class="pGroup"> <div class="pReload pButton" title="刷新"><span></span></div> </div> <div class="btnseparator"></div><div class="pGroup"><span class="pPageStat"></span></div>'; $('div', g.pDiv).html(html); $('.pReload', g.pDiv).click(function() { g.populate() }); $('.pFirst', g.pDiv).click(function() { g.changePage('first') }); $('.pPrev', g.pDiv).click(function() { g.changePage('prev') }); $('.pNext', g.pDiv).click(function() { g.changePage('next') }); $('.pLast', g.pDiv).click(function() { g.changePage('last') }); $('.pcontrol input', g.pDiv).keydown(function(e) { if (e.keyCode == 13) g.changePage('input') }); if ($.browser.msie && $.browser.version < 7) $('.pButton', g.pDiv).hover(function() { $(this).addClass('pBtnOver'); }, function() { $(this).removeClass('pBtnOver'); }); if (p.useRp) { var opt = ""; for (var nx = 0; nx < p.rpOptions.length; nx++) { if (p.rp == p.rpOptions[nx]) sel = 'selected="selected"'; else sel = ''; opt += "<option value='" + p.rpOptions[nx] + "' " + sel + " >" + p.rpOptions[nx] + "&nbsp;&nbsp;</option>"; }; $('.pDiv2', g.pDiv).prepend("<div class='pGroup'>每页 <select name='rp'>" + opt + "</select>条</div> <div class='btnseparator'></div>"); $('select', g.pDiv).change( function() { if (p.onRpChange) p.onRpChange(+this.value); else { p.newp = 1; p.rp = +this.value; g.populate(); } } ); } //add search button if (p.searchitems) { $('.pDiv2', g.pDiv).prepend("<div class='pGroup'> <div class='pSearch pButton'><span></span></div> </div> <div class='btnseparator'></div>"); $('.pSearch', g.pDiv).click(function() { $(g.sDiv).slideToggle('fast', function() { $('.sDiv:visible input:first', g.gDiv).trigger('focus'); }); }); //add search box g.sDiv.className = 'sDiv'; sitems = p.searchitems; var sopt = ""; var op = "Eq"; for (var s = 0; s < sitems.length; s++) { if (p.qtype == '' && sitems[s].isdefault == true) { p.qtype = sitems[s].name; sel = 'selected="selected"'; } else sel = ''; if (sitems[s].operater == "Like") { op = "Like"; } else { op = "Eq"; } sopt += "<option value='" + sitems[s].name + "$" + op + "$" + s + "' " + sel + " >" + sitems[s].display + "&nbsp;&nbsp;</option>"; } if (p.qtype == '') p.qtype = sitems[0].name; $(g.sDiv).append("<div class='sDiv2'>快速检索:<input type='text' size='30' name='q' class='qsbox' /> <select name='qtype'>" + sopt + "</select> <input type='button' name='qclearbtn' value='清空' /></div>"); $('input[name=q],select[name=qtype]', g.sDiv).keydown(function(e) { if (e.keyCode == 13) g.doSearch() }); $('input[name=qclearbtn]', g.sDiv).click(function() { $('input[name=q]', g.sDiv).val(''); p.query = ''; g.doSearch(); }); $(g.bDiv).after(g.sDiv); } } */ /*-------------end---------------*/ $(g.pDiv, g.sDiv).append("<div style='clear:both'></div>"); // add title if (p.title) { g.mDiv.className = 'mDiv'; g.mDiv.innerHTML = '<div class="ftitle">' + p.title + '</div>'; $(g.gDiv).prepend(g.mDiv); if (p.showTableToggleBtn) { $(g.mDiv).append('<div class="ptogtitle" title="Minimize/Maximize Table"><span></span></div>'); $('div.ptogtitle', g.mDiv).click ( function() { $(g.gDiv).toggleClass('hideBody'); $(this).toggleClass('vsble'); } ); } g.rePosDrag(); } //setup cdrops g.cdropleft = document.createElement('span'); /*------------------start-----------------*/ // by lwj 10.9.13 屏蔽表头列 鼠标经过时的 箭头样式 /* the old code g.cdropleft.className = 'cdropleft'; */ /*------------------end-----------------*/ g.cdropright = document.createElement('span'); /*------------------start-----------------*/ // by lwj 10.9.13 屏蔽表头列 鼠标经过时的 箭头样式 /* the old code g.cdropright.className = 'cdropright'; */ /*------------------end-----------------*/ //add block /*----------------start---------------*/ // modify by lwj 10.6.27 //g.block.className = 'gBlock'; /*----------------end---------------*/ var blockloading = $("<div/>"); blockloading.addClass("loading"); $(g.block).append(blockloading); var gh = $(g.bDiv).height(); var gtop = g.bDiv.offsetTop; $(g.block).css( { width: g.bDiv.style.width, height: gh, position: 'relative', marginBottom: (gh * -1), zIndex: 1, top: gtop, left: '0px' } ); $(g.block).fadeTo(0, p.blockOpacity); // add column control if ($('th', g.hDiv).length) { g.nDiv.className = 'nDiv'; g.nDiv.innerHTML = "<table cellpadding='0' cellspacing='0'><tbody></tbody></table>"; $(g.nDiv).css( { marginBottom: (gh * -1), display: 'none', top: gtop } ).noSelect() ; var cn = 0; $('th div', g.hDiv).each ( function() { var kcol = $("th[axis='col" + cn + "']", g.hDiv)[0]; if (kcol == null) return; var chkall = $("input[type='checkbox']", this); if (chkall.length > 0) { chkall[0].onclick = g.checkAllOrNot; return; } /*----------------start---------------*/ // add by lwj 10.8.6 //加上图片列判断 var pic = $("input[type='hidden']", this); if (pic.length > 0) { return; } /*----------------end---------------*/ if (kcol.toggle == false || this.innerHTML == "") { cn++; return; } var chk = 'checked="checked"'; if (kcol.style.display == 'none') chk = ''; $('tbody', g.nDiv).append('<tr><td class="ndcol1"><input type="checkbox" ' + chk + ' class="togCol noborder" value="' + cn + '" /></td><td class="ndcol2">' + this.innerHTML + '</td></tr>'); cn++; } ); if ($.browser.msie && $.browser.version < 7.0) $('tr', g.nDiv).hover ( function() { $(this).addClass('ndcolover'); }, function() { $(this).removeClass('ndcolover'); } ); $('td.ndcol2', g.nDiv).click ( function() { //---------------start----------------------// //modify by chw 12.04.13 //如果初始化只有一个的话,此时,点击勾选,导致直接返回false,无法进行列显示隐藏切换 //if ($('input:checked', g.nDiv).length <= p.minColToggle && $(this).prev().find('input')[0].checked) return false; if ($('input:checked', g.nDiv).length < p.minColToggle && $(this).prev().find('input')[0].checked) return false; //-----------end--------------------// return g.toggleCol($(this).prev().find('input').val()); } ); $('input.togCol', g.nDiv).click ( function() { if ($('input:checked', g.nDiv).length < p.minColToggle && this.checked == false) return false; $(this).parent().next().trigger('click'); //return false; } ); $(g.gDiv).prepend(g.nDiv); $(g.nBtn).addClass('nBtn') .html('<div></div>') //.attr('title', 'Hide/Show Columns') .click ( function() { $(g.nDiv).toggle(); return true; } ); if (p.showToggleBtn) $(g.gDiv).prepend(g.nBtn); } // add date edit layer $(g.iDiv) .addClass('iDiv') .css({ display: 'none' }) ; $(g.bDiv).append(g.iDiv); // add flexigrid events $(g.bDiv) .hover(function() { $(g.nDiv).hide(); $(g.nBtn).hide(); }, function() { if (g.multisel) g.multisel = false; }) ; $(g.gDiv) .hover(function() { }, function() { $(g.nDiv).hide(); $(g.nBtn).hide(); }) ; //add document events /* 屏蔽拖动功能 modify by lwj 10.3.29*/ $(document) .mousemove(function(e) { g.dragMove(e) }) .mouseup(function(e) { g.dragEnd() }) .hover(function() { }, function() { g.dragEnd() }) ; //browser adjustments if ($.browser.msie && $.browser.version < 7.0) { $('.hDiv,.bDiv,.mDiv,.pDiv,.vGrip,.tDiv, .sDiv', g.gDiv) .css({ width: '100%' }); $(g.gDiv).addClass('ie6'); if (p.width != 'auto') $(g.gDiv).addClass('ie6fullwidthbug'); } g.rePosDrag(); g.fixHeight(); //make grid functions accessible t.p = p; t.grid = g; // load data /* //原先的代码 if (p.url && p.autoload) { g.populate(); } */ //-----------------start----------------// //生成表格后面,不然火狐下宽度不对 modify by lwj 11.6.15 /* if (p.autoload) { p.isSuccessSearch = true; g.populate(); } */ //-----------------end----------------// /*-------------start---------------*/ // add by lwj 10.6.22 //对装表格容器的第一个table加样式grid_layout_style,防止列过宽时,撑大表格 var pts = $("#"+p.container_id).parents("table"); if(pts.length){ var pt = $(pts[0]); if(!pt.hasClass("grid_layout_style")){ pt.addClass("grid_layout_style"); } } //-----------------start----------------// //生成表格后面,不然火狐下宽度不对 modify by lwj 11.6.15 if (p.autoload) { p.isSuccessSearch = true; g.populate(); } //-----------------start----------------// return t; }; var docloaded = false; $(document).ready(function() { docloaded = true }); $.fn.createTreeGrid = function(p) { return this.each(function() { if (!docloaded) { $(this).hide(); var t = this; $(document).ready ( function() { $.addTreeFlex(t, p); } ); } else { $.addTreeFlex(this, p); } }); }; //end flexigrid $.fn.noSelect = function(p) { //no select plugin by me :-) if (p == null) prevent = true; else prevent = p; if (prevent) { return this.each(function() { if ($.browser.msie || $.browser.safari) $(this).bind('selectstart', function() { return false; }); else if ($.browser.mozilla) { $(this).css('MozUserSelect', 'none'); $('body').trigger('focus'); } else if ($.browser.opera) $(this).bind('mousedown', function() { return false; }); else $(this).attr('unselectable', 'on'); }); } else { return this.each(function() { if ($.browser.msie || $.browser.safari) $(this).unbind('selectstart'); else if ($.browser.mozilla) $(this).css('MozUserSelect', 'inherit'); else if ($.browser.opera) $(this).unbind('mousedown'); else $(this).removeAttr('unselectable', 'on'); }); } }; //end noSelect })(jQuery); var NLTreeTable = function(param){ //------------------start---------------------// // modify by lwj 11.6.14 String.prototype.replaceAll = function(s1,s2){ return this.replace(new RegExp(s1,"gm"),s2); } //------------------end---------------------// // 引用默认属性 param = jQuery.extend({ container_id: "",//容器ID table_id: "",//表格ID tableData: false,//表格数据 onChangePage: false,//页数变化事件 onAppendChild: false,//请求子行数据时,所注册的方法 height: 200, //flexigrid插件的高度,单位为px sortname: "id",//默认排序字段 sortorder: "desc",//默认排序方式 width: 'auto', //宽度值,auto表示根据每列的宽度自动计算 linkPicColumnWidth: 40,//关联图标列的宽度 striped: false, //是否显示斑纹效果,默认是奇偶交互的形式 novstripe: false, maskObject: false,//表格请求数据时,需要遮罩的对象。可以为ID,也可以为html对象 minwidth: 30, //列的最小宽度 minheight: 80, //列的最小高度 resizable: false, //resizable table是否可伸缩 url: false, //ajax url,ajax方式对应的url地址 method: 'POST', // data sending method,数据发送方式 dataType: 'json', // type of data loaded,数据加载的类型,xml,json errormsg: '数据请求失败!', //错误提升信息 usepager: true, //是否分页 nowrap: false, //是否不换行 page: 1, //current page,默认当前页 total: 1, //total pages,总页面数 useRp: true, //use the results per page select box,是否可以动态设置每页显示的结果数 rp: 10, // results per page,每页默认的结果数 rpOptions: [10, 15, 20, 25, 40, 100], //可选择设定的每页结果数 title: "数据列表", //是否包含标题 pagestat: '显示记录从{from}到{to},总数 {total} 条', //显示当前页和总页面的样式 procmsg: '正在处理数据,请稍候 ...', //正在处理的提示信息 query: '', //搜索查询的条件 qtype: '', //搜索查询的类别 qop: "Eq", //搜索的操作符 nomsg: '没有符合条件的记录存在', //无结果的提示信息 minColToggle: 1, //minimum allowed column to be hidden showToggleBtn: false, //show or hide column toggle popup colModel中的toggle属性是 是否在标题栏的下拉 是否显示菜单中 显示 hideOnSubmit: true, //显示遮盖 showTableToggleBtn: false, //显示隐藏Grid autoload: false, //自动加载 blockOpacity: 0.5, //透明度设置 onToggleCol: false, //当在行之间转换时 onChangeSort: false, //当改变排序时 onSuccess: false, //成功后执行 onSubmit: false, // using a custom populate function,调用自定义的计算函数 showcheckbox: false, //是否显示第一列的checkbox(用于全选) rowhandler: false, //是否启用行的扩展事情功能,在生成行时绑定事件,如双击,右键等(该事件每行构造的时候都会执行) onRowSelectedChangeClass: false,//add by lwj 10.3.3 当行选中时,要做的操作(只有当钩选框不显示的时候才有效) rowbinddata: true,//配合上一个操作,如在双击事件中获取该行的数据 extParam: [{}],//添加extParam参数可将外部参数动态注册到grid,实现如查询等操作 successResultID: "1",//后台处理时默认返回的成功的数字标识 showSuccessMsg: true,//后台处理时是否显示成功信息,默认不显示 showErrorMsg: true,//后台处理时是否显示错误信息,默认显示 cbLinked: true,//modify by lwj 12.5.14 加上钩选框是否关联孩子属性 //Style gridClass: "bbit-grid-tree", picOnMouseover: false, //配置第二列图标是否有mouseover事件,默认是没有 linkPicClass: false //自定义节点打开、关闭、以及叶子节点的图标样式 }, param); param.striped = false; //屏蔽显示斑纹效果 param.resizable = false; //resizable table是否可伸缩 var subLen = 25;//列头栏25 列头的1px不计算 subLen += 1;//排序样式 nBtn 1px; subLen += 1;//排序样式 nDiv 1px; if(param.title){ subLen += 23;//标题栏23 } if(param.buttons){ subLen += 26;//按钮栏26 } if(param.usepager){ subLen += 31;//分页栏31 } param.height = param.height - subLen; //-------------------start---------------------// // modify by lwj 11.6.16 if(param.height < 0){ param.height = 0; } //-------------------end---------------------// //param.colModel.unshift({display: '', name : '__TABLE_ROW_AND_ROW_LINK__',width : 50, sortable : false, align: 'left',hide: false,toggle : false}); /* *在容器中创建表格的html元素 */ function createTreeTable(){ jQuery("#"+param.container_id).append("<table id=\""+param.table_id+"\" style=\"display:none\"></table>"); } createTreeTable(); var treeGridObj = jQuery("#"+param.table_id).createTreeGrid(param); /*-------------start---------------*/ /* 这是原先的自有代码 $.fn.flexReload = function(p) { // function to reload grid return this.each(function() { if (this.grid && this.p.url) this.grid.populate(); }); }; //end flexReload*/ /*-------------end---------------*/ /*-------------start---------------*/ // modify by lwj 10.3.11 修改flexReload方法 this.flexReload = function(extParam, tableData) { // function to reload grid return treeGridObj.each(function() { if (treeGridObj[0].grid){ var param = { 'newp': treeGridObj[0].p.newp ? treeGridObj[0].p.newp : null, 'extParam': extParam ? extParam : [{}] }; if(tableData){ param.tableData = tableData; } treeGridObj[0].grid.freshParam(param); treeGridObj[0].grid.populate(); } }); }; //end flexReload /*-------------end---------------*/ /*-------------start---------------*/ // add by lwj 10.3.15 增加clearAllRows方法 this.clearAllRows = function() { if (treeGridObj[0].grid) { treeGridObj[0].grid.clearAllRows(); } }; //end flexReload /*-------------end---------------*/ //重新指定宽度和高度 this.flexResize = function(w, h) { //var p = { width: w, height: h-subLen }; //----------------start------------------// //modify by lwj 11.6.15 var p = {}; if(w){ p.width = w; } if(h){ h = parseInt(h,10); p.height = h-subLen; if(p.height < 0){ p.height = 0; } } //----------------end------------------// return treeGridObj.each(function() { if (treeGridObj[0].grid) { jQuery.extend(treeGridObj[0].p, p); treeGridObj[0].grid.reSize(); } }); } /* this.ChangePage = function(type) { return treeGridObj.each(function() { if (treeGridObj[0].grid) { treeGridObj[0].grid.changePage(type); } }) } */ this.flexOptions = function(p) { //function to update general options return treeGridObj.each(function() { if (treeGridObj[0].grid) jQuery.extend(treeGridObj[0].p, p); }); }; //end flexOptions this.GetOptions = function() { if (treeGridObj[0].grid) { return treeGridObj[0].p; } return null; } this.getCheckedRows = function() { if (treeGridObj[0].grid) { return treeGridObj[0].grid.getCheckedRows(); } return []; } /*-----------------start---------------------*/ //add by lwj 10.3.8 //增加search方法 //传入额外的初始化参数 this.search = function(extParam, tableData){ if (treeGridObj[0].grid) { var param = { 'newp': treeGridObj[0].p.newp ? treeGridObj[0].p.newp : null, 'extParam': extParam ? extParam : [{}] }; if(tableData){ param.tableData = tableData; } treeGridObj[0].grid.freshParam(param); treeGridObj[0].grid.populate(); } } /*-----------------end---------------------*/ /*-----------------start---------------------*/ //add by lwj 10.3.8 //增加getRowData方法 this.getRowData = function(row_object){ if (treeGridObj[0].grid) { return treeGridObj[0].grid.getRowData(row_object); } } /*-----------------end---------------------*/ /*-----------------start---------------------*/ //add by lwj 10.3.11 //增加getRowsData方法 this.getRowsData = function(){ if (treeGridObj[0].grid) { return treeGridObj[0].grid.getRowsData(); } } /*-----------------end---------------------*/ /*-----------------start---------------------*/ //add by lwj 10.3.8 //增加cancelAllSelectState方法,取消所有选中行的状态 this.cancelAllSelectState = function(){ if (treeGridObj[0].grid) { treeGridObj[0].grid.cancelAllSelectState(); } } /*-----------------end---------------------*/ /*-----------------start---------------------*/ //add by lwj 10.7.5 //增加mask遮罩方法 this.mask = function(){ if (treeGridObj[0].grid) { treeGridObj[0].grid.doMask('mask');; } } /*-----------------end---------------------*/ /*-----------------start---------------------*/ //add by lwj 10.3.8 //增加unmask方法,取消遮罩 this.unmask = function(){ if (treeGridObj[0].grid) { treeGridObj[0].grid.doMask('unmask');; } } /*-----------------end---------------------*/ this.flexToggleCol = function(cid, visible) { // function to reload grid return treeGridObj.each(function() { if (treeGridObj[0].grid) treeGridObj[0].grid.toggleCol(cid, visible); }); }; //end flexToggleCol this.flexAddData = function(data) { // function to add data to grid return treeGridObj.each(function() { if (treeGridObj[0].grid) treeGridObj[0].grid.addData(data); }); }; /*-----------------start---------------------*/ //add by lwj 10.8.12 //增加appendChild方法,展开子行数据 this.appendChild = function(data, param){ if (treeGridObj[0].grid) { if(param.parentId == undefined){ param.parentId = treeGridObj[0].grid.getParentId(param); } if(!param.noDel){//如果不允许删除孩子节点,则需要特殊处理 } var data = treeGridObj[0].grid.changeJsonObject(data, param); treeGridObj[0].grid.appendChild(data[0], param); } } /*-----------------end---------------------*/ /*-----------------start---------------------*/ //add by lwj 10.9.13 //增加stopPropagation方法,阻止事件冒泡 this.stopPropagation = function(e){ if (e && e.stopPropagation){ e.stopPropagation(); }else{ window.event.cancelBubble = true; } } /*-----------------end---------------------*/ /*----------------------start------------------------*/ this.openRow = function(param){ if(treeGridObj[0].grid){ treeGridObj[0].grid.openRow(param); } } /*----------------------end------------------------*/ /*----------------------start------------------------*/ this.closeRow = function(param){ if(treeGridObj[0].grid){ treeGridObj[0].grid.closeRow(param); } } /*----------------------end------------------------*/ /*---------------------start-----------------------*/ this.adjustOrder = function(param){ if(treeGridObj[0].grid){ treeGridObj[0].grid.adjustOrder(param); } } /*----------------------end------------------------*/ /*----------------------start------------------------*/ this.deleteRow = function(param){ if(treeGridObj[0].grid){ treeGridObj[0].grid.deleteRow(param); } } /*----------------------end------------------------*/ /*----------------------start------------------------*/ this.getAllData = function(param){ if(treeGridObj[0].grid){ return treeGridObj[0].grid.getAllData(param); } } /*----------------------end------------------------*/ } <file_sep>/web/js/UtilTool.js /** * 工具类 * @author weiys */ var util = new function() { //去掉字符串前后的空格; this.trim = function(sString) { return sString.replace(/(^\s*)|(\s*$)/g, ""); } //去掉左边的空格; this.lTrim = function(sString) { return sString.replace(/(^\s*)/g, ""); } //去掉右边的空格 this.rTrim = function(sString) { return sString.replace(/(\s*$)/g, ""); } /** * 根据控件ID获取控件对像 * @ctlId:控件ID */ this.getElement = function(ctlId) { if (!this.isNull(ctlId)) { if (typeof ctlId == "object") { return ctlId; } else { if (this.isNull(document.getElementById(ctlId))) { alert(ctlId + "控件不存在!"); } return document.getElementById(ctlId); } } else { return null; } } //判断对像是否为空 this.isNull = function(obj) { //alert(typeof obj); //alert(obj instanceof String); if (obj == undefined) { return true; } else if (obj == "undefined") { return true; } else if (obj == null) { return true; } else if (typeof obj == "string") { if (this.trim(obj) == "") { return true; } else { return false; } } else { return false; } } /** *多条件返回值 *source:用于判断的值 *condArr:[{cond:cond1,value:value1},{cond:cond2,value:value2}……]:为条件cond1返回value1 *other:不在条件里的默认值 *decode(sex,[{1:'男'},{2:'女'}],'未知'):当sex的值为1返回男,为2返回女,其他值返回未知 */ this.decode = function(source, condArr, other) { if (!this.isNull(source) && !this.isNull(condArr) && condArr.length > 0) { for (var i = 0; i < condArr.length; i++) { if (source == condArr[i].cond) { return condArr[i].value; } } if (!this.isNull(other)) { return other; } else { return ""; } } else { return ""; } } /** * 检查控件的值是否为空(验证作用) * @ctlName 控件中文描述 * @ctlId 控件id */ this.checkCtlIsNull = function(ctlName, ctlId) { var ctl = this.getElement(ctlId); if (!isNull(ctl)) { if (this.isNull(ctl.value)) { ctl.fucus; alert(ctlName + "不能为空!"); return true; } else { return false; } } else { alert(ctlId + "控件不存在!"); return true; } } /** * 获取控件的值 * @ctlId 控件id */ this.getCtlValue = function(ctlId) { var obj = this.getElement(ctlId); if (!this.isNull(obj)) { return obj.value; } else { alert(ctlId + "控件不存在!"); return ""; } } /** * 设置控件的值 * @ctlId 控件id * @value 控件值 */ this.setCtlValue = function(ctlId, value) { var obj = this.getElement(ctlId); if (!this.isNull(obj)) { obj.value = value; } else { alert(ctlId + "控件不存在!"); } } /** * 点击某个控件时获取其坐标和宽高大小 */ this.getPosition = function() { var aTag = event.srcElement; var eventObj = new Object(); eventObj.width = aTag.offsetWidth; eventObj.height = aTag.offsetHeight; var leftpos = 0; var toppos = 0; do { leftpos += aTag.offsetLeft; toppos += aTag.offsetTop; aTag = aTag.offsetParent; } while (aTag.tagName != "BODY"); eventObj.left = leftpos; eventObj.top = toppos; return eventObj; } /** * 判断页面某个元素是否是指定元素的子节点 * 判断obj对象是否是parentObj对象的子节点 */ this.isParentChild = function(obj, parentObj) { while (obj != undefined && obj != null && obj.tagName.toUpperCase() != 'BODY') { if (obj == parentObj) { return true; } obj = obj.parentNode; } return false; } /** * 替换字符串中的值 * @str 字符串 * @oldValue * @newValue */ this.replaceAll = function(str, oldValue, newValue) { var temp = str; if (!this.isNull(temp)) { temp = temp + ""; while (temp.indexOf(oldValue) >= 0) { temp = temp.replace(oldValue, newValue); } } return temp; } /** * 校验是否为数字 * @digit 检验值 */ this.isDigit = function(digit) { if (this.isNull(digit) || isNaN(digit)) { return false; } return true; } /** * 校验是否为合法日期 * @date 检验值 格式:(范围:18000101~29990101)(范围:1800-01-01~2999-01-01) */ this.isDate = function(date) { var pattern = /^(18|19|20|21|23|24|25|26|27|28|29)\d{2}-?(0?\d|1[012])-?(0?\d|[12]\d|3[01])$/; if (!pattern.exec(date)) { return false } return true } /** * 校验普通电话、传真号码:可以“+”开头,除数字外,可含有“-” * @tel 检验值 */ this.isTel = function(tel) { var patrn = /^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$/; if (!patrn.exec(tel)) { return false } return true } /** * 校验email地址 * @email 检验值 */ this.isEmail = function(email) { var patrn = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/; if (!patrn.exec(email)) { return false } return true } /** * 返回lista中所有不在listb中的元素集 * @id 判断lista和listb中对象是否相同的属性标志 */ this.getListNotInList = function(lista, listb, id) { var arr = []; if (!this.isNull(lista) && lista.length > 0) { if (this.isNull(listb) || listb.length <= 0) { arr = lista; } else { for (var i = 0; i < lista.length; i++) { for (var j = 0; j < listb.length; j++) { if (lista[i][id] == listb[j][id]) { break; } if (j + 1 == listb.length) { arr[arr.length] = lista[i]; } } } } } return arr; } /** * 返回lista中所有在listb中的元素集 * @id 判断lista和listb中对象是否相同的属性标志 */ this.getListInList = function(lista, listb, id) { var arr = []; if (!this.isNull(lista) && !this.isNull(listb) && listb.length > 0) { for (var i = 0; i < lista.length; i++) { for (var j = 0; j < listb.length; j++) { if (lista[i][id] == listb[j][id]) { arr[arr.length] = lista[i]; break; } } } } return arr; } /** * 将两个列表合并(去除相同的选项) * @id 判断lista和listb中对象是否相同的属性标志 */ this.mergeList = function(lista, listb, id) { var list = []; if (lista != null && listb != null) { if (lista.length > 0) { if (listb.length > 0) { for (var i = 0; i < listb.length; i++) { lista[lista.length] = listb[i] } for (var i = 0; i < lista.length; i++) { if (i == 0) { list[list.length] = lista[i]; } else { for (var j = 0; j < list.length; j++) { if (lista[i][id] == list[j][id]) { break; } if (j + 1 == list.length) { list[list.length] = lista[i]; } } } } } else { list = lista; } } else { list = listb; } } return list; } //=====================================复选框控件(checkbox)=====================================// /** * 设置复选框控件组全选或取消全选 * @tagName checkbox控件的name * @isChecked true:全选,false:取消全选 */ this.selectCheckBox = function(tagName, isChecked) { var arr = document.getElementsByName(tagName); if (!this.isNull(arr)) { for (var i = 0; i < arr.length; i++) { if (isChecked) { arr[i].checked = true; } else { arr[i].checked = false; } } } } /** * 判断复选框控件组是否全部选中 * @tagName checkbox控件的name */ this.isAllChecked = function(tagName) { var arr = document.getElementsByName(tagName); var flag = true if (!this.isNull(arr)) { var len = arr.length; for (i = 0; i < len; i++) { if (!arr[i].checked) { flag = false; break; } } } return flag; } /** * 获取复选框控件组中选中的值(用逗号隔开) * @tagName checkbox控件的name */ this.getCheckBoxValue = function(tagName) { var arr = document.getElementsByName(tagName); var value = ""; if (!this.isNull(arr)) { for (var i = 0; i < arr.length; i++) { if (arr[i].checked) { if (this.isNull(value)) { value = arr[i].value; } else { value += "," + arr[i].value; } } } } return value; } //==========================================================================================// //=====================================单选框控件(radio)=====================================// /** * 获取单选框控件组中选中的值 * @tagName radio控件的name */ this.getRadioValue = function(tagName) { var arr = document.getElementsByName(tagName); var value = ""; if (!this.isNull(arr)) { for (var i = 0; i < arr.length; i++) { if (arr[i].checked) { value = arr[i].value; } } } return value; } //==========================================================================================// //=====================================下拉框控件(select)=====================================// /** * 获取下拉框控件中选中的option对像(可以获得:option.value,option.text,option.index) * 选中时:selectedIndex获取选中下标 * @selId select控件的ID */ this.getSelectedOption = function(selId) { var sel = this.getElement(selId); var option = null; if (!this.isNull(sel)) { option = sel.options[sel.selectedIndex]; } return option; } /** * 获取下拉框控件的大小 * @selId select控件的ID */ this.getSelectSize = function(selId) { var sel = this.getElement(selId); if (!this.isNull(sel)) { return sel.options.length; } } /** * 获取下拉框控件的所有option对像(返回一个Array) * @selId select控件的ID */ this.getSelectOptons = function(selId) { var sel = this.getElement(selId); if (!this.isNull(sel) && this.getSelectSize(sel) > 0) { return sel.options; } else { return null; } } /** * 获取下拉框控件的所有option对像的值(用逗号隔开) * @selId select控件的ID */ this.getSelectValue = function(selId) { var options = this.getSelectOptons(selId); var values = ""; if (!this.isNull(options)) { for (var i = 0; i < options.length; i++) { if (i == 0) { values += options[i].value; } else { values += "," + options[i].value; } } } return values; } /** *判断下拉框中是否存在指定的中文值选项 *@selId select控件的ID *@text 中文值 */ this.isContainText = function(selId, text) { var flag = false; var options = this.getSelectOptons(selId); if (!this.isNull(options)) { for (var i = 0; i < options.length; i++) { if (options[i].text == text) { flag = true; break; } } } return flag; } /** * 删除下拉框控件中指定的下标的option * @selId select控件的ID */ this.removeSelect = function(selId, index) { var sel = this.getElement(selId); if (!this.isNull(sel) && !this.isNull(index) && this.getSelectSize(sel) > 0 && index >= 0) { sel.options.remove(index); } } /** * 清空下拉框控件的所有option * @selId select控件的ID */ this.clearSelect = function(selId) { var sel = this.getElement(selId); if (!this.isNull(sel) && !this.isNull(sel.options) && this.getSelectSize(sel) > 0) { while (this.getSelectSize(sel) > 0) { sel.options.remove(0); } } } /** * 往下拉框控件中加入一个新的option对像 * @selId select控件的ID * @text Option.text * @value Option.value */ this.addSelectOption = function(selId, text, value) { var sel = this.getElement(selId); if (!this.isNull(sel) && !this.isNull(text) && !this.isNull(value)) { var option = new Option(text, value); sel.options.add(option); } } /** * 根据value值选中下拉框的对应项 * @selId select控件的ID * @value Option.value */ this.selectedOption = function(selId, value) { var options = this.getSelectOptons(selId); if (!this.isNull(options)) { for (var i = 0; i < options.length; i++) { if (options[i].value == value) { options[i].selected = "selected"; break; } } } } //==========================================================================================// //========================================DIV动态显示=========================================// //在引用的JSP文件中写JS方法,再在JS方法中调用以下方法 /** * DIV渐渐展开 * @id * @timeOut:间隔时间 */ var isFirstClip = true; var clipTop = 0, clipRight = 0, clipBottom = 0, clipLeft = 0, width = 0, height = 0, clipWidthSpace = clipHeightSpace = 10; this.showClipDiv = function(id, timeOut) { var obj = document.getElementById(id); if (!this.isNull(obj)) { if (isFirstClip) { width = parseInt(obj.style.width, 10); height = parseInt(obj.style.height, 10); clipWidthSpace = width * 0.05; clipHeightSpace = height * 0.05; clipTop = height / 2 - 10; clipRight = width / 2 + 10; clipBottom = height / 2 + 10; clipLeft = width / 2 - 10; isFirstClip = false; } if (clipTop > 0 && clipBottom < height && clipRight < width && clipLeft > 0) { obj.style.clip = "rect(" + clipTop + "," + clipRight + "," + clipBottom + "," + clipLeft + ")"; clipTop = clipTop - clipHeightSpace; clipRight = clipRight + clipWidthSpace; clipBottom = clipBottom + clipHeightSpace; clipLeft = clipLeft - clipWidthSpace; window.setTimeout(function() { util.showClipDiv(obj.id, timeOut) }, timeOut) } else { clipTop = 0; clipRight = width; clipBottom = height; clipLeft = 0; obj.style.clip = "rect(" + clipTop + "," + clipRight + "," + clipBottom + "," + clipLeft + ")"; isFirstClip = true; } } } /** * DIV渐渐关闭 * @id * @timeOut:间隔时间 */ this.closeClipDiv = function(id, timeOut) { var obj = document.getElementById(id); if (!this.isNull(obj)) { if (isFirstClip) { width = parseInt(obj.style.width, 10); height = parseInt(obj.style.height, 10); clipWidthSpace = width * 0.05; clipHeightSpace = height * 0.05; clipTop = 0; clipRight = width; clipBottom = height; clipLeft = 0; isFirstClip = false; } if (clipTop < clipBottom) { obj.style.clip = "rect(" + clipTop + "," + clipRight + "," + clipBottom + "," + clipLeft + ")"; obj.style.display = ""; clipTop = clipTop + clipHeightSpace; clipRight = clipRight - clipWidthSpace; clipBottom = clipBottom - clipHeightSpace; clipLeft = clipLeft + clipWidthSpace; window.setTimeout(function() { util.closeClipDiv(obj.id, timeOut) }, timeOut) } else { clipTop = 0; clipRight = 0; clipBottom = 0; clipLeft = 0; obj.style.clip = "rect(" + clipTop + "," + clipRight + "," + clipBottom + "," + clipLeft + ")"; isFirstClip = true; } } } //==========================================================================================// } /***************************************************Map对像****************************************************/ /** * Map类 * @author weiys */ var Map = function() { var arr = new Array(); /** * 栈中对像个数 */ this.size = function() { return arr.length; } /** * 清空栈 */ this.clear = function() { arr = new Array(); } /** * 判断栈中是否存在key的对像 * @key */ this.contain = function(key) { var flag = false; if (this.size() > 0) { for (var i = 0; i < this.size(); i++) { if (arr[i].key == key) { flag = true; break; } } } return flag; } /** * 往栈中添加一个对像(栈中已存在则替换掉) * @key * @value */ this.put = function(key, value) { if (!util.isNull(key) && !util.isNull(value)) { var obj = new Object(); obj.key = key; obj.value = value; if (this.size() == 0) { arr[arr.length] = obj; } else { var i = 0; for (i = 0; i < this.size(); i++) { if (key == arr[i].key) { break; } } if (i == this.size()) { arr[arr.length] = obj; } else { arr[i] = obj; } } } } /** * 从栈中取一个指定key的对像,返回value的值 * @key */ this.get = function(key) { var value = null; if (!util.isNull(key) && this.size() > 0) { for (var i = 0; i < this.size(); i++) { if (key == arr[i].key) { value = arr[i].value; break; } } } return value; } /** * 从栈中取一个指定索引的对像(返回一个对像包括:obj.key,obj.value) * @index */ this.getByIndex = function(index) { var obj = null; if (this.size() > 0 && index < this.size()) { obj = arr[index]; } return obj; } /** * 从栈中删除一个指定KEY的对象 * @key */ this.deleteBykey = function(key) { if (this.contain(key)) { var tempArr = new Array; for (var i = 0; i < this.size(); i++) { if (key != arr[i].key) { tempArr[tempArr.length] = arr[i]; } } arr = tempArr; } } } <file_sep>/src/org/cola/sa/SelfAnalysisClient.java package org.cola.sa; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.cola.sa.bean.AttrBean; import org.cola.sa.bean.QryAttrBean; import com.alibaba.fastjson.JSON; import org.cola.sa.dao.SelfAnalysisDao; import org.cola.sa.dao.SelfAnalysisDaoImpl; /** * Description: <br/> * Copyright (C), 2001-2014, <NAME> <br/> * This program is protected by copyright laws. <br/> * Program Name:SelfAnalysisClient <br/> * Date:2014年12月8日 * * @author ChenMan * @version 1.0 */ public class SelfAnalysisClient { SelfAnalysisDao dao = new SelfAnalysisDaoImpl(); public String queryAttrList(QryAttrBean qryBean) { List<AttrBean> list = new ArrayList<AttrBean>(); AttrBean bean = new AttrBean(); list.add(bean); return JSON.toJSONString(list); } public List queryFrameList() { List list = null; try { list = dao.queryFrameList(); } catch (SQLException e) { e.printStackTrace(); } return list; } public List queryAttrClassList() { List list = null; try { list = dao.queryAttrClassList(); } catch (SQLException e) { e.printStackTrace(); } return list; } } <file_sep>/doc/ORACLE.sql drop table SA_USERS purge; -- Create table create table SA_USERS ( staff_id NUMBER, staff_name VARCHAR2(64), passwd varchar2(32), org_id NUMBER, staff_type NUMBER, create_time date ); -- Add comments to the columns comment on column SA_USERS.staff_type is '1:普通员工,2:经理'; select * from SA_USERS for update; commit; /* 属性版本编码 属性名称 数据周期 分析框架编码 分析框架名称 属性分类编码 属性分类名称 绑定维层编码 绑定维层名称 业务描述 敏感等级 加密策略 物理表编码 物理表中文名称 物理表名称 物理表字段 */ create table sa_users ( staff_id NUMBER, staff_name VARCHAR2(64), passwd varchar2(32), org_id NUMBER, staff_type NUMBER, create_time date ); /* create table sa_cfg_frame_detail as select * from pt166.sa_cfg_frame_detail where 1 = 0; truncate table sa_cfg_frame_detail; */ select * from sa_cfg_frame_detail; select tname, cname from sa_cfg_frame_detail group by tname, cname having count(0) > 1; create table sa_cfg_frame ( frame_id varchar2(64), frame_name varchar2(64), frame_desc varchar2(4000) ); create table sa_cfg_attr_class ( frame_id varchar2(64), attr_class_id varchar2(64), attr_class_name varchar2(256), attr_class_desc varchar2(4000) ); create table sa_cfg_attr ( attr_class_id varchar2(64), attr_id varchar2(64), attr_name varchar2(64), attr_desc varchar2(4000), dim_id varchar2(64), sensitive_type number,--敏感等级 encrypt_type number --加密类型 ); create table sa_cfg_dim ( dim_id varchar2(64), dim_name varchar2(64), dim_sql varchar2(4000) ); /* drop table sa_cfg_table purge; */ create table sa_cfg_table ( table_id varchar2(64), table_name varchar2(64), table_name_cn varchar2(64), table_desc varchar2(4000), update_date number, cycle_type number(1) --1,按日;2,按月 ); drop table sa_cfg_column purge; create table sa_cfg_column ( table_name varchar2(64), column_name varchar2(64), column_name_cn varchar2(64), column_type number, --1,数值类型;2,字符串;3,时间;4,BLOB column_desc varchar2(4000) ); create table sa_cfg_attr_column_rela ( attr_id varchar2(64), column_id varchar2(64) ); /* truncate table sa_cfg_frame; */ insert /*+APPEND NOLOGGING*/ into sa_cfg_frame (frame_id, frame_name) select distinct fcode, fname from sa_cfg_frame_detail ; commit; select * from sa_cfg_frame; /* truncate table sa_cfg_attr_class; */ insert /*+APPEND NOLOGGING*/ into sa_cfg_attr_class (frame_id, attr_class_id, attr_class_name) select distinct fcode, vcode, vname from sa_cfg_frame_detail; commit; select * from sa_cfg_attr_class where attr_class_id = 'V00000000450' for update; commit; select * from sa_cfg_attr_class; select * from sa_cfg_attr; select count(0) from sa_cfg_frame_detail; commit; select * from sa_cfg_attr; /* truncate table sa_cfg_attr; */ insert /*+APPEND NOLOGGING*/ into sa_cfg_attr (attr_class_id, attr_id, attr_name, attr_desc, dim_id, sensitive_type, encrypt_type) select distinct vcode, scode, sname, busi_desc, lcode, decode(seni_level, '工作秘密级', 1, '机密级', 2, '秘密级', 3), decode(encode_type, '完全开放', 1, '不开放', 2, '掩码加密', 3) from sa_cfg_frame_detail; commit; select * from sa_cfg_attr; select attr_id from sa_cfg_attr group by attr_id having count(0) > 1; select * from sa_cfg_frame_detail; /* truncate table sa_cfg_table; */ insert /*+APPEND NOLOGGING*/ into sa_cfg_table (table_id, table_name, table_name_cn, /*TABLE_DESC,*/ cycle_type) select distinct tcode, tname, tname_cn, decode(cycle_type, '日', 1, '月', 2, 99) from sa_cfg_frame_detail; commit; select * from sa_cfg_table; select table_name from sa_cfg_table group by table_name having count(0) > 1; insert /*+APPEND NOLOGGING*/ into sa_cfg_column () ; <file_sep>/src/org/cola/sa/bean/AttrClassBean.java package org.cola.sa.bean; public class AttrClassBean { private String frameId; private String attrClassId; private String attrClassName; public String getFrameId() { return frameId; } public void setFrameId(String frameId) { this.frameId = frameId; } public String getAttrClassId() { return attrClassId; } public void setAttrClassId(String attrClassId) { this.attrClassId = attrClassId; } public String getAttrClassName() { return attrClassName; } public void setAttrClassName(String attrClassName) { this.attrClassName = attrClassName; } } <file_sep>/web/js/NLComponent/table/com.newland.table.NLTable.js (function(a) { a.addFlex = function(u, w) { if (u.grid) { return false } a(u).show().attr({ cellPadding : 0, cellSpacing : 0, border : 0 }).removeAttr("width"); var z = { hset : {}, rePosDrag : function() { var p = 0 - this.hDiv.scrollLeft; if (this.hDiv.scrollLeft > 0) { p -= Math.floor(w.cgwidth / 2) } a(z.cDrag).css({ top : z.hDiv.offsetTop + 1 }); var g = this.cdpad; a("div", z.cDrag).hide(); a("thead tr:first th:visible", this.hDiv).each(function() { if (a(this).css("display") == "none") { return } var G = a("thead tr:first th:visible", z.hDiv).index(this); var F = parseInt(a("div", this).width()); var t = F; if (p == 0) { p -= Math.floor(w.cgwidth / 2) } F = F + p + g; a("div:eq(" + G + ")", z.cDrag).css({ left : F + "px" }).show(); p = F }) }, fixHeight : function(p) { p = false; if (!p) { p = a(z.bDiv).height() } var F = a(this.hDiv).height(); a("div", this.cDrag).each(function() { a(this).height(p + F) }); var t = parseInt(a(z.nDiv).height()); if (t > p) { a(z.nDiv).height(p).width(200) } else { a(z.nDiv).height("auto").width("auto") } a(z.block).css({ height : p, marginBottom : (p * -1) }); var g = z.bDiv.offsetTop + p; if (w.height != "auto" && w.resizable) { g = z.vDiv.offsetTop } a(z.rDiv).css({ height : g }) }, dragStart : function(G, F, t) { if (G == "colresize") { a(z.nDiv).hide(); a(z.nBtn).hide(); var H = a("div", this.cDrag).index(t); var g = a("th:visible div:eq(" + H + ")", this.hDiv) .width(); a(t).addClass("dragging").siblings().hide(); this.colresize = { startX : F.pageX, ol : parseInt(t.style.left), ow : g, n : H }; a("body").css("cursor", "col-resize") } else { if (G == "vresize") { var p = false; a("body").css("cursor", "row-resize"); if (t) { p = true; a("body").css("cursor", "col-resize") } this.vresize = { h : w.height, sy : F.pageY, w : w.width, sx : F.pageX, hgo : p } } else { if (G == "colMove") { a(z.nDiv).hide(); a(z.nBtn).hide(); this.hset = a(this.hDiv).offset(); this.hset.right = this.hset.left + a("table", this.hDiv).width(); this.hset.bottom = this.hset.top + a("table", this.hDiv).height(); this.dcol = t; this.dcoln = a("th", this.hDiv).index(t); this.colCopy = document.createElement("div"); this.colCopy.className = "colCopy"; this.colCopy.innerHTML = t.innerHTML; if (a.browser.msie) { this.colCopy.className = "colCopy ie" } a(this.colCopy).css({ position : "absolute", "float" : "left", display : "none", textAlign : t.align }); a("body").append(this.colCopy); a(this.cDrag).hide() } } } a("body").noSelect() }, calScrollBarWidth : function() { var G = document.createElement("p"); G.style.width = "100%"; G.style.height = "200px"; var H = document.createElement("div"); H.style.position = "absolute"; H.style.top = "0px"; H.style.left = "0px"; H.style.visibility = "hidden"; H.style.width = "200px"; H.style.height = "150px"; H.style.overflow = "hidden"; H.appendChild(G); document.body.appendChild(H); var p = G.offsetWidth; var F = G.offsetHeight; H.style.overflow = "scroll"; var g = G.offsetWidth; var t = G.offsetHeight; if (p == g) { g = H.clientWidth } if (F == t) { t = H.clientWidth } document.body.removeChild(H); window.scrollbarWidth = p - g; window.scrollbarHeight = F - t; return { scrollbarWidth : window.scrollbarWidth, scrollbarHeight : window.scrollbarHeight } }, calWidth : function(G) { var J = a("#" + w.container_id).outerWidth(); if (typeof w.width == "string" && w.width.indexOf("%") != -1) { if (w.showcheckbox) { J = J * parseFloat(w.width) * 0.01 - 2 - 32 } else { J = J * parseFloat(w.width) * 0.01 - 2 } } else { if (typeof w.width == "string" && w.width.indexOf("%") == -1) { if (w.showcheckbox) { J = parseFloat(w.width) - 32 - 2 } else { J = parseFloat(w.width) - 2 } } else { if (w.showcheckbox) { J = w.width - 32 - 2 } else { J = w.width - 2 } } } J = J * G.totalColsWidthPercent; var I = a("#" + w.container_id + " .bbit-grid .bDiv"); if (I[0].clientWidth < I[0].offsetWidth - 4) { J = J - z.calScrollBarWidth().scrollbarWidth } for ( var F = 0, t = w.colModel.length; F < t; F++) { var p = w.colModel[F]; var g; var H = a("#" + w.container_id + " .bbit-grid .hDiv th[axis=col" + F + "]"); if (typeof p.width == "string" && p.width.indexOf("%") != -1) { g = J * (parseFloat(p.width) * 0.01 / G.nowPerColPercent) - 10 } else { g = parseFloat(p.width) } H.attr("width", g); H.children("div").css("width", g); a(".bbit-grid .bDiv tr[id^='" + w.table_id + "_row_']") .each( function() { a(this).children("td").eq( w.showcheckbox ? F + 1 : F) .children("div") .css("width", g) }); z.rePosDrag() } }, calPerColPercent : function() { var t = 0; var O = 0; var J = 0; var K = 1; var g = true; var F = a("input.noborder", z.nDiv).filter(function() { return !a(this).attr("checked") }); var I = a("input.noborder", z.nDiv).filter(function() { return a(this).attr("checked") }); for ( var H = 0, L = w.colModel.length; H < L; H++) { var Q = w.colModel[H]; var R = Q.width; if (Q.hide) { var N = false; for ( var G = 0, M = F.length; G < M; G++) { var p = a( "th[axis='col" + a(F[G]).attr("value") + "']", this.hDiv).children() .text(); if (p == Q.display) { N = true; break } } for ( var G = 0, P = I.length; G < P; G++) { var p = a( "th[axis='col" + a(I[G]).attr("value") + "']", this.hDiv).children() .text(); if (p == Q.display) { N = true; break } } if (!N) { if (typeof Q.width == "string" && Q.width.indexOf("%") != -1) { O += parseInt(Q.width) } } } if (typeof R == "string" && R.indexOf("%") != -1) { g = true; J += parseInt(R) } else { g = false } } J = J * 0.01; for ( var H = 0, L = F.length; H < L; H++) { var R = a("th[axis='col" + a(F[H]).attr("value") + "']", this.hDiv).attr("oriWidth"); if (R.indexOf("%") == -1) { g = false; break } else { g = true } t += parseInt(R) } t = O + t; K = J - t * 0.01; return { isPercent : g, nowPerColPercent : K, hideColsWidth : t, totalColsWidthPercent : J } }, reSize : function() { a(this.gDiv).width(w.width); a(this.bDiv).height(w.height); var g = z.calPerColPercent(); if (g.isPercent) { z.calWidth(g) } }, dragMove : function(G) { if (this.colresize) { var p = this.colresize.n; var L = G.pageX - this.colresize.startX; var H = this.colresize.ol + L; var F = this.colresize.ow + L; if (F > w.minwidth) { a("div:eq(" + p + ")", this.cDrag).css("left", H); this.colresize.nw = F } } else { if (this.vresize) { var M = this.vresize; var J = G.pageY; var L = J - M.sy; if (!w.defwidth) { w.defwidth = w.width } if (w.width != "auto" && !w.nohresize && M.hgo) { var K = G.pageX; var t = K - M.sx; var g = M.w + t; if (g > w.defwidth) { this.gDiv.style.width = g + "px"; w.width = g } } var I = M.h + L; if ((I > w.minheight || w.height < w.minheight) && !M.hgo) { this.bDiv.style.height = I + "px"; w.height = I; this.fixHeight(I) } M = null } } }, dragEnd : function() { if (this.colresize) { var p = this.colresize.n; var g = this.colresize.nw; a("th:visible div:eq(" + p + ")", this.hDiv) .css("width", g); a("th:visible div:eq(" + p + ")", this.hDiv).parent("th") .css("width", g); a("tr", this.bDiv).each( function() { a( "td:visible div[candrag='true']:eq(" + p + ")", this) .css("width", g) }); this.hDiv.scrollLeft = this.bDiv.scrollLeft; a("div:eq(" + p + ")", this.cDrag).siblings().show(); a(".dragging", this.cDrag).removeClass("dragging"); this.rePosDrag(); this.fixHeight(); this.colresize = false } else { if (this.vresize) { this.vresize = false } else { if (this.colCopy) { a(this.colCopy).remove(); if (this.dcolt != null) { a(this.cdropleft).remove(); a(this.cdropright).remove(); this.rePosDrag() } this.dcol = null; this.hset = null; this.dcoln = null; this.dcolt = null; this.colCopy = null; a(".thMove", this.hDiv).removeClass("thMove"); a(this.cDrag).show() } } } a("body").css("cursor", "default"); a("body").noSelect(false) }, toggleCol : function(I, G) { var F = a("th[axis='col" + I + "']", this.hDiv)[0]; var H = a("thead th", z.hDiv).index(F); var g = a("input[value=" + I + "]", z.nDiv)[0]; var t = a("input[value=" + I + "]", z.eDiv)[0]; if (G == null) { G = F.hide } if (a("input:checked", z.nDiv).length < w.minColToggle && !G) { return false } if (G) { F.hide = false; a(F).show(); g.checked = true; if (t) { t.checked = true } } else { F.hide = true; a(F).hide(); g.checked = false; if (t) { t.checked = false } } a("tbody tr[id^='" + w.table_id + "_row_']", u).each( function() { var J = a(this).children("td"); if (G) { a(J[H]).show() } else { a(J[H]).hide() } }); var p = z.calPerColPercent(); if (p.isPercent) { z.calWidth(p) } this.rePosDrag(); if (w.onToggleCol) { w.onToggleCol(I, G) } return G }, switchCol : function(p, g) { a("tbody tr", u).each( function() { if (p > g) { a("td:eq(" + g + ")", this).before( a("td:eq(" + p + ")", this)) } else { a("td:eq(" + g + ")", this).after( a("td:eq(" + p + ")", this)) } }); if (p > g) { a("tr:eq(" + g + ")", this.nDiv).before( a("tr:eq(" + p + ")", this.nDiv)) } else { a("tr:eq(" + g + ")", this.nDiv).after( a("tr:eq(" + p + ")", this.nDiv)) } if (a.browser.msie && a.browser.version < 7) { a("tr:eq(" + g + ") input", this.nDiv)[0].checked = true } this.hDiv.scrollLeft = this.bDiv.scrollLeft }, scroll : function() { this.hDiv.scrollLeft = this.bDiv.scrollLeft; this.rePosDrag() }, hideLoading : function() { a(".pReload", this.pDiv).removeClass("loading"); if (w.hideOnSubmit) { z.doMask("unmask") } if (w.usepager) { a(".pPageStat", this.pDiv).html(w.errormsg) } this.loading = false }, addData : function(H) { if (w.preProcess) { H = w.preProcess(H) } a(".pReload", this.pDiv).removeClass("loading"); this.loading = false; if (!H) { if (w.usepager) { a(".pPageStat", this.pDiv).html(w.errormsg) } return false } var t = w.total; if (w.dataType == "xml") { w.total = +a("rows total", H).text() } else { w.total = H.total } if (w.total < 0) { w.total = t } if (w.total == 0) { a("tr, a, td, div", u).unbind(); a(u).empty(); w.pages = 1; w.page = 1; if (w.usepager) { this.buildpager(); a(".pPageStat", this.pDiv).html(w.nomsg) } if (w.hideOnSubmit) { z.doMask("unmask") } return false } w.pages = Math.ceil(w.total / w.rp); if (w.dataType == "xml") { w.page = +a("rows page", H).text() } else { w.page = H.page } if (w.usepager) { this.buildpager() } var p = a("thead tr:first th", z.hDiv); var I = a("thead tr:first th div", z.hDiv); var G = []; var F = H.oriDateValue; G.push("<tbody>"); if (w.dataType == "json") { if (H.rows != null) { a .each( H.rows, function(J, M) { G.push("<tr id='", w.table_id + "_row_", M.id, "'"); if (J % 2 && w.striped) { G.push(" class='erow'") } if (F && F.length > 0) { G.push(" value_type='" + F[J].type + "' date_value=" + F[J].value + " ") } if (w.rowbinddata) { var K = ""; for ( var J = 0; J < M.cell.length; J++) { if (typeof (M.cell[J]) == "string" && w.isFilter) { K = K + M.cell[J] .replace( /\</g, "&lt;") .replace( /\>/g, "&gt;") .replaceAll( '"', "&quot;") } else { K = K + M.cell[J] } if (J < M.cell.length - 1) { K = K + "_FG$SP_" } } G.push('chd="' + K + '"') } G.push(">"); var L = M.id; a(p) .each( function(O) { var S = ""; var Q = ""; G .push( "<td align='", this.align, "'"); var N = a(this) .attr( "axis") .substr( 3); if (w.sortname && w.sortname == a( this) .attr( "abbr")) { Q = "sorted" } if (this.hide) { G .push(" style='display:none;'") } var P = I[O].style.width; var T = []; var R = M.cell[N] || ""; if (N != "-1") { if (this.format) { R = this .format( R, L) } if (w.colModel[N].ct && w.colModel[N].ct.type == "date") { R = z .parseData({ data : R, colModel : w.colModel[N] }) } } if (typeof R == "string" && w.isFilter) { R = R .replace( /\</g, "&lt;") .replace( /\</g, "&lt;") .replaceAll( '"', "&quot;") } T .push( "<div candrag='true' title=\"" + R + "\" style='text-align:", this.align, ";width:" + P, ";"); if (w.nowrap == false) { T .push("white-space:normal;word-break:break-all;") } if (w.showcheckbox) { T .push(" padding:2px 4px 0px 4px;'>") } else { T .push(" padding:4px 4px 2px 4px;'>") } if (N == "-1") { if (w.disCheckbox) { T .push( "<input type='checkbox' id='chk_", M.id, "' class='itemchk' value='", M.id, "' disabled='disabled'/>") } else { T .push( "<input type='checkbox' id='chk_", M.id, "' class='itemchk' value='", M.id, "'/>") } if (Q != "") { Q += " chboxtd" } else { Q += "chboxtd" } } else { T.push(R) } T .push("</div>"); if (Q != "") { G .push( " class='", Q, "'") } G .push( ">", T .join(""), "</td>") }); G.push("</tr>") }) } } else { if (w.dataType == "xml") { i = 1; a("rows row", H) .each( function() { i++; var K = this; var J = new Array(); a("cell", K).each(function() { J.push(a(this).text()) }); var M = a(this).attr("id"); G.push("<tr id='", "row", M, "'"); if (i % 2 && w.striped) { G.push(" class='erow'") } if (w.rowbinddata) { G.push("chd='", J .join("_FG$SP_"), "'") } G.push(">"); var L = M; a(p) .each( function(O) { G .push( "<td align='", this.align, "'"); if (this.hide) { G .push(" style='display:none;'") } var Q = ""; var S = ""; var N = a(this) .attr( "axis") .substr( 3); if (w.sortname && w.sortname == a( this) .attr( "abbr")) { Q = "sorted" } var P = I[O].style.width; var T = []; T .push( "<div style='text-align:", this.align, ";width:", P, ";"); if (w.nowrap == false) { T .push("white-space:normal") } T.push("'>"); if (N == "-1") { T .push( "<input type='checkbox' id='chk_", M, "' class='itemchk' value='", M, "'/>"); if (Q != "") { Q += " chboxtd" } else { Q += "chboxtd" } } else { var R = J[N] || "&nbsp;"; if (w.rowbinddata) { S = J[N] || "" } if (this.format) { R = this .format( R, L) } T.push(R) } T .push("</div>"); if (Q != "") { G .push( " class='", Q, "'") } G .push( " axis='", S, "'", ">", T .join(""), "</td>") }); G.push("</tr>") }) } } G.push("</tbody>"); a(u).html(G.join("")); this.rePosDrag(); this.addRowProp(); this.applyEvent(); if (w.onSuccess) { w.onSuccess(this) } if (w.hideOnSubmit) { z.doMask("unmask") } this.hDiv.scrollLeft = this.bDiv.scrollLeft; if (a.browser.opera) { a(u).css("visibility", "visible") } var g = z.calPerColPercent(); if (g.isPercent) { z.calWidth(g) } }, clearAllRows : function() { a(u).html(""); if (w.showcheckbox) { a("input:first", z.hDiv).attr("checked", "") } z.doUsePager(); w.isSuccessSearch = false; z.freshSortClass() }, addCss : function(p) { var g; if (p.str) { g = document.createElement("style"); g.setAttribute("type", "text/css"); g.setAttribute("id", "grid_customBg_" + p.id); if (g.styleSheet) { document.getElementsByTagName("head")[0].appendChild(g); g.styleSheet.cssText = p.str } else { g.appendChild(document.createTextNode(p.str)); document.getElementsByTagName("head")[0].appendChild(g) } } if (p.url) { if (document.createStyleSheet) { try { g = document.createStyleSheet(p.url) } catch (t) { } } else { g = document.createElement("link"); g.rel = "stylesheet"; g.type = "text/css"; g.media = "all"; g.href = p.url; document.getElementsByTagName("head")[0].appendChild(g) } } }, reverseRowOrColumnCol : { setCol : { isCall : false, param : new Array(), bgColor : new Array() }, clearCol : { isCall : false, param : new Array() }, _index : 0 }, setRowOrColumnCol : function(H) { var g = []; var O = true; var T = a("tbody tr[id^='" + w.table_id + "_row_']", z.bDiv); if (H) { if (H.bgColor) { var G = H.bgColor.indexOf("#") == -1 ? H.bgColor : H.bgColor.substr(1); var L = ".bbit-grid tr td.customBgCol" + G + "{background-color: " + H.bgColor + ";}.bbit-grid tr.erow td.customBgCol" + G + "{background-color: " + H.bgColor + ";}.bbit-grid tr.newadd_tr td.customBgCol" + G + "{background-color: " + H.bgColor + ";}"; for ( var P = 0; P < z.reverseRowOrColumnCol.setCol.bgColor.length; P++) { var M = "grid_customBg_" + z.reverseRowOrColumnCol.setCol.bgColor[P]; if (a("#" + M).length >= 1 && z.reverseRowOrColumnCol.setCol.bgColor[P] == H.bgColor) { O = false } else { O = true } } } if (H.rowNum && H.colNum) { var R = H.colNum; if (w.showcheckbox) { R = ""; g = H.colNum.split(","); for ( var P = 0; P < g.length; P++) { if (!isNaN(parseInt(g[P]))) { R += (parseInt(g[P]) + 1) + "," } } var Q = R.lastIndexOf(","); R = R.substr(0, Q) } var t = H.rowNum.split(","); var I = R.split(","); if (H.bgColor && O) { z.addCss({ str : L, id : H.bgColor }) } for ( var P = 0; P < t.length; P++) { if (!isNaN(parseInt(t[P]))) { var W = T.eq(parseInt(t[P]) - 1); var V = W.children("td"); for ( var N = 0; N < I.length; N++) { if (!isNaN(parseInt(I[N]))) { if (H.color) { a(V[parseInt(I[N] - 1)]).css( "color", H.color) } if (H.bgColor) { if (O) { for ( var S = 0; S < z.reverseRowOrColumnCol.setCol.bgColor.length; S++) { var J = z.reverseRowOrColumnCol.setCol.bgColor[S]; if (J.indexOf("#") == -1) { if (a( V[parseInt(I[N] - 1)]) .hasClass( "customBgCol" + J)) { a( V[parseInt(I[N] - 1)]) .removeClass( "customBgCol" + J) } } else { if (a( V[parseInt(I[N] - 1)]) .hasClass( "customBgCol" + J .substr(1))) { a( V[parseInt(I[N] - 1)]) .removeClass( "customBgCol" + J .substr(1)) } } } } a(V[parseInt(I[N] - 1)]).addClass( "customBgCol"); a(V[parseInt(I[N] - 1)]).addClass( "customBgCol" + G) } } else { alert("\u8bf7\u4f20\u5165\u7531\u6570\u5b57\u7ec4\u6210\u7684\u5217\u53c2\u6570\uff01\uff01"); return false } } } else { alert("\u8bf7\u4f20\u5165\u7531\u6570\u5b57\u7ec4\u6210\u7684\u884c\u53c2\u6570!!"); return false } } } else { if (H.rowNum) { var g = H.rowNum.split(","); for ( var P = 0; P < g.length; P++) { if (!isNaN(parseInt(g[P]))) { continue } else { alert("rowNum\u53c2\u6570\u542b\u6709\u9664\u9017\u53f7\u4e4b\u5916\u7684\u5176\u4ed6\u975e\u6570\u5b57\u5b57\u7b26\uff01\uff01"); return false } } if (H.bgColor && O) { z.addCss({ str : L, id : H.bgColor }) } for ( var P = 0; P < g.length; P++) { var K = T.eq(g[P] - 1); var V = K.children("td"); for ( var N = 0; N < V.length - 1; N++) { if (H.color) { a( V[parseInt(w.showcheckbox ? N + 1 : N)]).css("color", H.color) } if (H.bgColor) { if (O) { for ( var S = 0; S < z.reverseRowOrColumnCol.setCol.bgColor.length - 1; S++) { var J = z.reverseRowOrColumnCol.setCol.bgColor[S]; if (J.indexOf("#") == -1) { if (a( V[parseInt(w.showcheckbox ? N + 1 : N)]) .hasClass( "customBgCol" + J)) { a( V[parseInt(w.showcheckbox ? N + 1 : N)]) .removeClass( "customBgCol" + J) } } else { if (a( V[parseInt(w.showcheckbox ? N + 1 : N)]) .hasClass( "customBgCol" + J .substr(1))) { a( V[parseInt(w.showcheckbox ? N + 1 : N)]) .removeClass( "customBgCol" + J .substr(1)) } } } } a( V[parseInt(w.showcheckbox ? N + 1 : N)]).addClass( "customBgCol"); a( V[parseInt(w.showcheckbox ? N + 1 : N)]).addClass( "customBgCol" + G) } } } } if (H.colNum) { var R = H.colNum; if (w.showcheckbox) { R = ""; g = H.colNum.split(","); for ( var P = 0; P < g.length; P++) { if (!isNaN(parseInt(g[P]))) { R += (parseInt(g[P]) + 1) + "," } else { alert("colNum\u53c2\u6570\u542b\u6709\u9664\u9017\u53f7\u4e4b\u5916\u7684\u5176\u4ed6\u975e\u6570\u5b57\u5b57\u7b26\uff01\uff01"); return false } } var Q = R.lastIndexOf(","); R = R.substr(0, Q) } else { g = R.split(","); for ( var P = 0; P < g.length; P++) { if (!isNaN(parseInt(R[P]))) { continue } else { alert("colNum\u53c2\u6570\u542b\u6709\u9664\u9017\u53f7\u4e4b\u5916\u7684\u5176\u4ed6\u975e\u6570\u5b57\u5b57\u7b26\uff01\uff01"); return false } } } if (g.length) { g = R.split(",") } if (H.bgColor && O) { z.addCss({ str : L, id : H.bgColor }) } for ( var P = 0; P < T.length; P++) { var W = T.eq(parseInt(P - 1)); var V = W.children("td"); for ( var N = 0; N < g.length; N++) { if (H.color) { a(V[parseInt(g[N] - 1)]).css("color", H.color) } if (H.bgColor) { if (O) { for ( var S = 0; S < z.reverseRowOrColumnCol.setCol.bgColor.length - 1; S++) { var J = z.reverseRowOrColumnCol.setCol.bgColor[S]; if (J.indexOf("#") == -1) { if (a(V[parseInt(g[N] - 1)]) .hasClass( "customBgCol" + J)) { a(V[parseInt(g[N] - 1)]) .removeClass( "customBgCol" + J) } } else { if (a(V[parseInt(g[N] - 1)]) .hasClass( "customBgCol" + J .substr(1))) { a(V[parseInt(g[N] - 1)]) .removeClass( "customBgCol" + J .substr(1)) } } } } a(V[parseInt(g[N] - 1)]).addClass( "customBgCol"); a(V[parseInt(g[N] - 1)]).addClass( "customBgCol" + G) } } } } } if (H.bgColor && O) { z.reverseRowOrColumnCol._index++ } if (H.isReloadCall == undefined) { var U = false; var p = (H.rowNum ? H.rowNum : "") + (H.colNum ? H.colNum : "") + (H.bgColor ? H.bgColor : ""); for ( var P = 0; P < z.reverseRowOrColumnCol.setCol.param.length; P++) { var F = z.reverseRowOrColumnCol.setCol.param[P].paramStr; if (F == p) { U = false; break } else { U = true } } if (!z.reverseRowOrColumnCol.setCol.param.length || U) { z.reverseRowOrColumnCol.setCol.param.push(H); z.reverseRowOrColumnCol.setCol.bgColor .push(H.bgColor); z.reverseRowOrColumnCol.setCol.param[z.reverseRowOrColumnCol.setCol.param.length - 1].paramStr = p } z.reverseRowOrColumnCol.setCol.isCall = true } } }, clearRowOrColumnCol : function(t) { var J = []; if (t) { if (t.rowNum && t.colNum) { var H = t.colNum; if (w.showcheckbox) { H = ""; J = t.colNum.split(","); for ( var I = 0; I < J.length; I++) { if (!isNaN(parseInt(J[I]))) { H += (parseInt(J[I]) + 1) + "," } } var L = H.lastIndexOf(","); H = H.substr(0, L) } var p = a("tbody tr[id^='" + w.table_id + "_row_']", z.bDiv); var O = t.rowNum.split(","); var M = H.split(","); for ( var I = 0; I < O.length; I++) { if (!isNaN(parseInt(O[I]))) { var K = p.eq(parseInt(O[I]) - 1); var N = K.children("td"); for ( var G = 0; G < M.length; G++) { if (!isNaN(parseInt(M[G]))) { if (t.color) { a(N[parseInt(M[G] - 1)]).css( "color", "") } if (t.bgColor) { for ( var P = 0; P < z.reverseRowOrColumnCol.setCol.bgColor.length; P++) { var g = z.reverseRowOrColumnCol.setCol.bgColor[P]; if (g && g.indexOf("#") == -1) { if (a(N[parseInt(M[G] - 1)]) .hasClass( "customBgCol" + g)) { a(N[parseInt(M[G] - 1)]) .removeClass( "customBgCol" + g) } } else { if (a(N[parseInt(M[G] - 1)]) .hasClass( "customBgCol" + g .substr(1))) { a(N[parseInt(M[G] - 1)]) .removeClass( "customBgCol" + g .substr(1)) } } } a(N[parseInt(M[G] - 1)]) .removeClass("customBgCol") } } else { alert("\u8bf7\u4f20\u5165\u7531\u6570\u5b57\u7ec4\u6210\u7684\u5217\u53c2\u6570\uff01\uff01"); return false } } } else { alert("\u8bf7\u4f20\u5165\u7531\u6570\u5b57\u7ec4\u6210\u7684\u884c\u53c2\u6570!!"); return false } } } else { if (t.rowNum) { var J = t.rowNum.split(","); for ( var I = 0; I < J.length; I++) { if (!isNaN(parseInt(J[I]))) { continue } else { alert("rowNum\u53c2\u6570\u542b\u6709\u9664\u9017\u53f7\u4e4b\u5916\u7684\u5176\u4ed6\u975e\u6570\u5b57\u5b57\u7b26\uff01\uff01"); return false } } var p = a( "tbody tr[id^='" + w.table_id + "_row_']", z.bDiv); for ( var I = 0; I < J.length; I++) { var F = p.eq(J[I] - 1); var N = F.children("td"); for ( var G = 0; G < N.length; G++) { if (t.color) { a( N[parseInt(w.showcheckbox ? G + 1 : G)]).css("color", "") } if (t.bgColor) { for ( var P = 0; P < z.reverseRowOrColumnCol.setCol.bgColor.length; P++) { var g = z.reverseRowOrColumnCol.setCol.bgColor[P]; if (g.indexOf("#") == -1) { if (a( N[parseInt(w.showcheckbox ? G + 1 : G)]) .hasClass( "customBgCol" + g)) { a( N[parseInt(w.showcheckbox ? G + 1 : G)]) .removeClass( "customBgCol" + g) } } else { if (a( N[parseInt(w.showcheckbox ? G + 1 : G)]) .hasClass( "customBgCol" + g .substr(1))) { a( N[parseInt(w.showcheckbox ? G + 1 : G)]) .removeClass( "customBgCol" + g .substr(1)) } } } a( N[parseInt(w.showcheckbox ? G + 1 : G)]).removeClass( "customBgCol") } } } } if (t.colNum) { var H = t.colNum; if (w.showcheckbox) { H = ""; J = t.colNum.split(","); for ( var I = 0; I < J.length; I++) { if (!isNaN(parseInt(J[I]))) { H += (parseInt(J[I]) + 1) + "," } else { alert("colNum\u53c2\u6570\u542b\u6709\u9664\u9017\u53f7\u4e4b\u5916\u7684\u5176\u4ed6\u975e\u6570\u5b57\u5b57\u7b26\uff01\uff01"); return false } } var L = H.lastIndexOf(","); H = H.substr(0, L) } else { J = H.split(","); for ( var I = 0; I < J.length; I++) { if (!isNaN(parseInt(H[I]))) { continue } else { alert("colNum\u53c2\u6570\u542b\u6709\u9664\u9017\u53f7\u4e4b\u5916\u7684\u5176\u4ed6\u975e\u6570\u5b57\u5b57\u7b26\uff01\uff01"); return false } } } if (J.length) { J = H.split(",") } var p = a( "tbody tr[id^='" + w.table_id + "_row_']", z.bDiv); for ( var I = 0; I < p.length; I++) { var K = p.eq(parseInt(I - 1)); var N = K.children("td"); for ( var G = 0; G < J.length; G++) { if (t.color) { a(N[parseInt(J[G] - 1)]).css("color", "") } if (t.bgColor) { for ( var P = 0; P < z.reverseRowOrColumnCol.setCol.bgColor.length; P++) { var g = z.reverseRowOrColumnCol.setCol.bgColor[P]; if (g.indexOf("#") == -1) { if (a(N[parseInt(J[G] - 1)]) .hasClass( "customBgCol" + g)) { a(N[parseInt(J[G] - 1)]) .removeClass( "customBgCol" + g) } } else { if (a(N[parseInt(J[G] - 1)]) .hasClass( "customBgCol" + g .substr(1))) { a(N[parseInt(J[G] - 1)]) .removeClass( "customBgCol" + g .substr(1)) } } } a(N[parseInt(J[G] - 1)]).removeClass( "customBgCol") } } } } } } else { var p = a("tbody tr[id^='" + w.table_id + "_row_']", z.bDiv); var N = p.children("td"); for ( var I = 0; I < N.length; I++) { if (t.color) { a(N[I]).css("color", "") } if (t.bgColor) { for ( var P = 0; P < z.reverseRowOrColumnCol.setCol.bgColor.length; P++) { var g = z.reverseRowOrColumnCol.setCol.bgColor[P]; if (g.indexOf("#") == -1) { if (a(N[I]).hasClass("customBgCol" + g)) { a(N[I]).removeClass("customBgCol" + g) } } else { if (a(N[I]).hasClass( "customBgCol" + g.substr(1))) { a(N[I]).removeClass( "customBgCol" + g.substr(1)) } } } a(N[I]).removeClass("customBgCol") } } } if (t.isReloadCall == undefined) { z.reverseRowOrColumnCol.clearCol.isCall = true; z.reverseRowOrColumnCol.clearCol.param.push(t) } }, checkRowsByKeyColumn : function(p) { var F = []; if (p && p.identifyColumn) { var I = p.identityColumnValue; for ( var H = 0; H < w.colModel.length; H++) { if (w.colModel[H].name == p.identifyColumn) { var g = a( "tbody tr[id^='" + w.table_id + "_row_']", z.bDiv); for ( var t = 0, J = I.length; t < J; t++) { for ( var G = 0; G < g.length; G++) { var K = a(g[G]).children("td"); var L = a("div", a(K[(w.showcheckbox ? H + 1 : H)])) .text(); if (L == I[t]) { F.push(g[G]); break } } } break } } for ( var H = 0, J = F.length; H < J; H++) { if (w.showcheckbox) { a(F[H]).addClass("trSelected"); a("input.itemchk", F[H]).attr("checked", "checked") } else { a(F[0]).addClass("trSelected") } if (p.callCheckEvent != "undefined" && p.callCheckEvent) { if (w.onrowchecked) { if (w.showcheckbox) { w.onrowchecked.call(this, { flag : true, tr_object : a(F[H]), isHeadCheckbox : false }) } else { w.onrowchecked.call(this, { flag : true, tr_object : a(F[0]), isHeadCheckbox : false }) } } } z.freshCheckboxState() } } }, updateRowData : function(t) { var H = []; if (t.identifyCloumn || t.identifyColumn) { for ( var J = 0; J < w.colModel.length; J++) { if (w.colModel[J].name == t.identifyCloumn || w.colModel[J].name == t.identifyColumn) { var g = a( "tbody tr[id^='" + w.table_id + "_row_']", z.bDiv); for ( var I = 0; I < g.length; I++) { var K = a(g[I]).children("td"); var N = a("div", a(K[(w.showcheckbox ? J + 1 : J)])) .text(); if (N == t.identifyCloumnValue || N == t.identifyColumnValue) { H.push(g[I]); break } } break } } } if (H.length) { if (t.data) { for ( var G = 0; G < H.length; G++) { var O = ""; var K = a(H[G]).children("td"); for ( var J = 0; J < w.colModel.length; J++) { var p = w.colModel[J].name; var M; if (p.indexOf(".") != -1) { var L = p.split("."); M = t.data; for ( var I = 0; I < L.length; I++) { if (M[L[I]] != undefined && M[L[I]] != null) { M = z.parseData({ data : M[L[I]], colModel : w.colModel[J] }) } else { M = "" } } } else { if (t.data[p] != undefined && t.data[p] != null) { M = z.parseData({ data : t.data[p], colModel : w.colModel[J] }) } else { M = "" } } M = M ? M : ""; if (typeof (M) == "string" && w.isFilter) { O = O + M.replace(/\</g, "&lt;").replace( /\>/g, "&gt;").replaceAll( '"', "&quot;") } else { O = O + M } if (J < w.colModel.length - 1) { O = O + "_FG$SP_" } var F = a("div", K[(w.showcheckbox ? J + 1 : J)]); F.text(M) } a(H[G]).attr("chd", O); for ( var J = 0; J < w.colModel.length; J++) { if (w.colModel[J] && w.colModel[J].fireEvent) { w.colModel[J].fireEvent({ tr_object : a(H[G]), div_object : w.showcheckbox ? a("div", K[J + 1])[0] : a("div", K[J])[0], grid : z }) } } } } } }, deleteRowData : function(H) { var g = []; if (H && H.rowNum) { var J = H.rowNum.split(","); str = ""; for ( var t = 0; t < J.length; t++) { if (!isNaN(parseInt(J[t]))) { if (str.indexOf(J[t]) == -1) { str = str + J[t] + ";"; g[g.length] = a( "tbody tr[id^=" + w.table_id + "_row_]:eq(" + (parseInt(J[t])) + ")", z.bDiv) } } } for ( var t = 0; t < g.length; t++) { g[t].remove() } } else { if (H && H.data) { var G = ""; for ( var t = 0; t < H.data.length; t++) { for ( var p = 0; p < w.colModel.length; p++) { colModel = w.colModel[p]; var F = colModel.name; tdData = z.parseJson({ data : H.data[t], colName : F, col : colModel }); G += tdData + "_FG$SP_" } var I = G.lastIndexOf("_FG$SP_"); G = G.substr(0, I); a("tbody tr", z.bDiv).each( function() { if (a(this).attr("chd") == G && a(this).attr("change")) { a(this).remove(); return false } }); G = "" } } else { if (w.showcheckbox) { g = a(":checkbox:checked.itemchk", z.bDiv).parent() .parent().parent() } else { g = a("tbody tr[id^=" + w.table_id + "_row_].trSelected", z.bDiv) } if (g) { g.each(function() { a(this).remove() }) } } } z.freshCheckboxState() }, addRowData : function(K) { var Q = 0; var t = rn = a("tbody tr[id^='" + w.table_id + "_row_']", z.bDiv).length; if (K && K.data) { for ( var H = 0; H < K.data.length; H++) { if (K.rowNum && !isNaN(parseInt(K.rowNum, 10))) { K.rowNum = parseInt(K.rowNum); if (K.rowNum <= 0) { K.rowNum = Q } else { if (K.rowNum >= rn) { K.rowNum = rn } } } else { K.rowNum = Q } if (rn == 0) { var M = { total : 1, page : 1, rows : [ { id : w.table_id + "_row_", cell : [ "", "", "", "", "" ] } ] }; if (w.usepager) { a(".pPageStat", this.pDiv).css("display", "none") } z.addData(M); if (w.usepager) { a(".pPageStat", this.pDiv).css("display", "block"); a(".pPageStat", this.pDiv).html(w.nomsg) } } var g = a(a("tbody tr[id^='" + w.table_id + "_row_']", z.bDiv)[0]); var G = g.clone(); if (t != 0) { G.attr("id", "grid_new_add") } G.removeClass("trSelected").addClass("newadd_tr"); a("td", G).removeClass(); a("td", G).css("color", "#000"); var N = G.children("td"); if (!z.reverseRowOrColumnCol.setCol.isCall) { for ( var F = 0; F < N.length; F++) { a(N[F]).css("color", "") } } G.removeClass(); if (w.rowbinddata) { G.attr("ch", "") } if (K.rowNum == Q || K.rowNum < rn) { var p = a( "tbody tr[id^='" + w.table_id + "_row_']", z.bDiv)[K.rowNum]; G.insertBefore(a(p)) } else { var p = a( "tbody tr[id^='" + w.table_id + "_row_']", z.bDiv)[K.rowNum - 1]; G.insertAfter(a(p)) } if (rn == 0) { g.remove() } rn = a("tbody tr[id^='" + w.table_id + "_row_']", z.bDiv).length } if (t == 0) { a("tbody tr[id^='" + w.table_id + "_row_']", z.bDiv) .attr("id", "grid_new_add") } var I = a("tr[id='grid_new_add']", z.bDiv); var J = I.length; var L = "", p = null; for ( var H = 0; H < J; H++) { var R = ""; var P = null; a(I[H]) .children("td") .each( function(S) { p = a("div", this); if (w.showcheckbox) { if (S > 0) { P = w.colModel[S - 1] } else { if (S == 0) { L = "<input type='checkbox' class='itemchk'/>" } } } else { P = w.colModel[S] } if (P) { var T = P.name; L = z.parseJson({ data : K.data[H], colName : T, col : P }) } p.html(L); if (w.showcheckbox && S == 0) { L = "" } else { R = R + L + "_FG$SP_" } p.attr("title", L); L = "" }); var O = R.lastIndexOf("_FG$SP"); R = R.substr(0, O); a(I[H]).attr("chd", R); if (!(typeof K.isLaterClearId != "undefined" && K.isLaterClearId)) { a(I[H]).attr("id", w.table_id + "_row_" + t) } for ( var F = 0; F < w.colModel.length; F++) { if (w.colModel[F] && w.colModel[F].fireEvent) { w.colModel[F].fireEvent({ tr_object : I[H], div_object : w.showcheckbox ? a("td:eq(" + (F + 1) + ") div", I[H])[0] : a( "td:eq(" + F + ") div", I[H])[0], grid : z }) } } z.rowTrProp.call(I[H]); z.rowProp.call(I[H]); z.freshCheckboxState() } } z.freshRowStriped() }, freshRowStriped : function() { if (w.striped) { a("tbody tr:even", z.bDiv).removeClass("erow"); a("tbody tr:odd", z.bDiv).addClass("erow") } }, getNewRows : function() { return a("tr[id='grid_new_add']", z.bDiv) }, getRowObject : function(p) { var t = []; if (p) { if (p.rowNum) { var G = p.rowNum.split(","); str = ""; for ( var F = 0; F < G.length; F++) { if (!isNaN(parseInt(G[F]))) { if (str.indexOf(G[F]) == -1) { str = str + G[F] + ";"; t[t.length] = a("tbody tr[id^=" + w.table_id + "_row_]:eq(" + G[F] + ")", z.bDiv) } } } } } else { if (w.showcheckbox) { var g = a(":checkbox:checked.itemchk", z.bDiv); for ( var F = 0; F < g.length; F++) { t.push(a(g[F]).parent().parent().parent()) } } else { t.push(a("tbody tr.trSelected", z.bDiv)) } } return t }, getSelectIndex : function(p) { var I = ""; if (p && p.rowObject) { I = p.rowObject.rowIndex; return I + "," } else { if (p && p.data) { var H = ""; for ( var F = 0; F < w.colModel.length; F++) { var G = w.colModel[F].name; tdData = z.parseJson({ data : p.data, colName : G, col : w.colModel[F] }); H = H + tdData + "_FG$SP_" } var t = H.lastIndexOf("_FG$SP_"); H = H.substr(0, t); var g = a("tbody tr[id^=" + w.table_id + "_row_]", z.bDiv); g.each(function(J) { if (a(this).attr("chd") == H) { I = J + "," } }); return I } else { if (w.showcheckbox) { arr = a(":checkbox:checked.itemchk", z.bDiv) .parent().parent().parent() } else { arr = a("tbody tr[id^=" + w.table_id + "_row_].trSelected", z.bDiv) } } } if (arr) { if (arr.length > 1) { for ( var F = 0; F < arr.length; F++) { I = I + a( "tbody tr[id^=" + w.table_id + "_row_]", z.bDiv).index( arr[F]) + "," } } else { I = a("tbody tr[id^=" + w.table_id + "_row_]", z.bDiv) .index(arr) + "," } return I } else { return "0," } }, applyEvent : function() { if (w.colModel) { var p, g, t; a("tbody tr", u) .each( function(F) { p = this; a(w.colModel) .each( function(G) { if (this.fireEvent) { g = a(p) .children()[w.showcheckbox ? (G + 1) : G]; t = a(g) .children()[0]; this .fireEvent({ tr_object : p, div_object : t, grid : z }) } }) }) } }, dealData : function(p) { try { var F = p.resultID; var g = p.resultMsg; if (F) { if (F == w.successResultID) { return true } else { if (w.showErrorMsg) { alert(g) } return false } } else { alert(w.errormsg); return false } } catch (t) { throw t } }, changeJsonObject : function(N, F) { try { var g; var G; var p = [ {} ]; p[0].total = N.total; p[0].page = N.page; p[0].rows = []; p[0].oriDateValue = []; var Q = w.colModel.length; var J = ""; var M; var L = 0; if (p[0].page) { L = w.rp * (parseInt(p[0].page) - 1); L = L >= 0 ? L : 0 } if (N && N.resultList) { for ( var I = 0; I < N.resultList.length; I++) { M = N.resultList[I]; if (M) { var K = new Array(Q); for ( var H = 0; H < Q; H++) { G = w.colModel[H].name; if (G.indexOf(".") != -1) { var O = G.split("."); J = M[O[0]]; for ( var t = 1; t < O.length; t++) { if (J != undefined && J[O[t]] != undefined && J[O[t]] != null) { J = typeof (J[O[t]]) == "boolean" ? J[O[t]] + "" : J[O[t]] } else { J = "" } } } else { if (M[G] != undefined && M[G] != null) { J = typeof (M[G]) == "boolean" ? M[G] + "" : M[G] } else { J = "" } } if (typeof (J) == "number") { J = J == 0 ? "0" : J } else { J = J ? J : "" } K[H] = J } p[0].rows.push({ id : (L + I), cell : K }) } } } return p } catch (P) { throw P } }, parseData : function(t) { if (t.colModel.ct && t.colModel.ct.type == "date") { var g = t.colModel.ct.format; return t.data = z.dateToStr(t.data, g) } else { return typeof (t.data) == "boolean" ? t.data + "" : t.data } }, dateToStr : function(t, G) { if (t.constructor == Date) { t = new Date(t) } else { if (t.constructor == String && t != "") { t = new Date(Date.parse(t.replace(/-/g, "/"))) } else { return "" } } if (t == "NaN") { return "" } else { if (G == null || G == "") { G = "yyyy-MM-dd hh:mm:ss" } var H = { "Y+" : "Y", "y+" : "y", "M+" : "M", "o+" : "o", "d+" : "d", "D+" : "D", "h+" : "h", "H+" : "H", "m+" : "m", "i+" : "i", "s+" : "s", "S+" : "S" }; var g = { Y : t.getFullYear(), y : t.getFullYear(), M : (t.getMonth() < 9) ? ("0" + (1 + t.getMonth())) : (1 + t.getMonth()), o : (1 + t.getMonth()), d : (t.getDate() < 10) ? ("0" + t.getDate()) : t .getDate(), D : t.getDate(), h : (t.getHours() < 10) ? ("0" + t.getHours()) : t .getHours(), H : t.getHours(), m : (t.getMinutes() < 10) ? ("0" + t.getMinutes()) : t .getMinutes(), i : t.getMinutes(), s : (t.getSeconds() < 10) ? ("0" + t.getSeconds()) : t .getSeconds(), S : t.getSeconds() }; var F = G; for ( var p in H) { if (new RegExp("(" + p + ")").test(G)) { F = F.replace(RegExp.$1, g[H[p]]) } } return F } }, freshParam : function(g) { a.extend(w, g) }, adjustOrder : function(G) { var F = a(z.bDiv).find( "tbody tr[id^=" + w.table_id + "_row_].trSelected"); if (F.length > 0) { if (F != undefined) { var g = F.attr("id"); var I = g.substr(0, g.lastIndexOf("_")); var p = g.substr(I.length + 1, g.length); if (G.order == "up") { p = p - 1; for ( var t = 0; t < F.length; t++) { var H = a(F[t]).prev(); if (H.length == 0) { alert("\u884c\u6570\u636e\u4e3a\u5f53\u524d\u5c42\u7ea7\u7684\u9876\u7ea7\uff0c\u65e0\u6cd5\u7ee7\u7eed\u5411\u4e0a\u79fb\u52a8"); return false } H.before(F[t]) } } else { if (G.order == "down") { p = parseInt(p) + 1; for ( var t = 0; t < F.length; t++) { var J = F.next(); if (J.length == 0) { alert("\u5f53\u524d\u8282\u70b9\u5904\u4e8e\u5f53\u524d\u5c42\u7ea7\u7684\u6700\u540e\u4e00\u4e2a\u8282\u70b9\uff0c\u65e0\u6cd5\u7ee7\u7eed\u5f80\u4e0b\u79fb"); return false } J.after(F[t]) } } } } else { alert("\u8bf7\u5148\u9009\u4e2d\u4e00\u884c\u6570\u636e\u8fdb\u884c\u79fb\u52a8") } } else { if (F.length > 1) { alert("\u53ea\u80fd\u9488\u5bf9\u4e00\u884c\u6570\u636e\u8fdb\u884c\u79fb\u52a8") } else { alert("\u8bf7\u5148\u9009\u4e2d\u4e00\u884c\u6570\u636e\u8fdb\u884c\u79fb\u52a8") } } }, changeChildrenId : function(I) { var t = I.oldId; for ( var p = 0; p < I.data.length; p++) { var g = a(I.data[p]).attr("id"); var F = g.replace(I.oldId, I.newId); var H = F.substr(I.trPrefix.length + 1, F.length); a(I.data[p]).attr("id", F); if (w.showcheckbox) { var G = a(I.data[p]).children("td.chboxtd").children( "div").find("input[id^='chk_']"); if (G != undefined) { G.attr("id", "chk_" + H); G.attr("value", H) } } } }, getRowData : function(p) { var F = []; var G = null; if (p) { G = a(p).attr("chd") } else { if (!w.showcheckbox) { var g = a(z.bDiv).find( "tbody tr[id^=" + w.table_id + "_row_]"); for ( var t = 0; t < g.length; t++) { if (a(g[t]).hasClass("trSelected")) { G = a(g[t]).attr("chd"); break } } } } if (G) { F.push({}); z.generalObject(F, G, 0) } return F }, getUnSelectedRowData : function(p) { var F = []; var G = null; if (p) { G = a(p).attr("chd") } else { if (w.showcheckbox) { var g = a(z.bDiv).find( "tbody tr[id^=" + w.table_id + "_row_].trUnselected"); for ( var t = 0; t < g.length; t++) { G = a(g[t]).attr("chd") } } } if (G) { F.push({}); z.generalObject(F, G, 0) } return F }, getUnselectRowsData : function() { var p = []; var g = a("tbody tr[id^=" + w.table_id + "_row_]:not(.trSelected)", z.bDiv); g.each(function(t) { p.push({}); chd = a(this).attr("chd"); z.generalObject(p, chd, t) }); return p }, changeSort : function(g) { if (this.loading) { return true } a(z.nDiv).hide(); a(z.nBtn).hide(); if (w.sortname == a(g).attr("abbr")) { if (w.sortorder == "asc") { w.sortorder = "desc" } else { w.sortorder = "asc" } } a(g).addClass("sorted").siblings().removeClass("sorted"); a(".sdesc", this.hDiv).removeClass("sdesc"); a(".sasc", this.hDiv).removeClass("sasc"); a("div", g).addClass("s" + w.sortorder); w.sortname = a(g).attr("abbr"); if (w.onChangeSort) { w.onChangeSort(w.sortname, w.sortorder) } else { if (w.sortByStatic) { this.populate({ changeSort : true }) } else { this.populate() } } }, buildpager : function() { a(".pcontrol input", this.pDiv).val(w.page); a(".pcontrol span", this.pDiv).html(w.pages); var p = (parseInt(w.page) - 1) * parseInt(w.rp) + 1; var g = p + parseInt(w.rp) - 1; if (w.total < g) { g = w.total } var t = w.pagestat; t = t.replace(/{from}/, p); t = t.replace(/{to}/, g); t = t.replace(/{total}/, w.total); if (w.usepager) { a(".pPageStat", this.pDiv).html(t) } a("select", z.pDiv).val(w.rp) }, doMask : function(H) { var g = z.gDiv; if (w.maskObject) { if (typeof (w.maskObject) == "string") { g = document.getElementById(w.maskObject) } else { if (typeof (w.maskObject) == "object") { g = w.maskObject } } } if (!z.maskDiv) { z.maskDiv = document.createElement("div"); z.maskDiv.setAttribute("id", w.container_id + "_maskDiv"); z.maskDiv.className = "gBlock"; a(z.maskDiv).fadeTo(0, w.blockOpacity); if (a.browser.msie && a.browser.version == 6) { var F = " <iframe style=\"display: block; z-index: -1; filter: alpha(Opacity='0'); left: -1px; left: expression(((parseInt(document.getElementById('" + w.container_id + "_maskDiv').currentStyle.borderLeftWidth)||0)*-1)+'px'); width: expression(document.getElementById('" + w.container_id + "_maskDiv').offsetWidth+'px'); position: absolute; top: -1px; top: expression(((parseInt(document.getElementById('" + w.container_id + "_maskDiv').currentStyle.borderTopWidth)||0)*-1)+'px'); height: expression(document.getElementById('" + w.container_id + "_maskDiv').offsetHeight+'px');\" tabIndex=-1 src=\"\" frameBorder=0> </iframe>"; a(z.maskDiv).prepend(F) } } var G = a(g).height(); var M = a(g).width() + 2; var I = 0; a(z.maskDiv).css({ width : M, height : G, position : "absolute", marginBottom : 0, zIndex : 1 }); if (!z.maskMsgDiv) { z.maskMsgDiv = document.createElement("div"); z.maskMsgDiv.className = "grid-mask-msg"; a(z.maskMsgDiv).html("<div>\u8bf7\u7a0d\u5019...</div>") } if (H == "mask") { if (!z.tmpDiv) { z.tmpDiv = document.createElement("div"); z.tmpDiv.className = w.gridClass } a(z.tmpDiv).append(z.maskDiv); a(z.tmpDiv).append(z.maskMsgDiv); if (w.maskObject) { a(g).prepend(z.tmpDiv) } else { a(this.gDiv).prepend(z.tmpDiv) } var K = Math.round(a(g).height() / 2 - (a(z.maskMsgDiv).height() - parseInt(a(z.maskMsgDiv).css( "padding-top")) - parseInt(a( z.maskMsgDiv).css("padding-bottom"))) / 2); var p = Math.round(a(g).width() / 2 - (a(z.maskMsgDiv).width() - parseInt(a(z.maskMsgDiv).css( "padding-left")) - parseInt(a( z.maskMsgDiv).css("padding-right"))) / 2); p = p - 4; var J, L; if (w.maskObject) { J = a(g).offset().top + K + "px"; L = a(g).offset().left + p + "px" } else { J = K + "px"; L = p + "px" } a(z.maskMsgDiv).css("top", J); a(z.maskMsgDiv).css("left", L) } else { if (H == "unmask") { a(z.maskMsgDiv).remove(); a(z.maskDiv).remove(); a(z.tmpDiv).remove() } } }, recordBeforeStatus : function(g) { var p = new Object(); if (w.showcheckbox) { p.checkData = z.getRowsData(); p.unCheckData = z.getUnSelectedRowData() } else { p.checkData = z.getRowData() } return p }, loadBeforeStatus : function(H, I) { if (I && H) { var N = []; var M = false; var K = []; for ( var p = 0; p < w.colModel.length; p++) { if (w.colModel[p].isKey) { K.push(w.colModel[p]) } } var g = a("tbody tr[id^='" + w.table_id + "_row_']", z.bDiv); for ( var J = 0; J < g.length; J++) { var G = z.getRowData(g[J]); if (H.checkData) { var O = H.checkData; for ( var F = 0; F < O.length; F++) { M = z.freshStyle({ trData : G[0], data : O[F], identifyColumn : K }); if (M) { a(g[J]).addClass("trSelected"); if (w.showcheckbox) { a("input:checkbox", g[J]).attr( "checked", true) } } } } if (H.unCheckData) { var L = H.unCheckData; for ( var t = 0; t < L.length; t++) { M = z.freshStyle({ trData : G[0], data : L[t], identifyColumn : K }); if (M) { if (!w.clickRowDoCheck) { a(g[J]).addClass("trUnselected") } } } } } } }, freshStyle : function(t) { var G = t.data; var F = false; flag = []; for ( var p = 0; p < t.identifyColumn.length; p++) { if (z.parseJson({ data : t.trData, col : t.identifyColumn[p], colName : t.identifyColumn[p].name }) == z.parseJson({ data : G, col : t.identifyColumn[p], colName : t.identifyColumn[p].name })) { flag.push(true) } else { flag.push(false) } } for ( var g = 0; g < flag.length; g++) { if (flag[g] == true) { F = true } else { F = false; break } } return F }, parseJson : function(J) { var F = ""; var p = J.col; var t = J.colName; var g = t.indexOf("."); if (g != -1) { var I = t.substr(0, g); var H = t.substr(g + 1, t.length); function G(L, M) { var K = M.indexOf("."); if (K != -1) { var N = M.substr(0, K); var M = M.substr(K + 1, M.length); G(L[N], M) } else { if (L != undefined && L[M] != undefined && L[M] != null) { return z.parseData({ data : L[M], colModel : p }) } else { return "" } } } F = G(J.data[I], H) } else { if (J.data[t] != undefined && J.data[t] != null) { F = z.parseData({ data : J.data[t], colModel : p }) } else { F = "" } } return F }, populate : function(t) { if (this.loading) { return true } if (w.onSubmit) { var p = w.onSubmit(); if (!p) { return false } } this.loading = true; if (w.usepager) { a(".pPageStat", this.pDiv).html(w.procmsg); a(".pReload", this.pDiv).addClass("loading") } a(z.block).css({ top : z.bDiv.offsetTop }); if (w.hideOnSubmit) { z.doMask("mask") } if (a.browser.opera) { a(u).css("visibility", "hidden") } if (!w.newp) { w.newp = 1 } if (w.page > w.pages) { w.page = w.pages } var G = [ { name : "pageNumber", value : w.newp }, { name : "pageSize", value : w.usepager ? w.rp : 1000 }, { name : "sortname", value : w.sortname }, { name : "sortorder", value : w.sortorder }, { name : "query", value : w.query }, { name : "qtype", value : w.qtype }, { name : "qop", value : w.qop } ]; if (w.extParam) { for ( var F = 0; F < w.extParam.length; F++) { G[G.length] = w.extParam[F] } } function g() { if (z.dealData(w.tableData)) { var J; if (t && t.fnName == "fresh" && t.isRecoverRowState) { J = z.recordBeforeStatus(t) } if (w.sortByStatic) { w.tableData.resultList = z .sortData(w.tableData.resultList) } z.addData(z.changeJsonObject(w.tableData, { pageNumber : w.newp, pageSize : w.rp })[0]); if (w.showcheckbox) { z.doUncheck() } if (t && t.fnName == "fresh" && t.isRecoverRowState) { z.loadBeforeStatus(J, t) } if (w.isReloadCall && z.reverseRowOrColumnCol.setCol.isCall) { for ( var H = 0; H < z.reverseRowOrColumnCol.setCol.bgColor.length; H++) { a( "#grid_customBg_" + z.reverseRowOrColumnCol.setCol.bgColor[H]) .remove() } for ( var I = 0; I < z.reverseRowOrColumnCol.setCol.param.length; I++) { z.reverseRowOrColumnCol.setCol.param[I].isReloadCall = true; z .setRowOrColumnCol(z.reverseRowOrColumnCol.setCol.param[I]) } } if (z.reverseRowOrColumnCol.clearCol.isCall) { for ( var I = 0; I < z.reverseRowOrColumnCol.clearCol.param.length; I++) { z.reverseRowOrColumnCol.clearCol.param[I].isReloadCall = true; z .clearRowOrColumnCol(z.reverseRowOrColumnCol.clearCol.param[I]) } } w.isSuccessSearch = true } else { z.hideLoading() } } if (w.tableData && !w.url) { g() } else { if (w.url) { if (t && t.changeSort != undefined && t.changeSort) { g() } else { a .ajax({ type : w.method, url : w.url, data : G, dataType : w.dataType, success : function(H) { if (H != null && H.error != null) { if (w.onError) { w.onError(H); z.hideLoading() } } else { w.tableData = H; g() } }, error : function(H) { try { if (w.onError) { w.onError(H) } else { alert("\u83b7\u53d6\u6570\u636e\u53d1\u751f\u5f02\u5e38") } z.hideLoading() } catch (I) { } } }) } } } }, sortData : function(t) { var g = null; for ( var p = 0; p < w.colModel.length; p++) { if (w.colModel[p].name == w.sortname) { g = w.colModel[p]; break } } if (g != null) { t.sort(function(G, F) { G = z.parseJson({ data : G, colName : w.sortname, col : g }); F = z.parseJson({ data : F, colName : w.sortname, col : g }); if (!isNaN(G - F)) { if (w.sortorder == "desc") { return F - G } else { return G - F } } else { if (w.sortorder == "desc") { return F.localeCompare(G) } else { return G.localeCompare(F) } } }) } return t }, doSearch : function() { var g = a("select[name=qtype]", z.sDiv).val(); var p = g.split("$"); var t = -1; if (p.length != 3) { w.qop = "Eq"; w.qtype = g } else { w.qop = p[1]; w.qtype = p[0]; t = parseInt(p[2]) } w.query = a("input[name=q]", z.sDiv).val(); if (w.query != "" && w.searchitems && t >= 0 && w.searchitems.length > t) { if (w.searchitems[t].reg) { if (!w.searchitems[t].reg.test(w.query)) { alert("\u4f60\u7684\u8f93\u5165\u4e0d\u7b26\u5408\u8981\u6c42!"); return } } } w.newp = 1; this.populate() }, changePage : function(t, p) { if (this.loading) { return true } switch (t) { case "first": w.newp = 1; break; case "prev": if (w.page > 1) { w.newp = parseInt(w.page) - 1 } break; case "next": if (w.page < w.pages) { w.newp = parseInt(w.page) + 1 } else { w.newp = w.pages } break; case "last": w.newp = w.pages; break; case "input": var g = parseInt(a(".pcontrol input", this.pDiv).val()); if (isNaN(g)) { g = 1 } if (g < 1) { g = 1 } else { if (g > w.pages) { g = w.pages } } a(".pcontrol input", this.pDiv).val(g); w.newp = g; break } if (w.newp == w.page) { if (t != "reload" && t != "change") { return false } } if (t != "reload" && w.onChangePage && !w.url) { w.onChangePage(w.newp, w.rp) } else { this.populate(p); if (!p) { p = { isCallOnChangePage : true } } if (p.isCallOnChangePage && w.onChangePage) { w.onChangePage(w.newp, w.rp) } } }, cellProp : function(H, G, F) { var t = document.createElement("div"); if (F != null) { if (w.sortname == a(F).attr("abbr") && w.sortname) { this.className = "sorted" } a(t).css({ textAlign : F.align, width : a("div:first", F)[0].style.width }); if (F.hide) { a(this).css("display", "none") } } if (w.nowrap == false) { a(t).css("white-space", "normal") } if (this.innerHTML == "") { this.innerHTML = "&nbsp;" } t.innerHTML = this.innerHTML; var p = a(this).parent()[0]; var g = false; if (p.id) { g = p.id.substr(3) } if (F != null) { if (F.format) { F.format(t, g) } } a("input.itemchk", t).each(function() { a(this).bind("click", function() { if (this.checked) { a(G).addClass("trSelected") } else { a(G).removeClass("trSelected") } if (w.onrowchecked) { w.onrowchecked.call(this, { isChecked : this.checked, tr_object : a(G), isHeadCheckbox : false }) } }) }); a(this).empty().append(t).removeAttr("width") }, addCellProp : function() { var g = this.cellProp; a("tbody tr td", z.bDiv).each(function() { var F = a("td", a(this).parent()).index(this); var p = a("th:eq(" + F + ")", z.hDiv).get(0); var t = a(this).parent(); g.call(this, F, t, p) }); g = null }, getAllData : function() { var t = []; var p = a("tbody tr[id^=" + w.table_id + "_row_]", z.bDiv); var g = p.length; var F = null; p.each(function(G) { t.push({}); F = a(this).attr("chd"); z.generalObject(t, F, G) }); return t }, getChangeData : function() { var t = []; var p = a("tr[id^=" + w.table_id + "_row_].change", z.bDiv); var g = p.length; var F = null; p.each(function(G) { t.push({}); F = a(this).attr("chd"); z.generalObject(t, F, G) }); return t }, getRowsData : function() { var p = a(":checkbox:checked.itemchk", z.bDiv); var g = p.length; var F = []; for ( var t = 0; t < g; t++) { F.push({}) } var G = null; for ( var t = 0; t < g; t++) { G = a(p[t]).parent().parent().parent().attr("chd"); z.generalObject(F, G, t) } return F }, flexTitle : function(p) { var g = a("#" + w.container_id + " .mDiv .ftitle"); g.text(p.title) }, cancelAllSelectState : function() { a("tbody tr[id^=" + w.table_id + "_row_]", z.bDiv).each( function() { if ((a(this).attr("class") + " ") .indexOf("trSelected") != -1) { a(this).removeClass("trSelected"); if (w.showcheckbox) { a("input:checkbox", this).attr("checked", false) } } }); z.freshCheckboxState() }, generalObject : function(g, K, I) { var H = K.split("_FG$SP_"); var p = w.colModel; var t = "", F = ""; for ( var G = 0; G < p.length; G++) { t = p[G].name; if (p[G].ct && p[G].ct.type == "date") { if (H[G] != "") { if (H[G] && H[G].indexOf("-") != -1) { F = new Date(Date .parse(H[G].replace(/-/g, "/"))) } else { F = new Date(H[G]) } } else { F = null } } else { F = H[G] } J({ col_name : t, row_object : g[I], col_value : F }) } function J(Q) { var N = Q.col_name; var L = N.indexOf("."); var M = Q.row_object; var R = Q.col_value; if (L == -1) { M[N] = R } else { var P = N.substr(0, L); var O = N.substr(L + 1, N.length); if (!M[P]) { M[P] = {} } J({ col_name : O, row_object : M[P], col_value : R }) } } }, getCellDim : function(t) { var I = parseInt(a(t).height()); var g = parseInt(a(t).parent().height()); var G = parseInt(t.style.width); var K = parseInt(a(t).parent().width()); var H = t.offsetParent.offsetTop; var p = t.offsetParent.offsetLeft; var J = parseInt(a(t).css("paddingLeft")); var F = parseInt(a(t).css("paddingTop")); return { ht : I, wt : G, top : H, left : p, pdl : J, pdt : F, pht : g, pwt : K } }, rowProp : function() { if (w.rowhandler) { w.rowhandler(this, { grid : z }) } if (a.browser.msie && a.browser.version < 7) { a(this).hover(function() { a(this).addClass("trOver") }, function() { a(this).removeClass("trOver") }) } a(this) .click( function(g) { if (a(g.target).hasClass("itemchk")) { return } if ((a(this).attr("class") + " ") .indexOf("trSelected") == -1) { if (w.showcheckbox) { if (w.disCheckbox) { if (!a("input.itemchk", this) .attr("disabled")) { if (w.clickRowDoCheck) { a(this).addClass( "trSelected"); a("input.itemchk", this) .attr( "checked", "checked"); z.freshCheckboxState() } else { a("tr.trUnselected", z.bDiv) .removeClass( "trUnselected"); a(this).addClass( "trUnselected") } } else { a("tr.trUnselected", z.bDiv) .removeClass( "trUnselected"); a(this).addClass( "trUnselected") } } else { if (w.clickRowDoCheck) { a(this).addClass( "trSelected"); a("input.itemchk", this) .attr("checked", "checked"); z.freshCheckboxState() } else { a("tr.trUnselected", z.bDiv) .removeClass( "trUnselected"); a(this).addClass( "trUnselected") } } } else { a("tr.trSelected", z.bDiv) .removeClass("trSelected"); a(this).addClass("trSelected") } } else { if (w.showcheckbox) { if (w.clickRowDoCheck) { a("input.itemchk", this).attr( "checked", ""); a(this).removeClass( "trSelected"); z.doUncheck() } else { a("tr.trUnselected", z.bDiv) .removeClass( "trUnselected"); a(this) .addClass( "trUnselected") } } else { if (w.onRowSelectedChangeClass) { a(this).removeClass( "trSelected") } } } }) }, addRowProp : function() { var g = this.rowProp; var p = this.rowTrProp; a("tbody tr", z.bDiv).each(function() { p.call(this); g.call(this) }); p = null; g = null }, stopPropagation : function(g) { if (g && g.stopPropagation) { g.stopPropagation() } else { window.event.cancelBubble = true } }, getRecordCount : function() { var g = a(z.bDiv).children("table").children("tbody").children( "tr"); return g.length }, rowTrProp : function() { a("input.itemchk", this).each(function() { var g = a(this).parent().parent().parent(); a(this).click(function(p) { if (this.checked) { g.addClass("trSelected"); z.freshCheckboxState() } else { g.removeClass("trSelected"); z.doUncheck() } if (w.onrowchecked) { w.onrowchecked.call(this, { isChecked : this.checked, tr_object : g, isHeadCheckbox : false }) } z.stopPropagation(p) }) }) }, checkAllOrNot : function(g) { var p = a(this).attr("checked"); a("tbody tr[id^=" + w.table_id + "_row_]", z.bDiv).each( function() { if (!a("input.itemchk", this).attr("disabled")) { if (p) { a(this).addClass("trSelected") } else { a(this).removeClass("trSelected") } } }); a("input.itemchk", z.bDiv).each(function() { if (!a(this).attr("disabled")) { this.checked = p; var t = a(this).parent().parent().parent(); if (w.onrowchecked) { w.onrowchecked.call(this, { isChecked : this.checked, tr_object : t, isHeadCheckbox : true }) } } }) }, freshCheckboxState : function() { if (a("tbody tr", z.bDiv).length > 0 && a( "tbody tr input[type='checkbox']:not(:disabled):not(:checked).itemchk", z.bDiv).length == 0) { if (a("tbody tr input[type='checkbox']:not(:disabled)", z.bDiv).length == 0) { z.doUncheck() } else { z.doCheck() } } else { z.doUncheck() } }, doUncheck : function() { a("th div input[type='checkbox']", z.hDiv).filter(function() { return a(this).hasClass("noborder") }).attr("checked", false) }, doCheck : function() { a("th div input[type='checkbox']", z.hDiv).filter(function() { return a(this).hasClass("noborder") }).attr("checked", true) }, enabledButton : function(t) { if (t.id) { var g = document.getElementById(t.id); if (g) { a(g).removeAttr("disabled"); if (!a.browser.msie) { a(g).css("color", "rgb(0,0,0)") } if (g.disabledClass) { jQuery("span", g).removeClass(g.disabledClass) } if (!(a(g).data("events") && a(g).data("events")["click"])) { a(g).bind("click", function() { this.onpress(this.name, z.gDiv) }) } } } }, disabledButton : function(t) { if (t.id) { var g = document.getElementById(t.id); if (g) { a(g).attr("disabled", "disabled"); if (!a.browser.msie) { a(g).css("color", "grey") } if (g.disabledClass) { jQuery("span", g).addClass(g.disabledClass) } } } if (a(g).data("events") && a(g).data("events")["click"]) { a(g).unbind("click") } }, doSortClass : function() { a("thead tr:first th", z.hDiv) .each( function() { var g = a(this).children("div"); if (a(this).attr("abbr")) { a(this).click(function(t) { if (!a(this).hasClass("thOver")) { return false } var p = (t.target || t.srcElement); if (p.href || p.type) { return true } if (z.getRecordCount() > 0) { z.changeSort(this) } }); if (a(this).attr("abbr") == w.sortname && z.getRecordCount() > 0) { a(this).attr("class", "sorted"); g.attr("class", "s" + w.sortorder) } } if (!a(this).attr("isch")) { a(this) .hover( function() { if (a(this).attr( "abbr") != w.sortname && !z.colCopy && !z.colresize && a(this) .attr( "abbr") && z .getRecordCount() > 0) { a("div", this) .addClass( "s" + w.sortorder) } else { if (a(this) .attr( "abbr") == w.sortname && !z.colCopy && !z.colresize && a( this) .attr( "abbr") && z .getRecordCount() > 0) { var p = ""; if (w.sortorder == "asc") { p = "desc" } else { p = "asc" } a("div", this) .removeClass( "s" + w.sortorder) .addClass( "s" + p) } else { a("div", this) .removeClass( "s" + w.sortorder) .removeClass( "s" + p) } } }, function() { if (a(this).attr( "abbr") != w.sortname && z .getRecordCount() > 0) { a("div", this) .removeClass( "s" + w.sortorder) } else { if (a(this) .attr( "abbr") == w.sortname && z .getRecordCount() > 0) { var p = ""; if (w.sortorder == "asc") { p = "desc" } else { p = "asc" } a("div", this) .addClass( "s" + w.sortorder) .removeClass( "s" + p) } else { a("div", this) .removeClass( "s" + w.sortorder) .removeClass( "s" + p) } } if (z.colCopy) { a(z.cdropleft) .remove(); a(z.cdropright) .remove(); z.dcolt = null } }) } }) }, freshSortClass : function() { var g = a("thead tr:first th", z.hDiv); for ( var p = 0; p < g.length; p++) { if (!a(g[p]).attr("isch") && a(g[p]).attr("abbr") == w.sortname) { if (!z.colCopy && !z.colresize && a(g[p]).attr("abbr") && z.getRecordCount() > 0) { a("div", g[p]).addClass("s" + w.sortorder) } else { if (!z.colCopy && !z.colresize && a(g[p]).attr("abbr") && z.getRecordCount() == 0) { a("div", g[p]).removeClass("s" + w.sortorder) } } break } } }, jsPath : function(F) { var p = document.getElementsByTagName("script"); for ( var g = 0; g < p.length; g++) { if (p[g].src.lastIndexOf(F) >= 0) { var t = p[g].src.replace(/\\/gi, "/"); return t.substring(0, t.lastIndexOf("/") + 1) } } return "" }, initExportDivContent : function() { var g = 0; var t = 0; var F = ""; var p = true; a("th div", z.hDiv) .each( function() { var J = false; var H = a("th[axis='col" + g + "']", z.hDiv)[0]; var I = a(this).parents("th").attr("axis"); I = I.substr(3); if (H == null) { return } var G = 'checked="checked"'; if (H.style.display == "none") { G = "" } if (p) { F += "<tr>\r"; p = false } if (I == -1) { g-- } if (!(I == -1) && w.colModel[I]["isData"]) { J = true; F = F + '\t<td class="ndcol1"><input type="checkbox" ' + G + ' class="togCol noborder" value="' + I + '" /></td>\r\t<td class="ndcol2">' + this.innerText + "</td>\r" } if (J && t % 2 != 0) { F += "</tr>\r"; p = true } if (J) { t++ } g++ }); a("tbody", z.eDiv).append(F) }, initExportDiv : function() { z.eDiv = document.createElement("div"); z.eDiv.style.overFlow = "auto"; z.eDiv.style.maxHeight = "300"; z.eDiv.className = "eDiv"; z.eDiv.innerHTML = "<table cellpadding='0' cellspacing='0'><tbody></tbody></table>"; a(z.eDiv).css({ display : "none" }).noSelect(); a(z.eDiv).children("tbody").empty(); z.initExportDivContent(); a("tbody", z.eDiv) .prepend( '<tr class="tBar"><td colspan="6" class="tBar"><table><tr><td><span class="title">\u8bf7\u9009\u62e9\u5217</span></td><td class="button"><span id="export">\u786e\u5b9a</span></td><td class="button"><span id="cancel">\u53d6\u6d88</span></td><td class="button"><span id="reverseCheck">\u53cd\u9009</span></td><td class="button"><span id="checkAll">\u5168\u9009</span></td></tr></table></td></tr>'); a(z.gDiv).prepend(z.eDiv); a("td.ndcol2", z.eDiv).click(function() { var g = a(this).prev().find("input")[0]; if (g.checked) { g.checked = "" } else { g.checked = "checked" } }) }, exportByColumns : function(t) { var M = {}; var p = []; if (t && t.btnName) { var g; if (a(z.eDiv).is(":visible")) { a(z.eDiv).hide() } else { if (z.eDiv) { a(z.eDiv).remove() } z.initExportDiv(); a(z.eDiv).show(); var K = a("div[name='" + t.btnName + "']", z.tDiv); var J = K.width(); var G = z.tDiv.offsetTop; if (K.width() == null) { a(z.eDiv).css({ top : G + 3, left : 0 }) } else { a(z.eDiv).css({ top : G + K.height() + 3, left : K.offset().left }) } if (!a("#export", z.eDiv).data("events") || !a("#export", z.eDiv).data("events")["click"]) { a("#export", z.eDiv) .click( function() { a(":checkbox:checked", z.eDiv) .each( function() { var N = a( this) .attr( "value"); p .push(w.colModel[N]) }); M.sortname = w.sortname; M.sortorder = w.sortorder; M.data = p; if (w.onSelectCol) { if (p.length) { w.onSelectCol.call( this, M); a(z.eDiv).hide() } else { alert("\u60a8\u8fd8\u6ca1\u6709\u9009\u62e9\u4efb\u4f55\u9700\u8981\u5bfc\u51fa\u7684\u5217") } } }) } if (!a("#cancel", z.eDiv).data("events") || !a("#cancel", z.eDiv).data("events")["click"]) { a("#cancel", z.eDiv).click(function() { a(z.eDiv).hide() }) } if (!a("#checkAll", z.eDiv).data("events") || !a("#checkAll", z.eDiv).data("events")["click"]) { a("#checkAll", z.eDiv).click( function() { a("td.ndcol1", z.eDiv).each( function() { a(this).children("input") .attr("checked", "checked") }) }) } if (!a("#reverseCheck", z.eDiv).data("events") || !a("#reverseCheck", z.eDiv).data("events")["click"]) { a("#reverseCheck", z.eDiv) .click( function() { a("td.ndcol1", z.eDiv) .each( function() { var N = a( this) .children( "input") .attr( "checked"); if ((N == true || (typeof N == "string" && N == "checked"))) { a(this) .children( "input") .attr( "checked", false) } else { a(this) .children( "input") .attr( "checked", true) } }) }) } } } else { var L = a(".bbit-grid .hDivBox") .children() .children() .children() .children() .filter( function() { return !(a(this).css("display") == "none") && a(this).attr("isData") }); for ( var H = 0; H < L.length; H++) { var F = a(L[H]).attr("axis"); var I = F.substr(3, F.length - 1); if (I < 0) { continue } p.push(w.colModel[I]) } M.sortname = w.sortname; M.sortorder = w.sortorder; M.data = p; return M } }, exportAll : function(g) { var F = []; var t = w.colModel; if (w.onSelectCol) { for ( var p = 0; p < t.length; p++) { if (t[p].isData) { F.push(t[p]) } } w.onSelectCol.call(this, { selectCols : F }) } }, pager : 0 }; if (w.colModel) { A = document.createElement("thead"); tr = document.createElement("tr"); if (w.showcheckbox) { var c = jQuery("<th/>"); var q = jQuery('<input type="checkbox"/>'); q.addClass("noborder"); c.addClass("cth").attr({ axis : "col-1", width : "22", isch : true }).append(q); c[0].hide = false; a(tr).append(c) } var r = a("#" + w.container_id).outerWidth(); if (typeof w.width == "string" && w.width.indexOf("%") != -1) { if (w.showcheckbox) { r = r * parseFloat(w.width) * 0.01 - 2 - 32 } else { r = r * parseFloat(w.width) * 0.01 - 2 } } else { if (typeof w.width == "string" && w.width.indexOf("%") == -1) { if (w.showcheckbox) { r = parseFloat(w.width) - 32 - 2 } else { r = parseFloat(w.width) - 2 } } else { if (w.showcheckbox) { r = w.width - 32 - 2 } else { r = w.width - 2 } } } var l = 0; var v = 1; for (i = 0; i < w.colModel.length; i++) { var o = w.colModel[i]; if (typeof o.width == "string" && o.width.indexOf("%") != -1) { if (o.hide) { l += parseInt(o.width) } } } v = 1 - l * 0.01; for (i = 0; i < w.colModel.length; i++) { o = w.colModel[i]; var h; var k = document.createElement("th"); k.innerHTML = o.display; if (o.name && o.sortable) { a(k).attr("abbr", o.name) } a(k).attr("axis", "col" + i); if (o.align) { k.align = o.align } if (o.width) { a(k).attr("oriWidth", o.width); if (typeof o.width == "string" && o.width.indexOf("%") != -1) { w.dragable = false; h = r * (parseFloat(o.width) * 0.01 / v) - 10 } else { h = parseFloat(o.width) } a(k).attr("width", h) } else { a(k).attr("width", 100) } if (o.hide) { k.hide = true } else { k.hide = false } if (o.toggle != undefined) { k.toggle = o.toggle } if (o.format) { k.format = o.format } if (o.isData == undefined) { o.isData = true } if (o.isData) { k.isData = true } else { o.isData = false; k.isData = false } if (o.ct) { k.ct = o.ct } else { k.ct = false } if (o.isKey) { k.isKey = o.isKey } else { k.isKey = false } if (o.title_align) { k.title_align = o.title_align } else { k.title_align = "center" } a(tr).append(k) } a(A).append(tr); a(u).prepend(A) } z.gDiv = document.createElement("div"); z.mDiv = document.createElement("div"); z.hDiv = document.createElement("div"); z.bDiv = document.createElement("div"); z.vDiv = document.createElement("div"); z.rDiv = document.createElement("div"); z.cDrag = document.createElement("div"); z.block = document.createElement("div"); z.nDiv = document.createElement("div"); z.nBtn = document.createElement("div"); z.iDiv = document.createElement("div"); z.tDiv = document.createElement("div"); z.sDiv = document.createElement("div"); if (w.usepager) { z.pDiv = document.createElement("div") } z.hTable = document.createElement("table"); z.gDiv.className = w.gridClass; a(z.gDiv).css({ position : "relative" }); if (w.width != "auto") { z.gDiv.style.width = w.width + (((w.width + "").indexOf("%") != -1) ? "" : "px") } if (a.browser.msie) { a(z.gDiv).addClass("ie") } if (w.novstripe) { a(z.gDiv).addClass("novstripe") } a(u).before(z.gDiv); a(z.gDiv).append(u); var E = a("#" + w.container_id).parents("table"); if (E.length) { var x = a(E[0]); if (!x.hasClass("grid_layout_style")) { x.addClass("grid_layout_style") } } if (w.buttons) { z.tDiv.className = "tDiv"; var C = document.createElement("div"); C.className = "tDiv2"; for (i = 0; i < w.buttons.length; i++) { var n = w.buttons[i]; if (!n.separator) { var y = document.createElement("div"); y.className = "fbutton"; y.innerHTML = "<div><span style='padding-top: 3px;'>" + n.displayname + "</span></div>"; y.disabled = n.disabled; if (n.title) { y.title = n.title } if (n.bclass) { a("span", y).addClass(n.bclass).css({ paddingLeft : 20 }) } y.name = n.name; y.id = n.id; y.onpress = n.onpress; if (n.disabledClass) { y.disabledClass = n.disabledClass } a(y).bind("click", function() { this.onpress(this.name, z.gDiv) }); a(C).append(y); if (a.browser.msie && a.browser.version < 7) { a(y).hover(function() { a(this).addClass("fbOver") }, function() { a(this).removeClass("fbOver") }) } if (n.disabled) { if (!a.browser.msie) { a(y).css("color", "grey") } if (n.disabledClass) { jQuery("span", y).addClass(n.disabledClass) } a(y).unbind("click") } } else { a(C).append("<div class='btnseparator'></div>") } } a(z.tDiv).append(C); a(z.tDiv).append("<div style='clear:both'></div>"); a(z.gDiv).prepend(z.tDiv) } z.hDiv.className = "hDiv"; a(u).before(z.hDiv); z.hTable.cellPadding = 0; z.hTable.cellSpacing = 0; a(z.hDiv).append('<div class="hDivBox"></div>'); a("div", z.hDiv).append(z.hTable); var A = a("thead:first", u).get(0); if (A) { a(z.hTable).append(A) } A = null; if (!w.colmodel) { var s = 0 } a("thead tr:first th", z.hDiv) .each( function() { var g = document.createElement("div"); if (this.hide) { a(this).hide() } if (!w.colmodel && !a(this).attr("isch")) { a(this).attr("axis", "col" + s++) } a(g).css({ textAlign : this.title_align, width : this.width + "px" }); g.innerHTML = this.innerHTML; a(this).empty().append(g); if (!a(this).attr("isch")) { a(this) .mousedown(function(p) { z.dragStart("colMove", p, this) }) .hover( function() { if (!z.colresize && !a(this) .hasClass( "thMove") && !z.colCopy) { a(this).addClass( "thOver") } if (z.colCopy) { var F = a("th", z.hDiv) .index(this); if (F == z.dcoln) { return false } if (F < z.dcoln) { a(this) .append( z.cdropleft) } else { a(this) .append( z.cdropright) } z.dcolt = F } else { if (!z.colresize) { var p = a( "th:visible", z.hDiv); var K = -1; for ( var I = 0, H = 0, G = p.length; I < G; I++) { if (a(p[I]) .css( "display") != "none") { if (p[I] == this) { K = H; break } H++ } } var K = a( "th:visible", z.hDiv) .index(this); var t = parseInt(a( "div:eq(" + K + ")", z.cDrag) .css("left")); var J = parseInt(a( z.nBtn) .width()) + parseInt(a( z.nBtn) .css( "borderLeftWidth")); nl = t - J + Math .floor(w.cgwidth / 2); a(z.nDiv).hide(); a(z.nBtn).hide(); a(z.nBtn) .css( { left : nl, top : z.hDiv.offsetTop }) .show(); var L = parseInt(a( z.nDiv) .width()); a(z.nDiv) .css( { top : z.bDiv.offsetTop }); if ((nl + L) > a( z.gDiv) .width()) { a(z.nDiv) .css( "left", t - L + 1) } else { a(z.nDiv).css( "left", nl) } if (a(this) .hasClass( "sorted")) { a(z.nBtn) .addClass( "srtd") } else { a(z.nBtn) .removeClass( "srtd") } } } }, function() { a(this).removeClass( "thOver"); if (z.colCopy) { a(z.cdropleft).remove(); a(z.cdropright) .remove(); z.dcolt = null } }) } }); z.bDiv.className = "bDiv"; if (w.bgColor) { a(z.bDiv).css("background-color", w.bgColor) } a(u).before(z.bDiv); a(z.bDiv).css({ height : (w.height == "auto") ? "auto" : w.height + "px" }).scroll(function(g) { z.scroll() }).append(u); if (w.height == "auto") { a("table", z.bDiv).addClass("autoht") } if (w.url == false || w.url == "") { z.addCellProp(); z.addRowProp() } var f = a("thead tr:first th:first", z.hDiv).get(0); if (f != null) { z.cDrag.className = "cDrag"; z.cdpad = 0; z.cdpad += (isNaN(parseInt(a("div", f).css("borderLeftWidth"))) ? 0 : parseInt(a("div", f).css("borderLeftWidth"))); z.cdpad += (isNaN(parseInt(a("div", f).css("borderRightWidth"))) ? 0 : parseInt(a("div", f).css("borderRightWidth"))); z.cdpad += (isNaN(parseInt(a("div", f).css("paddingLeft"))) ? 0 : parseInt(a("div", f).css("paddingLeft"))); z.cdpad += (isNaN(parseInt(a("div", f).css("paddingRight"))) ? 0 : parseInt(a("div", f).css("paddingRight"))); z.cdpad += (isNaN(parseInt(a(f).css("borderLeftWidth"))) ? 0 : parseInt(a(f).css("borderLeftWidth"))); z.cdpad += (isNaN(parseInt(a(f).css("borderRightWidth"))) ? 0 : parseInt(a(f).css("borderRightWidth"))); z.cdpad += (isNaN(parseInt(a(f).css("paddingLeft"))) ? 0 : parseInt(a(f).css("paddingLeft"))); z.cdpad += (isNaN(parseInt(a(f).css("paddingRight"))) ? 0 : parseInt(a(f).css("paddingRight"))); a(z.bDiv).before(z.cDrag); var e = a(z.bDiv).height(); var d = a(z.hDiv).height(); a(z.cDrag).css({ top : -d + "px" }); a("thead tr:first th", z.hDiv).each(function() { var p = document.createElement("div"); a(z.cDrag).append(p); if (!w.cgwidth) { w.cgwidth = a(p).width() } var g = a(this).attr("isch"); if (w.dragable) { a(p).css({ height : e + d }); if (!g) { a(p).mousedown(function(t) { z.dragStart("colresize", t, this) }) } z.fixHeight(a(z.gDiv).height()); a(p).hover(function() { z.fixHeight(); if (!g) { a(this).addClass("dragging") } }, function() { if (!z.colresize) { a(this).removeClass("dragging") } }) } }); z.rePosDrag() } if (w.striped) { a("tbody tr:odd", z.bDiv).addClass("erow") } if (w.resizable && w.height != "auto") { z.vDiv.className = "vGrip"; a(z.vDiv).mousedown(function(g) { z.dragStart("vresize", g) }).html("<span></span>"); a(z.bDiv).after(z.vDiv) } if (w.resizable && w.width != "auto" && !w.nohresize) { z.rDiv.className = "hGrip"; a(z.rDiv).mousedown(function(g) { z.dragStart("vresize", g, true) }).html("<span></span>").css("height", a(z.gDiv).height()); if (a.browser.msie && a.browser.version < 7) { a(z.rDiv).hover(function() { a(this).addClass("hgOver") }, function() { a(this).removeClass("hgOver") }) } a(z.gDiv).append(z.rDiv) } z.doUsePager = function() { if (w.usepager) { z.pDiv.className = "pDiv"; z.pDiv.innerHTML = '<div class="pDiv2"></div>'; a(z.bDiv).after(z.pDiv); var F = '<div class="pGroup"><div class="pFirst pButton" title="\u8f6c\u5230\u7b2c\u4e00\u9875"><span></span></div><div class="pPrev pButton" title="\u8f6c\u5230\u4e0a\u4e00\u9875"><span></span></div> </div><div class="btnseparator"></div> <div class="pGroup"><span class="pcontrol">\u5f53\u524d\u7b2c <input type="text" size="1" value="1" />\u9875\uff0c\u603b\u9875\u6570 <span> 1 </span></span></div><div class="btnseparator"></div><div class="pGroup"> <div class="pNext pButton" title="\u8f6c\u5230\u4e0b\u4e00\u9875"><span></span></div><div class="pLast pButton" title="\u8f6c\u5230\u6700\u540e\u4e00\u9875"><span></span></div></div><div class="btnseparator"></div><div class="pGroup"> <div class="pReload pButton" title="\u5237\u65b0"><span></span></div> </div> <div class="btnseparator"></div><div class="pGroup"><span class="pPageStat"></span></div>'; a("div", z.pDiv).html(F); a(".pReload", z.pDiv).click(function() { if (w.isSuccessSearch) { z.changePage("reload") } }); a(".pFirst", z.pDiv).click(function() { if (w.isSuccessSearch) { z.changePage("first") } }); a(".pPrev", z.pDiv).click(function() { if (w.isSuccessSearch) { z.changePage("prev") } }); a(".pNext", z.pDiv).click(function() { if (w.isSuccessSearch) { z.changePage("next") } }); a(".pLast", z.pDiv).click(function() { if (w.isSuccessSearch) { z.changePage("last") } }); a(".pcontrol input", z.pDiv).keydown(function(I) { if (I.keyCode == 13 && w.isSuccessSearch) { z.changePage("input") } }); if (a.browser.msie && a.browser.version < 7) { a(".pButton", z.pDiv).hover(function() { a(this).addClass("pBtnOver") }, function() { a(this).removeClass("pBtnOver") }) } if (w.useRp) { var t = ""; for ( var p = 0; p < w.rpOptions.length; p++) { if (w.rp == w.rpOptions[p]) { sel = 'selected="selected"' } else { sel = "" } t += "<option value='" + w.rpOptions[p] + "' " + sel + " >" + w.rpOptions[p] + "&nbsp;&nbsp;</option>" } a(".pDiv2", z.pDiv) .prepend( "<div class='pGroup'>\u6bcf\u9875 <select name='rp'>" + t + "</select>\u6761</div> <div class='btnseparator'></div>"); a("select", z.pDiv).change(function() { if (w.onRpChange) { w.onRpChange(+this.value) } else { w.newp = 1; w.rp = this.value; if (w.isSuccessSearch) { z.changePage("change") } } }) } if (w.searchitems) { a(".pDiv2", z.pDiv) .prepend( "<div class='pGroup'> <div class='pSearch pButton'><span></span></div> </div> <div class='btnseparator'></div>"); a(".pSearch", z.pDiv).click( function() { a(z.sDiv).slideToggle( "fast", function() { a(".sDiv:visible input:first", z.gDiv).trigger("focus") }) }); z.sDiv.className = "sDiv"; sitems = w.searchitems; var g = ""; var H = "Eq"; for ( var G = 0; G < sitems.length; G++) { if (w.qtype == "" && sitems[G].isdefault == true) { w.qtype = sitems[G].name; sel = 'selected="selected"' } else { sel = "" } if (sitems[G].operater == "Like") { H = "Like" } else { H = "Eq" } g += "<option value='" + sitems[G].name + "$" + H + "$" + G + "' " + sel + " >" + sitems[G].display + "&nbsp;&nbsp;</option>" } if (w.qtype == "") { w.qtype = sitems[0].name } a(z.sDiv) .append( "<div class='sDiv2'>\u5feb\u901f\u68c0\u7d22\uff1a<input type='text' size='30' name='q' class='qsbox' /> <select name='qtype'>" + g + "</select> <input type='button' name='qclearbtn' value='\u6e05\u7a7a' /></div>"); a("input[name=q],select[name=qtype]", z.sDiv).keydown( function(I) { if (I.keyCode == 13) { z.doSearch() } }); a("input[name=qclearbtn]", z.sDiv).click(function() { a("input[name=q]", z.sDiv).val(""); w.query = ""; z.doSearch() }); a(z.bDiv).after(z.sDiv) } } }; z.doUsePager(); a(z.pDiv, z.sDiv).append("<div style='clear:both'></div>"); if (w.title) { z.mDiv.className = "mDiv"; z.mDiv.innerHTML = '<div class="ftitle">' + w.title + "</div>"; a(z.gDiv).prepend(z.mDiv); if (w.showTableToggleBtn) { a(z.mDiv) .append( '<div class="ptogtitle" title="Minimize/Maximize Table"><span></span></div>'); a("div.ptogtitle", z.mDiv).click(function() { a(z.gDiv).toggleClass("hideBody"); a(this).toggleClass("vsble") }) } z.rePosDrag() } z.cdropleft = document.createElement("span"); z.cdropright = document.createElement("span"); var j = a("<div/>"); j.addClass("loading"); a(z.block).append(j); var B = a(z.bDiv).height(); var D = z.bDiv.offsetTop; a(z.block).css({ width : z.bDiv.style.width, height : B, position : "relative", marginBottom : (B * -1), zIndex : 1, top : D, left : "0px" }); a(z.block).fadeTo(0, w.blockOpacity); if (a("th", z.hDiv).length) { z.nDiv.className = "nDiv"; z.nDiv.innerHTML = "<table cellpadding='0' cellspacing='0'><tbody></tbody></table>"; a(z.nDiv).css({ marginBottom : (B * -1), display : "none", top : D }).noSelect(); var m = 0; a("th div", z.hDiv).each( function() { var p = a("th[axis='col" + m + "']", z.hDiv)[0]; if (p == null) { return } var t = a("input[type='checkbox']", this).filter( function() { return a(this).hasClass("noborder") }); if (t.length > 0) { t[0].onclick = z.checkAllOrNot; return } if (p.toggle == false || this.innerHTML == "") { m++; return } var g = 'checked="checked"'; if (p.style.display == "none") { g = "" } a("tbody", z.nDiv).append( '<tr><td class="ndcol1"><input type="checkbox" ' + g + ' class="togCol noborder" value="' + m + '" /></td><td class="ndcol2">' + this.innerText + "</td></tr>"); m++ }); if (a.browser.msie && a.browser.version < 7) { a("tr", z.nDiv).hover(function() { a(this).addClass("ndcolover") }, function() { a(this).removeClass("ndcolover") }) } a("td.ndcol2", z.nDiv).click( function() { if (a("input:checked", z.nDiv).length < w.minColToggle && a(this).prev().find("input")[0].checked) { return false } return z.toggleCol(a(this).prev().find("input").val()) }); a("input.togCol", z.nDiv).click( function() { if (a("input:checked", z.nDiv).length < w.minColToggle && this.checked == false) { return false } a(this).parent().next().trigger("click") }); a(z.gDiv).prepend(z.nDiv); a(z.nBtn).addClass("nBtn").html("<div></div>").click(function() { a(z.nDiv).toggle(); return true }); if (w.showToggleBtn) { a(z.gDiv).prepend(z.nBtn) } } a(z.iDiv).addClass("iDiv").css({ display : "none" }); a(z.bDiv).append(z.iDiv); a(z.bDiv).hover(function() { a(z.nDiv).hide(); a(z.nBtn).hide(); a(z.eDiv).hide() }, function() { if (z.multisel) { z.multisel = false } }); a(z.gDiv).hover(function() { }, function() { a(z.nDiv).hide(); a(z.nBtn).hide(); a(z.eDiv).hide() }); a(document).mousemove(function(g) { z.dragMove(g) }).mouseup(function(g) { z.dragEnd() }).hover(function() { }, function() { z.dragEnd() }); if (a.browser.msie && a.browser.version < 7) { a(".hDiv,.bDiv,.mDiv,.pDiv,.vGrip,.tDiv, .sDiv", z.gDiv).css({ width : "100%" }); a(z.gDiv).addClass("ie6"); if (w.width != "auto") { a(z.gDiv).addClass("ie6fullwidthbug") } } z.rePosDrag(); z.fixHeight(); u.p = w; u.grid = z; if (w.autoload) { w.isSuccessSearch = true; z.populate() } z.doSortClass(); return u }; var b = false; a(document).ready(function() { b = true }); a.fn.flexigrid = function(c) { return this.each(function() { if (!b) { a(this).hide(); var d = this; a(document).ready(function() { a.addFlex(d, c) }) } else { a.addFlex(this, c) } }) }; a.fn.noSelect = function(c) { if (c == null) { prevent = true } else { prevent = c } if (prevent) { return this.each(function() { if (a.browser.msie || a.browser.safari) { a(this).bind("selectstart", function() { return false }) } else { if (a.browser.mozilla) { a(this).css("MozUserSelect", "none"); a("body").trigger("focus") } else { if (a.browser.opera) { a(this).bind("mousedown", function() { return false }) } else { a(this).attr("unselectable", "on") } } } }) } else { return this.each(function() { if (a.browser.msie || a.browser.safari) { a(this).unbind("selectstart") } else { if (a.browser.mozilla) { a(this).css("MozUserSelect", "inherit") } else { if (a.browser.opera) { a(this).unbind("mousedown") } else { a(this).removeAttr("unselectable", "on") } } } }) } } })(jQuery); var NLTable = function(g) { this.timer = null; String.prototype.replaceAll = function(k, j) { return this.replace(new RegExp(k, "gm"), j) }; if (g.height) { g.isDefaultHeight = false } else { if (g.subIds && g.subIds.length > 0) { g.isDefaultHeight = true; var f = 0; for ( var b = 0, a = g.subIds.length; b < a; b++) { f += jQuery("#" + g.subIds[b]).outerHeight() } g.height = jQuery(window).height() - f } else { g.isDefaultHeight = true; g.height = jQuery(window).height() } } g = jQuery .extend( { container_id : "", table_id : "", tableData : false, onChangePage : false, height : 305, sortname : "id", sortorder : "desc", width : "auto", striped : true, novstripe : false, maskObject : false, minwidth : 30, minheight : 80, url : false, method : "POST", dataType : "json", errormsg : "\u6570\u636e\u8bf7\u6c42\u5931\u8d25!", usepager : true, nowrap : false, page : 1, total : 1, useRp : true, rp : 10, rpOptions : [ 10, 15, 20, 25, 40, 100 ], title : "\u6570\u636e\u5217\u8868", pagestat : "\u663e\u793a\u8bb0\u5f55\u4ece{from}\u5230{to},\u603b\u6570 {total} \u6761", procmsg : "\u6b63\u5728\u5904\u7406\u6570\u636e\uff0c\u8bf7\u7a0d\u5019 ...", query : "", qtype : "", qop : "Eq", nomsg : "\u6ca1\u6709\u7b26\u5408\u6761\u4ef6\u7684\u8bb0\u5f55\u5b58\u5728", minColToggle : 1, onWindowResize : false, showToggleBtn : false, hideOnSubmit : true, showTableToggleBtn : false, autoload : false, blockOpacity : 0.5, onToggleCol : false, onChangeSort : false, onSuccess : false, onSubmit : false, showcheckbox : false, rowhandler : false, clickRowDoCheck : true, onRowSelectedChangeClass : false, rowbinddata : true, extParam : [ {} ], successResultID : "1", showSuccessMsg : true, showErrorMsg : true, bgClass : false, gridClass : "bbit-grid", disCheckbox : false, dragable : true, isReloadCall : false, sortByStatic : false, isFilter : true }, g); g._rp = g.rp; g._page = g.page; g._sortname = g.sortname; g._sortorder = g.sortorder; g._query = g.query; g._qtype = g.qtype; g._qop = g.qop; g.resizable = false; var c = 26; c += 1; if (g.title) { c += 24 } if (g.buttons) { c += 26 } if (g.usepager) { c += 31 } g.height = g.height - c; if (g.height < 0) { g.height = 0 } g.table_id = g.container_id + "_table_id"; function d() { jQuery("#" + g.container_id).append( '<table id="' + g.table_id + '" style="display:none"></table>') } d(); var e = jQuery("#" + g.table_id).flexigrid(g); g.oldWidth = jQuery("#" + g.container_id).width(); if (g.onWindowResize) { var h = this; jQuery(window) .resize( function() { window.clearTimeout(h.timer); h.timer = window .setTimeout( function() { var k = g.onWindowResize(); if (k.width != undefined && k.height != undefined) { var j, m; if (typeof e[0].p.width == "string" && e[0].p.width .indexOf("%") != -1) { j = jQuery( "#" + e[0].p.container_id) .width() * e[0].p.width } else { j = parseInt(e[0].p.width) } if (typeof k.width == "string" && k.width .indexOf("%") != -1) { m = jQuery( "#" + g.container_id) .width() * k.width } else { m = parseInt(k.width) } var l = j != m; if ((e[0].p.width != k.width || l) || (parseInt( e[0].p.height, 10) + c) != k.height) { h.flexResize(k.width, k.height) } } }, 100) }) } else { if (g.subIds) { var h = this; jQuery(window) .resize( function() { window.clearTimeout(h.timer); h.timer = window .setTimeout( function() { if (g.isDefaultHeight) { var k = 0; if (g.subIds && g.subIds.length > 0) { var o = 0; for ( var m = 0, j = g.subIds.length; m < j; m++) { o += jQuery( "#" + g.subIds[m]) .outerHeight() } k = jQuery(window) .height() - o } else { k = jQuery(window) .height() } var n; if (typeof e[0].p.width == "string" && e[0].p.width .indexOf("%") != -1) { n = jQuery( "#" + e[0].p.container_id) .width() * e[0].p.width } else { n = parseInt(e[0].p.width) } var l = g.oldWidth != n; if (l || (parseInt( e[0].p.height, 10) + c) != k) { g.oldWidth = l; h.flexResize( g.width, k) } } }, 100) }) } } this.search = this.flexReload = function(j, k) { return e.each(function() { if (e[0].grid) { var l = { newp : g._page, rp : (g.tableData && !g.url) ? g.rp : g._rp, sortname : g._sortname, sortorder : g._sortorder, query : g._query, qtype : g._qtype, qop : g._qop, extParam : j ? j : [ {} ] }; if (k) { l.tableData = k } e[0].grid.freshParam(l); e[0].grid.populate() } }) }; this.clearAllRows = function() { if (e[0].grid) { e[0].grid.clearAllRows() } }; this.flexResize = function(j, k) { var l = {}; if (j) { l.width = j } if (k) { k = parseInt(k, 10); l.height = k - c; if (l.height < 0) { l.height = 0 } } return e.each(function() { if (e[0].grid) { jQuery.extend(e[0].p, l); e[0].grid.reSize() } }) }; this.flexOptions = function(j) { return e.each(function() { if (e[0].grid) { jQuery.extend(e[0].p, j) } }) }; this.getOptions = function() { if (e[0].grid) { return e[0].p } return null }; this.getCheckedRows = function() { if (e[0].grid) { return e[0].grid.getCheckedRows() } return [] }; this.getRowData = function(j) { if (e[0].grid) { return e[0].grid.getRowData(j) } }; this.getRowsData = function() { if (e[0].grid) { return e[0].grid.getRowsData() } }; this.cancelAllSelectState = function() { if (e[0].grid) { e[0].grid.cancelAllSelectState() } }; this.mask = function() { if (e[0].grid) { e[0].grid.doMask("mask") } }; this.unmask = function() { if (e[0].grid) { e[0].grid.doMask("unmask") } }; this.exportByColumns = function(j) { if (e[0].grid) { return e[0].grid.exportByColumns(j) } return null }; this.exportAll = function(j) { if (e[0].grid) { return e[0].grid.exportAll(j) } return null }; this.enabledButton = function(j) { if (e[0].grid) { e[0].grid.enabledButton(j) } }; this.disabledButton = function(j) { if (e[0].grid) { e[0].grid.disabledButton(j) } }; this.flexToggleCol = function(k, j) { return e.each(function() { if (e[0].grid) { e[0].grid.toggleCol(k, j) } }) }; this.flexAddData = function(j) { return e.each(function() { if (e[0].grid) { e[0].grid.addData(j) } }) }; this.stopPropagation = function(j) { if (e[0].grid) { e[0].grid.stopPropagation(j) } }; this.addRowData = function(j) { if (e[0].grid) { return e[0].grid.addRowData(j) } }; this.getSelectIndex = function(j) { if (e[0].grid) { return e[0].grid.getSelectIndex(j) } }; this.deleteRowData = function(j) { if (e[0].grid) { e[0].grid.deleteRowData(j) } }; this.getAllData = function() { if (e[0].grid) { return e[0].grid.getAllData() } }; this.getChangeData = function() { if (e[0].grid) { return e[0].grid.getChangeData() } }; this.getRowObject = function(j) { if (e[0].grid) { return e[0].grid.getRowObject(j) } }; this.setRowOrColumnCol = function(j) { if (e[0].grid) { return e[0].grid.setRowOrColumnCol(j) } }; this.clearRowOrColumnCol = function(j) { if (e[0].grid) { return e[0].grid.clearRowOrColumnCol(j) } }; this.getNewRows = function() { if (e[0].grid) { return e[0].grid.getNewRows() } }; this.updateRowData = function(j) { if (e[0].grid) { return e[0].grid.updateRowData(j) } }; this.getUnselectRowsData = function() { if (e[0].grid) { return e[0].grid.getUnselectRowsData() } }; this.fresh = function(j) { if (e[0].grid) { if (!j) { j = {} } j.fnName = "fresh"; if (j.isCallOnChangePage != undefined && (j.isCallOnChangePage == false || (typeof j.isCallOnChangePage == String && j.isCallOnChangePage .toUpperCase() == "false".toUpperCase()))) { j.isCallOnChangePage = false } else { j.isCallOnChangePage = true } e[0].grid.changePage("reload", j) } }; this.checkRowsByKeyColumn = function(j) { if (e[0].grid) { e[0].grid.checkRowsByKeyColumn(j) } }; this.flexTitle = function(j) { if (e[0].grid) { e[0].grid.flexTitle(j) } }; this.adjustOrder = function(j) { if (e[0].grid) { e[0].grid.adjustOrder(j) } } }; <file_sep>/src/org/cola/sa/dao/SelfAnalysisDaoImpl.java package org.cola.sa.dao; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.cola.dao.DaoImpl; import org.cola.sa.bean.AttrClassBean; import org.cola.sa.bean.FrameBean; import org.cola.util.db.DBResult; public class SelfAnalysisDaoImpl extends DaoImpl implements SelfAnalysisDao { public List queryAttrList () { return null; } public List<FrameBean> queryFrameList() throws SQLException { StringBuffer sb = new StringBuffer(); sb.append("select frame_id, frame_name from sa_cfg_frame"); DBResult result = executeSql(sb.toString()); List<FrameBean> list = new ArrayList<FrameBean>(); for (int i = 0; i < result.iTotalCnt; i++) { FrameBean bean = new FrameBean(); bean.setFrameId(result.aaRes[i][0]); bean.setFrameName(result.aaRes[i][1]); list.add(bean); } return list; } public List<AttrClassBean> queryAttrClassList() throws SQLException { StringBuffer sb = new StringBuffer(); sb.append("select frame_id, attr_class_id, attr_class_name from sa_cfg_attr_class"); DBResult result = executeSql(sb.toString()); List<AttrClassBean> list = new ArrayList<AttrClassBean>(); for (int i = 0; i < result.iTotalCnt; i++) { AttrClassBean bean = new AttrClassBean(); bean.setFrameId(result.aaRes[i][0]); bean.setAttrClassId(result.aaRes[i][1]); bean.setAttrClassName(result.aaRes[i][2]); list.add(bean); } return list; } } <file_sep>/doc/tmp.sql select distinct t0.user_id as s00000000568 from xdmiddle.ft_mid_user_daily t0 where 1 = 1 and t0.home_code in ((select distinct call_town_group1_code from xdmart.dim_home_town where call_town_group1_code != 0 and call_town_group1_code != 590 and call_town_group1_code = 594)) and t0.sum_date = 20141115 and t0.msisdn in (select value_id from nldpe_in10015751); select t1.msisdn as s0000000055320141115, t1.create_date as s0000000051020141115, t1.home_county as s0000000052220141115, t1.brand_id as s0000000110420141115, t1.user_status as s0000000056920141115, t0.* from nldpe_temp_s_10187884_x1 t0 left join xdmiddle.ft_mid_user_daily t1 on t0.s00000000568 = t1.user_id and 1 = 1 and t1.sum_date = 20141115; select t1.total_gprs_data as s00000001544201410, t0.* from nldpe_temp_s_10187885_y_1 t0 left join xdmiddle.ft_mid_flux_monitor_month t1 on t0.s00000000568 = t1.user_id and 1 = 1 and t1.sum_month = 201410; select t1.sum_fee as s00000000563201410, t0.* from nldpe_temp_s_10187886_y_2 t0 left join xdmiddle.ft_mid_user_info_month t1 on t0.s00000000568 = t1.user_id and 1 = 1 and t1.sum_month = 201410; select distinct (s0000000051020141115) nk_194377, (s0000000055320141115) nk_194378, (s0000000052220141115) nk_194379, (s0000000110420141115) nk_194380, (s0000000056920141115) nk_194381, (s00000001544201410) nk_194382, (s00000000563201410) nk_194383 from nldpe_temp_s_10187887_y_3 where s0000000055320141115 in (select value_id from nldpe_in10015752); select distinct t0.user_id as s00000000568 from xdmiddle.ft_mid_user_daily t0 join xdmiddle.ft_mid_user_daily t11 on 1101 = 1101 and t11.sum_date = 20141103 and t0.user_status = t11.user_status and t0.msisdn = t11.msisdn and t0.user_id = t11.user_id where 1 = 1 and t0.home_code in ((select distinct call_town_group1_code from xdmart.dim_home_town where call_town_group1_code != 0 and call_town_group1_code != 590 and call_town_group1_code = 594)) and t0.sum_date = 20141031 and t0.msisdn = 13850263232 and t11.user_status in (select distinct dim_value from (select dim_value, dim_value_desc as dim_value_cn, dim_value as parent_dim_value from (select distinct 'L00000000637' dim_level_id, to_char(t.status_id) as dim_value, t.status_desc dim_value_desc, to_char(t.status_id) as order_id, 1 value_is_current, sysdate value_eff_date, sysdate + 1 value_invalid_date from xdmart.dim_user_status t) where ((value_eff_date <= sysdate and value_is_current = 1) or (value_eff_date <= sysdate and value_invalid_date > sysdate))) where parent_dim_value in ('5')); select t1.msisdn as s0000000055320141031, t0.* from nldpe_temp_s_10207793_x1 t0 left join xdmiddle.ft_mid_user_daily t1 on t0.s00000000568 = t1.user_id and 1 = 1 and t1.sum_date = 20141031; select t1.user_status as s0000000056920141103, t1.home_town as s0000000052320141103, t1.brand_id as s0000000110420141103, t1.msisdn as s0000000055320141103, t0.* from nldpe_temp_s_10207794_y_1 t0 left join xdmiddle.ft_mid_user_daily t1 on t0.s00000000568 = t1.user_id and 1 = 1 and t1.sum_date = 20141103; select distinct (s0000000055320141103) nk_177087, (s0000000052320141103) nk_177088, (s0000000110420141103) nk_177089, (s0000000056920141103) nk_177090 from nldpe_temp_s_10207795_y_2 where s0000000055320141031 = 13850263232 and s0000000056920141103 in (select distinct dim_value from (select dim_value, dim_value_desc as dim_value_cn, dim_value as parent_dim_value from (select distinct 'L00000000637' dim_level_id, to_char(t.status_id) as dim_value, t.status_desc dim_value_desc, to_char(t.status_id) as order_id, 1 value_is_current, sysdate value_eff_date, sysdate + 1 value_invalid_date from xdmart.dim_user_status t) where ((value_eff_date <= sysdate and value_is_current = 1) or (value_eff_date <= sysdate and value_invalid_date > sysdate))) where parent_dim_value in ('5')); select distinct 'L00000000637' dim_level_id, to_char(t.status_id) as dim_value, t.status_desc dim_value_desc, to_char(t.status_id) as order_id, 1 value_is_current, sysdate value_eff_date, sysdate + 1 value_invalid_date from dim_user_status@tomart t; select distinct t0.family_account as s00000000370 from xdmiddle.ft_mid_fam_cus_view_month t0 where 1 = 1 and t0.sum_month = 201410 and t0.is_valid_family in (select distinct dim_value from (select t.dim_value, t.dim_value_desc as dim_value_cn, t.dim_value as parent_dim_value from st_dim_value_dictionary t where t.dim_level_id = 'L00000000421' and ((value_eff_date <= sysdate and value_is_current = 1)  or(value_eff_date <= sysdate and value_invalid_date > sysdate))) where parent_dim_value in ('1')); select t1.is_valid_family as s00000000379201410, t1.cell_id as s00000000364201410, t0.* from nldpe_temp_s_10207789_x1 t0 left join xdmiddle.ft_mid_fam_cus_view_month t1 on t0.s00000000370 = t1.family_account and 1 = 1 and t1.sum_month = 201410; select t1.msisdn as s00000000553201410, t0.* from nldpe_temp_s_10207790_y_1 t0 left join xdmiddle.ft_mid_fam_mem_view_month t1 on t0.s00000000370 = t1.family_account and 1 = 1 and t1.sum_month = 201410; select distinct (s00000000553201410) nk_215430, (s00000000379201410) nk_215431, (s00000000364201410) nk_215432 from nldpe_temp_s_10207791_y_2 where s00000000379201410 in (select distinct dim_value from (select t.dim_value, t.dim_value_desc as dim_value_cn, t.dim_value as parent_dim_value from st_dim_value_dictionary t where t.dim_level_id = 'L00000000421' and ((value_eff_date <= sysdate and value_is_current = 1)  or(value_eff_date <= sysdate and value_invalid_date > sysdate))) where parent_dim_value in ('1'));
4a319881a5f1d2aded8a140afba9ea353689301b
[ "JavaScript", "Java", "SQL" ]
8
JavaScript
chenman/selfAnalysis
845a653adcfda3b8cedb0ac18fa36d1d6ed7598b
df753cafdf2f4824cadc0531ccfa2351ca40dff5
refs/heads/master
<repo_name>zfh123/vue-vuex-Best<file_sep>/src/appCofing.js var hosts = 'http://ac-OnsG2j7w.clouddn.com/' window.confing = { api:{ 'lost1': hosts + 'ea2bb71a43d94579bbc8.json', 'lost2': hosts + '9696d5d6fb56adffa9d6.json', 'lost3': hosts + '03f462d6209d935d5a0d.json', 'lost4': hosts + '33a0f2e6ba3cd81c672d.json', 'singerList': hosts + 'b316dc4f0d18cd067e77.json', 'songList': hosts + '1b41aabf12954929b020.json', 'rankList': hosts + 'a4305b8a2c8587d862c7.json' } }<file_sep>/src/pages/common/js/base.js import { CART_PUB } from 'store/cart' export function getCommonData(data) { console.log(data) } export function common(callback) { console.log('common'); } export function comTest(param,callback) { if(param === 'index'){ var url = window.confing.api.lost1; }else if(param === 'home'){ var url = window.confing.api.lost2; }else{ var url = window.confing.api.lost3; } $.ajax({ type: "get", url: url, async: true, success: function (res) { typeof callback == 'function' && callback(res) }, error: function (res) { console.log(res) } }); var pub = { address: '125', userNo: '890765', City2Name: '杭州市', City3Name: '西湖区' } }<file_sep>/src/common/js/jsonp.js export default function comm(url){ console.log('-------------------------3--------------------------------') console.log('当前的地址'+url); als(url) } function als(url){ console.log('-------------------------4--------------------------------') console.log('als函数级别里面的'+url) }<file_sep>/src/store/cart.js import Vue from 'vue' export const CART_LIST = 'CART_LIST' //登录成功 export const CART_TIST = 'CART_TIST' //退出登录 export const CART_PUB = 'CART_PUB' //保存公用方法的区域 export default { state: JSON.parse(sessionStorage.getItem('cartData')) || {}, mutations: { [CART_LIST](state, busin) { const cart = state; cart.busin = busin; Object.assign(state, cart); localStorage.setItem('cartData', JSON.stringify(cart)); }, [CART_TIST](state,address) { const cart = state; cart.address = address; Object.assign(state, cart); localStorage.setItem('cartData', JSON.stringify(cart)); }, [CART_PUB](state,pub){ // alert('2') console.log('2') const cart = state; cart.pub = pub; Object.assign(state, cart); localStorage.setItem('cartData', JSON.stringify(cart)); } }, actions: { [CART_LIST]({ commit }, busin) { commit(CART_LIST, busin) }, [CART_TIST]({ commit },address) { commit(CART_TIST,address) }, [CART_PUB]({ commit },pub) { commit(CART_PUB,pub) } } }<file_sep>/src/api/cofing.js export const commonParams = { list:'zfh-list', qq:1278372, adress:'Chain-min', alset:'Getren' } export const options = { param:'MCallback' } export const ERR_OR = 0;<file_sep>/README.md Related content Vue.js vue-router vue-resource vuex webpack express docker How to run # install dependencies npm install npm run dev # run server npm start TODO<file_sep>/src/components/index.js import header from './header' import tab from './tab' import footer from './footer' import wathMain from './wathMain' import main from './main' import searchBox from './searchBox' import list from './List' import item from './item' import topMain from './topMain' import loading from './loading' import scroll from './scroll' import suggest from './suggest' import songList from './songList' export default { header, tab, footer, wathMain, main, searchBox, list, item, topMain, loading, scroll, suggest, songList }
e175cbaff29e39ec68058b59f0f555fc1342f66e
[ "JavaScript", "Markdown" ]
7
JavaScript
zfh123/vue-vuex-Best
04eb946c22a98ce0689e583ad1476a5c8e1b9314
81b010bf5009981a95498fe65c23b9ab474123f4
refs/heads/master
<repo_name>popotarosan/e-navigator<file_sep>/app/models/interview.rb class Interview < ApplicationRecord belongs_to :user enum status: {approve:1, reject:2, hold:3} end<file_sep>/db/migrate/20190213014425_add_columns_to_users.rb class AddColumnsToUsers < ActiveRecord::Migration[5.1] def change add_column :users,:name,:string add_column :users,:birthday,:datetime add_column :users,:gender,:integer,default:0 add_column :users,:school_name,:string end end <file_sep>/app/controllers/interviews_controller.rb class InterviewsController < ApplicationController before_action :set_user, only: [:index,:new,:create,:update,:destroy] before_action :set_interview, only: [:edit,:update,:destroy] def index @interviews = @user.interviews end def new @interview = Interview.new end def create @interview = current_user.interviews.new(interview_params) if @interview.save flash[:success] = "保存に成功しました" redirect_to user_interviews_path(@user) else flash[:failure] = "保存に失敗しました" render 'new' end end def edit end #面接情報を更新する def update if @interview.update_attributes(interview_params) flash[:success] = "保存に成功しました" redirect_to user_interviews_path(@user) else flash[:failure] = "保存に失敗しました" render 'edit' end end #面接情報を削除する def destroy if @interview.destroy flash[:success] = "削除に成功しました" else flash[:failure] = "削除に失敗しました" end redirect_to user_interviews_path(@user) end private def interview_params params.require(:interview).permit(:scheduled_at) end def set_user @user = User.find(params[:user_id]) end def set_interview @interview = Interview.find(params[:id]) end end <file_sep>/app/controllers/users_controller.rb class UsersController < ApplicationController before_action :set_user, only: [:edit,:update] def update if @user.update_attributes(user_params) flash[:success] = "保存に成功しました" render 'edit' else flash[:failure] = "保存に失敗しました" render 'edit' end end def edit end private def set_user @user = User.find(params[:id]) end def user_params params.require(:user).permit(:name, :birthday, :gender, :school_name) end end
4d688520a6bf2c40f1e19b5ade6f6926f04c45d4
[ "Ruby" ]
4
Ruby
popotarosan/e-navigator
ef938c6995d7c56dfe601a942ccdcbfad14c7ccc
3d002dabf4813f9d09ad9872fffe79e87aa2fd6b
refs/heads/master
<file_sep>logging.level.org.springframework=INFO spring.jpa.hibernate.ddl-auto=none spring.jpa.show-sql=true spring.cache.cache-names=taskCount,userCount,tasksForToday spring.cache.caffeine.spec=maximumSize=200,expireAfterWrite=30s scheduler.task.cron=0 0/1 * * * ? management.endpoints.web.exposure.include=* <file_sep>package com.example.todo.service; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.example.todo.model.Notification; import com.example.todo.model.Task; import com.example.todo.model.User; import com.example.todo.repo.NotificationRepo; import com.example.todo.repo.UserRepo; import lombok.Data; @Service @Data public class NotificationService { @Autowired private NotificationRepo notificationRepo; @Autowired UserRepo userRepo; public Iterable<Notification> getNotifications() { return notificationRepo.findAll(); } public Optional<Notification> getNotification(Integer notificationId) { return notificationRepo.findById(notificationId); } public Notification saveNotification(Notification notification) { return notificationRepo.save(notification); } public void deleteNotification(Notification notification) { notificationRepo.delete(notification); } public List<Notification> notificationByUserId(Integer userId) { Optional optional = userRepo.findById(userId); User user = (User) optional.get(); return notificationRepo.findByUser(user); } } <file_sep>package com.example.todo.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.example.todo.exceptionhandlers.NotFoundException; import com.example.todo.model.Notification; import com.example.todo.model.Task; import com.example.todo.model.User; import com.example.todo.service.CacheService; import com.example.todo.service.NotificationService; import com.example.todo.service.TaskService; import com.example.todo.service.UserService; import lombok.Data; import lombok.extern.slf4j.Slf4j; @RestController @Data @Slf4j public class TodoController { private Map<Integer, Task> tasksMap = new HashMap<Integer, Task>(); @Autowired private UserService userService; @Autowired private TaskService taskService; @Autowired private NotificationService notificationService; @Autowired private CacheService cacheService; @ResponseStatus(HttpStatus.OK) @GetMapping("/users") public Iterable<User> getUsers() { return userService.getUsers(); } @ResponseStatus(HttpStatus.OK) @GetMapping("/user/{userId}") public User getUsers(@PathVariable("userId") Integer userId) { return userService.getUser(userId).orElseThrow(() -> new NotFoundException("User could not be found. userId = " + userId)); } @ResponseStatus(HttpStatus.CREATED) @PostMapping("/user") public User createUser(@Valid @RequestBody User user) { return userService.saveUser(user); } @ResponseStatus(HttpStatus.NO_CONTENT) @DeleteMapping("/user/{userId}") public void deleteUser(@PathVariable("userId") Integer userId) { userService.getUser(userId).map(u -> { userService.deleteUser(u); return 0; }).orElseThrow(() -> new NotFoundException("user could not be found. userId = " + userId)); } @ResponseStatus(HttpStatus.OK) @GetMapping("/tasks") public Iterable<Task> getAllTasks() { Iterable<Task> tasks = taskService.getTasks(); return tasks; } @ResponseStatus(HttpStatus.OK) @GetMapping(value = "/task/{taskId}") public Task getTask(@PathVariable("taskId") Integer taskId) { return taskService.getTask(taskId).orElseThrow(() -> new NotFoundException("task could not be found. taskId = " + taskId)); } @ResponseStatus(HttpStatus.CREATED) @PostMapping(value = "/user/{userId}/task") public Task createTaskByUserId(@PathVariable("userId") Integer userId, @Valid @RequestBody Task task) { return userService.getUser(userId).map(u -> { log.info("taskName={}",task.getTaskName()); task.setUser(u); taskService.saveTask(task); return task; }).orElseThrow(() -> new NotFoundException("user could not be found. userId = " + userId)); } @ResponseStatus(HttpStatus.ACCEPTED) @PutMapping(value = "/task/{taskId}") public void updateTask(@PathVariable("taskId") Integer taskId, @Valid @RequestBody Task updateTask) { taskService.getTask(taskId).map(t -> { updateTask.setId(t.getId()); taskService.saveTask(updateTask); return updateTask; }).orElseThrow(() -> new NotFoundException("task could not be found. taskId = " + taskId)); } @ResponseStatus(HttpStatus.NO_CONTENT) @DeleteMapping(value = "/task/{taskId}") public void deleteTask(@PathVariable("taskId") Integer taskId) { taskService.getTask(taskId).map(t -> { taskService.deleteTask(t); return 0; }).orElseThrow(() -> new NotFoundException("task could not be found. taskId = " + taskId)); } @ResponseStatus(HttpStatus.OK) @GetMapping("/user/{userId}/tasks") public List<Task> getTaskByUserId(@PathVariable("userId") Integer userId) { return taskService.taskByUserId(userId); } @ResponseStatus(HttpStatus.CREATED) @PostMapping("/user/{userId}/notification") public Notification createNotification(@Valid @PathVariable("userId") Integer userId, @RequestBody Notification notification) { return userService.getUser(userId).map(u -> { notification.setUser(u); notificationService.saveNotification(notification); return notification; }).orElseThrow(() -> new NotFoundException("user could not be found. userId = " + userId)); } @ResponseStatus(HttpStatus.OK) @GetMapping("/notifications") public Iterable<Notification> getNotification() { return notificationService.getNotifications(); } @ResponseStatus(HttpStatus.OK) @GetMapping("/user/{userId}/notification") public List<Notification> getNotification(@PathVariable("userId") Integer userId) { return notificationService.notificationByUserId(userId); } @ResponseStatus(HttpStatus.CREATED) @PostMapping("/tasks/poc") public List<Task> createPOCTask() { List<Task> tasks = taskService.createPocTasks(); return tasks; } @ResponseStatus(HttpStatus.OK) @GetMapping("/tasks/today") public List<Task> getTasksForToday() { return cacheService.getTasksForToday(); } } <file_sep>package com.example.todo.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import com.example.todo.model.Task; import com.example.todo.repo.NotificationRepo; import com.example.todo.repo.TaskRepo; import com.example.todo.repo.UserRepo; import lombok.Data; import lombok.extern.slf4j.Slf4j; @Slf4j @Data @Service public class CacheService { @Autowired TaskRepo taskRepo; @Autowired UserRepo userRepo; @Autowired NotificationRepo notificationRepo; @Cacheable("taskCount") public long getTaskCount() { log.info("Getting task count"); return taskRepo.count(); } @Cacheable("userCount") public long getUsersCount() { log.info("Getting user count"); return userRepo.count(); } @Cacheable("tasksForToday") public List<Task> getTasksForToday() { log.info("Getting tasks for today count"); return taskRepo.getTasksForToday(); } } <file_sep># TODO Application This application is designed by me to showcase Spring boot technologies. This is a work in progress. I hope to highlight many spring modules with this project including Spring Web, JPA, Caching, Security and Validation. My goal is to develop this as a cloud native application. The application is a Task Management app powered by REST services. Currently it has the following features: - - Spring REST Controllers. They return 200 for GET calls, 201 for POST, 202 (ACCEPTED) for PUT and 204 (NO CONTENT) for delete calls - Exception Controller Advice to handle errors. A HTTP 404 code is returned if the record could not be found - Spring Authentication. Currently it has an in memory authentication. Future TODO is to do JDBC authentication. - Spring JPA Repo is used to interact with the database. Future TODO is to extend PagingAndSortingRepository. - Spring Actuator. We can ping the /health and the /info endpoints, /metrics and /logger endpoints. These are very useful for metrics and managing the health of the application. - Spring Caching which shows the cached stats data - Spring Scheduled which has the capability to run every minute. Future TODO is to send SMS messages via Twilio Integration - Liquibase is used for database table creation. Developers have full control over their database, say goodbye to DDL sql scripts. - Authenticate user and return 401 code if the user is not authenticated - Unit Tests have been written using MockitoJunitRunner and Spring Test Controller - Postman Calls with Tests have been built. These tests have been executed using POSTMAN Runner. A screenshot is given below Follows many of the 12 Factor App (https://12factor.net/) guiding principles for Cloud Native Development. 1. Codebase in github and heroku. All deploys come out of this codebase. 2. All dependencies are isolated into property files. Example is the JDBC_DATABASE_URL to set the application database url. 3. All configuration like passwords are set outside the repo. It was tested using Heroku's CLI config:set command. 4. Backing services as resources: Liquibase is used to configure the database. 5. Build, Release and Run are all separated. Tested with Heroku. 6. The app is a stateless process. 7. Port Binding is implemented. Please look at the Procfile for how this was achieved for Heroku. 9. Disposability: Part of Spring Boot, gracefully shuts down 10. Dev/Prod Parity: The artifact is the same between dev and prod. The same jar file can be moved between environments. 11. Logs as event streams. The output logs are written to the console and not to a file. Tested this by using Heroku CLI logs command. 12. Admin Processes: N/A. No admin processes need to be run. ![Alt text](Todo_Test_run.PNG?raw=true "Postman REST calls with tests") <file_sep>package com.example.todo.service; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.example.todo.model.Task; import com.example.todo.model.User; import com.example.todo.repo.UserRepo; import lombok.Data; @Service @Data public class UserService { @Autowired UserRepo userRepo; public Iterable<User> getUsers() { return userRepo.findAll(); } public Optional<User> getUser(Integer userId) { return userRepo.findById(userId); } public User saveUser(User user) { return userRepo.save(user); } public void deleteUser(User user) { userRepo.delete(user); } } <file_sep>package com.example.todo.component; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.DependsOn; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import com.example.todo.model.Task; import com.example.todo.service.TaskService; import lombok.extern.slf4j.Slf4j; @Slf4j @Component public class ScheduleTask { @Autowired TaskService taskService; @Scheduled(cron = "${scheduler.task.cron:0 0/1 * * * ?}") public void sendNotification() { List<Task> tasks = taskService.getTasksForToday(); log.info("SendNotification: notification tasks={}", tasks); } } <file_sep>package com.example.todo.repo; import java.util.List; import org.springframework.data.repository.CrudRepository; import com.example.todo.model.Notification; import com.example.todo.model.User; public interface NotificationRepo extends CrudRepository<Notification, Integer> { public List<Notification> findByUser(User user); } <file_sep>spring.datasource.driver-class-name=org.postgresql.Driver spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL9Dialect spring.datasource.url=${JDBC_DATABASE_URL} spring.datasource.username=${JDBC_DATABASE_USERNAME} spring.datasource.password=${<PASSWORD>_DATABASE_PASSWORD}
2d8602db0ffd5aa923b3eae792f4283291fd8e6d
[ "Markdown", "Java", "INI" ]
9
INI
jiniswamy/taskmanagement
202e043aa7de75d743683e6a8b5989d3cee326df
a699560d7019edae16ae6427cfff8b645bcb3edd
refs/heads/master
<repo_name>larry2967/scrapy_news<file_sep>/info-scraper-master/task.sh #!/bin/bash . /home/lala/project/env/bin/activate python3 /home/lala/project/info-scraper/scraper/manager.py<file_sep>/info-scraper-master/scraper/crawl_sites/put_cna.py import redis import pymongo import ujson import argparse from utils import load_config from scutils.redis_queue import Base, RedisQueue, RedisPriorityQueue, RedisStack config = load_config() SETTINGS = config['services']['mycrawler']['environment'] def get_config(): urls = [ "https:/www.google.com/" ] for url in urls: yield { "media": "cna", "name": "cna", "scrapy_key": "cna:start_urls", "url": "https://tw.yahoo.com/?p=us", "priority": 1, "search": False, "enabled": True, "interval": 3600 * 2, "days_limit": 3600 * 24 , "url": url, "url_pattern":"https://www.cna.com.tw/cna2018api/api/WNewsList", "headers":{ 'authority': 'www.cna.com.tw', 'sec-ch-ua': '"Chromium";v="86", ""Not\\A;Brand";v="99", "Google Chrome";v="86"', 'accept': 'application/json, text/javascript, */*; q=0.01', 'x-requested-with': 'XMLHttpRequest', 'sec-ch-ua-mobile': '?0', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36', 'content-type': 'application/json', 'origin': 'https://www.cna.com.tw', 'sec-fetch-site': 'same-origin', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': 'https://www.cna.com.tw/list/asoc.aspx', 'accept-language': 'zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7', 'cookie': 'ASP.NET_SessionId=hhql1tqyberadyrrhgzggyuq; __auc=bb901549175f3d8f68ce4014d78; _ga=GA1.3.1566804492.1606113884; _gid=GA1.3.1749205380.1606113884; CnaCloseLanguage=1; __asc=90bf7ff8175f42c505ffc56cd9b; _gat_UA-6826760-1=1' }, 'page': '1', 'page_idx':'0' } def save_to_redis(media): redis_key = "{}:start_urls".format(media) password = SETTINGS['REDIS_PASSWORD'] r = redis.StrictRedis(password=password) q = RedisPriorityQueue(r, redis_key, encoding=ujson) for d in get_config(): q.push(d, d['priority']) def save_to_mongo(media): # m = pymongo.MongoClient(SETTINGS['MONGODB_SERVER'], SETTINGS['MONGODB_PORT']) m = pymongo.MongoClient('mongodb://%s:%s@%s'%(SETTINGS['MONGODB_USER'],SETTINGS['MONGODB_PASSWORD'],'localhost')) db = m['config'] collection = db['urls'] collection.delete_many({"media": media}) for config in get_config(): collection.insert_one(config) if __name__ == '__main__': media = 'ltn' my_parser = argparse.ArgumentParser() my_parser.add_argument('-a') args = my_parser.parse_args() if 'run' == args.a: save_to_redis(media) elif 'save' == args.a: save_to_mongo(media) else: print('Please give action call') <file_sep>/info-scraper-master/scraper/scraper/spiders/mirrormedia.py # -*- coding: utf-8 -*- import scrapy from bs4 import BeautifulSoup import traceback, sys from datetime import datetime, timedelta import re from dateutil.parser import parse as date_parser from scraper.items import NewsItem import json from .redis_spiders import RedisSpider import datetime # from scrapy_redis.spiders import RedisSpider # class LtnSpider(RedisSpider): class MirrormediaSpider(scrapy.Spider): name = "mirrormedia" def start_requests(self): if isinstance(self, RedisSpider): return search_day=[] now=datetime.datetime.now() today=now.strftime("%Y%m%d") search_day.append(today) day_before=2 for i in range(1,day_before+1): time_delta=datetime.timedelta(days=i) day_before=(now-time_delta).strftime("%Y%m%d") search_day.append(day_before) # url requests=[{ "url": 'https://www.myip.com/', "url_pattern":"https://www.mirrormedia.mg/story/{}soc{}/", "interval": 3600 * 2, "days_limit": 3600 * 24 * 2, "media": "mirrormedia", "name": "mirrormedia_keywords", "scrapy_key": "mirrormedia:start_urls", "day":search_day, "priority": 1, "search": False, "enabled": True, }] for request in requests: yield scrapy.Request(request['url'], meta=request, dont_filter=True, callback=self.parse) def parse(self, response): meta = response.meta url_pattern=meta['url_pattern'] for day in meta['day']: meta['url_pattern']=url_pattern url=url_pattern.format(day,'001') meta['url_pattern']=url yield scrapy.Request(url, meta=meta, dont_filter=True, callback=self.recursive_parse) def recursive_parse(self,response): # 回傳404停止尋找 if(response.status==404): return elif(response.status==200): # 繼續parse回傳200的url meta = response.meta url=meta['url_pattern'] yield scrapy.Request(url, meta=meta, dont_filter=True, callback=self.parse_article) # 回傳200繼續往下找 num=url[-4:-1] print(num) story_num=int(num) # 填成3位數:如'1'->'001' story_num=str(story_num+1).zfill(3) # 下一篇文章的url next_url=meta['url_pattern'][:-4]+story_num+'/' meta['url_pattern']=next_url yield scrapy.Request(next_url, meta=meta, dont_filter=True, callback=self.recursive_parse) def parse_article(self, response): meta = response.meta soup = BeautifulSoup(response.body, 'html.parser') metadata = {'category':'','image_url':[]} content, author, author_url,metadata['image_url'] = self.parse_content_author_image(soup) title=soup.find('title').get_text() metadata['category']=soup.find('meta',{'property':'article:section2'})['content'] item = NewsItem() item['url'] = response.url item['article_title'] = title item['author'] = author item['author_url'] = [author_url] item['comment'] = [] item['date'] = self.parse_datetime(soup) item['content'] = content item['metadata'] = metadata item['content_type'] = 0 item['media'] = 'mirrormedia' item['proto'] = 'MIRRORMEDIA_PARSE_ITEM' return item def parse_datetime(self,soup): date = soup.find('meta', {'property':'article:published_time'}) if date: return date['content'].replace('Z', '+0800') date = soup.find('span', {'class':'time'}) if date: return date_parser(date.text).strftime('%Y-%m-%dT%H:%M:%S+0800') date = soup.find('div', {'class':'article_header'}) if date: return datetime.datetime.strptime(date.find_all('span')[1].text, '%Y-%m-%d').strftime('%Y-%m-%dT%H:%M:%S+0800') date = soup.find('div', {'class':'writer'}) if date: return datetime.datetime.strptime(date.find_all('span')[1].text, '%Y-%m-%d %H:%M').strftime('%Y-%m-%dT%H:%M:%S+0800') def parse_title_metadata(self,soup): title = soup.find('title').text.replace(' - 自由時報電子報', '').replace(' 自由電子報', '') title_ = title.split('-') if not title_[-1]: del title_[-1] if len(title_) > 2: category = title_[-1] del title_[-1] ti = ''.join(x for x in title_) return ti.strip(), category.strip() elif len(title_) == 2: category = title_[1] ti = title_[0] return ti.strip(), category.strip() elif '3C科技' in title_[0]: category = '3C科技' ti = title_[0].replace('3C科技', '') return ti.strip(), category elif '玩咖Playing' in title_[0]: category = '玩咖Playing' ti = title_[0].replace('玩咖Playing', '') return ti.strip(), category else: category = '' ti = title_[0] return ti.strip(), category def parse_content_author_image(self,soup): # content content='' for text in soup.findAll('p')[2:-3]: content=content+text.get_text() # author # au = soup.find(property='dable:author')['content'] au=json.loads(soup.findAll('script', {'type': 'application/ld+json'})[1].get_text())['name'] au_url=json.loads(soup.findAll('script', {'type': 'application/ld+json'})[1].get_text())['url'] # image image_url = [] image_url.append(json.loads(soup.find('script', {'type': 'application/ld+json'}).get_text())['image']) return content, au, au_url, image_url <file_sep>/info-scraper-master/scraper/scraper/spiders/cna.py import scrapy import traceback, sys from dateutil.parser import parse as date_parser from scraper.items import NewsItem from .redis_spiders import RedisSpider from datetime import datetime, timedelta from bs4 import BeautifulSoup import json import re class CnaSpider(scrapy.Spider): name = "cna" def start_requests(self): if isinstance(self, RedisSpider): return requests = [{ "media": "cna", "name": "cna", "enabled": True, "days_limit": 3600 * 24 * 2, "interval": 3600 * 2, "url": "https://www.cna.com.tw/list/asoc.aspx", "url_pattern":"https://www.cna.com.tw/cna2018api/api/WNewsList", "headers":{ 'authority': 'www.cna.com.tw', 'sec-ch-ua': '"Chromium";v="86", ""Not\\A;Brand";v="99", "Google Chrome";v="86"', 'accept': 'application/json, text/javascript, */*; q=0.01', 'x-requested-with': 'XMLHttpRequest', 'sec-ch-ua-mobile': '?0', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36', 'content-type': 'application/json', 'origin': 'https://www.cna.com.tw', 'sec-fetch-site': 'same-origin', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', 'referer': 'https://www.cna.com.tw/list/asoc.aspx', 'accept-language': 'zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7', 'cookie': 'ASP.NET_SessionId=hhql1tqyberadyrrhgzggyuq; __auc=bb901549175f3d8f68ce4014d78; _ga=GA1.3.1566804492.1606113884; _gid=GA1.3.1749205380.1606113884; CnaCloseLanguage=1; __asc=90bf7ff8175f42c505ffc56cd9b; _gat_UA-6826760-1=1' }, 'page': '1', 'page_idx':'0' }] for request in requests: yield scrapy.Request(request['url'], meta=request, dont_filter=True, callback=self.parse) def parse(self, response): meta = response.meta print('-----parse-------') now = datetime.now() past = now - timedelta(seconds=meta['days_limit']) while True: payload = {'action':'0','category':'asoc','pagesize':'20','pageidx':'1'} yield scrapy.FormRequest( url = meta["url_pattern"], headers=meta['headers'], method='POST', body = json.dumps(payload), meta=meta, dont_filter=True, callback=self.parse_list) now = now - timedelta(seconds=3600 * 24) if now <= past: break def parse_list(self, response): meta = response.meta data = json.loads(response.body) print(data['Result']) #find the lastest_time in parse_list print(type(data)) _iteration = data print(_iteration['ResultData']['Items'][1]['CreateTime']) latest_datetime = max(_iteration['ResultData']['Items'][i]['CreateTime'] for i in range(len(_iteration['ResultData']['Items']))) print(latest_datetime) #change to datetime format latest_datetime = datetime.strptime(latest_datetime,'%Y/%m/%d %H:%M') if len(_iteration) == 0: raise scrapy.exceptions.CloseSpider('Response is Empty') category_name = _iteration['ResultData']['CategoryName'] print(category_name) meta.update({'category_name':category_name}) for i in range(len(_iteration['ResultData']['Items'])): url = _iteration['ResultData']['Items'][i]['PageUrl'] idx = str(i) meta.update({'page_idx':idx}) yield scrapy.Request(url, callback=self.parse_article, meta=meta) past = datetime.now() - timedelta(seconds=meta['days_limit']) if latest_datetime < past: return page = int(meta['page']) page = page + 1 meta.update({'page': str(page)}) payload=response.body print(payload) #next_page = re.search("\"pageidx\":\d+", payload).group(0)[10:12] #payload = re.sub("\"pageidx\":\d+","\"pageidx\":{}".format(int(next_page)+1),payload) payload = {'action':'0','category':'asoc','pagesize':'20','pageidx':page} yield scrapy.FormRequest( url = meta["url_pattern"], body = json.dumps(payload), method='POST', headers=meta['headers'], meta=meta, dont_filter=True, callback=self.parse_list) def parse_article(self, response): meta = response.meta idx = meta['page_idx'] category = meta['category_name'] soup = BeautifulSoup(response.body, 'html.parser') item = NewsItem() item['url'] = response.url item['author'] = self.parse_author(soup) item['article_title'] = self.parse_title(soup) item['author_url'] = [] item['content'] = self.parse_content(soup) item['comment'] = [] item['date'] = self.parse_datetime(soup) item['metadata'] = self.parse_metadata(soup,idx,category) item['content_type'] = 0 item['media'] = 'cna' item['proto'] = 'CNA_PARSE_ITEM' return item def parse_datetime(self,soup): datetime = soup.find('div',{'class':'updatetime'}).find('span').text return datetime def parse_title(self,soup): title = soup.find_all('h1')[0].text title = ' '.join(title.split()) return title def parse_author(self,soup): try: # try Columnist author = soup.find_all('p')[0].text author = author[6:9] return author except: print('no author ') def parse_content(self,soup): content = soup.find('div',{'class':'paragraph'}).text return content def parse_metadata(self,soup,idx,category): idx = int(idx) metadata = {'category':'', 'fb_like_count': '','image_url':[]} image_url = soup.find_all('div',{'class':'wrap'}) image_url = image_url[idx].find('img')['data-src'] metadata['image_url'] = image_url metadata['category_name'] = category return metadata <file_sep>/info-scraper-master/scraper/scraper/spiders/cna_keyword.py # -*- coding: utf-8 -*- import scrapy import traceback, sys from dateutil.parser import parse as date_parser from scraper.items import NewsItem from .redis_spiders import RedisSpider # from scrapy_redis.spiders import RedisSpider from datetime import datetime, timedelta from bs4 import BeautifulSoup import json import re # class Cna_keywordSpider(RedisSpider): class Cna_keywordSpider(scrapy.Spider): name = "cna_keyword" def start_requests(self): if isinstance(self, RedisSpider): return requests = [{ "media": "cna_keyword", "name": "cna_keyword", "enabled": True, "days_limit": 3600 * 24 * 2, "interval": 3600 * 2, "url":"https://www.cna.com.tw", "url_pattern": "https://www.cna.com.tw/search/hysearchws.aspx?q={}", "scrapy_key": "cna_keyword:start_urls", "keywords_list":['吸金','地下通匯','洗錢','賭博','販毒','走私','仿冒','犯罪集團','侵占','背信','內線交易','行賄','詐貸','詐欺','貪汙','逃稅'], "priority": 1 }] for request in requests: yield scrapy.Request(request['url'], meta=request, dont_filter=True, callback=self.parse) def parse(self, response): # self.logger.debug('parse function called on %s',response.url) # import logging # logger = logging.getLogger(__name__) # logger.error('parse function called on %s',response.url) meta = response.meta keywords_list = meta['keywords_list'] for i in range(len(keywords_list)): yield scrapy.Request(meta['url_pattern'].format(keywords_list[i]), meta = meta, dont_filter=True, callback = self.parse_list) def parse_list(self,response): meta = response.meta soup = BeautifulSoup(response.body, 'html.parser') soup = soup.find('ul',{'id':'jsMainList'}) for s in soup.find_all("li"): url = s.find('a').get('href') print('----') print(url) time = s.find('div',{'class':'date'}).text print('---------') print(time) time = datetime.strptime(time, '%Y/%m/%d %H:%M') past = datetime.now() - timedelta(seconds=meta['days_limit']) if (time < past): return yield scrapy.Request(url, meta=meta, callback=self.parse_article) def parse_article(self, response): soup = BeautifulSoup(response.body, 'html.parser') item = NewsItem() item['url'] = response.url item['author'] = self.parse_author(soup) item['article_title'] = self.parse_title(soup) item['author_url'] = [] item['comment'] = [] item['date'] = self.parse_datetime(soup) item['metadata'] = self.parse_metadata(soup) item['content'] = self.parse_content(soup) item['content_type'] = 0 item['media'] = 'cna' item['proto'] = 'CNA_PARSE_ITEM' return item def parse_datetime(self, soup): date = soup.find('div',{'class':'updatetime'}).text[5:] date = datetime.strptime( date , '%Y/%m/%d %H:%M') date = date.strftime('%Y-%m-%dT%H:%M:%S+0800') return date def parse_author(self, soup): author = soup.find('div',{'class':'paragraph'}).find_all('p')[0].text author = author[6:9] #print('------') #print(author) return author def parse_title(self, soup): title = soup.find('div',{'class':'centralContent'}) title = soup.find_all('h1')[0].get('span') #print('-----') #print(title) return title def parse_content(self, soup): # content = soup.find('head').find('meta',{'name':'description'})['content'] articlebody = soup.find('div',{'class':'paragraph'}).text content = articlebody return content def parse_metadata(self, soup): category = soup.find('div',{'class':'breadcrumb'}).find_all('a')[1].text try: image_url = soup.find('div',{'class':'wrap'}).find('img').get('src') except: image_url = '' metadata = {'category':category, 'image_url':image_url} return metadata <file_sep>/info-scraper-master/scraper/crawl_sites/put_ltn_keywords.py import redis import pymongo import ujson import argparse from utils import load_config from scutils.redis_queue import Base, RedisQueue, RedisPriorityQueue, RedisStack import datetime config = load_config() SETTINGS = config['services']['mycrawler']['environment'] def get_config(): urls = [ "https:/www.google.com/" ] for url in urls: yield {"url": urls, "url_pattern":"https://search.ltn.com.tw/list?keyword={}&type=all&sort=date&start_time={}&end_time={}&sort=date&type=all&page=1", "keywords_list": ['吸金','地下通匯','洗錢','賭博','販毒','走私','仿冒','犯罪集團','侵占','背信','內線交易','行賄','詐貸','詐欺','貪汙','逃稅'], "interval": 3600 * 2, "days_limit": 3600 * 24 * 2, "media": "ltn", "name": "ltn_keywords", "scrapy_key": "ltn_keywords:start_urls", "priority": 1, "search": False, "enabled": True, } def save_to_redis(media): redis_key = "{}:start_urls".format(media) password = SETTINGS['REDIS_PASSWORD'] r = redis.StrictRedis(password=password) q = RedisPriorityQueue(r, redis_key, encoding=ujson) for d in get_config(): q.push(d, d['priority']) def save_to_mongo(media): # m = pymongo.MongoClient(SETTINGS['MONGODB_SERVER'], SETTINGS['MONGODB_PORT']) m = pymongo.MongoClient('mongodb://%s:%s@%s'%(SETTINGS['MONGODB_USER'],SETTINGS['MONGODB_PASSWORD'],'localhost')) db = m['config'] collection = db['urls'] collection.delete_many({"media": media}) for config in get_config(): collection.insert_one(config) if __name__ == '__main__': media = 'ltn' my_parser = argparse.ArgumentParser() my_parser.add_argument('-a') args = my_parser.parse_args() if 'run' == args.a: save_to_redis(media) elif 'save' == args.a: save_to_mongo(media) else: print('Please give action call') <file_sep>/info-scraper-master/scraper/crawl_sites/utils.py import yaml def load_config(): with open('../docker-compose.yaml', 'r') as stream: config = yaml.safe_load(stream) return config<file_sep>/info-scraper-master/scraper/run.py from scrapy.utils.project import get_project_settings from scrapy.crawler import CrawlerProcess ''' 使用 CrawlerProcess 來達成同一個process運行多個spider get_project_settings() 方法會取得爬蟲專案中的 settings.py 檔案設定 啟動爬蟲前要提供這些設定給 Scrapy Engine p.s. 另一個進階選擇:CrawlerRunner ''' setting = get_project_settings() process = CrawlerProcess(setting) for spider_name in process.spider_loader.list(): print ("Running spider %s" % (spider_name)) process.crawl(spider_name) process.start()<file_sep>/info-scraper-master/scraper/scraper/spiders/ltn.py # -*- coding: utf-8 -*- import scrapy from bs4 import BeautifulSoup import traceback, sys from datetime import datetime, timedelta import re from dateutil.parser import parse as date_parser from scraper.items import NewsItem import json from .redis_spiders import RedisSpider # from scrapy_redis.spiders import RedisSpider # class LtnSpider(RedisSpider): class LtnSpider(scrapy.Spider): name = "ltn" def start_requests(self): if isinstance(self, RedisSpider): return requests = [ { "url": "https://www.myip.com/", "priority": 3, "search": False, "url_pattern": "https://news.ltn.com.tw/ajax/breakingnews/society/{}", "interval": 3600, "days_limit": 3600 * 24 }, { "url": "https://www.myip.com/", "priority": 3, "search": False, "url_pattern": "https://news.ltn.com.tw/ajax/breakingnews/politics/{}", "interval": 3600, "days_limit": 3600 * 24 }] for request in requests: yield scrapy.Request(request['url'], meta=request, dont_filter=True, callback=self.parse) # yield scrapy.Request(request['url'], # meta = request) def parse(self, response): meta = response.meta meta['page'] = 1 url = meta['url_pattern'].format(1) yield scrapy.http.Request(url, dont_filter=True, callback=self.parse_list, meta=meta ) def parse_list(self, response): content = response.body meta = response.meta page = meta['page'] search_page = meta['search'] if not search_page: data = json.loads(response.body) if isinstance(data['data'], list): _iteration = data['data'] latest_datetime = date_parser(_iteration[0]['time']) elif isinstance(data['data'], dict): _iteration = data['data'].values() latest_datetime = date_parser(list(_iteration)[0]['time']) if len(_iteration) == 0: return #raise scrapy.exceptions.CloseSpider('Response is Empty') for article in _iteration: url = article['url'] new_meta = article.copy() new_meta.update(meta) yield scrapy.Request(url, callback=self.parse_article, meta=new_meta) else: soup = BeautifulSoup(content, 'html.parser') latest_datetime = '' for link in soup.find_all('a', class_='tit'): url = link.get('href') yield scrapy.Request(url, callback=self.parse_article, dont_filter=True) past = datetime.now() - timedelta(seconds=meta['days_limit']) if latest_datetime < past: return page = page + 1 meta.update({'page': page}) url = meta['url_pattern'].format(page) yield scrapy.Request(url, callback=self.parse_list, dont_filter=True, meta=meta) def parse_article(self, response): meta = response.meta soup = BeautifulSoup(response.body, 'html.parser') metadata = {'category':'','image_url':[]} content, author, metadata['image_url'] = self.parse_content_author_image(soup) if 'title' in meta and 'tagText' in meta: title = meta['title'] metadata['category'] = meta.get('tagText', "") else: title, metadata['category'] = self.parse_title_metadata(soup) item = NewsItem() item['url'] = response.url item['article_title'] = title item['author'] = author item['author_url'] = [] item['comment'] = [] item['date'] = self.parse_datetime(soup) item['content'] = content item['metadata'] = metadata item['content_type'] = 0 item['media'] = 'ltn' item['proto'] = 'LTN_PARSE_ITEM' return item def parse_datetime(self,soup): date = soup.find('meta', {'name':'pubdate'}) if date: return date['content'].replace('Z', '+0800') date = soup.find('span', {'class':'time'}) if date: return date_parser(date.text).strftime('%Y-%m-%dT%H:%M:%S+0800') date = soup.find('div', {'class':'article_header'}) if date: return datetime.datetime.strptime(date.find_all('span')[1].text, '%Y-%m-%d').strftime('%Y-%m-%dT%H:%M:%S+0800') date = soup.find('div', {'class':'writer'}) if date: return datetime.datetime.strptime(date.find_all('span')[1].text, '%Y-%m-%d %H:%M').strftime('%Y-%m-%dT%H:%M:%S+0800') def parse_title_metadata(self,soup): title = soup.find('title').text.replace(' - 自由時報電子報', '').replace(' 自由電子報', '') title_ = title.split('-') if not title_[-1]: del title_[-1] if len(title_) > 2: category = title_[-1] del title_[-1] ti = ''.join(x for x in title_) return ti.strip(), category.strip() elif len(title_) == 2: category = title_[1] ti = title_[0] return ti.strip(), category.strip() elif '3C科技' in title_[0]: category = '3C科技' ti = title_[0].replace('3C科技', '') return ti.strip(), category elif '玩咖Playing' in title_[0]: category = '玩咖Playing' ti = title_[0].replace('玩咖Playing', '') return ti.strip(), category else: category = '' ti = title_[0] return ti.strip(), category def find_author(self,list_text): list_text = [x for x in list_text if x!='文'] tmp = [x for x in list_text if '記者' in x] if tmp: author = tmp[0].replace('記者', '').replace('攝影', '').strip() else: author = min(list_text, key=len) return author def parse_content_author_image(self,soup): content = soup.find('div',{'itemprop':'articleBody'}) # image image_url = [] for photo in content.find_all('div','photo boxTitle'): image_url.append(photo.find('img')['src']) # content for appE1121 in content.find_all('p','appE1121'): appE1121.clear() for photo in content.find_all('div','photo boxTitle'): photo.clear() for photo in content.find_all('span','ph_b ph_d1'): photo.clear() for tag in content.find_all('script'): tag.clear() content = ''.join(x.text for x in content.find_all('p') if x.text!='爆') content = ''.join(content.split()) #author au = '' reg = re.compile(r'([\D*/\D*]|〔\D*/\D*〕)', re.VERBOSE) author_reg = reg.findall(content) if author_reg: au = author_reg[0].split('/')[0].replace('〔', '').replace('[', '').replace('記者', '').replace('編譯', '') if not au: author = soup.find('div', {'class':'writer boxTitle'}) if author: au = author.find('a')['data-desc'] if not au: author = soup.find('p', {'class':'auther'}) if author: tmp = author.find('span').text.split('/') au = self.find_author(tmp) if not au: author = soup.find('p', {'class':'writer'}) if author: tmp = author.find('span').text.split('/') au = self.find_author(tmp) if not au: author = soup.find('div', {'class':'writer'}) if author: tmp = author.find('span').text.split('/') au = self.find_author(tmp) if not au: author = soup.find('div', {'class':'conbox_tit boxTitle'}) if author: au = author.find('a')['data-desc'] if not au: author = soup.find('div', {'class':'article_header'}) if author: tmp = author.find('span').text.split('/') au = self.find_author(tmp) if not au: try: author = soup.find('div', {'itemprop':'articleBody'}).find('p') except: author = '' if author: if '/' in author.text: tmp = author.text.split('/') au = self.find_author(tmp) if author.find('strong'): au = author.find('strong').text.split('◎')[1].replace('記者', '').replace('攝影', '').strip() if '■' in author.text: au = author.text.replace('■', '') if not au: try: author = soup.find('div', {'itemprop':'articleBody'}).find('span', {'class':'writer'}) except: author = '' if author: if '/' in author.text: tmp = author.text.split('/') au = self.find_author(tmp) if not au: try: author = soup.find('div', {'itemprop':'articleBody'}).find('h4') except: author = '' if author: if '/' in author.text: tmp = author.text.split('/') au = self.find_author(tmp) elif '◎' in author.text: au = author.text.replace('◎', '') return content, au, image_url<file_sep>/info-scraper-master/scraper/scraper/spiders/.ipynb_checkpoints/chinatimes_keywords-checkpoint.py # -*- coding: utf-8 -*- import scrapy import traceback, sys from dateutil.parser import parse as date_parser from scraper.items import NewsItem from .redis_spiders import RedisSpider # from scrapy_redis.spiders import RedisSpider from datetime import datetime, timedelta from bs4 import BeautifulSoup import json import re # class ChinatimesSpider(RedisSpider): class Chinatimes_keywordsSpider(scrapy.Spider): name = "chinatimes_keywords" def start_requests(self): if isinstance(self, RedisSpider): return # url requests=[{"media": "chinatimes", "name": "chinatimes_keywords", "enabled": True, "url_pattern":'https://www.chinatimes.com/search/{}?page=1&chdtv', "keywords_list":['吸金','地下通匯','洗錢','賭博','販毒','走私','仿冒','犯罪集團','侵占','背信','內線交易','行賄','詐貸','詐欺','貪汙','逃稅'], "days_limit": 3600 * 24 * 2, "interval": 3600 * 2, "url": 'https://www.myip.com/', "scrapy_key": "chinatimes_keywords:start_urls", "priority": 1}] for request in requests: yield scrapy.Request(request['url'], meta=request, dont_filter=True, callback=self.parse) def parse(self, response): meta = response.meta meta['page'] = 1 for keyword in meta['keywords_list']: url=meta['url_pattern'].format(keyword) yield scrapy.Request(url, meta=meta, dont_filter=True, callback=self.parse_list) def parse_list(self, response): # self.logger.debug('parse function called on %s',response.url) # import logging # logger = logging.getLogger(__name__) # logger.error('parse function called on %s',response.url) meta = response.meta soup = BeautifulSoup(response.body, 'html.parser') past = datetime.now() - timedelta(seconds=meta['days_limit']) link_date=[] for s in soup.findAll("div", class_="col"): link_date.append(datetime.strptime(s.find("time")['datetime'], '%Y-%m-%d %H:%M')) latest_datetime = link_date[-1] if(latest_datetime > past): url = s.find("h3", class_="title").find('a').get('href') yield response.follow(url, meta=meta, callback=self.parse_article) latest_datetime = max(link_date) past = datetime.now() - timedelta(seconds=meta['days_limit']) if latest_datetime < past: return current_page = re.search("page=(\d+)", response.url).group(1) next_page = re.sub("page=(\d+)", "page={}".format(int(current_page) + 1), response.url) yield scrapy.Request(next_page, dont_filter=True, meta=meta, callback=self.parse_list) def parse_article(self, response): soup = BeautifulSoup(response.body, 'html.parser') item = NewsItem() item['url'] = response.url item['author'] = self.parse_author(soup) item['article_title'] = self.parse_title(soup) item['author_url'] = [] item['comment'] = [] item['date'] = self.parse_datetime(soup) item['metadata'] = self.parse_metadata(soup) item['content'] = self.parse_content(soup) item['content_type'] = 0 item['media'] = 'chinatimes' item['proto'] = 'CHINATIMES_PARSE_ITEM' return item def parse_datetime(self, soup): date = soup.find('div','meta-info').find('time')['datetime'] date = datetime.strptime( date , '%Y-%m-%d %H:%M') date = date.strftime('%Y-%m-%dT%H:%M:%S+0800') return date def parse_author(self, soup): author = re.findall('\S',soup.find('div','author').text) author = ''.join([x for x in author ]) return author def parse_title(self, soup): title = soup.find('h1','article-title').text title = ' '.join(title.split()) return title def parse_content(self, soup): # content = soup.find('head').find('meta',{'name':'description'})['content'] articlebody = soup.find('div','article-body') for promote in articlebody.find_all('div','promote-word'): promote.clear() for hashtag in articlebody.find_all('div','article-hash-tag'): hashtag.clear() content = ''.join(articlebody.text.split()) return content def parse_metadata(self, soup): keywords = soup.find('div','article-hash-tag').find_all('span','hash-tag') keywords = [x.text.replace('#','') for x in keywords] category = soup.find('meta',{'property':'article:section'})['content'] image_url = soup.find('article','article-box').find_all('div','photo-container') image_url = [x.find('img')['src'] for x in image_url] metadata = {'tag': keywords, 'category':category, 'image_url':image_url} return metadata <file_sep>/info-scraper-master/scraper/scraper/proxyMiddleware.py from scrapy import signals from scrapy.downloadermiddlewares.httpproxy import HttpProxyMiddleware from collections import defaultdict import json import random import redis class RandomProxyMiddleware(object): def __init__(self, settings): self.proxies = defaultdict(list) host = settings.get('REDIS_HOST') port = settings.get('REDIS_PORT') redis_params = settings.get('REDIS_PARAMS', {}) password = redis_params.get('password', '<PASSWORD>') self.redis = redis.Redis (host, port, 0, password) @classmethod def from_crawler(cls, crawler): return cls(crawler.settings) def process_request(self, request, spider): if 'random_proxy' not in request.meta: return # Get the Proxy List in Redis proxies = self.redis.smembers('eng_proxies') if not proxies: proxies = self.redis.smembers('all_proxies') if not proxies: return proxies = list(proxies) proxy_index = random.randint(0, len(proxies) - 1) ip_port = proxies[proxy_index] print('random proxy {}'.format(ip_port)) request.meta['proxy'] = str(ip_port, 'utf-8')<file_sep>/info-scraper-master/README.md # info-scraper ## 架構簡述 以Scrapy-Redis當作主架構來做分散式爬取,將要爬取的網站url存到redis,讓每個子爬蟲到redis中領取url進行任務。 ## 爬取網站 - 聯合新聞網_要聞 - 中時電子報_社會 - 自由時報_社會 - Ettoday新聞雲_社會 - 蘋果日報_社會 ## 啟動爬蟲service (測試時,建議使用scrapy.Spider) ### 1. scrapy.Spider 從spider資料夾裡的各個爬蟲的程式碼中,start_requests function來讀取start_urls #### 啟動docker-compose: `docker-compose -f docker-compose-dev.yaml up` #### spider繼承物件 scrapy.Spider #### 執行某隻特定spider 需要在 ~/info-scraper-master/scraper 資料層底下 `scrapy crawl [spider-name]` ### 2. RedisSpider 從指定的redis列表,讀取start_urls #### 啟動docker-compose: `docker-compose -f docker-compose.yaml up` 若有更動程式碼,皆須重新build docker image,所以測試來說,不建議使用 #### spider繼承物件 RedisSpider #### 新增爬蟲任務config到mongodb 在 /crawl_sites 資料夾裡,有各個網站的config,可透過執行.py檔,將config塞到mongodb mongodb: `python3 crawl_sites/[檔案名稱] -a save` #### 將爬蟲任務config塞到redis 1.將特定網站的config塞到redis: `python3 crawl_sites/[檔案名稱] -a run` 2.將所有網站的config從mongoDB讀取並塞到redis `python3 manager.py` <file_sep>/info-scraper-master/scraper/manager.py #!/usr/bin/python3 import redis import pymongo import ujson import yaml from scutils.redis_queue import Base, RedisQueue, RedisPriorityQueue, RedisStack # get settings from docker-compose.yaml with open('../docker-compose.yaml', 'r') as stream: config = yaml.safe_load(stream) SETTINGS = config['services']['mycrawler']['environment'] # mongo connection # connection = pymongo.MongoClient(SETTINGS['MONGODB_SERVER'], SETTINGS['MONGODB_PORT']) connection = pymongo.MongoClient('mongodb://%s:%s@%s'%(SETTINGS['MONGODB_USER'],SETTINGS['MONGODB_PASSWORD'],'localhost')) db = connection['config'] collection = db['urls'] docs = collection.find({'enabled': True}) # redis connection password = SETTINGS['REDIS_<PASSWORD>'] r = redis.StrictRedis(password=<PASSWORD>) for doc in docs: # Command crawler by scrapy scrapy_key = doc.get('scrapy_key') if scrapy_key: print('doc:',doc) interval = doc.get('interval', 0) priority = doc.get('priority', 0) doc['_id'] = str(doc['_id']) q = RedisPriorityQueue(r, scrapy_key, encoding=ujson) q.push(doc, doc['priority'])<file_sep>/info-scraper-master/scraper/scraper/spiders/.ipynb_checkpoints/appledaily-checkpoint.py # -*- coding: utf-8 -*- import numpy as np import scrapy from itertools import chain from datetime import datetime, timedelta from bs4 import BeautifulSoup from scraper.items import NewsItem import re import json from .redis_spiders import RedisSpider # class AppledailySpider(RedisSpider): class AppledailySpider(scrapy.Spider): name = 'appledaily' def start_requests(self): if isinstance(self, RedisSpider): return request = { "url_pattern": 'https://tw.appledaily.com/pf/api/v3/content/fetch/query-feed?query=%7B%22feedOffset%22%3A0%2C%22feedQuery%22%3A%22taxonomy.primary_section._id%3A%5C%22%2Frealtime%2Flocal%5C%22%2BAND%2Btype%3Astory%2BAND%2Bpublish_date%3A%5Bnow-48h%2Fh%2BTO%2Bnow%5D%22%2C%22feedSize%22%3A%22100%22%2C%22sort%22%3A%22display_date%3Adesc%22%7D&d={}&_website=tw-appledaily', "url": 'https://tw.appledaily.com/realtime/local/', "priority": 1, "interval": 3600 * 2, "days_limit": 3600 * 24 * 2, 'scrapy_key': 'appledaily:start_urls', 'media': 'appledaily', 'name': 'appledaily', 'enabled': True, } yield scrapy.Request(request['url'], dont_filter=True, meta = request) def parse(self, response): meta = response.meta soup = BeautifulSoup(response.body, 'html.parser') fusion_engine_script = soup.find('script',{'id':'fusion-engine-script'}) d = fusion_engine_script['src'].split('?d=')[-1] yield scrapy.Request(meta['url_pattern'].format(d), dont_filter=True, callback=self.parse_article) def parse_article(self, response): result = json.loads(response.body) news_lists = result['content_elements'] for news_list in news_lists: if 'video' in news_list['website_url']: continue content = self.parse_content(news_list['content_elements']) item = NewsItem() item['url'] = 'https://tw.appledaily.com' + news_list['website_url'] item['article_title'] = ' '.join(news_list['headlines']['basic'].split()) item['metadata'] = self.parse_metadata(news_list['taxonomy'],news_list['additional_properties'],news_list['content_elements']) item['date'] = self.parse_datetime(news_list['created_date']) item['content'] = content item['author'] = self.parse_author(content) item['author_url'] = [] item['comment'] = [] item['media'] = 'appledaily' item['content_type'] = 0 item['proto'] = 'APPLEDAILY_PARSE_ITEM' yield item def parse_datetime(self,created_date): date = datetime.strptime(created_date.split('.')[0] , '%Y-%m-%dT%H:%M:%S') date = date + timedelta(hours=8) return date.strftime('%Y-%m-%dT%H:%M:%S+0800') def parse_content(self,content_elements): content_html = '' for cont in content_elements[:2]: if cont['type']=='text' or cont['type']=='raw_html': content_html += cont['content'] soup = BeautifulSoup(content_html,'html.parser') content = soup.text return ''.join(content.split()) def parse_metadata(self,taxonomy,promo_items,content_elements): image_url = [] if 'basic' in promo_items.keys(): if 'url' in promo_items['basic'].keys(): image_url.append(promo_items['basic']['url']) for cont in content_elements[2:]: if 'additional_properties' in cont.keys(): if 'originalUrl' in cont['additional_properties'].keys(): image_url.append(cont['additional_properties']['originalUrl']) metadata = { 'tag': [tag['text'] for tag in taxonomy['tags']], 'category': taxonomy['primary_section']['name'], 'image_url':image_url } return metadata def parse_author(self,content): content = content.replace('(','(') content = content.replace(')',')') end_indx = [] for m in re.finditer('報導)', content): end_indx.append(m.start()) start_indx = [] for m in re.finditer('(', content): start_indx.append(m.end()) if len(end_indx)!=1 or len(start_indx)==0: author = '' else: find_close = end_indx[0] - np.array(start_indx) start_indx = start_indx[ np.where( find_close == min(find_close[find_close>0]) )[0][0] ] author = re.split('/',content[start_indx:end_indx[0]])[0] return author <file_sep>/info-scraper-master/scraper/scraper/spiders/.ipynb_checkpoints/udn-checkpoint.py # -*- coding: utf-8 -*- import scrapy import traceback, sys from dateutil.parser import parse as date_parser from scraper.items import NewsItem from .redis_spiders import RedisSpider # from scrapy_redis.spiders import RedisSpider from datetime import datetime, timedelta from bs4 import BeautifulSoup import requests import json import re import urllib # class UDNSpider(RedisSpider): class UDNSpider(scrapy.Spider): name = "udn" def start_requests(self): if isinstance(self, RedisSpider): return requests = [{ "media": "udn", "name": "udn", "enabled": True, "days_limit": 3600 * 24, "interval": 3600, "url": "https://udn.com/api/more?page=1&id=&channelId=1&cate_id=1&type=breaknews&totalRecNo=287", "scrapy_key": "udn:start_urls", "priority": 1, }] for request in requests: yield scrapy.Request(request['url'], meta=request, dont_filter=True, callback=self.parse) def parse(self, response): meta = response.meta body = json.loads(response.body) # no more news if body['end'] == True: return links_date = [] for url in body['lists']: str_date = url['time']['date'] links_date.append(datetime.strptime(str_date, '%Y-%m-%d %H:%M')) meta.update({ 'title': url['title'], 'datetime': str_date, 'view_count': url['view'], 'image_url': url['url'] }) yield response.follow(url['titleLink'].split('?')[0], meta=meta, callback=self.parse_article) latest_datetime = max(links_date) past = datetime.now() - timedelta(seconds=meta['days_limit']) if latest_datetime < past: return current_page = re.search("page=(\d+)", response.url).group(1) next_page = re.sub("page=(\d+)", "page={}".format(int(current_page) + 1), response.url) yield scrapy.Request(next_page, dont_filter=True, meta=meta, callback=self.parse) def parse_article(self, response): meta = response.meta soup = BeautifulSoup(response.body, 'html.parser') if 'opinion.udn.com' in response.url: content = self.parse_opinion_content(soup) author = self.parse_opinion_author(soup) else: content = self.parse_content(soup) author = self.parse_author(soup) item = NewsItem() item['url'] = response.url item['date'] = self.parse_datetime(meta['datetime']) item['content'] = content item['author'] = author item['article_title'] = meta['title'] #self.parse_title(soup) item['author_url'] = [] item['comment'] = [] item['metadata'] = self.parse_metadata(soup,meta['view_count'],meta['image_url']) item['content_type'] = 0 item['media'] = 'udn' item['proto'] = 'UDN_PARSE_ITEM' yield item def parse_datetime(self, date): date = datetime.strptime(date, '%Y-%m-%d %H:%M').strftime('%Y-%m-%dT%H:%M:%S+0800') return date def parse_title(self, soup): return soup.find('meta', {'property':'og:title'})['content'].split(' | ')[0] def parse_content(self, soup): article = soup.find('article', class_='article-content') # filter java script for tag in article.find_all('script'): tag.clear() # filter paywall-content for tag in article.find_all('div','paywall-content'): tag.clear() content = ''.join([ent.text for ent in article.find_all('p')]) content = ''.join(content.split()) if '【相關閱讀】' in content: content = content.split('【相關閱讀】')[0] return content def parse_opinion_content(self, soup): for tag in soup.find_all('style', {'type': 'text/css'}): tag.clear() return ''.join([ent.text for ent in soup.find_all('p')[:-1]]).replace('\n', '') def parse_author(self, soup): if soup.find('div',{'id':'story_author'}) != None: author = soup.find('div',{'id':'story_author'}) author = author.find('h2',{'id':'story_author_name'}).text elif soup.find('span','article-content__author') != None: if soup.find('span','article-content__author').find('a') != None: author = soup.find('span','article-content__author').find('a').text else: author = soup.find('span','article-content__author').text else: author = '' author = ''.join(author.split()) return author def parse_opinion_author(self, soup): author = soup.find('div', class_='story_bady_info_author').find('a').text return author def parse_metadata(self, soup, view_count, image_url,fb_like_count_html=None): metadata = {'tag':[], 'category':'','view_count':view_count, 'image_url':[],'fb_like_count':''} try: metadata['tag'] = soup.find('meta', {'name':'news_keywords'})['content'].split(',') except: pass category = soup.find_all('a','breadcrumb-items') if len(category) == 3: metadata['category'] = category[1].text else: metadata['category'] = soup.find('meta', {'name': 'application-name'})['content'] if image_url!='': metadata['image_url'].append(image_url) return metadata <file_sep>/info-scraper-master/scraper/scraper/items.py # -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html from scrapy import Item, Field class NewsItem(Item): url = Field() article_title = Field() author = Field() author_url = Field() comment = Field() date = Field() content = Field() metadata = Field() media = Field() content_type = Field() proto = Field() proto_id = Field() <file_sep>/info-scraper-master/Dockerfile FROM ubuntu:bionic RUN apt-get update && apt-get install -y \ python3 python3-pip WORKDIR /app COPY ./scraper /app RUN pip3 install --no-cache-dir -r requirements.txt CMD [ "python3", "run.py" ]<file_sep>/info-scraper-master/scraper/scraper/pipelines.py # -*- coding: utf-8 -*- from scrapy.utils.project import get_project_settings from dateutil.parser import parse as parse_time from elasticsearch import Elasticsearch import mysql.connector from mysql.connector import errorcode import pymongo import psycopg2 import hashlib import pytz import datetime import logging import json import yaml # env setted by docker-compose.yaml SETTINGS = get_project_settings() MONGO_USERNAME = SETTINGS['MONGODB_USER'] MONGO_PASSWORD = SETTINGS['MONGODB_PASSWORD'] MONGODB_SERVER = SETTINGS['MONGODB_SERVER'] # env setted by docker-compose-dev.yaml if MONGO_USERNAME==None or MONGO_PASSWORD==None: # get settings from docker-compose-dev.yaml with open('../docker-compose-dev.yaml', 'r') as stream: config = yaml.safe_load(stream) MONGO_SETTINGS = config['services']['mongo']['environment'] MONGO_USERNAME = MONGO_SETTINGS[0].split('=')[-1] MONGO_PASSWORD = MONGO_SETTINGS[1].split('=')[-1] MONGODB_SERVER = "localhost" logger = logging.getLogger(__name__) # Define your item pipelines here class SaveToMongoPipeline: ''' pipeline that save data to mongodb ''' def __init__(self): connection = pymongo.MongoClient('mongodb://%s:%s@%s'%(MONGO_USERNAME,MONGO_PASSWORD,MONGODB_SERVER)) self.db = connection[SETTINGS['MONGODB_DB']] self.collection = self.db[SETTINGS['MONGODB_DATA_COLLECTION']] def process_item(self, item, spider): data = self.collection.find_one({'url': item['doc_url']}) if data is None: res = self.collection.insert_one(dict(item)) _id = res.inserted_id else: _id = data['_id'] item['proto_id'] = str(_id) return item class SaveToSqlDBPipeline: ''' pipeline that save data to SqlDB ''' def __init__(self): self.connection = self.get_conn() self.columns = ['raw_id', 'create_date', 'post_date', 'media', 'category', 'author', 'title', 'content', 'doc_url', 'image_url'] self.table_name = SETTINGS['SQLDB_DATA_TABLE'] def get_conn(self): conn = psycopg2.connect(user=SETTINGS['SQLDB_USERNAME'], password=SETTINGS['<PASSWORD>'], host=SETTINGS['SQLDB_SERVER'], port=SETTINGS['SQLDB_PORT'], database=SETTINGS['SQLDB_DB']) return conn def process_item(self, item, spider): # check db is connected or not try: cur = self.connection.cursor() cur.execute('SELECT 1') cur.close() except: self.connection = self.get_conn() raw_id = item['raw_id'] self.cur = self.connection.cursor() query = f"select * from {self.table_name} where raw_id='{raw_id}';" self.cur.execute(query) data_len = self.cur.rowcount if data_len ==0: columns_str = ','.join(self.columns) placeholders_str = ','.join(['%s'] * len(self.columns)) sql_insert = f'INSERT INTO {self.table_name} ({columns_str}) VALUES ({placeholders_str})' records = (item['raw_id'], item['create_date'], item['post_date'], item['media'],\ item['category'], item['author'], item['title'], item['content'],\ item['doc_url'], item['image_url']) self.cur.execute(sql_insert, records) else: update_columns = list(filter(lambda x: x!='create_date',self.columns)) columns_str = ','.join(map(lambda x: x + '=(%s)', update_columns)) sql_update = f"UPDATE {self.table_name} SET {columns_str} WHERE raw_id='{raw_id}'" records = (item['raw_id'], item['post_date'], item['media'], item['category'],\ item['author'], item['title'], item['content'], item['doc_url'],\ item['image_url']) self.cur.execute(sql_update, records) self.connection.commit() self.cur.close() return item class SaveToElasticsearchPipeline: def __init__(self): es_timeout = SETTINGS['ELASTICSEARCH_TIMEOUT'] es_servers = SETTINGS['ELASTICSEARCH_SERVERS'] es_servers = es_servers if isinstance(es_servers, list) else [es_servers] es_settings = dict() es_settings['hosts'] = es_servers es_settings['timeout'] = es_timeout if SETTINGS['ELASTICSEARCH_USERNAME'] and SETTINGS['ELASTICSEARCH_PASSWORD']: es_settings['http_auth'] = (SETTINGS['ELASTICSEARCH_USERNAME'], SETTINGS['ELASTICSEARCH_PASSWORD']) self.index = SETTINGS['ELASTICSEARCH_INDEX'] self.type = SETTINGS['ELASTICSEARCH_TYPE'] self.es = Elasticsearch(**es_settings) def upsert(self, _id, data): doc = dict({ 'doc_as_upsert': True, 'doc': data }) return self.es.update( index=self.index, doc_type=self.type, id=_id, body=doc) def process_item(self, item, spider): print('-' * 100) print('-' * 100) print('-' * 100) print('save to ES') print('-' * 100) print('-' * 100) print('-' * 100) _id = item['raw_id'] self.upsert(_id, item) return item class TransformDataPipeline: def __init__(self): self.media_dict = { 'udn' : '聯合新聞網', 'chinatimes' : '中時電子報', 'ltn' : '自由時報', 'ettoday' : 'ETtoday新聞雲', 'appledaily' : '蘋果日報', } def transfer_number(self, data): if type(data) == str: if not data.isdigit(): data = '0' data = int(data) return data def hash_code(self, data): str_data = json.dumps({ 'date': data['date'], 'url': data['url'], 'title': data['article_title'] }, sort_keys=True, indent=2) return hashlib.md5(str_data.encode("utf-8")).hexdigest() def process_item(self, item, spider): # comment_body = [] docurl = item.get('url', '') time = item.get('date', '') tw = pytz.timezone('Asia/Taipei') create_date = datetime.datetime.strftime(datetime.datetime.now(tw), '%Y-%m-%dT%H:%M:%S') metadata = item.get('metadata', {}) fb_like_count = self.transfer_number(metadata.get('fb_like_count', '')) fb_share_count = self.transfer_number(metadata.get('fb_share_count', '')) line_share_count = self.transfer_number(metadata.get('line_share_count', '')) like_count = self.transfer_number(metadata.get('like_count', '')) share_count = self.transfer_number(metadata.get('fb_like_count', '')) reply_count = self.transfer_number(metadata.get('reply_count', '')) thanks_count = self.transfer_number(metadata.get('thanks_count', '')) agree_count = self.transfer_number(metadata.get('agree_count', '')) disagree_count = self.transfer_number(metadata.get('disagree_count', '')) view_count = self.transfer_number(metadata.get('view_count', '')) category = metadata.get('category','') news_source = metadata.get('news_source','') image_url = metadata.get('image_url','') all_comments = item.get('comment', []) if reply_count == 0: reply_count = len(all_comments) if view_count != 0: brocount = view_count else: brocount = fb_like_count + fb_share_count + line_share_count + like_count + \ share_count + reply_count + thanks_count + agree_count + disagree_count raw_media = item.get('media', '') media = self.media_dict.get(raw_media, raw_media) datafrom = 0 # datafrom: type of website. (e.g. datafrom=0:news datafrom=2:forum) if time is None: time = '' if isinstance(time, str) and time != '': time_obj = parse_time(time, ignoretz=True) timestamp = time_obj.timestamp() post_date = datetime.datetime.fromtimestamp(timestamp) post_date = datetime.datetime.strftime(post_date, '%Y-%m-%dT%H:%M:%S') elif isinstance(time, datetime.datetime): post_date = datetime.datetime.strftime(time, '%Y-%m-%dT%H:%M:%S') else: post_date = create_date raw_id = self.hash_code(item) return dict({ "raw_id": raw_id, "author": item.get('author', ''), "author_url": item.get('author_url', ''), "create_date": create_date, # "docid": raw_id, # "MainID": raw_id, "category": category, "news_source": news_source, "content": item['content'], "media": media, "spider_name": item.get("media", ''), # "SourceType": 0, "doc_url": docurl, "post_date": post_date, "content_type": item['content_type'], #0:main 1:comment # "candidate": '', # "mediatype": datafrom, # "data_from": datafrom, #0:news 1:forum 2:... "title": item.get('article_title', ''), "browse_count": brocount, "reply_count": int(reply_count), "image_url": image_url, # "datatype": 0, # "posscore": 0, # "negscore": 0, # "evaluation": -1, # "candidates": [] })<file_sep>/info-scraper-master/scraper/scraper/spiders/ettoday.py # -*- coding: utf-8 -*- import scrapy import traceback, sys from dateutil.parser import parse as date_parser from scraper.items import NewsItem from .redis_spiders import RedisSpider from datetime import datetime, timedelta from bs4 import BeautifulSoup import json import re # class EttodaySpider(RedisSpider): class EttodaySpider(scrapy.Spider): name = "ettoday" def start_requests(self): if isinstance(self, RedisSpider): return requests = [{ "media": "ettoday", "name": "ettoday", "enabled": True, "days_limit": 3600 * 24 * 2, "interval": 3600 * 2, "url": "https://www.ettoday.net/", "tFile_format": "{date}-6.xml", "tPage":str(3), "tOt":str(6), "offset":1, "scrapy_key": "ettoday:start_urls", "priority": 1 }] for request in requests: yield scrapy.Request(request['url'], meta=request, dont_filter=True, callback=self.parse) def parse(self, response): meta = response.meta now = datetime.now() past = now - timedelta(seconds=meta['days_limit']) while True: meta['tFile'] = meta['tFile_format'].format(date=now.strftime('%Y%m%d')) meta['date'] = now.replace(hour=0, minute=0, second=0, microsecond=0) data = { 'tFile': meta['tFile'], 'tPage': meta['tPage'], 'tOt': meta['tOt'], 'offset': str(meta['offset']), } yield scrapy.FormRequest( url = "https://www.ettoday.net/show_roll.php", formdata= data, method='POST', meta=meta, dont_filter=True, callback=self.parse_list) now = now - timedelta(seconds=3600 * 24) if now <= past: break def parse_list(self, response): meta = response.meta soup = BeautifulSoup(response.body, 'lxml') # no more news_list if not soup.find('h3'): return posts = soup.find_all('h3') for s in posts: yield response.follow(s.find('a')['href'], meta=meta, callback=self.parse_article) # if the time < 00:00, stop crawl the date last_datetime = datetime.strptime(posts[-1].find('span','date').text, '%Y/%m/%d %H:%M') if meta['date'] > last_datetime: return # scroll meta['offset'] += 1 data = { 'tFile': meta['tFile'], 'tPage': meta['tPage'], 'tOt': meta['tOt'], 'offset': str(meta['offset']), } yield scrapy.FormRequest( url = "https://www.ettoday.net/show_roll.php", formdata= data, method='POST', meta=meta, dont_filter=True, callback=self.parse_list) def parse_article(self, response): soup = BeautifulSoup(response.body, 'html.parser') item = NewsItem() item['url'] = response.url item['author'] = self.parse_author(soup) item['article_title'] = self.parse_title(soup) item['author_url'] = [] item['content'] = self.parse_content(soup) item['comment'] = [] item['date'] = self.parse_datetime(soup) item['metadata'] = self.parse_metadata(soup) item['content_type'] = 0 item['media'] = 'ettoday' item['proto'] = 'ETTODAY_PARSE_ITEM' return item def parse_datetime(self,soup): try: datetime = soup.find_all('time', {'class': 'date'})[0]['datetime'] except: datetime = soup.find_all('time', {'class': 'news-time'})[0]['datetime'] datetime = datetime[:22]+datetime[-2:] #remove ':' return datetime def parse_title(self,soup): title = soup.select('h1')[0].text title = ' '.join(title.split()) return title def parse_author(self,soup): try: # try Columnist block = soup.find_all('div', {'class': 'penname_news clearfix'}) for ele in block: penname = ele.find_all('a', {'class': 'pic'}) author = penname[0]['href'].split('/')[-1] return author except: script = re.search('"creator": ."[0-9]+....', str(soup.select('script')[0])) author = re.findall(re.compile(u"[\u4e00-\u9fa5]+"), str(script)) return author[0] if len(author) else '' def parse_content(self,soup): article = soup.find('div', class_='story') paragraph = [] for p in article.find_all('p'): text = p.text.strip() if len(text) == 0 or text[0]=='►': continue paragraph.append(text) content = '\n'.join(paragraph) content = content.split('【更多鏡週刊相關報導】')[0] return content def parse_metadata(self,soup): metadata = {'category':'', 'fb_like_count': '','image_url':[]} metadata['category'] = soup.find('meta',{'property':'article:section'})['content'] image_url = soup.find('div', class_='story').find_all('img') metadata['image_url'] = ['https:' + x['src'] for x in image_url] return metadata <file_sep>/info-scraper-master/scraper/scraper/spiders/ltn_keywords.py # -*- coding: utf-8 -*- import scrapy from bs4 import BeautifulSoup import traceback, sys from datetime import datetime, timedelta import re from dateutil.parser import parse as date_parser from scraper.items import NewsItem import json from .redis_spiders import RedisSpider import datetime # from scrapy_redis.spiders import RedisSpider # class LtnSpider(RedisSpider): class Ltn_keywordsSpider(scrapy.Spider): name = "ltn_keywords" def start_requests(self): if isinstance(self, RedisSpider): return # url requests=[{ "url": 'https://www.myip.com/', "url_pattern":"https://search.ltn.com.tw/list?keyword={}&type=all&sort=date&start_time={}&end_time={}&sort=date&type=all&page=1", "keywords_list": ['吸金','地下通匯','洗錢','賭博','販毒','走私','仿冒','犯罪集團','侵占','背信','內線交易','行賄','詐貸','詐欺','貪汙','逃稅'], "interval": 3600 * 2, "days_limit": 3600 * 24 * 2, "media": "ltn", "name": "ltn_keywords", "scrapy_key": "ltn_keywords:start_urls", "priority": 1, "search": False, "enabled": True, }] for request in requests: yield scrapy.Request(request['url'], meta=request, dont_filter=True, callback=self.parse) def parse(self, response): meta = response.meta meta['page'] = 1 #搜尋時間範圍 now=datetime.datetime.now() end_time=now.strftime("%Y%m%d") time_delta=datetime.timedelta(days=2) start_time=(now-time_delta).strftime("%Y%m%d") for keyword in meta['keywords_list']: url=meta['url_pattern'].format(keyword,start_time,end_time) yield scrapy.Request(url, meta=meta, dont_filter=True, callback=self.parse_list) def parse_list(self, response): meta = response.meta soup = BeautifulSoup(response.body, 'html.parser') if(len(soup.findAll(class_="cont"))!=0): for s in soup.findAll(class_="cont"): url = s.find('a').get('href') if 'ec.ltn.com.tw' in url: yield response.follow(url, meta=meta, callback=self.parse_article_ec) elif ('news.ltn.com.tw' in url): yield response.follow(url, meta=meta, callback=self.parse_article_news) current_page = re.search("page=(\d+)", response.url).group(1) next_page = re.sub("page=(\d+)", "page={}".format(int(current_page) + 1), response.url) yield scrapy.Request(next_page, dont_filter=True, meta=meta, callback=self.parse_list) def parse_article_ec(self, response): meta = response.meta soup = BeautifulSoup(response.body, 'html.parser') metadata = {'category':'','image_url':[]} content, author, metadata['image_url'] = self.parse_content_author_image_ec(soup) title=soup.find(class_="whitecon boxTitle boxText").find('h1').string metadata['category'] = '自由財經' item = NewsItem() item['url'] = response.url item['article_title'] = title item['author'] = author item['author_url'] = [] item['comment'] = [] item['date'] = self.parse_datetime(soup) item['content'] = content item['metadata'] = metadata item['content_type'] = 0 item['media'] = 'ltn' item['proto'] = 'LTN_PARSE_ITEM' return item def parse_article_news(self, response): meta = response.meta soup = BeautifulSoup(response.body, 'html.parser') metadata = {'category':'','image_url':[]} content, author, metadata['image_url'] = self.parse_content_author_image_news(soup) if 'title' in meta and 'tagText' in meta: title = meta['title'] metadata['category'] = meta.get('tagText', "") else: title, metadata['category'] = self.parse_title_metadata(soup) item = NewsItem() item['url'] = response.url item['article_title'] = title item['author'] = author item['author_url'] = [] item['comment'] = [] item['date'] = self.parse_datetime(soup) item['content'] = content item['metadata'] = metadata item['content_type'] = 0 item['media'] = 'ltn' item['proto'] = 'LTN_PARSE_ITEM' return item def parse_datetime(self,soup): date = soup.find('meta', {'name':'pubdate'}) if date: return date['content'].replace('Z', '+0800') date = soup.find('span', {'class':'time'}) if date: return date_parser(date.text).strftime('%Y-%m-%dT%H:%M:%S+0800') date = soup.find('div', {'class':'article_header'}) if date: return datetime.datetime.strptime(date.find_all('span')[1].text, '%Y-%m-%d').strftime('%Y-%m-%dT%H:%M:%S+0800') date = soup.find('div', {'class':'writer'}) if date: return datetime.datetime.strptime(date.find_all('span')[1].text, '%Y-%m-%d %H:%M').strftime('%Y-%m-%dT%H:%M:%S+0800') def parse_title_metadata(self,soup): title = soup.find('title').text.replace(' - 自由時報電子報', '').replace(' 自由電子報', '') title_ = title.split('-') if not title_[-1]: del title_[-1] if len(title_) > 2: category = title_[-1] del title_[-1] ti = ''.join(x for x in title_) return ti.strip(), category.strip() elif len(title_) == 2: category = title_[1] ti = title_[0] return ti.strip(), category.strip() elif '3C科技' in title_[0]: category = '3C科技' ti = title_[0].replace('3C科技', '') return ti.strip(), category elif '玩咖Playing' in title_[0]: category = '玩咖Playing' ti = title_[0].replace('玩咖Playing', '') return ti.strip(), category else: category = '' ti = title_[0] return ti.strip(), category def find_author(self,list_text): list_text = [x for x in list_text if x!='文'] tmp = [x for x in list_text if '記者' in x] if tmp: author = tmp[0].replace('記者', '').replace('攝影', '').strip() else: author = min(list_text, key=len) return author def parse_content_author_image_ec(self,soup): # content content='' for text in soup.find(class_="text").findAll('p')[1:4]: content=content+text.get_text() for text in soup.find(class_="text").findAll('p')[5:-2]: content=content+text.get_text() # author au = '' author_text=soup.find(class_='text').findAll('p')[1].get_text() begin=author_text.rfind('〔') end=author_text.find('/') if begin!=-1 & end!=-1: au=author_text[begin+1:end] if '記者' in au: au=au.replace('記者', '') # image image_url = [] image_url.append(soup.find(class_='text').find(class_="lazy_imgs_ltn")['data-src']) return content, au, image_url def parse_content_author_image_news(self,soup): content = soup.find('div',{'itemprop':'articleBody'}) # image image_url = [] for photo in content.find_all('div','photo boxTitle'): image_url.append(photo.find('img')['src']) # content for appE1121 in content.find_all('p','appE1121'): appE1121.clear() for photo in content.find_all('div','photo boxTitle'): photo.clear() for photo in content.find_all('span','ph_b ph_d1'): photo.clear() for tag in content.find_all('script'): tag.clear() content = ''.join(x.text for x in content.find_all('p') if x.text!='爆') content = ''.join(content.split()) #author au = '' reg = re.compile(r'([\D*/\D*]|〔\D*/\D*〕)', re.VERBOSE) author_reg = reg.findall(content) if author_reg: au = author_reg[0].split('/')[0].replace('〔', '').replace('[', '').replace('記者', '').replace('編譯', '') if not au: author = soup.find('div', {'class':'writer boxTitle'}) if author: au = author.find('a')['data-desc'] if not au: author = soup.find('p', {'class':'auther'}) if author: tmp = author.find('span').text.split('/') au = self.find_author(tmp) if not au: author = soup.find('p', {'class':'writer'}) if author: tmp = author.find('span').text.split('/') au = self.find_author(tmp) if not au: author = soup.find('div', {'class':'writer'}) if author: tmp = author.find('span').text.split('/') au = self.find_author(tmp) if not au: author = soup.find('div', {'class':'conbox_tit boxTitle'}) if author: au = author.find('a')['data-desc'] if not au: author = soup.find('div', {'class':'article_header'}) if author: tmp = author.find('span').text.split('/') au = self.find_author(tmp) if not au: try: author = soup.find('div', {'itemprop':'articleBody'}).find('p') except: author = '' if author: if '/' in author.text: tmp = author.text.split('/') au = self.find_author(tmp) if author.find('strong'): au = author.find('strong').text.split('◎')[1].replace('記者', '').replace('攝影', '').strip() if '■' in author.text: au = author.text.replace('■', '') if not au: try: author = soup.find('div', {'itemprop':'articleBody'}).find('span', {'class':'writer'}) except: author = '' if author: if '/' in author.text: tmp = author.text.split('/') au = self.find_author(tmp) if not au: try: author = soup.find('div', {'itemprop':'articleBody'}).find('h4') except: author = '' if author: if '/' in author.text: tmp = author.text.split('/') au = self.find_author(tmp) elif '◎' in author.text: au = author.text.replace('◎', '') return content, au, image_url
6ffe0309e0b7cb18bd30fb50a1988b397899de8d
[ "Markdown", "Python", "Dockerfile", "Shell" ]
20
Shell
larry2967/scrapy_news
5d67a21211750120e356e308c9dd6da4b2fd68a9
c9ed46acb1c800059e900dee03a217b159a7c615
refs/heads/master
<file_sep># react-redux-typescript-setup react, react-redux and redux-thunk setup with typescript <file_sep>import { DeleteTodoAction, FetchTodosAction } from '../actions/index'; export enum ActionTypes { fetchTodos, deleteTodo } export type Actions = DeleteTodoAction | FetchTodosAction;
73e81e66484b0ccb2ab5121af02d28fe59fb6dbd
[ "Markdown", "TypeScript" ]
2
Markdown
OmarAwwad77/react-redux-typescript-setup
5e4fa49d04478c35d98625aa8c92b2f11951d1a1
c27008576bcaf33daafa1632fd5d03ce31e9255f
refs/heads/master
<repo_name>arrosh/learning-python<file_sep>/most_frq_words.py def most_frq_words(s): empty = {} for string in s: if string in empty: empty[string] += 1 else SyntaxError: invalid syntax def most_frq_words(s): empty = {} for string in s: if string in empty: empty[string] += 1 else: empty[string] = 1 print(empty) def most_frq_words(s): empty = {} for string in s: if string in empty: empty[string] += 1 else: empty[string] = 1 print(empty) >>> most_frq_words("mom") {'m': 2, 'o': 1} >>> def most_frq_words(s): empty = {} for list in s: if string in empty: empty[string] += 1 else: empty[string] = 1 print(empty) most_frq_words("cat, bat, bat, cat") Traceback (most recent call last): File "<pyshell#21>", line 1, in <module> most_frq_words("cat, bat, bat, cat") File "<pyshell#19>", line 4, in most_frq_words if string in empty: NameError: name 'string' is not defined >>> def most_frq_words(s): empty = {} s = s.split() for string in s: if string in empty: empty[string] += 1 else: empty[string] = 1 print(empty) >>> most_frq_words("cat bat bat cat") {'cat': 2, 'bat': 2} >>> def most_frq_words(s): empty = {} s = s.replace(" ","") for string in s: if string in empty: empty[string] += 1 else: empty[string] = 1 print(empty) >>> most_frq_words("cdad mom") {'c': 1, 'd': 2, 'a': 1, 'm': 2, 'o': 1} >>> <file_sep>/return.py num1 = float(input("Enter first number ")) num2 = float(input("Enter second number ")) num3 = float(input("Enter third number ")) op = input("Enter opeartor ") if op == "+" : print (num1 + num2 + num3) elif op == "-" : print (num1 - num2 - num3) <file_sep>/game.py secret_name = "wuraola" name = "" name_count = 0 name_limit = 3 out_of_names = False while secret_name != name and not (out_of_names): if name_count < name_limit: name = input("what is my name ") name_count += 1 else: out_of_names = True if out_of_names: print ("Out of Guesses, You Lose!") else: print("you win!") <file_sep>/takebreak.py import time import webbrowser total_breaks = 3 break_count = 0 print ("This program started at "+time.ctime()) while (break_count < total_breaks): time.sleep(10) webbrowser.open("https://www.youtube.com/watch?v=yIzT_p_8GLY") break_count = break_count + 1 <file_sep>/loop.py i = 1 while i >= 10 : print (i) i += 1 print("End of loop") <file_sep>/SirajRavel1.py from sklearn import tree <file_sep>/renamefiles.py import os def rename_files(): file_list = os.listdir("/Users/macbook/Desktop/prank") print (file_list) saved_file = os.getcwd() os.chdir("/Users/macbook/Desktop/prank") for file_name in file_list: os.rename(file_name, file_name.translate print("current working is " +saved_file) rename_files()<file_sep>/testing.py #Ask user how many courses they offer user_input = int(input("how many courses did you offer? ")) total_course_unit_of_course = int(input("what is the total course unit: ")) #create an empty list total_course_unit = [] #Create a for loop to ask user for input for i in range(user_input): user_grade = input(f"What is your grade in course {i+1}? ") user_unit = int(input("what is the course unit? ")) user_grade = user_grade.upper() print("") #create a conditional statement that compares Values if user_grade == "A": grade_point = user_unit * 5 #Append each value to the list total_course_unit.append(grade_point) elif user_grade == "B": grade_point = user_unit * 4 #Append each value to the list total_course_unit.append(grade_point) elif user_grade == "C": grade_point = user_unit * 3 #Append each value to the list total_course_unit.append(grade_point) elif user_grade == "D": grade_point = user_unit * 2 #Append each value to the list total_course_unit.append(grade_point) elif user_grade == "E": grade_point = user_unit * 1 #Append each value to the list total_course_unit.append(grade_point) elif user_grade == "F": grade_point = user_unit * 0 #Append each value to the list total_course_unit.append(grade_point) print(sum(total_course_unit) / int(total_course_unit_of_course)) print(total_course_unit_of_course) #Sum the values in the list #Dvide the total Value by the entire course Unit <file_sep>/forloop.py friends = ["Jide", "Temi", "Ade"] for i in friends: print(i) for index in range(5): if index == 2: print("first iteration") else: print("not first") <file_sep>/workbook1.py def new_fun(var1, var2): pass diction = { 'name':'oye', 'class':'' } def another_fun(**kwargs): if kwargs.get('class'): print('works') else: print('not works') another_fun(**diction)<file_sep>/phone.py class phone: def __init__(self, name, colour, maker, is_gorrilla_screen): self.name = name self.colour = colour self.maker = maker self.is_gorrilla_screen = is_gorrilla_screen <file_sep>/tryexcept.py try: 10/0 except ZeroDivisionError as err: print(err) number = int(input("Enter a number ")) print(number) except: print("Invalid Input")<file_sep>/quest.py from question import question question_prompt = [ "what colour is apples?\n(a) Red/green\n(b) yellow\n(c) white", "what colour is strawberry?\n(a)\nRed\n(b) yellow\n(c) purple", "what colour is orange?\n(a) Yellow\n(b)red\n(c) white" ] questions = [ question(question_prompt[0], "a"), question(question_prompt[1], "a"), question(question_prompt[2], "a"), ] def run_test(questions): score = 0 for question in questions: answer = input(question_prompt) if answer == question.answer: score += 1 print("you got " + str(score) + "/" + str(len(questions)) + " correct") else: print("you got only " + str(score)) run_test(questions) <file_sep>/pone.py from phone import phone phone1 = phone("iphone1", "silver", "Aplle_inc", False) print(phone1.colour)<file_sep>/word count.py import webbrowser webbrowser.open("https://www.youtube.com/watch?v=yIzT_p_8GLY")<file_sep>/number.py print "hello" if True: print "a" i = 0 if i == 0: print "b" j = 1 if j == 1: print "c" u = 1 while u <= 100: print (int(u)) u += 1 print (list(range(1,101)))
da349a4a00c958bdd6b4c3cdedb80637ca79d433
[ "Python" ]
16
Python
arrosh/learning-python
dd31eb215053bc78bca63fa8b0eb70d982bad648
036d41209a1bd9b96bac0101976c63f74b0a1f2f
refs/heads/master
<file_sep># DMOJ-Bot A Discord bot built with Python to fetch problems from https://dmoj.ca/. ~ Info ~ - Used Beautiful Soup and Selenium to scrape dmoj.ca for problems and their credentials. - Wrote an algorithm to parse through HTML/CSS and find problems that met the specifications of the request made to the bot. An example of using the bot: ![DMOJ-Bot_q_example](https://i.imgur.com/AHSy40P.png) The bots help command: ![DMOJ-Bot_help_example](https://i.imgur.com/jbVepqk.png) <file_sep>beautifulsoup4 discord discord.py numpy pandas requests selenium soupsieve urllib3 PyNaCl==1.3.0 dnspython==1.16.0 async-timeout==3.0.1 <file_sep>import discord from discord.ext import commands token = "<KEY>" client = commands.Bot(command_prefix="&") badchannels = [] bad = False # web scraping def choose_problem_type(ptword): ptword = ptword.lower() ptword = ptword.replace(" ", "") pttypes = ["simplemath", "datastructures", "graphtheory", "stringalgorithms", "dynamicprogramming", "divideandconquer", "greedyalgorithms", "advancedmath", "intermediatemath", "adhoc", "bruteforce", "implementation", "regularexpressions", "recursion", "geometry", "gametheory", "simulation", "uncategorized"] ptnums = [] for type in range(len(pttypes)): if pttypes[type] in ptword: ptnums.append(type+1) final = "https://dmoj.ca/problems/?show_types=1" for num in ptnums: final += "&type="+str(num) return final def get_point_range(urll, lower, upper): if not lower: if not upper: return urll elif upper > 0: urll += "&point_end=" + str(upper) elif not upper: if lower > 0: urll += "&point_start=" + str(lower) else: if upper >= lower > 0: urll += "&point_start=" + str(lower) + "&point_end=" + str(upper) return urll def point_input(inp): inp = inp.replace(" ", "") if inp == "": return None try: return int(inp) except ValueError: return 999 # replaced driver with requests library # maybe be subject to change def get_problems(baseurl): import requests import os from random import choice from bs4 import BeautifulSoup from selenium import webdriver numberofpages = 49 problemlist = [] for pg in range(1, numberofpages+1): # modifying url for each page url = baseurl url += "&page="+str(pg) chrome_options = webdriver.ChromeOptions() chrome_options.binary_location = os.environ.get("GOOGLE_CHROME_BIN") chrome_options.add_argument("--headless") chrome_options.add_argument("--disable-dev-shm-usage") chrome_options.add_argument("--no-sandbox") driver = webdriver.Chrome(executable_path=os.environ.get("CHROMEDRIVER_PATH"), chrome_options=chrome_options) driver.get(url) content = driver.page_source # page = requests.get(url) soup = BeautifulSoup(content, 'html.parser') # dmoj url: dmoj.ca/problems/?showtypes=1&type=(specifiedtype) # &point_start=(lowerbound)&point_end=(upperbound)&page=(pg#) # reaching the end page try: table = soup.find(id="problem-table").find("tbody").find_all("tr") except AttributeError: break for problem in table: problemlist.append(problem.find('a').get('href')) final = "https://dmoj.ca"+choice(problemlist) return final def scrape(problemtype, lowerp, higherp): from selenium import webdriver # driver = webdriver.Chrome(executable_path=r'C:/webdrivers/chromedriver.exe') url = get_point_range(choose_problem_type(problemtype), lowerp, higherp) final = get_problems(url) return final def do(inputt): temp = [x for x in inputt.split("-")] if len(temp) < 3: return None, True ptype = temp[0] lowerpointrange = point_input(temp[1]) higherpointrange = point_input(temp[2]) if lowerpointrange == 999 or higherpointrange == 999: return None, True return scrape(ptype, lowerpointrange, higherpointrange), False # actual bot @client.event async def on_message(message): id = client.get_guild(662421888710213636) if str(message.author) != "Dmoj Bot#9919": if message.content.find("&d") != -1 and "help" in str(message.content).lower(): await message.channel.send("Please Enter:\n &d (problem type(s))-(lowest point value)-(highest point value)\n -> to skip a category, leave it blank") elif message.content.find("&d") != -1: if "add" in str(message.content): badchannels.remove(str(message.channel)) await message.channel.send("Dmojbot added to #"+str(message.channel)) elif "remove" in str(message.content): badchannels.append(str(message.channel)) await message.channel.send("Dmojbot removed from #"+str(message.channel)) else: if str(message.channel) not in badchannels: out = do(str(message.content)) if out[1]: bad = True await message.channel.send("ur bad\nPlease type: '&d help' for help") elif not out[1]: await message.channel.send(out[0]) client.run(token)
77dbef287cae0c01c3d54d0f5819d9b890647f7b
[ "Markdown", "Python", "Text" ]
3
Markdown
MowMowchow/DMOJ-Bot
6e7a5e0118de8d46638226b92c96136af6494692
b6bf8bd0b5d2b88db8d5b36b0dd2b1e6112dc0a3
refs/heads/master
<file_sep>apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.3" defaultConfig { applicationId "io.mdx.app.menu" minSdkVersion 16 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { debug { applicationIdSuffix ".DEBUG" } release { minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } productFlavors { base {} mexxis { applicationId "com.mexxis.app.menu" } } } repositories { maven { url 'https://jitpack.io' } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.4.0' compile 'com.android.support:design:23.4.0' compile 'com.android.support:recyclerview-v7:23.4.0' compile 'com.android.support:support-v4:23.4.0' compile 'com.squareup.retrofit2:retrofit:2.0.2' compile 'com.squareup.retrofit2:converter-gson:2.0.2' compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2' compile 'com.squareup.picasso:picasso:2.5.2' compile 'io.reactivex:rxandroid:1.2.0' compile 'io.reactivex:rxjava:1.1.5' compile 'com.jakewharton.rxbinding:rxbinding:0.4.0' compile 'com.jakewharton.timber:timber:4.1.2' compile 'com.trello:rxlifecycle:0.6.0' compile 'com.trello:rxlifecycle-components:0.6.0' compile 'com.github.moltendorf:RecyclerViewAdapter:0.6.4' } <file_sep>package io.mdx.app.menu.data.favorites; import android.database.Cursor; import java.util.concurrent.Callable; import io.mdx.app.menu.data.Bus; import io.mdx.app.menu.data.Cache; import io.mdx.app.menu.data.CanonicalSet; import io.mdx.app.menu.data.Database; import io.mdx.app.menu.model.MenuItem; import rx.Observable; import rx.functions.Action1; import rx.functions.Func1; import rx.schedulers.Schedulers; import timber.log.Timber; /** * Created by moltendorf on 16/5/12. */ public class Favorites { private static final String[] NONE = new String[0]; public static final String TABLE = "favorites"; public static final String C_NAME = "name"; public static final String C_PRICE = "price"; public static final String C_DESCRIPTION = "description"; public static final String C_PICTURE = "picture"; private static Observable<CanonicalSet<MenuItem>> favorites; private static Bus<FavoritesEvent> eventBus = new Bus<>(); public static Bus<FavoritesEvent> getEventBus() { return eventBus; } public static void createTable() { Database .observe(new Runnable() { @Override public void run() { Database.getInstance().getWritableDatabase() .execSQL(SQL.CREATE_TABLE); Timber.d("Favorites table created."); } }) .subscribe(); } public static Observable<CanonicalSet<MenuItem>> getFavorites() { if (favorites == null) { favorites = Database .observe(new Callable<Cursor>() { @Override public Cursor call() throws Exception { return Database.getInstance().getReadableDatabase() .rawQuery(SQL.GET_FAVORITES, NONE); } }) .observeOn(Schedulers.computation()) .map(new Func1<Cursor, CanonicalSet<MenuItem>>() { @Override public CanonicalSet<MenuItem> call(Cursor cursor) { CanonicalSet<MenuItem> items = new CanonicalSet<>(cursor.getCount()); cursor.moveToFirst(); while (!cursor.isAfterLast()) { items.add(new MenuItem(cursor)); cursor.moveToNext(); } cursor.close(); Cache.addOrUpdateItems(items, true); Timber.d("Found %d favorites.", items.size()); return items; } }) .cache(); } return favorites; } public static Observable<Boolean> isFavorite(final String name) { return Database .observe(new Callable<Cursor>() { @Override public Cursor call() throws Exception { return Database.getInstance().getReadableDatabase() .rawQuery(SQL.IS_FAVORITE, new String[]{name}); } }) .observeOn(Schedulers.computation()) .map(new Func1<Cursor, Boolean>() { @Override public Boolean call(Cursor cursor) { Boolean isFavorite = cursor.getCount() > 0; cursor.close(); return isFavorite; } }); } public static void addFavorite(final MenuItem item) { Database .observe(new Runnable() { @Override public void run() { Timber.d("Added favorite to database: %s.", item.getName()); Database.getInstance().getWritableDatabase() .execSQL(SQL.ADD_FAVORITE, new String[]{ item.getName(), item.getPrice(), item.getDescription(), item.getPicture() }); } }) .observeOn(Database.getScheduler()) .subscribe(new Action1<Void>() { @Override public void call(Void aVoid) { synchronized (Favorites.class) { favorites = null; // @todo Modify set instead of nulling it. } eventBus.send(new FavoritesEvent(FavoritesEvent.Type.ADD, item)); } }); } public static void removeFavorite(final MenuItem item) { Database .observe(new Runnable() { @Override public void run() { Timber.d("Removed favorite from database: %s.", item.getName()); Database.getInstance().getWritableDatabase() .execSQL(SQL.REMOVE_FAVORITE, new String[]{item.getName()}); } }) .subscribe(new Action1<Void>() { @Override public void call(Void aVoid) { synchronized (Favorites.class) { favorites = null; // @todo Modify set instead of nulling it. } eventBus.send(new FavoritesEvent(FavoritesEvent.Type.REMOVE, item)); } }); } public static void updateFavorite(final MenuItem item) { Database .observe(new Runnable() { @Override public void run() { Timber.d("Updated favorite in database: %s.", item.getName()); Database.getInstance().getWritableDatabase() .execSQL(SQL.UPDATE_FAVORITE, new String[]{ item.getPrice(), item.getDescription(), item.getPicture(), item.getName() // WHERE clause }); } }) .subscribe(new Action1<Void>() { @Override public void call(Void aVoid) { synchronized (Favorites.class) { favorites = null; // @todo Modify set instead of nulling it. } eventBus.send(new FavoritesEvent(FavoritesEvent.Type.UPDATE, item)); } }); } public static class FavoritesEvent { private Type type; private MenuItem item; public FavoritesEvent(Type type, MenuItem item) { this.type = type; this.item = item; } public Type getType() { return type; } public MenuItem getItem() { return item; } public enum Type { ADD, REMOVE, UPDATE } } } <file_sep>package io.mdx.app.menu.fragment; import android.view.MotionEvent; import android.view.View; import com.trello.rxlifecycle.FragmentEvent; import net.moltendorf.android.recyclerviewadapter.RecyclerViewAdapter; import java.util.Set; import io.mdx.app.menu.Action; import io.mdx.app.menu.R; import io.mdx.app.menu.data.Backend; import io.mdx.app.menu.model.Specials; import io.mdx.app.menu.view.ItemHolder; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; /** * Created by moltendorf on 16/4/29. */ public class SpecialsFragment extends ItemRecyclerFragment { public static final Action ACTION_SPECIALS = new Action("SPECIALS"); private static Factory<SpecialsFragment> factory = new Factory<SpecialsFragment>() { @Override public Action getAction() { return ACTION_SPECIALS; } @Override public SpecialsFragment newInstance() { return SpecialsFragment.newInstance(); } }; public static Factory<SpecialsFragment> getFactory() { return factory; } public static SpecialsFragment newInstance() { return new SpecialsFragment(); } public SpecialsFragment() { super(R.layout.fragment_specials_list); } @Override public void populateFactories(Set<RecyclerViewAdapter.Factory> factories) { ItemHolder.Factory factory = new ItemHolder.Factory(R.layout.row_special_item); registerItemHolderFactory(factory); factories.add(factory); } @Override public Subscription fetchData() { return Backend.getSpecials() .compose(this.<Specials>bindUntilEvent(FragmentEvent.DESTROY)) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<Specials>() { @Override public void call(Specials specials) { changeDataSet(specials.getItems()); } }); } @Override public void setupList() { super.setupList(); list.setOnTouchListener(new View.OnTouchListener() { private int position = 0; @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_UP: int current = list.computeVerticalScrollOffset(); int previous = position * list.getHeight(); // Very simple, does not use velocity. May feel buggy if the user scrolls one direction then goes the other. if (current > previous) { list.smoothScrollToPosition(++position); } else if (current < previous) { list.smoothScrollToPosition(--position); } } return false; } }); } } <file_sep>package io.mdx.app.menu.fragment; import android.os.Bundle; import android.view.View; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import com.trello.rxlifecycle.FragmentEvent; import io.mdx.app.menu.Action; import io.mdx.app.menu.R; import io.mdx.app.menu.data.Cache; import io.mdx.app.menu.model.MenuItem; import rx.functions.Action1; /** * Created by moltendorf on 16/5/19. */ public class DetailFragment extends BaseFragment { public static final Action ACTION_DETAIL = new Action("DETAIL"); private static final String ITEM_ID = "ITEM_ID"; public static Bundle createBundle(int itemId) { Bundle bundle = new Bundle(); bundle.putInt(ITEM_ID, itemId); return bundle; } private int itemId = -1; public DetailFragment() { super(R.layout.fragment_detail); } @Override public void setArguments(Bundle args) { super.setArguments(args); if (args != null) { itemId = args.getInt(ITEM_ID, -1); } } @Override public void onViewCreated(final View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); if (itemId != -1) { Cache.getItem(itemId) .compose(this.<MenuItem>bindUntilEvent(FragmentEvent.DESTROY_VIEW)) .subscribe(new Action1<MenuItem>() { @Override public void call(MenuItem item) { TextView name = (TextView) view.findViewById(R.id.item_name); TextView price = (TextView) view.findViewById(R.id.item_price); TextView description = (TextView) view.findViewById(R.id.item_description); ImageView picture = (ImageView) view.findViewById(R.id.item_picture); CheckBox favorite = (CheckBox) view.findViewById(R.id.item_favorite); name.setText(item.getName()); price.setText(item.getPrice()); description.setText(item.getDescription()); if (item.getPicture() != null && !item.getPicture().isEmpty()) { Picasso.with(getContext()).load(item.getPicture()).fit().centerCrop().into(picture); } else { picture.setImageResource(android.R.color.transparent); } favorite.setChecked(item.getFavorite()); } }); } } } <file_sep>package io.mdx.app.menu.model; import java.util.List; /** * Created by moltendorf on 16/5/9. */ public class MenuSection { private String _name; private List<MenuItem> _items; public String getName() { return _name; } public List<MenuItem> getItems() { return _items; } } <file_sep>package io.mdx.app.menu.data; import java.util.List; import java.util.ListIterator; import io.mdx.app.menu.model.MenuItem; import io.mdx.app.menu.util.ObjectUtils; import rx.Observable; import rx.Subscriber; import rx.schedulers.Schedulers; /** * Created by moltendorf on 16/5/21. */ public class Cache { private static final CanonicalSet<MenuItem> items = new CanonicalSet<>(); private static Bus<MenuItem> updatedItemBus = new Bus<>(); public static Observable<MenuItem> getItem(final Object item) { return Observable .create(new Observable.OnSubscribe<MenuItem>() { @Override public void call(Subscriber<? super MenuItem> subscriber) { MenuItem existing; synchronized (items) { existing = items.get(item); } subscriber.onNext(existing); } }) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.immediate()); } public static MenuItem addOrUpdateItem(MenuItem item, boolean setFavorite) { MenuItem existing = null; synchronized (items) { if (items.add(item)) { return item; } else { existing = items.get(item); } } if (existing != null) { check: { if (!existing.getName().equals(item.getName())) { break check; } if (!ObjectUtils.equals(existing.getPrice(), item.getPrice())) { break check; } if (!ObjectUtils.equals(existing.getDescription(), item.getDescription())) { break check; } if (!ObjectUtils.equals(existing.getPicture(), item.getPicture())) { break check; } if (!ObjectUtils.equals(existing.getDisplay(), item.getDisplay())) { break check; } return existing; } if (!setFavorite) { item.setFavorite(existing.getFavorite()); } synchronized (items) { items.update(item); } updatedItemBus.send(item); } return item; } public static void addOrUpdateItems(List<MenuItem> items, boolean setFavorite) { ListIterator<MenuItem> iterator = items.listIterator(); while (iterator.hasNext()) { iterator.set(addOrUpdateItem(iterator.next(), setFavorite)); } } public static Bus<MenuItem> getUpdatedItemBus() { return updatedItemBus; } } <file_sep>package io.mdx.app.menu; import android.content.Intent; import android.content.pm.PackageManager; /** * Created by moltendorf on 16/5/24. */ public class Action { private static final String packageName = MenuApplication.getInstance().getPackageName(); private boolean enabled; private Intent intent; private String action; private String local; private String name; public Action(String local) { this.local = local; action = String.format("%s.%s", packageName, local); intent = new Intent(action); MenuApplication application = MenuApplication.getInstance(); enabled = application.getPackageManager() .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY) .size() > 0; int resource = application.getResources() .getIdentifier(String.format("action_%s", local.toLowerCase()), "string", packageName); if (resource != 0) { name = application.getString(resource); } else { name = local; } } public Intent getIntent() { return intent.cloneFilter(); } public String getAction() { return action; } public String getLocal() { return local; } public boolean isEnabled() { return enabled; } public String getName() { return name; } @Override public String toString() { return action; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Action action = (Action) o; return local.equals(action.local); } @Override public int hashCode() { return local.hashCode(); } } <file_sep>package io.mdx.app.menu.data; import android.support.annotation.NonNull; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Set; import java.util.TreeSet; // @todo Could probably use a single TreeMap for backing. // @todo Some methods probably broken. Needs testing. /** * Created by moltendorf on 16/5/21. */ public class CanonicalSet<T> implements List<T>, Set<T> { private ArrayList<Node<T>> list; private HashMap<T, Node<T>> map; public CanonicalSet() { list = new ArrayList<>(); map = new HashMap<>(); } public CanonicalSet(int capacity) { list = new ArrayList<>(capacity); map = new HashMap<>(capacity); } public T get(Object object) { Node<T> node = map.get(object); if (node != null) { return node.value; } return null; } public boolean update(T object) { Node<T> node = map.get(object); if (node != null) { node.value = object; return true; } return false; } @Override public void add(int index, T object) { if (!map.containsKey(object)) { Node<T> node = new Node<>(index, object); map.put(object, node); list.add(index, node); for (int i = index + 1, j = list.size(); i < j; ++i) { list.get(i).index++; } } } @Override public boolean add(T object) { if (!map.containsKey(object)) { Node<T> node = new Node<>(list.size(), object); map.put(object, node); list.add(node); return true; } return false; } @Override public boolean addAll(int index, Collection<? extends T> collection) { int size = list.size(); // @todo Fix terrible performance; but this method is unused for now. for (T object : collection) { add(index++, object); } return list.size() != size; } @Override public boolean addAll(Collection<? extends T> collection) { int size = list.size(); for (T object : collection) { add(object); } return list.size() != size; } @Override public void clear() { list.clear(); map.clear(); } @Override public boolean contains(Object object) { return map.containsKey(object); } @Override public boolean containsAll(Collection<?> collection) { for (Object object : collection) { if (!map.containsKey(collection)) { return false; } } return true; } @Override public T get(int index) { return list.get(index).value; } @Override public int indexOf(Object object) { return map.get(object).index; } @Override public boolean isEmpty() { return list.isEmpty(); } @NonNull @Override public Iterator<T> iterator() { return listIterator(); } @Override public int lastIndexOf(Object object) { return indexOf(object); } @Override public ListIterator<T> listIterator() { return new CanonicalSetIterator<>(this); } @NonNull @Override public ListIterator<T> listIterator(int location) { return new CanonicalSetIterator<>(location, this); } @Override public T remove(int index) { Node<T> node = list.remove(index); map.remove(node.value); return node.value; } @Override public boolean remove(Object object) { Node<T> node = map.remove(object); if (node != null) { list.remove(node.index); return true; } return false; } @Override public boolean removeAll(Collection<?> collection) { int size = list.size(); for (Object object : collection) { remove(object); } return list.size() != size; } @Override public boolean retainAll(Collection<?> collection) { int size = list.size(); TreeSet<Node<T>> retained = new TreeSet<>(); for (Object object : collection) { Node<T> node = map.get(object); if (node != null) { retained.add(node); } } int newSize = list.size(); list = new ArrayList<>(retained); map = new HashMap<>(newSize); int index = 0; for (Node<T> node : list) { node.index = index++; map.put(node.value, node); } return newSize != size; } @Override public T set(int index, T object) { Node<T> node = list.get(index); T previous = node.value; map.remove(previous); node.value = object; map.put(object, node); return previous; } @Override public int size() { return list.size(); } @NonNull @Override public List<T> subList(int start, int end) { List<Node<T>> nodes = list.subList(start, end); ArrayList<T> sub = new ArrayList<>(nodes.size()); for (Node<T> node : nodes) { sub.add(node.value); } return sub; } @NonNull @Override public Object[] toArray() { Object[] array = new Object[list.size()]; for (int i = 0, j = array.length; i < j; ++i) { array[i] = list.get(i).value; } return array; } @NonNull @Override public <T1> T1[] toArray(@NonNull T1[] array) { int size = list.size(); if (array.length < size) { array = Arrays.copyOf(array, size); } for (int i = 0; i < size; ++i) { array[i] = (T1) list.get(i).value; } for (int i = size, j = array.length; i < j; ++i) { array[i] = null; } return array; } public static class CanonicalSetIterator<T> implements ListIterator<T> { private CanonicalSet<T> set; private ListIterator<Node<T>> iterator; private Node<T> node; public CanonicalSetIterator(CanonicalSet<T> set) { this.set = set; iterator = set.list.listIterator(); } public CanonicalSetIterator(int location, CanonicalSet<T> set) { this.set = set; iterator = set.list.listIterator(location); node = set.list.get(location); } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public T next() { node = iterator.next(); return node.value; } @Override public void remove() { iterator.remove(); set.map.remove(node.value); } @Override public void add(T object) { node = new Node<>(iterator.previousIndex() + 1, object); iterator.add(node); set.map.put(object, node); } @Override public boolean hasPrevious() { return iterator.hasPrevious(); } @Override public int nextIndex() { return iterator.nextIndex(); } @Override public T previous() { node = iterator.previous(); return node.value; } @Override public int previousIndex() { return iterator.previousIndex(); } @Override public void set(T object) { // This will change the hash, so we need to replace it in the map. set.map.remove(node.value); node.value = object; set.map.put(object, node); } } private static class Node<T> implements Comparable<Node<T>> { int index; T value; public Node(int index, T value) { this.index = index; this.value = value; } @Override public int compareTo(Node<T> another) { return index - another.index; } @Override public boolean equals(Object o) { return value.equals(o); } @Override public int hashCode() { return value.hashCode(); } } } <file_sep>package io.mdx.app.menu; import android.app.Application; import timber.log.Timber; /** * Created by moltendorf on 16/5/4. */ public class MenuApplication extends Application { private static MenuApplication instance; public static MenuApplication getInstance() { return instance; } @Override public void onCreate() { super.onCreate(); instance = this; if (BuildConfig.DEBUG) { Timber.plant(new Timber.DebugTree()); } } } <file_sep>package io.mdx.app.menu.data.favorites; /** * Created by moltendorf on 16/5/12. */ interface SQL { String CREATE_TABLE = "CREATE TABLE " + Favorites.TABLE + " (" + Favorites.C_NAME + " VARCHAR(255) PRIMARY KEY, " + Favorites.C_PRICE + " VARCHAR(255) DEFAULT NULL, " + Favorites.C_DESCRIPTION + " VARCHAR(255) DEFAULT NULL," + Favorites.C_PICTURE + " VARCHAR(255) DEFAULT NULL" + ")"; String GET_FAVORITES = "SELECT * " + "FROM " + Favorites.TABLE; String IS_FAVORITE = "SELECT 1 " + "FROM " + Favorites.TABLE + " " + "WHERE " + Favorites.C_NAME + " = ?"; String ADD_FAVORITE = "INSERT INTO " + Favorites.TABLE + " " + "(" + Favorites.C_NAME + ", " + Favorites.C_PRICE + ", " + Favorites.C_DESCRIPTION + ", " + Favorites.C_PICTURE + ") " + "VALUES (?, ?, ?, ?)"; String REMOVE_FAVORITE = "DELETE FROM " + Favorites.TABLE + " " + "WHERE " + Favorites.C_NAME + " = ?"; String UPDATE_FAVORITE = "UPDATE " + Favorites.TABLE + " " + "SET " + Favorites.C_PRICE + " = ?, " + Favorites.C_DESCRIPTION + " = ?, " + Favorites.C_PICTURE + " = ? " + "WHERE " + Favorites.C_NAME + " = ?"; } <file_sep>package io.mdx.app.menu.data; import com.google.gson.FieldNamingStrategy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.lang.reflect.Field; import java.util.List; import io.mdx.app.menu.data.favorites.Favorites; import io.mdx.app.menu.model.Menu; import io.mdx.app.menu.model.MenuItem; import io.mdx.app.menu.model.MenuSection; import io.mdx.app.menu.model.Specials; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.http.GET; import rx.Observable; import rx.functions.Func2; import rx.schedulers.Schedulers; import timber.log.Timber; /** * Created by moltendorf on 16/5/9. */ abstract public class Backend { private static Gson gson = new GsonBuilder() .setFieldNamingStrategy(new FieldNamingStrategy() { @Override public String translateName(Field field) { return field.getName().substring(1); } }).create(); private static Service service = (new Retrofit.Builder()) .baseUrl("https://mexxis.mdx.co/data/") .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .build() .create(Service.class); private static Observable<Specials> specials; private static Observable<Menu> menu; /** * Creates an observable that, when subscribed to, fetches both the current specials and the user's favorites, then uses both * data sets to create a list of specials with each special that's in the user's favorites list properly flagged as a * favorite. * * @return Observable to fetch Specials */ public static Observable<Specials> getSpecials() { if (specials == null) { specials = service.getSpecials() .subscribeOn(Schedulers.io()) // Use IO threads for network request. .observeOn(Schedulers.computation()) // Use computation threads for processing data. .zipWith(Favorites.getFavorites(), new Func2<Specials, CanonicalSet<MenuItem>, Specials>() { @Override public Specials call(Specials specials, CanonicalSet<MenuItem> favorites) { List<MenuItem> items = specials.getItems(); Cache.addOrUpdateItems(items, false); Timber.d("Found %d specials.", items.size()); return specials; } }) .cache(); } return specials; } /** * Creates an observable that, when subscribed to, fetches both the current menu and the user's favorites, then uses both data * sets to create the menu with each item that's in the user's favorites list properly flagged as a favorite. * * @return Observable to fetch menu */ public static Observable<Menu> getMenu() { if (menu == null) { menu = service.getMenu() .subscribeOn(Schedulers.io()) // Use IO threads for network request. .observeOn(Schedulers.computation()) // Use computation threads for processing data. .zipWith(Favorites.getFavorites(), new Func2<Menu, CanonicalSet<MenuItem>, Menu>() { @Override public Menu call(Menu menu, CanonicalSet<MenuItem> favorites) { // Iterate through all sections. for (MenuSection section : menu.getSections()) { List<MenuItem> items = section.getItems(); Cache.addOrUpdateItems(items, false); Timber.d("Found %d items in %s section.", items.size(), section.getName()); } return menu; } }) .cache(); } return menu; } // @todo Make backend query when item doesn't exist. public static Observable<MenuItem> getItem(Object key) { return Cache.getItem(key); } public interface Service { @GET("specials.json") Observable<Specials> getSpecials(); @GET("menu.json") Observable<Menu> getMenu(); } } <file_sep>package io.mdx.app.menu.fragment; import android.annotation.SuppressLint; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.trello.rxlifecycle.FragmentEvent; import net.moltendorf.android.recyclerviewadapter.RecyclerViewAdapter; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import io.mdx.app.menu.data.favorites.Favorites; import rx.Subscription; import rx.functions.Action1; /** * Created by moltendorf on 16/4/29. */ @SuppressLint("ValidFragment") abstract public class RecyclerFragment extends BaseFragment { protected RecyclerViewAdapter adapter; protected List data = new ArrayList(); protected RecyclerView list; protected Subscription subscription; public RecyclerFragment(int layout) { super(layout); registerObservers(); subscription = fetchData(); } private void registerObservers() { Favorites.getEventBus().observe() .compose(this.<Favorites.FavoritesEvent>bindUntilEvent(FragmentEvent.DESTROY)) .subscribe(new Action1<Favorites.FavoritesEvent>() { @Override public void call(Favorites.FavoritesEvent favoritesEvent) { if (!getUserVisibleHint()) { // @todo Use a scalpel and inject/replace the row directly into the view. if (subscription != null && !subscription.isUnsubscribed()) { subscription.unsubscribe(); } fetchData(); } } }); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); createAdapter(); setupList(); } public void changeDataSet(List data) { this.data = data; if (adapter != null) { adapter.changeDataSet(data); } } public void createAdapter() { Set<RecyclerViewAdapter.Factory> factories = new LinkedHashSet<>(); populateFactories(factories); adapter = new RecyclerViewAdapter(getContext()); adapter.setViewHolders(factories); adapter.changeDataSet(data); } public void setupList() { list = (RecyclerView) getView(); list.setLayoutManager(new LinearLayoutManager(getContext())); list.setAdapter(adapter); } abstract public Subscription fetchData(); abstract public void populateFactories(Set<RecyclerViewAdapter.Factory> factories); }
8ee366f89a8975842e1e3484aa5451ece9a97f6b
[ "Java", "Gradle" ]
12
Gradle
moltendorf/Menu-Android
6c2dc4471aa704eb078b7049534762a620bb6dce
fbcc57c2adbe6bce4b7a6df7cfc02d578d0cc0f2
refs/heads/master
<file_sep>package com.jjs.csdn.controller; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.jjs.csdn.entity.User; import com.jjs.csdn.entity.WxUserInfo; import com.jjs.csdn.service.UserService; import com.jjs.csdn.service.WxAuthenService; import com.jjs.csdn.util.AjaxResult; import com.jjs.csdn.util.ApiConnector; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.servlet.http.HttpSession; @Controller public class WxController { @Resource WxAuthenService wxAuthenService; @Resource UserService userService; @RequestMapping("/codeUrl") @ResponseBody public AjaxResult codeUrl() { String url = "http://payhub.dayuanit.com/weixin/connect/qrconnect.do?" + "appid=2018101019365510690&redirect_uri=http://127.0.0.1:8080/loginCallback&response_type=code&scope=snsapi_login"; return AjaxResult.success(url); } @RequestMapping("/loginCallback") public String loginCallback(String code, HttpSession session) { String accessTokenUrl = "http://payhub.dayuanit.com/weixin/sns/oauth2/access_token.do?appid=2018101019365510690&secret=01856405049204689921779748470570" + "&code=" + code + "&grant_type=authorization_code"; String result = ApiConnector.get(accessTokenUrl, null); JSONObject jsonObject = JSON.parseObject(result); String accessToken = jsonObject.getString("access_token"); String openid = jsonObject.getString("openid"); //获取微信用户信息 String wxUserUrl = "http://payhub.dayuanit.com/weixin/sns/userinfo.do?access_token=" + accessToken + "&openid=" + openid; result = ApiConnector.get(wxUserUrl, null); JSONObject userInfoJsonObject = JSON.parseObject(result); //去绑定页面 or 自动登录去个人中心 WxUserInfo wxUserInfo = wxAuthenService.getWxUserInfoByOpenId(openid); if (null == wxUserInfo) { //去绑定页面 session.setAttribute("nickName", userInfoJsonObject.getString("nickname")); session.setAttribute("headimgurl", userInfoJsonObject.getString("headimgurl")); session.setAttribute("openid", openid); return "redirect:/html/bind.html"; } return "/html/home.html"; } @RequestMapping("/bind") @ResponseBody public AjaxResult bind(String userName, String password, HttpSession session) { try { User user = userService.login(userName, password); wxAuthenService.saveBindInfo(user.getId(), (String) session.getAttribute("openid"), (String) session.getAttribute("nickName"), (String) session.getAttribute("headimgurl")); } catch (Exception e) { e.printStackTrace(); return AjaxResult.fail(e.getMessage()); } return AjaxResult.success(); } } <file_sep>function validate() { var money = $("#money").val(); if (!money) { alert("金额不能为空!"); return false; } if (isNaN(money)) { alert("金额不是有效数字!"); return false; } return true; } function submitForm() { var v = validate(); if (v) { form1.submit(); } } <file_sep>var app = new Vue({ el: '#app', data: { movieInfo: {}, selectedSeats: [], unAvailableSeats: [], chooseSeatInfo: [] }, watch: { unAvailableSeats: function (newValue, oldValue) { $.each(newValue, function (index, value) { $("#" + value).removeClass("available").addClass("unavailable");//改成已售出 }) } }, methods: { formatSeat: function (seat) { var strs = seat.split('_'); return strs[0] + '排' + strs[1] + '座'; }, choose: function (event) { console.log(event); var target = event.currentTarget; console.log(target); console.log($(target).attr("i" + "d")); var id = $(target).attr("id"); if (this.unAvailableSeats.includes(id)) { return; } if (!this.selectedSeats.includes(id)) { $(target).removeClass("available").addClass("selected");//改成选中 this.selectedSeats.push(id); } else { $(target).removeClass("selected").addClass("available"); this.selectedSeats.splice(this.selectedSeats.indexOf(id), 1);//改成可选 } }, insertOrder: function () { var showTimeId = UrlParam.param("showTimeId"); $.ajax({ type: 'post', //默认get url: "/api/order/insertOrder.do", data: { showTimeId: showTimeId, movieId: 59, selectedSeats: app.selectedSeats }, async: true, //是否异步(默认true:异步) dataType: "json",//定义服务器返回的数据类型 success: function (data) {//data服务器返回的json字符串 if (data.success) { $("#app").html(data.data); } else { alert(data.errorMsg); if (data.errorCode === 111) { window.location.href = "/login.html"; } else { app.listSaledSeats(); } } } }); }, getMovieInfo: function () { var showTimeId = UrlParam.param("showTimeId"); $.ajax({ type: 'post', //默认get url: "/api/getMovieInfoByShowTimeId.do", data: { showTimeId: showTimeId, }, async: true, //是否异步(默认true:异步) dataType: "json",//定义服务器返回的数据类型 success: function (data) {//data服务器返回的json字符串 if (data.success) { app.movieInfo = data.data; } else { alert(data.errorMsg); } app.listSaledSeats(); } }); }, listSaledSeats: function () { var showTimeId = UrlParam.param("showTimeId"); $.ajax({ type: 'post', //默认get url: "/api/order/listSaledSeats.do", data: { showTimeId: showTimeId }, async: true, //是否异步(默认true:异步) dataType: "json",//定义服务器返回的数据类型 success: function (data) {//data服务器返回的json字符串 if (data.success) { app.unAvailableSeats = data.data; } else { alert(data.errorMsg) } } }); } }, mounted: function () { this.getMovieInfo(); // this.listSaledSeats(); } }); <file_sep>package com.dayuan.mapper; import com.dayuan.entity.OrderInfo; public interface OrderInfoMapper { int deleteByPrimaryKey(Integer id); int insert(OrderInfo record); OrderInfo selectByPrimaryKey(Integer id); void insertOrderInfo(OrderInfo orderInfo); }<file_sep>var app = new Vue({ el: '#app', data: { article: [] }, methods: { editText: function () { if ($("#edit").html()=='编辑') { $("#content").attr("contenteditable",true); $("#edit").html('提交'); }else if ($("#edit").html()=='提交') { app.editContent(); $("#content").removeAttr("contenteditable"); $("#edit").html('编辑'); } }, getArticle:function () { $.ajax({ type: 'post', //默认get url: "/article/getArticle", data: {id: 1}, async: true, //是否异步(默认true:异步) dataType: "json",//定义服务器返回的数据类型 success: function (data) {//data服务器返回的json字符串 if (data.success) { app.article = data.data; } else { alert(data.errorMsg) } } }); }, editContent:function () { var content=$("#content").html(); $.ajax({ type: 'post', //默认get url: "/article/editContent", data: { id:1, content: content }, async: true, //是否异步(默认true:异步) dataType: "json",//定义服务器返回的数据类型 success: function (data) {//data服务器返回的json字符串 if (data.success) { alert("更新成功") } else { alert(data.errorMsg) } } }); } }, mounted: function () { this.getArticle(); } });<file_sep>jdbc.driverClassName=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/film?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&autoReconnect=true jdbc.username=root jdbc.password=<PASSWORD><file_sep>package com.dayuan.mapper; import com.dayuan.entity.ShowTime; import org.apache.ibatis.annotations.Param; import java.util.List; public interface ShowTimeMapper { int deleteByPrimaryKey(Integer id); int insert(ShowTime record); ShowTime selectByPrimaryKey(Integer id); List<ShowTime> selectShowTimes(@Param("showDayId") Integer showDayId); }<file_sep>package com.dayuan.exception; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 统一异常处理类 */ @Component public class CustomExceptionResolver implements HandlerExceptionResolver { private static Logger log = LoggerFactory.getLogger(CustomExceptionResolver.class); @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception ex) { log.error("系统异常",ex); //如果是自定义异常,则显示ex.getMessage ,否则显示 系统系统异常,请稍后再试 String errorMsg = null; if(ex instanceof TransforException){ errorMsg = ex.getMessage(); }else{ errorMsg = "系统异常,请稍后再试"; } //向前台返回错误信息 ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("errorMsg", errorMsg); modelAndView.setViewName("fail"); return modelAndView; } }<file_sep> function validate() { var money = $("#money").val(); if (!money) { alert("金额不能为空!"); return false; } if (isNaN(money)) { alert("金额不是有效数字!"); return false; } return true; } <file_sep>logging.path=D://springbootdemo/log logging.level.com.favorites=DEBUG logging.level.org.springframework.web=INFO mybatis.config-location=classpath:mybatis-config.xml mybatis.mapper-locations=classpath:mapper/*.xml spring.datasource.driverClassName = com.mysql.jdbc.Driver spring.datasource.url = jdbc:mysql://localhost:3306/film?useUnicode=true&characterEncoding=utf-8 spring.datasource.username = root spring.datasource.password = <PASSWORD> spring.thymeleaf.cache=false<file_sep>package com.dayuan.interceptor; import com.alibaba.fastjson.JSON; import com.dayuan.util.AjaxResult; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.PrintWriter; public class LoginHandlerIntercepter implements HandlerInterceptor { /** * preHandler :在进入Handler(Controller)方法之前执行了, * 使用于身份认证,身份授权,登陆校验等, * 比如身份认证,用户没有登陆,拦截不再向下执行, * 返回值为 false ,即可实现拦截;否则,返回true时,拦截不进行执行; * * @param request * @param response * @param handler * @return * @throws Exception */ // @Override // public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // // //用户认证 // System.out.println("会话验证...."); // // String requestURI = request.getRequestURI();// http://localhost:8080/login.html /login.html // // /** // * 将不需要认证的url排除掉 // */ // if (!requestURI.equals("/api/user/login.do")) { // HttpSession session = request.getSession(false); // if (session != null && session.getAttribute("cardNo") != null) { // //登录成功 // return true;//请求响应继续向下传递,传递给servlet // } else { // response.sendRedirect("/login.html"); // return false; // } // } // // return true; // } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //用户认证 System.out.println("会话验证...."); String requestURI = request.getRequestURI();// http://localhost:8080/login.html /login.html /** * 将不需要认证的url排除掉 */ HttpSession session = request.getSession(false); if (session != null && session.getAttribute("cardNo") != null) { //登录成功 return true;//请求响应继续向下传递,传递给servlet } else { AjaxResult result = AjaxResult.fail(111, "未登录,请登录后操作"); PrintWriter writer = response.getWriter(); response.setContentType("text/html;charset=utf-8"); writer.write(JSON.toJSONString(result)); return false; } } /** * postHandler : 进入Handler方法之后,返回ModelAndView之前执行, * 使用场景从ModelAndView参数出发, * 比如,将公用的模型数据在这里传入到视图,也可以统一指定显示的视图等; * * @param request * @param response * @param handler * @param modelAndView * @throws Exception */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } /** * afterHandler : 在执行Handler完成后执行此方法, * 使用于统一的异常处理,统一的日志处理等; * * @param request * @param response * @param handler * @param ex * @throws Exception */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } } <file_sep>package com.dayuan.atmspringboot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class AtmSpringbootApplication { public static void main(String[] args) { SpringApplication.run(AtmSpringbootApplication.class, args); } } <file_sep> function validate() { var money = $("#money").val(); var name = $("#name").val(); var cardNo = $("#cardNo").val(); if (!cardNo) { alert("卡号不能为空!"); return false; } if (!name) { alert("请输入转入用户名!"); return false; } if (!money) { alert("金额不能为空!"); return false; } if (isNaN(money)) { alert("金额不是有效数字!"); return false; } return true; }<file_sep>package com.jjs.csdn.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.*; @Controller public class UserController { @RequestMapping("/user/uploadAvatar") public void uploadAvatar(MultipartFile avatar, HttpSession session, HttpServletResponse response) { try (OutputStream os = response.getOutputStream()) { avatar.transferTo(new File("F:/csdn/"+1)); os.write("<script>parent.showAvatar();</script>".getBytes()); os.flush(); } catch (IOException e) { e.printStackTrace(); } } @RequestMapping("/show/avatar") public void avatar(HttpSession session, HttpServletResponse response) { try (OutputStream os = response.getOutputStream(); InputStream is = new FileInputStream("F:/csdn/"+1)) { byte[] buff = new byte[1024]; int length = -1; while (-1 != (length = is.read(buff))) { os.write(buff, 0, length); os.flush(); } } catch (Exception e) { e.printStackTrace(); } } } <file_sep> var app = new Vue({ el: '#app', data: { movie: {}, selectedSeats: [],//已选择 unavailableSeats: []//已售出 }, methods: { sendCode:function(){ var loginName = $("#loginName").val(); if(!loginName){ alert("请输入邮箱"); return; } $("#btn_sendcode").attr('disabled','disabled').html('发送中'); $.ajax({ type: 'post', //默认get url: "/api/user/sendCode.do", data: {email: loginName}, async: true, //是否异步(默认true:异步) dataType: "json",//定义服务器返回的数据类型 success: function (data) {//data服务器返回的json字符串 if (data.success) { alert("发送成功"); app.codeCount(10); } else { alert(data.errorMsg) } } }); }, signup:function(){ $.ajax({ type: 'post', //默认get url: "/api/user/signup.do", data: $("#form1").serialize(), async: true, //是否异步(默认true:异步) dataType: "json",//定义服务器返回的数据类型 success: function (data) {//data服务器返回的json字符串 if (data.success) { alert("注册成功"); } else { alert(data.errorMsg) } } }); }, codeCount:function (c) { if (c === 0) { $("#btn_sendcode").removeAttr('disabled').html('发送验证码'); return; } $("#btn_sendcode").html(c--); setTimeout(function () { app.codeCount(c); },1000) } } });<file_sep>host.name=172.16.58.3 host.port=6379<file_sep>mybatis.config-location=classpath:mybatis-config.xml mybatis.mapper-locations=classpath:mapper/*.xml spring.datasource.driverClassName = com.mysql.jdbc.Driver spring.datasource.url = jdbc:mysql://172.16.31.10:3306/csdn?useUnicode=true&characterEncoding=utf-8 spring.datasource.username = root spring.datasource.password = <PASSWORD> spring.servlet.multipart.max-file-size=20MB<file_sep>jdbc_url=jdbc:mysql://192.168.127.12:3306/csdn?characterEncoding=utf8 jdbc_driver=com.mysql.jdbc.Driver jdbc_username=root jdbc_password=<PASSWORD> targetProject=src/main/java resourceTargetProject=src/main/resources modelPackage=com.jjs.csdn.entity sqlMapperPackage=mapper daoMapperPackage=com.jjs.csdn.mapper<file_sep>var app = new Vue({ el: '#app', data: {}, methods: { submitForm: function () { var cardNo = $('#cardNo').val(); var password = $('#password').val(); $.ajax({ type: 'post', //默认get url: "/api/user/login.do", data: { cardNo: cardNo, password: <PASSWORD> }, async: true, //是否异步(默认true:异步) dataType: "json",//定义服务器返回的数据类型 success: function (data) {//data服务器返回的json字符串 if (data.success) { window.location.href = '/home.html'; } else { alert(data.errorMsg) } } }); } }, mounted: function () { } });<file_sep>function validate() { var cardNo = $("#cardNo").val(); var password = $("#password").val(); if (!cardNo) { alert("账号不能为空!"); return false; } if (isNaN(cardNo)) { alert("非法的账号!"); return false; } if (!password) { alert("密码不能为空!"); return false; } return true; }
5d7e6565473c8a3fff28d321fd61d2e71cbaa502
[ "JavaScript", "Java", "INI" ]
20
Java
JJSlumen/codeRepository
396b4ec31e42aa316d31aa2eababc1c809bfbdc9
130130d7e69c3515950e15a1b73f6035aad2b1c2
refs/heads/master
<file_sep>using Assets.Classes; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using UnityEngine.SceneManagement; public class Options : MonoBehaviour { [SerializeField] public bool ShowHintBoards = true; [SerializeField] public const int LivesBase = 5; [SerializeField] public int LivesCurrent; [SerializeField] int highestLevel = 0; [SerializeField] int currentHighestLevel; [SerializeField] public int baseForScore = 10; [SerializeField] int score = 0; [SerializeField] int ScoreItemsCount = 5; [SerializeField] List<ScoreItem> scoreList; //caches SceneLoader sceneLoader; public int HighestLevel { get { return highestLevel; } set { if (HighestLevel < value) highestLevel = value; if (value == intconstants.MRBRICKWORM) currentHighestLevel = 8; else currentHighestLevel = value; } } public int Score { get { return score; } set { score = value; } } private void Start() { InicializeCaches(); } private void InicializeCaches() { SceneManager.sceneLoaded += OnScreenLoad; sceneLoader = FindObjectOfType<SceneLoader>(); LivesCurrent = LivesBase; scoreList = new List<ScoreItem>(); } public void AddScore(int newScore) { if (score + newScore < 0) score = 0; else score += newScore; } public void ToggleShowHintBoards() { ShowHintBoards = !ShowHintBoards; } private void OnScreenLoad(Scene loadedScene, LoadSceneMode mode) { ProcessGameData(); } private void ProcessGameData() { if (sceneLoader && !sceneLoader.isCurrentSceneLevel()) { ProcessLives(); if(Score > 0) ProcessScore(); } else if (!sceneLoader) print("Options/ProcessGameData: missing sceneLoader"); } private void ProcessLives() { print("Options/OnScreenLoad: setting LivesCurrent to " + LivesBase); LivesCurrent = LivesBase; } private void ProcessScore() { ScoreItem newScore = new ScoreItem(Score, currentHighestLevel); print("Options/ProcessScore: Score: " + Score + " scoreList.count: " + scoreList.Count + " ScoreItemsCount: " + ScoreItemsCount); Score = 0; if (scoreList.Count > 0) { foreach (ScoreItem record in scoreList) record.isNewRecord = false; for (int i = 0; i < Mathf.Min(scoreList.Count, ScoreItemsCount); i++) { if (scoreList[i].Score < newScore.Score) { print("Options/ProcessScore: adding new score to list at " + i + " position."); scoreList.Insert(i, newScore); if (scoreList.Count > ScoreItemsCount) scoreList.RemoveAt(ScoreItemsCount); break; } } } if (scoreList.Count == 0 || (scoreList.Count < ScoreItemsCount && !scoreList.Contains(newScore))) { print("Options/ProcessScore: Adding score to first empty position"); scoreList.Add(newScore); } } public List<ScoreItem> GetScoreItems() { return scoreList; } private void OnDisable() { SceneManager.sceneLoaded -= OnScreenLoad; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class CreditsButton : MonoBehaviour { public void OnCreditsButtonClick() { SceneLoader SL = FindObjectOfType<SceneLoader>(); if (SL) SL.ManageCreditsSceneView(); else { print("CreditsButton: OnCreditButtonClick: SceneLoader not found"); } } } <file_sep>#pragma warning disable 0414 using Assets.Classes; using System; using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class SceneLoader : MonoBehaviour { [SerializeField] int sceneToReturnTo = 0; [SerializeField] public int SceneToBeLoaded; [SerializeField] public float SplashScreenDelay = 2f; [SerializeField] public float SplScrProlongOffset = 0.75f; //Caches [SerializeField] Button continueButton; Animator splashScreen; Options options; List<string> notLevelScenes = new List<string> { scenes.START, scenes.WIN, scenes.GAME_OVER, scenes.CREDITS }; SoundSystem SFXPlayer; private void OnEnable() { SceneManager.sceneLoaded += OnSceneLoad; } private void Start() { if (splashScreen) splashScreen = FindObjectOfType<SplashScreen>().GetComponent<Animator>(); SFXPlayer = FindObjectOfType<SoundSystem>(); options = FindObjectOfType<Options>(); ManageContinueButtonText(); } public void LoadScene() { int currentSceneIndex = SceneManager.GetActiveScene().buildIndex; FetchLevel(currentSceneIndex + 1); } public void LoadScene(int sceneNr) { FetchLevel(sceneNr); } void FetchLevel(int sceneToBeLoaded) { Debug.Log("SceneLoader/FetchLevel: Loading Screen index: " + (sceneToBeLoaded)); SceneToBeLoaded = sceneToBeLoaded; if (splashScreen) { splashScreen.SetTrigger(triggers.SHOW_UP); } else { print("SceneLoader/FetchLevel: splashScreen not found, fetching level without animation"); SceneManager.LoadScene(sceneToBeLoaded); } } public void LoadFirstScene() { LoadScene(0); } public void QuitApplication() { Application.Quit(); print("Request to quit received"); } public void LoadGameOverScene() { int gameOverSceneNr = sceneIndexFromName(scenes.GAME_OVER); LoadScene(gameOverSceneNr); } public void ManageCreditsSceneView() { Scene currentScreen = SceneManager.GetActiveScene(); int creditsSceneNr = sceneIndexFromName(scenes.CREDITS); //print("SceneLoader/ManageCreditsSceneView: creditsSceneNr: " + creditsSceneNr); if (currentScreen.name != scenes.CREDITS) { sceneToReturnTo = currentScreen.buildIndex; LoadScene(creditsSceneNr); } else if (currentScreen.name == scenes.CREDITS) LoadScene(sceneToReturnTo); } public bool isCurrentSceneLevel() { if (notLevelScenes.Contains(SceneManager.GetActiveScene().name)) return false; return true; } void OnSceneLoad(Scene loadedScene, LoadSceneMode mode) { //print("SceneLoader: scene buildIndex: " + SceneManager.GetActiveScene().buildIndex + " loaded. SceneLoader Hash: " + this.GetHashCode()); ChooseMusicByScene(); RunSplashScreen(); ManageContinueButtonText(); AssignContinueButton(); } private void AssignContinueButton() { if(SceneManager.GetActiveScene().buildIndex == 0 && continueButton == null) { //print("SceneLoader/AssignContinueButton: assigning button"); continueButton = GameObject.Find(gameobjects.CONTINUE_BUTTON).GetComponent<Button>(); continueButton.onClick.AddListener(ContinueButtonClick); } } private void ChooseMusicByScene() { if (SFXPlayer) { if (isCurrentSceneLevel()) SFXPlayer.PlayGameMusic(); else SFXPlayer.PlayMenuMusic(); } //else print("SceneLoader/ChooseMusicByScene: no SFX player found"); } private void RunSplashScreen() { if (!splashScreen) splashScreen = FindObjectOfType<SplashScreen>().GetComponent<Animator>(); if (!options) options = FindObjectOfType<Options>(); if (splashScreen) { if (options.ShowHintBoards && isCurrentSceneLevel()) { //print("SceneLoader/OnSceneLoad: before CORoutine"); StartCoroutine(DelaySplScrFade()); } else splashScreen.SetTrigger(triggers.FADE); } else print("SceneLoader/OnSceneLoad: No splashScreen found"); } public void ManageContinueButtonText() { if (isCurrentSceneName(scenes.START)) { TextMeshProUGUI targetText = GameObject.Find(gameobjects.TARGET_TEXT).GetComponentInChildren<TextMeshProUGUI>(); if (options && targetText) { print("options.highestLevel: " + options.HighestLevel); String levelToGoTo = "Level "; switch (options.HighestLevel) { case -1: case 0: case 1: levelToGoTo += sceneIndexFromName(scenes.FIRST_LEVEL).ToString(); break; case intconstants.MRBRICKWORM: levelToGoTo = scenes.MRBRICKWORM; break; default: levelToGoTo += options.HighestLevel.ToString(); break; } if (!options) print("SceneLoader/ManageContinueButtonText: missing options"); print("SceneLoader/MCBT: targetText: " + levelToGoTo); targetText.text = levelToGoTo; } } } public void ContinueButtonClick() { int targetLevel = 1; if (options) { //print("SceneLoader/ContinueButtonClick: HighestLevel is: " + options.HighestLevel); switch (options.HighestLevel) { case -1: case 0: case 1: targetLevel = intconstants.FIRSTLEVEL; break; case intconstants.MRBRICKWORM: targetLevel = sceneIndexFromName(scenes.MRBRICKWORMLEVEL); break; default: targetLevel = options.HighestLevel; break; } } else if (!options) print("SceneLoader/ContinueButtonClick: missing options"); LoadScene(targetLevel); } IEnumerator DelaySplScrFade() { //print("SceneLoader: DelaySplScrFade - start "); yield return new WaitForSeconds(SplashScreenDelay); //print("SceneLoader: DelaySplScrFade - delayed " + SplashScreenDelay + "s"); splashScreen.SetTrigger(triggers.FADE); } private string NameFromIndex(int BuildIndex) { ///@Author: Iamsodarncool/UnityAnswers string path = SceneUtility.GetScenePathByBuildIndex(BuildIndex); int slash = path.LastIndexOf('/'); string name = path.Substring(slash + 1); int dot = name.LastIndexOf('.'); return name.Substring(0, dot); } private int sceneIndexFromName(string sceneName) { for (int i = 0; i < SceneManager.sceneCountInBuildSettings; i++) { string testedScreen = NameFromIndex(i); //print("SceneLoader/sceneIndexFromName: i: " + i + " sceneName = " + testedScreen); if (testedScreen == sceneName) return i; } return -1; } private bool isCurrentSceneName(String sceneName) { if (SceneManager.GetActiveScene().name == sceneName) return true; return false; } private void OnDisable() { SceneManager.sceneLoaded -= OnSceneLoad; } } <file_sep>#pragma warning disable 0414 using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class SplashScreen : MonoBehaviour { [SerializeField] List<GameObject> messageBoards; //cache MessageBoard chosenMessageBoard = null; private void Start() { SceneManager.sceneLoaded += OnSceneLoadMessageBoard; } void triggerNextLevel() { SceneLoader SL = FindObjectOfType<SceneLoader>(); Options options = FindObjectOfType<Options>(); if (options && options.ShowHintBoards) { ActivateRandomMessageBoard(); } if (SL) SceneManager.LoadScene(SL.SceneToBeLoaded); else print("SplashScreen/triggerNextLevel: SceneLoader not found."); } void ActivateRandomMessageBoard() { deactivateMessageBoards(); messageBoards[Random.Range(0, messageBoards.Count)]. GetComponentInChildren<MessageBoard>().isActive = true; } void deactivateMessageBoards() { foreach (GameObject board in messageBoards) board.GetComponentInChildren<MessageBoard>().isActive = false; } void OnSceneLoadMessageBoard(Scene loadedScene, LoadSceneMode mode) { } private void OnDisable() { SceneManager.sceneLoaded -= OnSceneLoadMessageBoard; } } <file_sep>using Assets.Classes; using Classes; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class PickupManager : MonoBehaviour { [Header("Setup")] [SerializeField] GameObject[] ListOfUsedPickups; [SerializeField] float PickupDropChance = 40f; [SerializeField] float dropCD = 10f; [SerializeField] bool dropOffCD = true; [Header("Glue setup")] [SerializeField] float GlueDuration = 10f; [Header("Laser setup")] [SerializeField] float LaserDuration = 10f; [SerializeField] MagicShot magicShot; [SerializeField] float MagicShotYOffset = 0.2f; [Header("Fireball setup")] [SerializeField] float FireballDuration = 10f; [SerializeField] Sprite FireballSprite; [SerializeField] Sprite NormalBallSprite; [Header("Enlarge setup")] [SerializeField] float EnlargeDuration = 10f; [Header("Multiple setup")] [SerializeField] int MaxBallsSpawnedAtOnce = 10; //[SerializeField] Fireball fireball; //[SerializeField] int GlueCount = 0; //[SerializeField] int LaserCount = 0; //[SerializeField] int FireballCount = 0; //[SerializeField] int EnlargeCount = 0; //status GameSession gameSession; bool isLaserActive = false; bool isEnlargeActive = false; Vector3 MagicShotOffset; private int GlueCount = 0; private int LaserCount = 0; private int FireballCount = 0; private int EnlargeCount = 0; private void Start() { gameSession = FindObjectOfType<GameSession>(); MagicShotOffset = new Vector3(0, MagicShotYOffset, 0); } private void Update() { if (isLaserActive && Input.GetMouseButtonDown(0)) { FireMagicShot(); } } private void FireMagicShot() { MagicBall[] balls = FindObjectsOfType<MagicBall>(); foreach (MagicBall ball in balls) { Instantiate(magicShot, ball.transform.position + MagicShotOffset, Quaternion.identity); } } public GameObject[] GetList() { return ListOfUsedPickups; } public void ProcessPickupChanceOfSpawning(Vector2 spawnPosition) { int chanceRoll = UnityEngine.Random.Range(1, 101); if (dropOffCD && chanceRoll <= PickupDropChance) { SpawnPickup(spawnPosition); StartCoroutine(StartDropCD()); } } IEnumerator StartDropCD() { dropOffCD = false; yield return new WaitForSeconds(dropCD); dropOffCD = true; } private void SpawnPickup(Vector2 spawnPosition) { int chanceRatio = UnityEngine.Random.Range(0, ListOfUsedPickups.Length); Instantiate(ListOfUsedPickups[chanceRatio], spawnPosition, new Quaternion(0, 0, 0, 0)); } public void ApplyEffect(Pickup.PickupType pickupType) { //Debug.Log("Applying effect of Pickup: " + pickupType.ToString()); switch (pickupType) { case (Pickup.PickupType.Glue): StartCoroutine(ActivateGlue()); break; case (Pickup.PickupType.Life): ActivateLife(); break; case (Pickup.PickupType.Laser): StartCoroutine(ActivateLaser()); break; case (Pickup.PickupType.Multiple): ActivateMultiple(); break; case (Pickup.PickupType.Enlarge): StartCoroutine(ActivateEnlarge()); break; case (Pickup.PickupType.Fireball): StartCoroutine(ActivateFireball()); break; } } IEnumerator ActivateFireball() { foreach (Ball ball in FindObjectsOfType<Ball>()) { ball.GetComponent<SpriteRenderer>().sprite = FireballSprite; ball.tag = tags.FIREBALL; foreach(ParticleSystem effect in ball.GetComponentsInChildren<ParticleSystem>()) effect.Play(); //ball.GetComponent<CircleCollider2D>().isTrigger = true; } foreach(Brick brick in FindObjectsOfType<Brick>()) { brick.GetComponent<PolygonCollider2D>().isTrigger = true; } FireballCount++; //print("Activating Fireball"); yield return new WaitForSeconds(FireballDuration); //print("End of waiting" + Time.time); FireballCount--; //print("Laser Count= " + LaserCount); if (FireballCount <= 0) { foreach (Ball ball in FindObjectsOfType<Ball>()) { ball.GetComponent<SpriteRenderer>().sprite = NormalBallSprite; ball.tag = tags.BALL; foreach (ParticleSystem effect in ball.GetComponentsInChildren<ParticleSystem>()) { //print("PickupManager: ActivateFireball: effect name to switch off: " + effect.name); if(effect.name != gameobjects.SPARKLES) effect.Stop(); } } foreach (Brick brick in FindObjectsOfType<Brick>()) { brick.GetComponent<PolygonCollider2D>().isTrigger = false; } //Debug.Log("Suspending Fireball"); } } IEnumerator ActivateEnlarge() { if (!isEnlargeActive) { foreach (EnlargeShield shield in FindObjectsOfType<EnlargeShield>()) { //shield.GetComponent<SpriteRenderer>().enabled = true; shield.GetComponent<Animator>().SetTrigger(triggers.ARRIVE); shield.GetComponent<PolygonCollider2D>().enabled = true; } } EnlargeCount++; isEnlargeActive = true; //print("Start waiting" + Time.time); yield return new WaitForSeconds(EnlargeDuration); //print("End of waiting" + Time.time); EnlargeCount--; //print("Laser Count= " + LaserCount); if (EnlargeCount <= 0) { foreach (EnlargeShield shield in FindObjectsOfType<EnlargeShield>()) { shield.GetComponent<Animator>().SetTrigger(triggers.VANISH); //shield.GetComponent<SpriteRenderer>().enabled = false; shield.GetComponent<PolygonCollider2D>().enabled = false; } //Debug.Log("Suspending Laser"); isEnlargeActive = false; } } private void ActivateMultiple() { if (gameSession.BallAmount() < MaxBallsSpawnedAtOnce + 1) { Ball[] balls = FindObjectsOfType<Ball>(); //Debug.Log("ActivateMultiple(): number of balls in a field: " + balls.Length); foreach (Ball oldBall in balls) { for (int i = 0; i < 3; i++) { Vector2 spawnPosition = new Vector2(Mathf.Clamp(oldBall.transform.position.x + i/10 + 0.2f, 1, 15), Mathf.Clamp(oldBall.transform.position.y + i + 0.2f, 1, 11)); //Vector3 altSpawnPosition = new Vector2(UnityEngine.Random.Range(0.2f, 0.5f), UnityEngine.Random.Range(0.2f, 0.5f)); if (FindObjectsOfType<Ball>().Length < MaxBallsSpawnedAtOnce + 1) { Ball newBall = Instantiate(oldBall, spawnPosition, Quaternion.identity); newBall.isGlueApplied = oldBall.isGlueApplied; newBall.GetComponent<Rigidbody2D>().velocity = oldBall.GetComponent<Rigidbody2D>().velocity; newBall.hasStarted = oldBall.hasStarted; //Debug.Log("ActivateMultiple(): Spawned new Ball, balls total: " + gameSession.BallAmount()); } } } } } IEnumerator ActivateLaser() { if (!isLaserActive) { foreach (MagicBall ball in FindObjectsOfType<MagicBall>()) { ball.GetComponent<Animator>().SetTrigger(triggers.ARRIVE); } } LaserCount++; isLaserActive = true; //print("Start waiting" + Time.time); yield return new WaitForSeconds(LaserDuration); //print("End of waiting" + Time.time); LaserCount--; //print("Laser Count= " + LaserCount); if (LaserCount <= 0) { foreach (MagicBall ball in FindObjectsOfType<MagicBall>()) { ball.GetComponent<Animator>().SetTrigger(triggers.VANISH); } //Debug.Log("Suspending Laser"); isLaserActive = false; } } private void ActivateLife() { //Debug.Log("PickupManager: Activating addLife"); gameSession.AddLife(); } IEnumerator ActivateGlue() { GlueActiveEffect glueEffectOnPaddle = FindObjectOfType<GlueActiveEffect>(); if (glueEffectOnPaddle) { glueEffectOnPaddle.GetComponent<SpriteRenderer>().enabled = true; glueEffectOnPaddle.GetComponent<ParticleSystem>().Play(); } GlueCount++; foreach (Ball ball in FindObjectsOfType<Ball>()) { ball.isGlueApplied = true; } //print("Start waiting" + Time.time); yield return new WaitForSeconds(GlueDuration); //print("End of waiting" + Time.time); GlueCount--; if (GlueCount <= 0) { if (glueEffectOnPaddle) { glueEffectOnPaddle.GetComponent<ParticleSystem>().Stop(); SwitchSpriteOff<GlueActiveEffect>(); } //Debug.Log("Suspending Glue"); foreach (Ball ball in FindObjectsOfType<Ball>()) { ball.isGlueApplied = false; } } } private void SwitchSpriteOff<T>() where T : Component { FindObjectOfType<T>().GetComponent<SpriteRenderer>().enabled = false; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Assets.Classes { public static class intconstants { public const int FIRSTLEVEL = 1; public const int MRBRICKWORM = 1001; } } <file_sep>#pragma warning disable 0414 using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using UnityEngine.EventSystems; public class ResponsiveElementUI : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler { [SerializeField] bool isOver = false; [SerializeField] UnityEvent MouseOver; [SerializeField] UnityEvent MouseLeave; public void OnPointerEnter(PointerEventData eventData) { isOver = true; MouseOver.Invoke(); } public void OnPointerExit(PointerEventData eventData) { isOver = false; MouseLeave.Invoke(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class CleaningAtStart : MonoBehaviour { void Start () { Destroy(GameObject.Find("Game Session")); } }
400895c55ee761ac7f6d0667aefe69aa6d1e532e
[ "C#" ]
8
C#
dqtoy/BrickBreaker
aa66c459f1a2b784b7aafe2000160aa4d3f41183
209e7e19799b14903afd92afebe4c9e02671a844
refs/heads/master
<repo_name>JYASKOWICH/CMPT104-Cssnge<file_sep>/cssnge.js var store; var css; function toggleCSS(css1, css2){ var oldlink = document.getElementsByTagName("link").item(0); var css = oldlink.href.split("/")[oldlink.href.split("/").length - 1] var css1 = css1.substring(1, css1.length) var css2 = css2.substring(1, css2.length) var stem = oldlink.href.substring(0 , oldlink.href.length - css.length -1); if (oldlink.href == stem + css2){ console.log(oldlink.href + " " + stem + css1) var newlink = document.createElement("link"); newlink.setAttribute("rel", "stylesheet"); newlink.setAttribute("type", "text/css"); newlink.setAttribute("href", "." + css1); } else{ console.log(oldlink.href + " " + stem + css2) var newlink = document.createElement("link"); newlink.setAttribute("rel", "stylesheet"); newlink.setAttribute("type", "text/css"); newlink.setAttribute("href", "." + css2); } document.getElementsByTagName("head").item(0).replaceChild(newlink, oldlink); } function setCSS(css1){ var oldlink = document.getElementsByTagName("link").item(0); var newlink = document.createElement("link"); newlink.setAttribute("rel", "stylesheet"); newlink.setAttribute("type", "text/css"); newlink.setAttribute("href", "." + css1); document.getElementsByTagName("head").item(0).replaceChild(newlink, oldlink); } <file_sep>/README.md # CMPT104-Cssnge A Simple Javascript file created for CMPT 104
6823dc0e5b29f6a19dc8dd9ef06a16698a1ae722
[ "JavaScript", "Markdown" ]
2
JavaScript
JYASKOWICH/CMPT104-Cssnge
b659e853ee3563aa058dae6e9da8dd7c23f770d8
d8df9656474389ea8fa70c301de6bbdd78cdec20
refs/heads/master
<file_sep>//nõuame seda supereheroes paketti,mida tõmbasime //let superheroes = require("superheroes"); //see on omadus ja tema meetod //console.log(superheroes.all); //loome uue muutuja randomhero ja proovime console.logiga kuvada //console.log(superheroes.random()); //foraech t;;tab ainult massiiviga //superheroes.all.forEach(hero => { // console.log(hero); //}); const supervillains = require("supervillains"); //console.log(supervillains.all); //console.log(supervillains.random()); const supereheroes = require("superheroes"); //console.log(supervillains.random()); supervillains.all.forEach(supervillain => { console.log(supervillain); }); console.log(`${superheroes.random()} fights ${supervillains.random()}`);
a8f7364e64771a06da4ac38dbaa2fd1a3ecc61d1
[ "JavaScript" ]
1
JavaScript
maarjaryytel/superheroes
56296bf805eb139e3a8091b0dc419cffa7b610ec
3b7e67b80c431fef0aade5d4526b94fd10d9d5fa
refs/heads/master
<repo_name>opteroncx/TAN<file_sep>/model8b8x.py # -*- coding:utf-8 -*- import torch import torch.nn as nn import numpy as np import math class MeanShiftY(nn.Conv2d): def __init__(self, y_mean, y_std, sign=-1): super(MeanShiftY, self).__init__(1, 1, kernel_size=1) std = torch.Tensor(y_std) self.weight.data = torch.eye(1).view(1, 1, 1, 1) self.weight.data.div_(std.view(1, 1, 1, 1)) self.bias.data = sign * torch.Tensor(y_mean) self.bias.data.div_(std) self.requires_grad = False class upsample_block(nn.Module): def __init__(self,in_channels,out_channels): super(upsample_block,self).__init__() self.conv = nn.Conv2d(in_channels,out_channels,3,stride=1,padding=1) self.shuffler = nn.PixelShuffle(2) self.prelu = nn.PReLU() def forward(self,x): return self.prelu(self.shuffler(self.conv(x))) class make_mix(nn.Module): def __init__(self, nChannels, growthRate, kernel_size=3): super(make_mix, self).__init__() # self.conv = nn.Conv2d(nChannels, growthRate, kernel_size=kernel_size, padding=(kernel_size-1)//2, bias=False) self.conv1 = nn.Conv2d(nChannels, growthRate, kernel_size=3, padding=1, bias=False) self.conv2 = nn.Conv2d(nChannels, growthRate, kernel_size=5, padding=2, bias=False) self.relu1 = nn.PReLU() self.relu2 = nn.PReLU() self.frm = FRM(growthRate,growthRate) self.channels = nChannels # kernel attention # self.ka = KAM(growthRate,growthRate) self.krelu = nn.PReLU() self.squeeze = nn.AdaptiveAvgPool2d(1) self.conv_down = nn.Conv2d(growthRate, growthRate // 4, kernel_size=1, bias=False) self.conv_up = nn.Conv2d(growthRate // 4, growthRate, kernel_size=1, bias=False) self.sig = nn.Sigmoid() def forward(self, x): # original channel=64,growth rate=32 y1 = self.relu1(self.conv1(x)) y2 = self.relu2(self.conv2(x)) y = y1+y2 ks = self.squeeze(y) cd = self.krelu(self.conv_down(ks)) cu = self.conv_up(cd) w = self.sig(cu) y1 = y1*w y2 = y2*w y = y1+y2 y = self.frm(y) x_left = x[:,0:self.channels-32,:,:] x_right = x[:,self.channels-32:self.channels,:,:] y_left = y[:,0:32,:,:] y_right = y[:,32:64,:,:] iden = x_left addi = x_right+y_left tmp = torch.cat((iden,addi),1) out = torch.cat((tmp,y_right),1) return out # Mixed Link Block architecture class MLB(nn.Module): def __init__(self, nChannels, nDenselayer, growthRate): super(MLB, self).__init__() nChannels_ = nChannels modules = [] for i in range(nDenselayer): modules.append(make_mix(nChannels_, growthRate)) nChannels_ += 32 self.dense_layers = nn.Sequential(*modules) # reshape the channel size self.conv_1x1 = nn.Conv2d(nChannels_, nChannels, kernel_size=1, padding=0, bias=False) self.frm = FRM(nChannels,nChannels) def forward(self, x): out = self.dense_layers(x) out = self.conv_1x1(out) out = out + self.frm(x) return out class FRM(nn.Module): '''The feature recalibration module''' def __init__(self,inChannels,outChannels): super(FRM, self).__init__() self.swish = nn.Sigmoid() self.channel_squeeze = nn.AdaptiveAvgPool2d(1) self.conv_down = nn.Conv2d(inChannels * 4, inChannels // 4, kernel_size=1, bias=False) self.conv_up = nn.Conv2d(inChannels // 4, inChannels * 4, kernel_size=1, bias=False) self.sig = nn.Sigmoid() self.trans1 = nn.Sequential( nn.Conv2d(in_channels=inChannels, out_channels=inChannels * 4, kernel_size=1, stride=1, padding=0, bias=False), nn.PReLU(), ) self.trans2 = nn.Sequential( nn.Conv2d(in_channels=inChannels * 4, out_channels=outChannels, kernel_size=1, stride=1, padding=0, bias=False), nn.PReLU(), ) def forward(self, x): ex = self.trans1(x) out1 = self.channel_squeeze(ex) out1 = self.conv_down(out1) # swish out1 = out1*self.swish(out1) out1 = self.conv_up(out1) weight = self.sig(out1) out=ex*weight out=self.trans2(out) return out class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.sub_mean = MeanShiftY([0.43806],[1.0]) self.add_mean = MeanShiftY([0.43806],[1.0],1) self.conv_input = nn.Conv2d(in_channels=1, out_channels=64, kernel_size=3, stride=1, padding=1, bias=False) self.conv_input2 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1, bias=False) self.relu = nn.PReLU() self.u1 = upsample_block(64,64*4) self.u2 = upsample_block(64,64*4) self.u3 = upsample_block(64,64*4) self.ures1 = upsample_block(64,64*4) self.ures2 = upsample_block(64,64*4) self.ures3 = upsample_block(64,64*4) self.sa = nn.Conv2d(in_channels=128, out_channels=1, kernel_size=1, stride=1, padding=0, bias=False) self.conv_G = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=1, stride=1, padding=0, bias=False) self.convt_R1 = nn.Conv2d(in_channels=64, out_channels=1, kernel_size=3, stride=1, padding=1, bias=False) # add multi supervise self.convt_F11 = MLB(64, 4, 64) self.convt_F12 = MLB(64, 4, 64) self.convt_F13 = MLB(64, 4, 64) self.convt_F14 = MLB(64, 4, 64) self.convt_F15 = MLB(64, 4, 64) self.convt_F16 = MLB(64, 4, 64) self.convt_F17 = MLB(64, 4, 64) self.convt_F18 = MLB(64, 4, 64) self.convt_shape1 = nn.Conv2d(in_channels=64, out_channels=1, kernel_size=3, stride=1, padding=1, bias=False) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) if m.bias is not None: m.bias.data.zero_() def forward(self, x): x = self.sub_mean(x) out = self.relu(self.conv_input(x)) conv1 = self.conv_input2(out) convt_F11 = self.convt_F11(conv1) convt_F12 = self.convt_F12(convt_F11) convt_F13 = self.convt_F13(convt_F12) convt_F14 = self.convt_F14(convt_F13) convt_F15 = self.convt_F15(convt_F14) convt_F16 = self.convt_F16(convt_F15) convt_F17 = self.convt_F17(convt_F16) convt_F18 = self.convt_F18(convt_F17) # multi supervise convt_F = [convt_F11,convt_F12,convt_F13,convt_F14,convt_F15,convt_F16,convt_F17,convt_F18] u1 = self.u1(out) u2 = self.u2(u1) u3 = self.u3(u2) u3 = self.convt_shape1(u3) HR = [] HUR = [] for i in range(len(convt_F)): # edge attention res1 = self.ures1(convt_F[i]) res2 = self.ures2(res1) res3 = self.ures3(res2) G = self.conv_G(res3) g1 = G[:,0:64,:,:] g2 = G[:,64:128,:,:] gu1 = self.sa(G) ga = g1*gu1 # combine gc = (ga+g2)/2 convt_R1 = self.convt_R1(gc) tmp = u3 + convt_R1 tmp = self.add_mean(tmp) HR.append(tmp) HUR.append(convt_R1) return HR,u2,HUR class ScaleLayer(nn.Module): def __init__(self, init_value=0.25): super(ScaleLayer,self).__init__() self.scale = nn.Parameter(torch.FloatTensor([init_value])) def forward(self, input): return input * self.scale class L1_Charbonnier_loss(nn.Module): """L1 Charbonnierloss.""" def __init__(self): super(L1_Charbonnier_loss, self).__init__() self.eps = 1e-6 def forward(self, X, Y): diff = torch.add(X, -Y) error = torch.sqrt( diff * diff + self.eps ) loss = torch.sum(error) return loss <file_sep>/main.py # -*- coding:utf-8 -*- import argparse, os import torch import random import torch.backends.cudnn as cudnn import torch.nn as nn import torch.optim as optim from torch.autograd import Variable from torch.utils.data import DataLoader from model6b import Net, L1_Charbonnier_loss,ScaleLayer from dataset import DatasetFromHdf5 # Training settings parser = argparse.ArgumentParser(description="TAN") parser.add_argument("--batchSize", type=int, default=60, help="training batch size") parser.add_argument("--nEpochs", type=int, default=100, help="number of epochs to train for") parser.add_argument("--lr", type=float, default=1e-4, help="Learning Rate. Default=1e-4") parser.add_argument("--step", type=int, default=40, help="Sets the learning rate to the initial LR decayed by momentum every n epochs, Default: n=10") parser.add_argument("--cuda", action="store_true", help="Use cuda?") parser.add_argument("--resume", default="", type=str, help="Path to checkpoint (default: none)") parser.add_argument("--start-epoch", default=1, type=int, help="Manual epoch number (useful on restarts)") parser.add_argument("--threads", type=int, default=1, help="Number of threads for data loader to use, Default: 1") parser.add_argument("--momentum", default=0.9, type=float, help="Momentum, Default: 0.9") parser.add_argument("--weight-decay", "--wd", default=1e-4, type=float, help="weight decay, Default: 1e-4") parser.add_argument("--pretrained", default="", type=str, help="path to pretrained model (default: none)") def main(): global opt, model opt = parser.parse_args() print(opt) cuda = opt.cuda if cuda and not torch.cuda.is_available(): raise Exception("No GPU found, please run without --cuda") opt.seed = random.randint(1, 10000) print("Random Seed: ", opt.seed) torch.manual_seed(opt.seed) if cuda: torch.cuda.manual_seed(opt.seed) cudnn.benchmark = True print("===> Loading datasets") train_set = DatasetFromHdf5("../../../data3/DIV2K/2x_4x/div2k.h5") training_data_loader = DataLoader(dataset=train_set, num_workers=opt.threads, batch_size=opt.batchSize, shuffle=True) print("===> Building model") model = Net() criterion = L1_Charbonnier_loss() print("===> Setting GPU") if cuda: model=nn.DataParallel(model,device_ids=[0,1,2]).cuda() criterion = criterion.cuda() else: model = model.cpu() loadmultiGPU = True if opt.resume: if os.path.isfile(opt.resume): print("=> loading checkpoint '{}'".format(opt.resume)) checkpoint = torch.load(opt.resume) opt.start_epoch = checkpoint["epoch"] + 1 saved_state = checkpoint["model"].state_dict() # multi gpu loader if loadmultiGPU: from collections import OrderedDict new_state_dict = OrderedDict() for k, v in saved_state.items(): namekey = 'module.'+k new_state_dict[namekey] = v model.load_state_dict(new_state_dict) else: model.load_state_dict(saved_state) else: print("=> no checkpoint found at '{}'".format(opt.resume)) # optionally copy weights from a checkpoint if opt.pretrained: if os.path.isfile(opt.pretrained): print("=> loading model '{}'".format(opt.pretrained)) weights = torch.load(opt.pretrained) pretrained_dict = weights['model'].state_dict() model_dict = model.state_dict() pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict} model_dict.update(pretrained_dict) model.load_state_dict(model_dict) else: print("=> no model found at '{}'".format(opt.pretrained)) print("===> Setting Optimizer") optimizer = optim.Adam(model.parameters(), lr=opt.lr) print("===> Training") for epoch in range(opt.start_epoch, opt.nEpochs + 1): train(training_data_loader, optimizer, model, criterion, epoch) save_checkpoint(model, epoch) def adjust_learning_rate(optimizer, epoch): """Sets the learning rate to the initial LR decayed by 10 every 100 epochs""" lr = opt.lr * (0.1 ** (epoch // opt.step)) return lr def train(training_data_loader, optimizer, model, criterion, epoch): lr = adjust_learning_rate(optimizer, epoch-1) for param_group in optimizer.param_groups: param_group["lr"] = lr print("epoch =", epoch,"lr =",optimizer.param_groups[0]["lr"]) model.train() for iteration, batch in enumerate(training_data_loader, 1): input=Variable(batch[0]) label_x2 = Variable(batch[1], requires_grad=False) label_x4 = Variable(batch[2], requires_grad=False) label_x8 = Variable(batch[3], requires_grad=False) if opt.cuda: input = input.cuda() label_x2 = label_x2.cuda() label_x4 = label_x4.cuda() label_x8 = label_x8.cuda() HR= model(label_x2) SLoss = layerLoss(HR, label_x8 ,criterion) loss = SLoss optimizer.zero_grad() SLoss.backward() optimizer.step() if iteration%100 == 0: print("===> Epoch[{}]({}/{}): Loss: {:.10f}".format(epoch, iteration, len(training_data_loader), loss.item())) def save_checkpoint(model, epoch): model_folder = "checkpoints/" model_out_path = model_folder + "model_epoch_{}.pth".format(epoch) state = {"epoch": epoch ,"model": model} if not os.path.exists(model_folder): os.makedirs(model_folder) torch.save(state, model_out_path) print("Checkpoint saved to {}".format(model_out_path)) def layerLoss(imglist,img,criterion): loss=0 for i in range(len(imglist)): l=criterion(imglist[i], img) loss+=l return loss/len(imglist) def genWeights(num): scales=[] for i in range(num): scale = ScaleLayer() scale.cuda() scales.append(scale) return scales if __name__ == "__main__": main()<file_sep>/train.sh CUDA_VISIBLE_DEVICES=0,1,2 python3 main.py --cuda --nEpochs 100<file_sep>/README.md # TAN Code for paper Triple-Attention Mixed-Link Network for Single-Image Super-Resolution
4f445faf93e72856a20a831702302ef3056f7950
[ "Markdown", "Python", "Shell" ]
4
Python
opteroncx/TAN
1ce1674d9c846bce22f31fdb95fb54996ebf8aa4
70d9102f8b7b0799810fd8d73e9bebf8f05b65f2
refs/heads/master
<file_sep>using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Text.RegularExpressions; using System.IO; using System.Xml.XPath; using System.Xml; using System.Web; using System.Xml.Linq; using System.Globalization; using System.Windows.Forms; using Microsoft.AppEx.Ingestion.Utilities; namespace HuojinTool { public partial class Form1 : Form { XmlProcessor XmlPro = new XmlProcessor(); List<FileInfo> fileInfolist = new List<FileInfo>(); List<Article> articles = new List<Article>(); public Form1() { InitializeComponent(); } private void btnRun_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(richTextBox.Text) & !string.IsNullOrEmpty(this.txtProvider.Text) & !string.IsNullOrEmpty(this.txtMarket.Text) &!string.IsNullOrEmpty(this.txtWebPageID.Text)) { var IsIncludeEntityList = rbArticleAndEntityList.Checked ? true : false; foreach (string str in richTextBox.Lines) { var article = new Article(cmboxDC.SelectedValue.ToString(), cmboxApp.SelectedValue.ToString(), str, cmboxFeedType.SelectedValue.ToString(), txtProvider.Text.Trim(), txtMarket.Text.Trim(),txtWebPageID.Text.Trim(), IsIncludeEntityList); //var doc=XmlPro.LoadFeed(str); //XmlPro.ValidateFeed(doc, ref article); articles.Add(article); } XamlProcessor xamlPro = new XamlProcessor(); xamlPro.Generate(this.articles[0]); TsvProcessor tsvPro = new TsvProcessor(); tsvPro.Generate(this.articles); IniProcessor iniPro = new IniProcessor(); iniPro.Generate(this.articles[0]); XmlProcessor xmlPro = new XmlProcessor(); xmlPro.Generate(this.articles); } else { MessageBox.Show("FeedUrl and Provider can not empty"); } } private void Form1_Load(object sender, EventArgs e) { txtProvider.Text = "ABC"; txtMarket.Text = "en-gb"; txtWebPageID.Text = "250036798"; List<DictionaryEntry> DCList = new List<DictionaryEntry>(); DCList.Add(new DictionaryEntry("EMEA", "EMEA")); DCList.Add(new DictionaryEntry("BLU", "BLU")); DCList.Add(new DictionaryEntry("SG", "SG")); DCList.Add(new DictionaryEntry("JP", "JP")); this.cmboxDC.DataSource = DCList; this.cmboxDC.DisplayMember = "Key"; this.cmboxDC.ValueMember = "Value"; List<DictionaryEntry> AppList = new List<DictionaryEntry>(); AppList.Add(new DictionaryEntry("News", "News")); AppList.Add(new DictionaryEntry("Sports", "Sports")); AppList.Add(new DictionaryEntry("Finance", "Finance")); AppList.Add(new DictionaryEntry("Travel", "Travel")); this.cmboxApp.DataSource = AppList; this.cmboxApp.DisplayMember = "Key"; this.cmboxApp.ValueMember = "Value"; List<DictionaryEntry> ContentTypeList = new List<DictionaryEntry>(); XmlDocument xmlConfig = XmlHelper.LoadXmlFromFileorPath(System.Environment.CurrentDirectory + @"\ConfigMetaData.xml"); if (xmlConfig != null & xmlConfig.HasChildNodes) { var contenttypelist = xmlConfig.SelectNodes("root/ContentType"); foreach (XmlNode node in contenttypelist) { ContentTypeList.Add(new DictionaryEntry(node.Attributes["FeedType"].Value, node.Attributes["FeedType"].Value)); } this.cmboxFeedType.DataSource = ContentTypeList; this.cmboxFeedType.DisplayMember = "Key"; this.cmboxFeedType.ValueMember = "Value"; } } } } <file_sep> namespace Microsoft.AppEx.Ingestion.Utilities { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; using System.Xml; public class XmlHelper { public static XmlDocument LoadXmlFromFileorPath(string FileorPath) { FileorPath = FileorPath.Trim(); XmlDocument xmldoc = new XmlDocument(); if (FileorPath.EndsWith(".xml", StringComparison.InvariantCultureIgnoreCase)) { try { xmldoc.Load(FileorPath); return xmldoc; } catch (Exception ex) { throw ex; } } else { return null; } } /// <summary> /// Get a value of some xpath from node /// </summary> /// <param name="element">XMl node of document</param> /// <param name="xpath">path to traverse</param> /// <returns>value of path</returns> public static string GetFromElement(XElement element, string xpath) { string ret = null; //XElement selectedElement = element.XPathSelectElement(xpath); //if (selectedElement != null) //{ // ret = selectedElement.Value; //} return ret; } /// <summary> /// Get a value of some xpath from node /// </summary> /// <param name="node">XMl node of document</param> /// <param name="xpath">path to traverse</param> /// <returns>value of path</returns> public static string GetFromNode(XmlNode node, string xpath, XmlNamespaceManager xmlnsManager=null, bool text=true, bool isNtoSpace=false) { string ret = string.Empty; if (!string.IsNullOrEmpty(xpath)) { XmlNode selectedNode = node.SelectSingleNode(xpath, xmlnsManager); if (selectedNode != null && selectedNode.InnerText != null) { if (text) { ret = selectedNode.InnerText.Trim(); // Bug 444455: Trim() used to remove empty space at the begining and End which was causing misalignment. } else { ret = selectedNode.InnerXml.Trim(); } } if (isNtoSpace) { return HTMLAgilityUtils.replaceNWithSpace(ret); } else { return HTMLAgilityUtils.removeNRT(ret); } } return ret; } public static string GetOuterXmlFromNode(XmlNode node, string xpath, XmlNamespaceManager xmlnsManager = null) { string ret = string.Empty; XmlNode selectedNode = node.SelectSingleNode(xpath, xmlnsManager); if (selectedNode != null) { ret = selectedNode.OuterXml; } return HTMLAgilityUtils.removeNRT(ret); } /// <summary> /// Get a vaule from complet xml document /// </summary> /// <param name="doc">Loaded xml document</param> /// <param name="nodeName">Path of node</param> /// <param name="xmlnsManager">namespace manager</param> /// <returns>value of path</returns> public static string GetFromXML(XmlDocument doc, string nodeName, System.Xml.XmlNamespaceManager xmlnsManager=null, bool text=true) { string temp = string.Empty; XmlNode node = null; if (xmlnsManager != null) { node = doc.SelectSingleNode(nodeName, xmlnsManager); } else { node = doc.SelectSingleNode(nodeName); } if (node != null) { temp = text ? node.InnerText : node.InnerXml; } return HTMLAgilityUtils.removeNRT(temp); } public static string GetAttributeFromNode(XmlNode node, string attribute, XmlNamespaceManager xmlnsManager=null) { if (node != null && node.Attributes[attribute] != null && !string.IsNullOrEmpty(node.Attributes[attribute].Value)) { return node.Attributes[attribute].Value; } return null; } public static string RemoveXmlTag(string xmlContent) { string contentToReturn = xmlContent; // TODO: to use a regex string removal = "<?xml version=\"1.0\" encoding=\"utf-16\"?>"; if (!string.IsNullOrEmpty(xmlContent)) { contentToReturn = xmlContent.Replace(removal, string.Empty); } return contentToReturn; } public static string GetAttributeAndNode(XmlNode node, XmlNamespaceManager xmlnsManager, string xpath, string attribute) { string data = string.Empty; XmlNode askedNode = node.SelectSingleNode(xpath, xmlnsManager); if (askedNode != null) { data = XmlHelper.GetAttributeFromNode(askedNode, attribute, xmlnsManager); } return HTMLAgilityUtils.removeNRT(data); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Text.RegularExpressions; using System.IO; using System.Xml.XPath; using System.Xml; using System.Web; using System.Xml.Linq; using System.Globalization; using System.Windows.Forms; using Microsoft.AppEx.Ingestion.Utilities; namespace HuojinTool { class TsvProcessor { public void Generate(List<Article> articles) { StringBuilder sb = new StringBuilder(); foreach (Article article in articles) { sb.AppendLine(article.FeedUrl); } OpFile.WriteStringToFile(articles[0].Folder, articles[0].TsvOutputFileName, sb.ToString()); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Text.RegularExpressions; using System.IO; using System.Xml.XPath; using System.Xml; using System.Web; using System.Xml.Linq; using System.Globalization; using System.Windows.Forms; using Microsoft.AppEx.Ingestion.Utilities; namespace HuojinTool { public class Article { public XmlDocument ConfigMetaData = XmlHelper.LoadXmlFromFileorPath(System.Environment.CurrentDirectory + @"\ConfigMetaData.xml"); public Bedrock bedrock; public DirectoryInfo Folder { get; set; } public string TsvSampleFileName { get; set; } public string XamlSampleFileName { get; set; } public string IniSampleFileName { get; set; } public string XmlSampleFileName { get; set; } public string TsvOutputFileName { get; set; } public string XamlOutputFileName { get; set; } public string IniOutputFileName { get; set; } public string XmlOutputFileName { get; set; } public string WebService { get; set; } public string SiteId { get; set; } public string ParentFolderId { get; set; } public string App { get; set; } public string FeedUrl { get; set; } public string FeedType { get; set; } public string Provider { get; set; } public string Market { get; set; } public string WebPageID { get; set; } public bool IsIncludeEntityList { get; set; } public string Title { get; set; } public string Abstract { get; set; } public string SubTitle { get; set; } public string Author { get; set; } public string Published { get; set; } public string Updated { get; set; } public string Body { get; set; } public string MoreLink { get; set; } public Image Image { get; set; } public Article(string datacenter, string app, string feedurl,string feedtype,string provider,string market,string webpageid,bool isincludeentitylist) { bedrock = new Bedrock(); this.WebService = bedrock.WebService[datacenter]; this.SiteId = bedrock.SiteId[datacenter]; this.ParentFolderId = bedrock.ParentFolderId[datacenter]; this.App = app; this.FeedUrl = feedurl; this.FeedType = feedtype; this.Provider = provider; this.Market = market; this.WebPageID = webpageid; this.IsIncludeEntityList = isincludeentitylist; this.Folder = new DirectoryInfo(System.Environment.CurrentDirectory + @"\" + provider + app); this.TsvOutputFileName = this.Folder.FullName + @"\" + this.Provider + this.App + "Generic.tsv"; this.XamlOutputFileName = this.Folder.FullName + @"\" + this.Provider + this.App + "Generic.xaml"; this.IniOutputFileName = this.Folder.FullName + @"\" + this.Provider + this.App + "Generic.xaml.params.ini"; this.XmlOutputFileName = this.Folder.FullName + @"\" + this.Provider + this.App + "GenericConfig.xml"; if (ConfigMetaData != null & ConfigMetaData.HasChildNodes) { XmlNode itemNode = ConfigMetaData.SelectSingleNode("root/ContentType[@FeedType='" + feedtype + "']/ConfiguationLocation"); this.XamlSampleFileName = itemNode.SelectSingleNode("XamlFile").InnerXml; this.IniSampleFileName = itemNode.SelectSingleNode("IniFile").InnerXml; this.TsvSampleFileName = itemNode.SelectSingleNode("TsvFile").InnerXml; this.XmlSampleFileName = itemNode.SelectSingleNode("XmlFile").InnerXml; } } public Article(string webservice, string app, string feedurl, string provider) { this.WebService = webservice; this.App = app; this.FeedUrl = feedurl; this.Provider = provider; } } public class Image { public string Url { get; set; } public string Copyright { get; set; } public string Attribution { get; set; } public string Alttext { get; set; } public string Imgtext { get; set; } } public class Bedrock { public Dictionary<string, string> WebService = new Dictionary<string, string>(); public Dictionary<string, string> SiteId = new Dictionary<string, string>(); public Dictionary<string, string> ParentFolderId = new Dictionary<string, string>(); public Bedrock() { WebService.Add("EMEA", "http://bedrockemea:202/Editorial/WebServices"); WebService.Add("BLU", "http://bedrockblu:616/Editorial/WebServices"); WebService.Add("SG", "http://bedrocksg:414/Editorial/WebServices"); WebService.Add("JP", "http://bedrockjp:616/Editorial/WebServices"); SiteId.Add("EMEA", "250000715"); SiteId.Add("BLU", "32125811"); SiteId.Add("SG", "250000216"); SiteId.Add("JP", "250000217"); ParentFolderId.Add("EMEA", "250046960"); ParentFolderId.Add("BLU", "265439458"); ParentFolderId.Add("SG", "250033251"); ParentFolderId.Add("JP", "250007877"); } } } <file_sep>[Main] ; default value ArgFeedUrlList=/local/AppEx/Ingestion/ConfigData/{App}/dev/{TsvFile} SDP-Int-Ch1$ArgFeedUrlList=/local/AppEx/Ingestion/ConfigData/{App}/int/{TsvFile} SDP-Prod-Ch1$ArgFeedUrlList=/local/AppEx/Ingestion/ConfigData/{App}/prod/{TsvFile} DevMachine$ArgFeedUrlList=/local/AppEx/Ingestion/ConfigData/{App}/dev/{TsvFile} ARG_FEED_CONFIG_FILE_PATH=/local/AppEx/Ingestion/ConfigData/{App}/dev/{ConfigFile} SDP-Int-Ch1$ARG_FEED_CONFIG_FILE_PATH=/local/AppEx/Ingestion/ConfigData/{App}/int/{ConfigFile} SDP-Prod-Ch1$ARG_FEED_CONFIG_FILE_PATH=/local/AppEx/Ingestion/ConfigData/{App}/prod/{ConfigFile} DevMachine$ARG_FEED_CONFIG_FILE_PATH=/local/AppEx/Ingestion/ConfigData/{App}/dev/{ConfigFile} ARG_CACHE_ENVIRONMENT={App}/dev/{Environment}Article SDP-Int-Ch1$ARG_CACHE_ENVIRONMENT={App}/int/{Environment}Article SDP-Prod-Ch1$ARG_CACHE_ENVIRONMENT={App}/prod/{Environment}Article DevMachine$ARG_CACHE_ENVIRONMENT={App}/dev/{Environment}Article ARG_ARTICLE_PROCESSOR=Microsoft.AppEx.Ingestion.CommonScopeUtilities.dll:Microsoft.AppEx.Ingestion.CommonScopeUtilities.AppexGenericContentProcessor<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Text.RegularExpressions; using System.IO; using System.Xml.XPath; using System.Xml; using System.Web; using System.Xml.Linq; using System.Globalization; using System.Windows.Forms; using Microsoft.AppEx.Ingestion.Utilities; using System.Xml.XPath; namespace HuojinTool { public class ConfigurationCreateProcessor { } public class XamlProcessor { public void Generate(Article article) { FileInfo fi = new FileInfo(article.XamlSampleFileName); if (fi.Extension == ".xaml") { if (!string.IsNullOrEmpty(OpFile.GetFileToString(fi))) { var str = OpFile.GetFileToString(fi); str = str.Replace("{0}", article.Provider + article.App + "Generic"); OpFile.WriteStringToFile(article.Folder, article.XamlOutputFileName, str); } else { MessageBox.Show("Can not loading the xaml file."); } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Text.RegularExpressions; using System.IO; using System.Xml.XPath; using System.Xml; using System.Web; using System.Xml.Linq; using System.Globalization; using System.Windows.Forms; using Microsoft.AppEx.Ingestion.Utilities; namespace HuojinTool { class OpFile { public static string GetFileToString(FileInfo fi) { try { using (StreamReader sr = fi.OpenText()) { var str = sr.ReadToEnd(); sr.Close(); return str; } } catch (Exception ex) { MessageBox.Show(ex.Message); return null; } } public static XmlDocument GetFileToXml(string filename) { try { var xmldoc = new XmlDocument(); xmldoc.Load(filename); return xmldoc; } catch (Exception ex) { MessageBox.Show(ex.Message); return null; } } public static void WriteStringToXaml(string data, Article article) { if (string.IsNullOrEmpty(data) && article != null) { WriteStringToFile(article.Folder, article.XamlOutputFileName, data); } } public static void WriteStringToTsv(string data, Article article) { if (string.IsNullOrEmpty(data) && article != null) { WriteStringToFile(article.Folder, article.TsvOutputFileName, data); } } public static void WriteStringToIni(string data, Article article) { if (string.IsNullOrEmpty(data) && article != null) { WriteStringToFile(article.Folder, article.IniOutputFileName, data); } } public static void WriteStringToXml(string data, Article article) { if (string.IsNullOrEmpty(data) && article != null) { WriteStringToFile(article.Folder, article.XmlOutputFileName, data); } } public static void WriteStringToFile(DirectoryInfo folder,string filename,string data) { if (!string.IsNullOrEmpty(filename) && !string.IsNullOrEmpty(data)) { if (!folder.Exists) { folder.Create(); } try { using (FileStream fs = new FileStream(filename, FileMode.Create)) { using (StreamWriter sw = new StreamWriter(fs)) { sw.Write(data); sw.Close(); } } } catch (Exception ex) { MessageBox.Show(ex.Message); return; } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Threading.Tasks; using System.Text.RegularExpressions; using System.IO; using System.Xml.XPath; using System.Xml; using System.Web; using System.Xml.Linq; using System.Globalization; using System.Windows.Forms; using Microsoft.AppEx.Ingestion.Utilities; namespace HuojinTool { public class XmlProcessor { public XmlDocument LoadFeed(string feedurl) { var xmldoc = new XmlDocument(); try { xmldoc.Load(feedurl); } catch (XmlException ex) { MessageBox.Show(ex.Message); } return xmldoc; } public void Generate(List<Article> articles) { StringBuilder sb = new StringBuilder(); var samplexml = OpFile.GetFileToXml(articles[0].XmlSampleFileName); if (samplexml != null) { //var node = samplexml.SelectSingleNode("PartnerConfig/FeedConfig/Feed[@href='default']/ContentConfig[@type='article']/UniqueContentId/DefaultPrefix"); var feedRootNode = samplexml.SelectSingleNode("PartnerConfig/FeedConfig"); var bedrockRootNode = samplexml.SelectSingleNode("PartnerConfig/BedrockConfig"); //var feedNode = articles[0].ConfigMetaData.SelectSingleNode("root/ContentType[@FeedType='" + articles[0].FeedType + "']/Feed"); foreach(Article article in articles) { //var guidNode = itemNode.SelectSingleNode("//DefaultPrefix"); //guidNode.InnerText= article.Market + "." + article.App + "." + article.Provider; //samplexml.ImportNode( var feedNode = GenerateFeed(article); feedNode = samplexml.ImportNode(feedNode, true); feedRootNode.AppendChild(feedNode); var articleNode = this.GenerateArticleFeed(article); articleNode = samplexml.ImportNode(articleNode, true); bedrockRootNode.AppendChild(articleNode); } samplexml.Save(articles[0].XmlOutputFileName); } else { MessageBox.Show("Can not loading the xaml file."); } } public XmlNode GenerateFeed(Article article) { var itemNode = article.ConfigMetaData.SelectSingleNode("root/ContentType[@FeedType='" + article.FeedType + "']/Feed"); itemNode.Attributes["href"].Value = HttpUtility.HtmlEncode(article.FeedUrl); itemNode.SelectSingleNode("//DefaultPrefix").InnerText = article.Market + "." + article.App + "." + article.Provider; return itemNode; } public XmlNode GenerateArticleFeed(Article article) { var itemNode = article.ConfigMetaData.SelectSingleNode("root/ContentType[@FeedType='" + article.FeedType + "']/ArticleFeed"); itemNode.Attributes["href"].Value = HttpUtility.HtmlEncode(article.FeedUrl); itemNode.SelectSingleNode("SiteId").InnerText = article.SiteId; itemNode.SelectSingleNode("ParentFolderId").InnerText = article.ParentFolderId; itemNode.SelectSingleNode("WebPageID").InnerText = article.WebPageID; itemNode.SelectSingleNode("FolderPath").InnerText = string.Format("BingDaily/{0}/{1}/{2}/topStories/Article", article.Market, article.App, article.Provider); itemNode.SelectSingleNode("Market").InnerText = article.Market; return itemNode; } //public void ValidateFeed(XmlDocument xmldoc, ref Article article) //{ // if (xmldoc != null) // { // var newsitemlist = xmldoc.SelectNodes("NewsML/NewsItem"); // foreach (XmlNode newitem in newsitemlist) // { // var morelink = newitem.SelectSingleNode("NewsComponent/NewsComponent/NewsComponent/NewsLines/MoreLink"); // var imagemedia = newitem.SelectSingleNode("NewsComponent/NewsComponent/NewsComponent/ContentItem/DataContent/nitf/body/body.content/media[@media-type='image']/media-reference[@mime-type='image/jpeg']/@source"); // if (imagemedia == null) // { // newitem.SelectSingleNode("NewsComponent/NewsComponent/NewsComponent[Role/@FormalName='Supporting']/NewsComponent[1]/ContentItem/@Href"); // } // } // } //} } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Text.RegularExpressions; using System.IO; using System.Xml.XPath; using System.Xml; using System.Web; using System.Xml.Linq; using System.Globalization; using System.Windows.Forms; using Microsoft.AppEx.Ingestion.Utilities; namespace HuojinTool { class IniProcessor { public void Generate(Article article) { FileInfo fi = new FileInfo(article.IniSampleFileName); StringBuilder sb=new StringBuilder(); if (fi.Extension == ".ini") { if (!string.IsNullOrEmpty(OpFile.GetFileToString(fi))) { sb.Append(OpFile.GetFileToString(fi)); //sb.AppendFormat(OpFile.GetFileToString(fi), articles[0].Provider + articles[0].App, articles[0].App); sb = sb.Replace("{TsvFile}", article.Provider + article.App + "Generic.tsv"); sb = sb.Replace("{ConfigFile}", article.Provider + article.App + "GenericConfig.xml"); sb = sb.Replace("{Environment}", article.Provider + article.App); sb = sb.Replace("{App}", article.App); OpFile.WriteStringToFile(article.Folder, article.IniOutputFileName, sb.ToString()); } else { MessageBox.Show("Can not loading the xaml file."); } } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Globalization; namespace Microsoft.AppEx.Ingestion.Utilities { public static class DateTimeUtils { public static DateTime convertToDateTime(String dateString, String dateformat) { if (!string.IsNullOrEmpty(dateString)) { DateTime dateTime; if (DateTime.TryParseExact(dateString, dateformat, null, DateTimeStyles.None, out dateTime)) { return dateTime.ToUniversalTime(); } } throw new ArgumentException("dateString or dateformat is wrong"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.IO; using System.Xml.XPath; using System.Xml; using System.Web; using System.Xml.Linq; using System.Globalization; using System.Windows.Forms; namespace Microsoft.AppEx.Ingestion.Utilities { public static class HTMLAgilityUtils { public static List<string> RestrictedHtmlNodes = new List<string> { "iframe", "embed", "script" }; /// <summary> /// cleanup scope markers /// </summary> /// <param name="input"></param> /// <returns></returns> public static string CleanupText(string input) { string response = null; if (!string.IsNullOrEmpty(input)) { //remove scope pattern string pattern = "#R##N#|#N#|#TAB#|\r|\n|\t"; Regex rx = new Regex(pattern); response = rx.Replace(input, " "); } return response; } /// <summary> /// replace scope markers for parsing /// </summary> /// <param name="input"></param> /// <returns></returns> public static string RemoveScopeMarkers(string input) { string response = null; if (!string.IsNullOrEmpty(input)) { //remove scope markers response = input.Replace("#R##N#", "\n"); response = response.Replace("#N#", "\n"); response = response.Replace("#TAB#", "\t"); } return response; } /// <summary> /// Extract the data string from a byte array /// </summary> /// <param name="byteArray"></param> /// <returns></returns> public static string GetDataString(byte[] byteArray, out Encoding feedencoding) { string dataString = null; bool encodingFound = false; feedencoding = Encoding.UTF8; dataString = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length); string encoderType = null; string matchPattern = "<?xml.*?>"; Regex re = new Regex(matchPattern, RegexOptions.IgnoreCase); // optimization reduce matching to first 100 characters. var matchStr = dataString; if (dataString.Length > 100) { matchStr = dataString.Substring(0, 100); } var match = re.Match(dataString); while (match.Success && !encodingFound) { for (var i = 0; i < match.Groups.Count; i++) { string val = match.Groups[i].Value; var str = "encoding="; var idx = val.IndexOf(str, StringComparison.OrdinalIgnoreCase); if (idx > str.Length) { var quoteStartIdx = val.IndexOf("\"", idx); if (quoteStartIdx > 0) { quoteStartIdx++; var quoteEndIdx = val.IndexOf("\"", quoteStartIdx); if (quoteEndIdx > 0) { encoderType = val.Substring(quoteStartIdx, quoteEndIdx - quoteStartIdx); //log (encoderType); var encoding = Encoding.GetEncoding(encoderType); if (encoding != null) { //set the encoding used here feedencoding = encoding; } } } encodingFound = true; break; } } match = match.NextMatch(); } //if no encoding found assume the string is encoded as utf-8 and return the same, otherwise returns the converted string var encodedStr = GetStringFromEncoding(feedencoding, byteArray); if (encodedStr != null) { dataString = encodedStr; } return dataString; } /// <summary> /// Extract the data bytes from a string /// </summary> /// <param name="string"></param> /// <returns></returns> public static byte[] GetDataBytes(string data) { byte[] dataString = null; bool encodingFound = false; string encoderType = null; Encoding feedencoding = Encoding.UTF8; dataString = feedencoding.GetBytes(data); string matchPattern = "<?xml.*?>"; Regex re = new Regex(matchPattern, RegexOptions.IgnoreCase); // optimization reduce matching to first 100 characters. var matchStr = data; if (data.Length > 100) { matchStr = data.Substring(0, 100); } var match = re.Match(data); while (match.Success && !encodingFound) { for (var i = 0; i < match.Groups.Count; i++) { string val = match.Groups[i].Value; var str = "encoding="; var idx = val.IndexOf(str, StringComparison.OrdinalIgnoreCase); if (idx > str.Length) { var quoteStartIdx = val.IndexOf("\"", idx); if (quoteStartIdx > 0) { quoteStartIdx++; var quoteEndIdx = val.IndexOf("\"", quoteStartIdx); if (quoteEndIdx > 0) { encoderType = val.Substring(quoteStartIdx, quoteEndIdx - quoteStartIdx); //log (encoderType); var encoding = Encoding.GetEncoding(encoderType); if (encoding != null && encoding.WebName != "utf-8") { //set the encoding used here feedencoding = encoding; var encodedStr = feedencoding.GetBytes(data); if (encodedStr != null) { dataString = encodedStr; } } } } encodingFound = true; break; } } match = match.NextMatch(); } //if no encoding found assume the string is encoded as utf-8 and return the same, otherwise returns the converted string return dataString; } /// <summary> /// get a unicode string from the byte array of specified encoding /// </summary> /// <param name="encoding">input encoding</param> /// <param name="byteArray">inout byte array</param> /// <returns></returns> public static string GetStringFromEncoding(Encoding encoding, byte[] byteArray) { string dataString = null; var start = 0; var numBytes = byteArray.Length; byte[] preambleBytes = encoding.GetPreamble(); if (numBytes >= preambleBytes.Length) { for (var i = 0; i < preambleBytes.Length; i++) { if (byteArray[i] != preambleBytes[i]) { // if the preamble byte code match was purely // co-incidental then ignore any count observations. start = 0; break; } // need to explicitly skip the pre-amble as it's // not parsed out by the encoder/decoder start++; } dataString = encoding.GetString(byteArray, start, numBytes - start); } return dataString; } /// <summary> /// Convert the string to a stream object /// </summary> /// <param name="str">input string</param> /// <returns>stream object</returns> public static Stream ToStream(this string str, Encoding feedencoding) { MemoryStream stream = new MemoryStream(); StreamWriter writer = new StreamWriter(stream, feedencoding); writer.Write(str); writer.Flush(); stream.Position = 0; return stream; } /// <summary> /// Return the value for any one of the specified xml nodes, returns the first valid value found /// </summary> /// <param name="item">RSS item</param> /// <param name="node">node name to parse</param> /// <returns>XpathNavigator object for the specified node</returns> public static XPathNavigator GetFirstAvailableNode(XPathNavigator item, string node) { return GetFirstAvailableNode(item, node, null); } /// <summary> /// Return the value for any one of the specified xml nodes, returns the first valid value found /// </summary> /// <param name="item">RSS item</param> /// <param name="node">node name to parse</param> /// <param name="xmlNS">Namespaces used</param> /// <returns>XpathNavigator object for the specified node</returns> public static XPathNavigator GetFirstAvailableNode(XPathNavigator item, string node, XmlNamespaceManager xmlNS) { XPathNavigator nodeItem = null; if (xmlNS != null) { nodeItem = item.SelectSingleNode(node, xmlNS); } else { nodeItem = item.SelectSingleNode(node); } return nodeItem; } /// <summary> /// Return a list of all nodes with the name specified /// </summary> /// <param name="item">RSS item</param> /// <param name="node">node name to parse</param> /// <returns>XpathNavigator object for the specified node</returns> public static List<XPathNavigator> GetAllNodesWithName(XPathNavigator item, string node) { return GetAllNodesWithName(item, node, null); } /// <summary> /// Return a list of all nodes with the name specified /// </summary> /// <param name="item">RSS item</param> /// <param name="node">node name to parse</param> /// <param name="xmlNS">Namespaces used</param> /// <returns>XpathNavigator object for the specified node</returns> public static List<XPathNavigator> GetAllNodesWithName(XPathNavigator item, string node, XmlNamespaceManager xmlNS) { var nodeItems = new List<XPathNavigator>(); XPathNodeIterator nodeIter = null; if (xmlNS != null) { nodeIter = item.Select(node, xmlNS); } else { nodeIter = item.Select(node); } if (nodeIter != null) { foreach (XPathNavigator xpathNavItem in nodeIter) { nodeItems.Add(xpathNavItem); } } return nodeItems; } /// <summary> /// Return the value for any one of the specified xml nodes, returns the first valid value found /// </summary> /// <param name="item">RSS item</param> /// <param name="nodes">node names to parse</param> /// <returns>first valid node value found</returns> public static string GetFirstAvailableNodeValue(XPathNavigator item, string node) { return GetFirstAvailableNodeValue(item, node, null); } /// <summary> /// Return the value for any one of the specified xml nodes, returns the first valid value found /// </summary> /// <param name="item">RSS item</param> /// <param name="nodes">node names to parse</param> /// <param name="xmlNS">Namespaces used</param> /// <returns>first valid node value found</returns> public static string GetFirstAvailableNodeValue(XPathNavigator item, string node, XmlNamespaceManager xmlNS) { XPathNavigator nodeItem = null; if (xmlNS != null) { nodeItem = item.SelectSingleNode(node, xmlNS); } else { nodeItem = item.SelectSingleNode(node); } if (nodeItem != null) { //found, return the value. return nodeItem.Value; } return null; } private static string CleanupSnippet(string text, int textLen) { if (!string.IsNullOrEmpty(text)) { text = Regex.Replace(text, "<!--.*-->", string.Empty); text = text.Trim(); } if (textLen > text.Length) return text; string snip = text.Substring(0, textLen); while (!Char.IsWhiteSpace(text[textLen]) && textLen < text.Length) { snip += text[textLen]; textLen++; } snip += " ..."; //remove extra spaces snip = Regex.Replace(snip, "\\s+", " "); return snip; } /// <summary> /// Generates XML string from an XElement /// summary> /// <param name="xml">XElement source</param> public static string GetXmlString(this XElement xml) { // could also be any other stream StringBuilder sb = new StringBuilder(); // Initialize a new writer settings XmlWriterSettings xws = new XmlWriterSettings(); xws.OmitXmlDeclaration = true; xws.Indent = true; xws.ConformanceLevel = ConformanceLevel.Auto; using (XmlWriter xw = XmlWriter.Create(sb, xws)) { // the actual writing takes place xml.WriteTo(xw); } return sb.ToString(); } /// <summary> /// Generates XML string from an XElement /// summary> /// <param name="xml">XElement source</param> public static string GetXmlString(this XNode xml) { // could also be any other stream StringBuilder sb = new StringBuilder(); // Initialize a new writer settings XmlWriterSettings xws = new XmlWriterSettings(); xws.OmitXmlDeclaration = true; xws.Indent = true; xws.ConformanceLevel = ConformanceLevel.Auto; using (XmlWriter xw = XmlWriter.Create(sb, xws)) { // the actual writing takes place xml.WriteTo(xw); } return sb.ToString(); } public static XPathNavigator GetFirstItemNode(this List<XPathNavigator> itemList) { if (itemList == null) { return null; } foreach (var nodeItem in itemList) { if (nodeItem != null) return nodeItem; } return null; } private static string ReplaceTimeZoneAbbreviation(string datetimestr) { if (string.IsNullOrEmpty(datetimestr)) { return datetimestr; } string pattern = "GMT|EDT"; Regex rx = new Regex(pattern); if (!rx.IsMatch(datetimestr)) { return datetimestr; } string rplcDateTimeStr = datetimestr; if (datetimestr.Contains("GMT")) { rplcDateTimeStr = datetimestr.Replace("GMT", "+0000"); } else if (datetimestr.Contains("EDT")) { rplcDateTimeStr = datetimestr.Replace("EDT", "-0400"); } return rplcDateTimeStr; } public static DateTime? ParseDatetimeString(string dateValue) { DateTime? updatedtimeVal = null; try { if (!string.IsNullOrEmpty(dateValue)) { string dateValTimZoneAbbrvReplaced = ReplaceTimeZoneAbbreviation(dateValue); updatedtimeVal = DateTime.Parse(dateValTimZoneAbbrvReplaced); if (updatedtimeVal.Value.Kind != DateTimeKind.Unspecified) { updatedtimeVal = TimeZoneInfo.ConvertTimeToUtc(updatedtimeVal.Value); } } } catch (FormatException) { } return updatedtimeVal; } public static DateTime? ParseUTCDatetimeString(string dateValue, string format) { if (string.IsNullOrEmpty(format)) { return ParseDatetimeString(dateValue); } DateTime? dateTimeVal = null; try { if (!string.IsNullOrEmpty(dateValue)) { dateTimeVal = DateTime.ParseExact(dateValue, format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToUniversalTime(); } } catch (Exception) { } return dateTimeVal; } public static DateTime? ParseDatetimeString(string dateValue, string format) { if (string.IsNullOrEmpty(format)) { return ParseDatetimeString(dateValue); } DateTime? dateTimeVal = null; try { if (!string.IsNullOrEmpty(dateValue)) { dateTimeVal = DateTime.ParseExact(dateValue, format, CultureInfo.InvariantCulture).ToUniversalTime(); } } catch (Exception) { } return dateTimeVal; } /// <summary> /// Parses the datetime string. /// </summary> /// <param name="dateValue">The date value.</param> /// <param name="format">The format.</param> /// <param name="offset">The offset.</param> /// <returns></returns> public static DateTime? ParseDatetimeString(string dateValue, string format, string offset) { if (string.IsNullOrEmpty(offset)) { return ParseDatetimeString(dateValue, format); } DateTime? dateTimeVal = null; try { DateTime dateConverted; // Convert the dateValue into a datetime if (string.IsNullOrEmpty(format)) { dateConverted = DateTime.Parse(dateValue); } else { dateConverted = DateTime.ParseExact(dateValue, format, CultureInfo.InvariantCulture); } // Ensure the offset conforms to the standard if (!offset.StartsWith("+") & !offset.StartsWith("-")) { offset = offset.Insert(0, "+").PadRight(5, '0'); } // Convert the offset into timespan TimeSpan offsetConverted = new TimeSpan(int.Parse(offset.Substring(0, 3)), int.Parse(offset.Substring(3, 2)), 0); dateTimeVal = new DateTimeOffset(dateConverted, offsetConverted).ToUniversalTime().DateTime; } catch (Exception) { } return dateTimeVal; } public static string EscapeHtml(string text) { if (text != null) { return HttpUtility.HtmlEncode(text); } return null; } public static string removeNRT(string text) { if (!String.IsNullOrEmpty(text)) return Regex.Replace(text, @"\t|\n|\r", ""); return null; } public static string replaceNWithSpace(string text) { if (!String.IsNullOrEmpty(text)) { text = Regex.Replace(text, @"\t|\r", ""); return Regex.Replace(text, @"\n", " "); } return null; } /// <summary> /// DEPRICATED: Use RemoveTag /// </summary> /// <param name="text"></param> /// <returns></returns> public static string RemoveLinkTags(string text) { if (!String.IsNullOrEmpty(text)) return Regex.Replace(text, @"<\/?(?i)(link)[^>]*>", ""); return null; } /// <summary> /// DEPRICATED: Use RemoveTag /// </summary> /// <param name="text"></param> /// <returns></returns> public static string RemoveAnchorTags(string text) { if (!String.IsNullOrEmpty(text)) return Regex.Replace(text, @"<\/?[aA][^>]*>", ""); return null; } public static string RemoveHeaderTags(string htmlTxt) { if (!String.IsNullOrEmpty(htmlTxt)) return Regex.Replace(htmlTxt, @"<\/?[hH0-9][^>]*>", ""); return null; } /// <summary> /// Removes the all decendents of refnode with Nodename==tag but retains their inner content. /// </summary> /// <param name="refNode">reference node</param> /// <param name="tag">name of the tag to be removed</param> /// <returns></returns> public static XmlNode RemoveTag(XmlNode refNode, string tag) { List<XmlNode> nodeList = new List<XmlNode>(); //get all 'tag' nodes that are descendents of refnode foreach (XmlNode node in refNode.SelectNodes(".//" + tag)) { nodeList.Add(node); } //reverse the node list so that the each node comes before its parent nodeList.Reverse(); //delete the 'tag' node and move its children to its parents foreach (XmlNode node in nodeList) { XmlNode parent = node.ParentNode; while (node.HasChildNodes) { parent.InsertAfter(node.FirstChild, node); } parent.RemoveChild(node); } return refNode; } public static string GetURLQueryValue(string Url, string queryName) { string queryVal = string.Empty; Uri uri = new Uri(Url); string[] parameters = uri.Query.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries); foreach (string parameter in parameters) { if (parameter.Contains(queryName + "=")) { string[] parts = parameter.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length >= 2) { queryVal = parts[1]; break; } } } return queryVal; } public static String HtmlDecode(String htmlString) { if (!string.IsNullOrEmpty(htmlString)) { return HttpUtility.HtmlDecode(htmlString); } else { return htmlString; } } /// <summary> /// Remove a Xpath from the XHtml /// </summary> /// <param name="xpath">xpath to remove</param> /// <param name="xHtml">xHtml Nodes</param> /// <returns></returns> public static XmlNode RemoveXpath(XmlNode node, string xpath) { if (node != null) { foreach (XmlNode selectedNode in node.SelectNodes(xpath)) { selectedNode.ParentNode.RemoveChild(selectedNode); } } return node; } public static string RemoveStrongTags(string text) { if (!String.IsNullOrEmpty(text)) return Regex.Replace(text, @"<\/?(?i)(strong)[^>]*>", ""); return null; } public static string RemoveEmptyPTags(string text) { if (!String.IsNullOrEmpty(text)) return Regex.Replace(text, @"<p\s*>\s*</p\s*>|<p\s*/\s*>", ""); return null; } public static string RemoveSpanTags(string text) { if (!String.IsNullOrEmpty(text)) return Regex.Replace(text, @"<\/?(?i)(span)[^>]*>", ""); return null; } public static string RemoveDetailTags(string text) { if (!String.IsNullOrEmpty(text)) return Regex.Replace(text, @"<\/?(?i)(detail)[^>]*>", ""); return null; } public static string DecodeHtmlString(string htmlStr) { // purpose here is to remove all HTML encodings in the html text if (string.IsNullOrWhiteSpace(htmlStr)) { return htmlStr; } int strLen = htmlStr.Length; int prvLen = 0; // decode as long as there is reduction in the string length // whenever there is a decoding the string length will reduce by at least a few characters. // e.g. S&P represented as S&amp;amp;P along with S&amp;P // - in some cases encodings have found to be left out in the text while (prvLen != strLen) { prvLen = strLen; htmlStr = HttpUtility.HtmlDecode(htmlStr); strLen = htmlStr.Length; } return htmlStr; } /// <summary> /// remove junk characters from the string /// </summary> /// <param name="text"></param> /// <returns></returns> private static string TrimText(string text) { if (!string.IsNullOrEmpty(text)) { text = Regex.Replace(text, "<!--.*-->", string.Empty); text = text.Trim(); } //remove extra spaces text = Regex.Replace(text, "\\s+", " "); return text; } } }
68c0734b18fbc233ff5a69f28c796de69f0373b5
[ "C#", "INI" ]
11
C#
jelink/HuojinTool
cc56d711aa006d9297ffe26b2321d75226a7e04d
3058ac6e541a2927c5ef0aebdfa0015f1eddf5a5
refs/heads/main
<repo_name>AkshadaSayajiGhadge594/Tuple<file_sep>/Tuple.py print("-------Demonstration of Tuple--------"); tup=(11,"Akshada",308,225,"Ghadge") print(tup); print(tup[0]); print(tup[1]); print(tup[1:]); print(tup[:2]); print(tup[1:2]); #tup[1]="Akshada" It is not allowed to change the content print(len(tup)); print("Akshada" in tup) del tup <file_sep>/README.md # Tuple Tuple in Python
0196ab684eb87e3387b34b99dfec079d3d4d583d
[ "Markdown", "Python" ]
2
Python
AkshadaSayajiGhadge594/Tuple
7600b09efd302fbdef1589671cf91dc8131997c1
1090759c7bd7e9d624905ae0eb64e024e5b762b4
refs/heads/master
<repo_name>binocarlos/ambassadord<file_sep>/consulcache.go package main import ( "log" "net/url" "strings" "github.com/armon/consul-api" ) type ConsulCacheStore struct { client *consulapi.Client waitIndex uint64 } func NewConsulCacheStore(uri *url.URL) ConfigStore { config := consulapi.DefaultConfig() if uri.Host != "" { config.Address = uri.Host } client, err := consulapi.NewClient(config) assert(err) return &ConsulStore{client: client} } func (s *ConsulCacheStore) List(name string) []string { services, _, err := s.client.Catalog().Service(name, "", &consulapi.QueryOptions{}) if err != nil { log.Println("consul:", err) return []string{} } list := make([]string, 0) for _, service := range services { list = append(list, service.Address + string(service.ServicePort)) } return list } func (s *ConsulCacheStore) Get(name string) string { list := s.List(name) return strings.Join(list, ",") } func (s *ConsulCacheStore) Watch(name string) { _, meta, err := s.client.Catalog().Service(name, "", &consulapi.QueryOptions{WaitIndex: s.waitIndex}) if err != nil { log.Println("consul:", err) } else { s.waitIndex = meta.LastIndex } }
9325f42f3cb147b79141a3fad99142feb2eb7155
[ "Go" ]
1
Go
binocarlos/ambassadord
530162d3542a1449248dc6c6b6f32947f9acc6f5
839c193d200a32f9219e9d0f8ddab327806f2942
refs/heads/master
<file_sep># 無線制御(GRAFFIAS) - 書いた人: <NAME>(nichiden_28) - 更新日時: 2018/08/26 - 実行に必要な知識・技能: Web制作、JavaScript、php - タスクの重さ: 2/数日かかる - タスクの必須度: 4/毎年やるべき ## 概要 `GRAFFIAS`は28代で開発した指示書作成補助用Webアプリケーションです。現状、`Acrab`で使用するJSON形式の指示書を作成しやすくする機能のみを持ちます。 最新のブラウザ(Chrome推奨)があれば、どんな環境でも使うことができます。 `Acrab`の補助として用いることから、さそり座β星`Acrab`の別名である`Graffias`から名前を取っていますがあまり深い意味はありません。`Graffias`はラテン語で「爪」を意味するそうですが本アプリに爪要素は一切ありません。 ※無線制御と直接関係はしませんが、性質上`Acrab`から切り離せないアプリなので無線制御の項に分類しました。 ## 使い方 ### 下準備と起動 使いはじめる前に、その年に使用する星座絵を`GRAFFIAS.php`に入力する必要がある。`GRAFFIAS.php`内のHTML部分に、 ```html <select id="projector_a[0]" name="projector_a[0]"> <option value="XXX">--使用星座絵を選択--</option> ``` などと書かれた部分がある。(`projector`は5個まで用意しているので計5か所、1か所書いてコピペすればよい) この後に、使用する星座絵及び星座グループを、(※ただし、2017年現在Acrab側の不具合により現状星座グループ指定は行えないので注意) ```html <option value="Lep">うさぎ</option> ``` のように、`<option value="(三文字コード)">(星座名か星座グループ名)</option>`の形で書いていく。 `ACRAB`ディレクトリ内に、`88星座+略符一覧.txt`という三文字コードと星座名の対応を書いたテキストファイルを置いておいたので参考程度にどうぞ。 書き換えが終わったら、`GRAFFIAS`を使う環境の整備を行う。 `GRAFFIAS`はphpで書かれているので、`Acrab`と同様にローカルにWebサーバを立てないと使えない。 ローカルにWebサーバを立てる方法としては[Acrabの使い方#下準備](acrab.html)を参照のこと。`Acrab`本体とはルート環境を別にしておこう。 なお、`GRAFFIAS`のみを別のPCで使うときは、`Acrab`ディレクトリ内の`GRAFFIAS`ディレクトリのみを移せば使える仕様になっている。 これにより、プログラミング担当者以外の人や日電メンバー以外にも指示書作成を手伝ってもらえる…といいなあ。 localhostにアクセスすると、以下のような画面が表示される。 ![GRAFFIASメイン画面](_media/graffias-main.png) ### 操作 #### JSONファイルの作成 `GRAFFIAS`で作成しようとするJSONの構造は以下のとおり。 ``` ├── "info" [番組情報] │   ├── "day" [(ライブ解説の場合)何日目か] │   ├── "title" [番組名] │   └── "name" [担当者名] └── "scenario" [配列: 指示が入る部分]    ├── 0    │   ├── "word" [セリフ: 0番目は空欄にする]    │   ├── "timing" [タイミング: 0番目は空欄にする]    │   └── "projector" [投影機]    │      ├── "(三文字コード)" [点灯なら1/消灯なら0]    │      └── (以下同様)    ├── 1    │   ├── "word" [セリフ]    │   ├── "timing" [タイミング]    │   └── "projector" [投影機]    │      ├── "(三文字コード)" [点灯なら1/消灯なら0]    │      └── (以下同様)    └── (以下同様) ``` `GRAFFIAS`の画面上の各フォームは、このJSONの構造に対応している。 ![GRAFFIAS操作画面](_media/graffias-opscreen.png) - ファイル名…JSONファイルのファイル名。自由に決めていいが、タイトルと一致させた方が分かりやすいと思われる。 - 公演日…`day`と対応。セレクトボックスから一日目~三日目、ソフトのいずれかを選ぶ。 - タイトル…`title`と対応。番組名を入力する。 - 担当者…`name`と対応。担当者の名前を入力する。ソフト製作の番組の場合、空白にしておくといいだろう。 - シナリオ以下…`scenario`以下に対応する。下のプラスボタンを押せばフォームが増え、マイナスボタンを押せば直前のフォームが消える。0番目は「JSONを作成」ボタンを押した時に自動生成されるので、入力不要である。 - タイミング…`timing`と対応。セリフの前か後かを選択できるようにしたが、その他の「セリフの3秒ほど後」のような指示は`GRAFFIAS`上では対応できないので、出来上がったJSONに手入力することになる。 - 操作…`projector`と対応。星座絵と、その星座絵のon/offを選択する。入力ミスが一番多いところなので注意。 星座のグループも選択できるが、Acrabがこれに対応できていないので現状無効である。詳しくは[Acrabの実装解説#acrab_main.js](acrab-code.html)参照のこと。 - セリフ…星座絵点灯/消灯の合図となるセリフ。エクセルからコピペ可。 情報を入力していると、指示書の曖昧な点や不明点、矛盾点が見えてくることもある。これらは入力中にソフトの人やライブ解説担当者に問い合わせて、できるだけ潰しておくといいだろう。 全ての情報を入力し終わったら右下の「JSONを作成」ボタンをクリックする。 すると、JSONファイルが`GRAFFIAS/scenario`ディレクトリ内に作成される。 実は、このままでは**AcrabからJSONファイルを参照できない**ため、JSONファイルが揃ったら、 **ACRAB/scenarioディレクトリ内にJSONファイルをコピーして使う**のが必須となる。 なぜこんな面倒な仕様なのかというと、`GRAFFIAS`は、`GRAFFIAS`のみをコピーしてプログラム担当ではない人に渡して使ってもらうことを想定しているためである。 年にもよるが、基本的に指示書の数は多いうえに大体本番ギリギリにならないと揃わない。このため、とにかく作業人数が多いほど本番直前の負担が減る。よって、`GRAFFIAS`ディレクトリのみをコピーして複数人に渡し、各自の`GRAFFIAS/scinario`内に出力されたJSONを、USBなりLINEなりメールなりでJSONを取りまとめる人に送信する…ということを考えた。 全員がGitを使いこなせれば無問題な気もするが、そういう専門知識のない人にも容易に使えるような仕様を目指したのでこうなった。 #### JSONリストの作成 全ての番組のJSONファイルを作成し終わったら、`GRAFFIAS/scenario`ディレクトリに全ての番組のJSONファイルがあることを確認する。 **GRAFFIASディレクトリがACRABディレクトリの直下にあることも確認する。** ここまで確認できたら、`GRAFFIAS`の画面で「**↑↑↓↓←→←→BA**」と入力すると、画面一番下の右側(赤っぽいエリアの外)に赤い「JSONリストの作成」ボタンが表示される。 これをクリックすると、`ACRAB`ディレクトリ内に`scenario_list.json`が作成される。 既に`scenario_list.json`がある状態で押すと、これが上書きされる仕様。 このため直前のタイトル変更にもササッと対応できる。 `scenario_list.json`は、`Acrab`がサーバにある指示書ファイルの数を知るために使われる。詳しくは[Acrabの実装解説#acrab_main.js](acrab-code.html)参照のこと。 ## プログラム `GRAFFIAS`はWebの技術を使って内部処理や画面表示を行っている。 画面の情報はHTML、デザインはCSS、画面の書き換えはJavaScript(以下JS)、内部処理やファイルの生成はphpという構成だ。 phpの仕様上、HTMLは`GRAFFIAS.php`の中に書いてある。基本的にはphpをプログラム前半に、HTML部分をプログラムの後半に書いてあるので、編集時はそれぞれを参照してほしい。 プログラムの細かい仕様については説明を省くが、要所については説明を加えておく。 ### GRAFFIAS.phpの実装解説(HTML部) `GRAFFIAS`では、入力された情報を受け取るのに、HTMLの`<FORM>`タグを使用している。`<FORM>`タグ内にラジオボタン、セレクトボックス、テキストボックス等を配置し、入力された情報を ```html <form id="frm" name="frm" action="GRAFFIAS.php" method="post" > ``` で`GRAFFIAS.php`に送信する。送信したデータをphp部分で処理するという流れだ。php部分の説明は後述。 ```html <select id="projector_a[0]" name="projector_a[0]"> ``` 等のセレクトボックスについては、セレクトボックスの中身をいじれば、その年に使用する星座にも対応できる。 セレクトボックスの中身を操作するようなGUIは、時間の都合上作ることができなかったので、もし余裕があったら考えてみるのもいいかもしれない。(GUIを丸ごと作り直した方が速いかもしれないが…) 他のHTML部については、後述する`script.js`に関連する部分以外は、基本的にググればすぐ分かる程度の内容しか書いていないため、割愛する。 ### script.jsの実装解説 一旦`GRAFFIAS.php`からは外れるが、`GRAFFIAS.php`のフォームの追加・削除機能に関する部分である、`script.js`の解説に入る。 `GRAFFIAS.php`には、フォーム追加用の+ボタンと、フォーム削除用の-ボタンがあるが、これは`GRAFFIAS.php`のみではただのボタンであり、何の機能もない。 これにフォームを追加/削除し、現在のフォームの数を変数を用いカウントして`GRAFFIAS.php`に渡すのが`script.js`の主な役割である。 また、`script.js`には`jQuery`が使われている。これは`Acrab`関連のjavascriptを触った人ならお馴染みであろう。ネット上に参考文献が大量にあるので分からない場合は参照してほしい。 今回は[こちらのページ](https://qiita.com/SiskAra/items/5f4bc7ee4e598b863add)を参考にした…というかほとんど丸パクしたのでまずリンク先を参照してほしい。 - `$(obj).attr('id').replace(/\[\d{1,3}\]+$/, '[' + frm_cnt + ']')`などの`/\[\d{1,3}\]+$/`の部分は「正規表現」と呼ばれる表記である。 ここだけではなく、日電が作成した他のプログラムにも含まれている…し、プログラミングに関わったことがあるなら見たことがあるかもしれない。 表記がややこしいので、[参考文献へのリンク](https://www.sejuku.net/blog/20973#i-3)を貼っておく。 ```js $('#send_button').click(this,function(){ document.forms['frm'].elements['count'].value = frm_cnt + 1; document.frm.submit(); }); ``` 上記の部分は、「JSONを作成」ボタンを押した時に、現在のフォームの数を、`script.js`内でフォームの数を数える変数である、`frm_cnt`の数に1を足した数として`GRAFFIAS.php`内のHTML部に組み込むためのコードである。これは、javascriptで変更したフォームの数を、どうしてもphp側で参照できるようにしたかったからである。 色々と調べてはみたが、作成者の技術では、javascript→HTML→phpという流れで受け渡す方法しか思いつかなかったのでこの仕様である。もっとスマートな方法もあるのかもしれない。 ```js var inputKey = []; var konamiCommand = [38,38,40,40,37,39,37,39,66,65]; $(window).keyup(function(e) { inputKey.push(e.keyCode); if (inputKey.toString().indexOf(konamiCommand) >= 0) { $('#listmake').css("display","inline"); inputKey = []; } }); ``` …上記の部分は、完全にお遊びで入れてしまった部分である。指示書用のJSONを全て作成し終わった後、`Acrab`から参照できるように、JSONの一覧をまとめたJSONファイルを作らないといけないのだが、このJSONリストを作る機会は少ない。というか基本1回しかない。 このため、隠しコマンドでJSONリスト作成用のボタンが出せたらいいな…隠しコマンドと言えばコナミコマンドかな?という発想から付け足しただけである。(と思ったが同世代に伝わらなかった)世の中同じことを考える人は多いようで、「コナミコマンド javascript」でググるといろいろ文献が出てくる。このコードもネット上から引っ張ってきた。 ### GRAFFIAS.phpの実装解説(php部) さて、ここからが本題のphp部分になる。php初学者が何とか動くように1週間で無理矢理書き上げたものなので、非常にエラーが多いことに留意していただきたい。 冒頭の、`ini_set('display_errors', "Off");`をコメントアウトすると、phpの実行時にエラーが表示されるようになる。デバッグ時の参考にしてほしい。 #### FORMから送信されたデータの変数への格納 ```php if(isset($_POST['filename'])){ $filename = $_POST['filename']; //echo $filename; ``` 上記の形式で記述した部分は、入力された内容をphp部で扱う変数に格納する役割だ。 コメントアウトしている`echo`部は出力が正しいかのテスト時に使える。 セリフ、タイミングにあたる`word`、`timing`や星座絵にあたる`projector`、各フォームのON/OFFボタンにあたる`on_off`については、配列として格納している。 これは、1つの指示書内にこれらが複数あるからである。 また、現在のフォーム数もこの形式で受け取って、`$count`という変数に格納している。 ここで注意してほしいのが、`projector`については、1個目のフォームの、1番上の星座絵用セレクトボックスがprojector_a[0]、1個目のフォームの、上から2番目のものは**projector_a[1]ではなく、projector_b[0]**になるということである。`on_off`のラジオボタンも同じ仕様になっている。 あらかた作った後で、この分かりにくさに気が付いてしまったが時間的に修正できなかったのでこのままである。非常に分かりにくい仕様になってしまって申し訳ない。 #### JSONファイルとして出力するための雛形の作成 ```php $DATA_ARRAY = array( "info" => array( "day" => $day, "title" => $title, "name" => $staffname, ), "scenario" => array( array( "timing" => "", "word" => "", "projector" => array( "Fst" => 1, "Gxy" => 1, ), ), ), ); ``` 上記の部分は、JSONファイルを作成する際のいわば初期設定にあたる部分を作るためのものである。指示書用のJSONファイルをいくつか見てもらえればすぐ分かると思うが、 各JSONファイルの冒頭部は`day`、`title`、`name`以外は全て一致している。この部分を配列として作成するのが上記コードである。この雛形に、他の星座絵やそのON/OFFについての 情報を加えていき、最終的にJSONとして出力する形である。この部分の記法については[こちらのページ](https://syncer.jp/how-to-use-json)が大いに参考になった。 ```php $word = str_replace(array("\r", "\n"), '', $word); ``` このコードはセリフ部分に書き込まれた内容から、改行コードを削除するためのものである。載せる場所に困ったので、ここに記載する。 セリフ部分に改行が入っていると指示書中に変な文字化けが発生することが指示書作成中に発覚したため、急遽追加した箇所である。 これにより、改行コードによる文字化けは防げるようになったが、同時に、そもそもセリフが改行されなくなるというデメリットも発生するようになった。(当然だが) 具体的には、長いセリフの場合にAcrab上で読みにくくなる、Acrab上で「次へ」/「前へ」ボタンが大きく横に伸びてしまうことがあるなどの点が欠点である。 このコードを置き換える、削除する、AcrabのCSSをいじってデザイン面からなんとかする…等の対応をしてほしいところである。 #### 星座絵用セレクトボックスで、星座が未選択の場合の配列からの削除 ```php for($n = 0;$n < $count; $n++){ if($projector_a[$n] == "XXX"){ unset($projector_a[$n]); unset($on_off_a[$n]); } if($projector_b[$n] == "XXX"){ unset($projector_b[$n]); unset($on_off_b[$n]); } if($projector_c[$n] == "XXX"){ unset($projector_c[$n]); unset($on_off_c[$n]); } if($projector_d[$n] == "XXX"){ unset($projector_d[$n]); unset($on_off_d[$n]); } if($projector_e[$n] == "XXX"){ unset($projector_e[$n]); unset($on_off_e[$n]); } } ``` 星座絵がセレクトボックスで選択されている場合、各星座に対応した3文字のアルファベットがphp側に送信されるが、未選択の場合は`XXX`を送るように割り当てている。 そこで、配列である`$projector`と`$on_off`の中から、`XXX`に対応する部分を削除するためのコードが上記のコードである。 これで一応はちゃんと動くのだが、冒頭で触れた**大量のエラーの一番の原因**となっている部分でもある。もっと良い方法がある気がしてならないが、作成者の知識ではこれが限界だった。 #### on/off関連の配列作成 on/offラジオボタンの情報(0か1)は配列として格納しているが、実はこの情報は数値としての`int型`ではなく、`string型`として格納されている。これを、 ```php $on_off_int_a = clone_int($on_off_a); ... function clone_int($array){ if(is_array($array)){ return array_map("clone_int",$array); }else{ return intval($array); } } ``` と、上記の記述でint型の配列に作成しなおしている。 #### scinarioの中に入れる配列の作成とJSONの出力 ここまでで`scenario`に入れるデータの用意が全て終わったため、`scenario`以下の配列を作る。 ```php $DATA_ARRAY["scenario"][$i]["projector"] = array_filter($DATA_ARRAY["scenario"][$i]["projector"],"strlen"); ``` 上記の記述は`projector`内の空の要素を一括で削除するものである。 配列が出来上がったら、あとはJSONを出力するのみ。 ```php $make = json_encode($DATA_ARRAY,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT); ``` 上記の記述だけで、ここまで作ってきた配列($DATA_ARRAY)をJSONに変換して出力できる。後半は出力形式の指定なので、正直おまじないに近い。何か追加したい人は別途調べてみてほしい。 出来上がったJSONファイルは、 ```php if($filename){ file_put_contents("scenario/".$filename.".json",$make); $result = file_get_contents("scenario/".$filename.".json"); } ``` の記述により、**GRAFFASディレクトリ内の**`GRAFFIAS/scenario`ディレクトリに、`(ファイル名).json`の形式でJSONが出力される。最初の方にも書いたが、このままでは`Acrab`から参照できないので注意。 実際に使う場合は、**ACRAB/scenarioディレクトリ内に、GRAFFIAS/scenarioディレクトリの中身をコピーして使う**こと。 #### JSONリストの作成 全てのJSON作成が終わったら、`Acrab`が参照できるJSONリストを、JSON形式で出力する。 ```php if(isset($_POST['listmake'])){ foreach(glob("scenario/*.json") as $ListMake){ $FileList[] = $ListMake; } for($j=0;$j<count($FileList);$j++){ $FileListResult["scenariolist"][$j] = $FileList[$j]; } $FileListMake = json_encode($FileListResult,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT); file_put_contents("../scenario_list.json",$FileListMake); } ``` 上記の記述により、「JSONリストの作成」を押すとJSONファイルの一覧をJSON形式で出力したものが**GRAFFIASディレクトリの1つ上のディレクトリ**内に出力される。 ## 今後の課題点 知識0からのスタート&1週間弱で作ったプログラムなので、非常に課題点が多い。ここで挙げた点以外にも、何か気づくところあればどんどん修正なり、機能追加なりしてほしい。 よりよいものが作れそうであれば、もう原型残さず改造でいいレベルでもある。 - 使い始める前の、HTML部の書き換えが面倒。これをさくっと選択形式で直せるような仕様にすると後々楽かも…? - 現状指示書を作る機能しかないので、 Acrabの方でファイルを書き換える作業には非対応。ただ、GRAFFIASは色んな人にGRAFFIAS単体で渡して使ってもらうのを想定しているので、そこまで作成するなら別でAcrab用設定画面UIを作った方が便利な可能性は高い - 改行コードを一括削除する仕様にしたが、長いセリフが来ると読みにくい&ACRABのボタンレイアウトが崩れる。これはAcrabで時々指示書の表示チェックをしながら、AcrabのCSSも弄るのを考えておくといいかもしれない。 - **肝心の星座グループ指定が機能していない。**これはGRAFFIAS自体の問題ではないが、かなりの痛手である。原因はAcrabにあるのが分かっているので、是非本番までに直していただきたい。 - エラーがとにかく多い。これでどのような問題が発生しているかはよく分かっていないが、動作の遅さがどうしても気になるなら改善すべき…なのかもしれない。 <file_sep>引き継ぎ資料の作成方法 ====================== - 書いた人: <NAME>(nichiden_27) - 更新: <NAME>(nichiden_28) - 更新日時: 2018/09/02 - 実行に必要な知識・技能 - CUIを扱ったことがある - Gitを使ったことがある(できれば) - GitHubを使ったことがある(できれば) - 難易度: 3/練習・勉強が必要 - 情報の必須度: 3/必要な場合がある 概要 ---- | 引継ぎ文書の作成法解説です。 | 下で紹介する方法ではGit、Githubの知識が必要になりますが、引継ぎ文書をWebサイトで公開できるようになります。 | URLさえ記録しておけばどの端末からも簡単に閲覧できるのが強みです。 日電引き継ぎに使用している技術やツール -------------------------------------- 1. Markdown記法 2. Sphinx 3. Pandoc 4. GitとGitHub 日電は引き継ぎをWordや\ :math:`\rm{\LaTeX}`\ などで作っていましたが、27でSphinxを使用したWebサイト形式に変えました。 各代でそれぞれPDFの資料を作成していては分量は増える一方で、\ **読む側の負担**\ が増してしまいます。 今は不要な情報と必要な情報が混ざった古い資料が沢山あるのです(これはこれで歴史を感じられて楽しいですが)。 従って、多くの情報を閲覧しやすく、また追記修正しやすい形にまとめる必要がありました。 結果的に、ソフトウェアエンジニア寄りの技術を多用しています。 ただ、多くの事はツール任せで済むはずです。 GitとGitHubを使う事は必須ではないので、皆さんの都合に応じて決めてください。 Markdown ~~~~~~~~ フォーマット付きの文書を作成できる「軽量マークアップ言語」の一種です。 見出しや太字、画像などが入った文書を作成することができます。 Wordとの一番の違いは、\ **テキストデータ**\ であることです。 WindowsでもMacでも、特定のソフトに依存せずに閲覧できます。 誰がどんなPCで開いても問題なく表示・編集できるので、次世代への引き継ぎが簡単です。 また、\ **デザインは後から好きなように適用できる**\ (HTMLとCSSのような関係になる)ので、執筆するときはデザインを一切気にしなくていいのもありがたいです。 文法については\ `Markdown記法 チートシート <https://gist.github.com/mignonstyle/083c9e1651d7734f84c99b8cf49d57fa>`__\ などを見てください。 一つ注意が必要なのが、Markdownは\ **環境によって微妙に仕様が違う**\ ことです。 例えば、太字にする際に **空白を両側に入れる** か\ **空白を入れない**\ かの違いなどです(日電引き継ぎの環境では空白は不要)。 変換した結果を確認して、表示が崩れていないか確認することを勧めます。 Sphinx ~~~~~~ Markdownだけでは単なる文法なので、それを綺麗に表示するツールが必要です。 **Sphinx**\ はドキュメント作成に特化したツールで、本来はPythonのドキュメント作成用に作られました。 WebページやPDF(要\ :math:`\rm{\LaTeX}`)をはじめ、多数の形式で出力できます。 導入 ^^^^ Sphinx自体もPythonでできています。 pipがある環境なら、導入は\ ``sudo pip install Sphinx``\ で大丈夫です。 Windowsの方は以下などを参考にしてください。 - `python3.6にsphinxをインストール(Windows) <https://qiita.com/cosmos4701141/items/949b2c785a85a0cd5db9>`__ 基本的には好きな方法でPythonを導入して、SphinxをインストールすればOKです。 ``sphinx-quickstart``\ と入力してなにやら表示されれば、導入に成功しています。 **(追記)** ``easy_install``\ だと失敗する場合、\ ``pip``\ を使ってみてください。 .. code-block:: bash sudo easy_install pip sudo pip install Sphinx とか。それでもダメなら、pipを入れ直すとか…… | また、変換時に必要になるので、ここで\ ``pip install sphinx_rtd_theme``\ と入力して\ ``sphinx_rtd_theme``\ を導入しておいてください。 | 後述しているPandocも導入しておく必要があります。 | **Windowsの場合** | 使っているシェルにもよりますが、後の変換作業で\ ``make``\ コマンドが入っていないために\ ``make html``\ でエラーが出ることがあります。 もし\ ``make``\ コマンドが入っていない場合は以下のページ等を参照してください。 - `Windowsでmakeコマンドを使う <https://qiita.com/tokikaze0604/items/e13c04192762f8d4ec85>`__ reST記法について ^^^^^^^^^^^^^^^^ Sphinxについてググっていると、「reStructuredText」とか「.rst」のような単語をよく見ると思います。 **reStructuredText**\ は、Sphinxが標準で使う軽量マークアップ言語です。 Markdownの仲間ですが、できることがより多くなっています。 その分書き方が難しいので、日電では採用していません。 唯一\ ``index.rst``\ だけは目次作成のために書く必要があるので、ご注意ください。 他の記事は、一旦reSTに変換してからSphinxに読ませています。 SphinxはMarkdownをそのまま処理することもできますが、諸々の理由(数式を入れたいなど)から断念しました。 出力 ^^^^ 日電引き継ぎの一番上のディレクトリにある\ ``build.sh``\ を実行すると、変換作業を行って\ ``doc/``\ 以下に全ページを出力するようになってます。 ただ、macOSで作っていたので、Windowsのコマンドプロンプトではおそらく動かないです……。 | もしWin環境で出力したいのであれば、Win10ではbashが使えるので導入するか、スクリプト自体を書き換える必要があると思います。 **(追記)** Windows7でも、Gitをインストールした時についてくる\ ``Git bash``\ でスクリプト動かせました。 | ただ、\ ``make``\ コマンドが標準では入っていないのでインストールの必要ありです。 | スクリプトも、そのままでは動かなかったので微修正して\ ``buildwin.sh``\ として\ ``build.sh``\ と同じディレクトリに放り込んでいます。 | Windowsの人はこちらを試してみてください。 編集 ^^^^ 既存の記事を編集する場合は、単に該当のファイルを書き換えて保存してからビルドを行うだけです。 記事を追加するときは、\ ``index.rst``\ に記事のファイル名を忘れずに追加しましょう。 でないとせっかく書いた記事が目次に出てきません。 Pandoc ~~~~~~ Pandocは、文書の形式を互いに変換してくれるツールです。 その威力は、\ `Try Pandoc! <https://pandoc.org/try/>`__\ で簡単に試せます。 日電引き継ぎでは、MarkdownをreSTに自動変換するのに使っています。 導入は、\ `Pandocのリリースページ <https://github.com/jgm/pandoc/releases>`__\ から最新版のインストーラを落として実行するだけです。 ``pandoc -v``\ コマンドでバージョン情報が出てくれば導入完了です。 GitとGitHub ~~~~~~~~~~~ `27引き継ぎのサイト <https://kn1cht.github.io/nichiden-handover/>`__\ は、GitHub Pagesという無料(!)サービスで公開しています。 ``docs/``\ フォルダにデータを入れておくと、Webサイトを公開してくれるありがたいものです(\ `解説 <https://qiita.com/tonkotsuboy_com/items/f98667b89228b98bc096>`__)。 ただ、GitとGitHubの操作がわかっている必要があります。 Gitはバージョン管理や差分・履歴の管理がとても簡単で、この先ソフトウェアを触るならぜひ習得しておくべきものです。 ただ概念がとっつきにくいのも事実で、Gitの操作がわからず作業が止まることがもしあれば、それは本末転倒だと思います。 引き継ぎのデータを自分のPCにコピーし、Sphinxで出力した\ ``index.html``\ をブラウザで開くだけでも閲覧自体に全く問題はありません。 皆さんの技術レベルに応じて適切な方法を選択して頂ければと思います。 引き継ぎ資料のディレクトリ構造 ------------------------------ 引き継ぎは記事数がかなり多いので、\ **ディレクトリ分け**\ を少し工夫してます。 Sphinxの動作に絶対必要なものや、必須ではないが見栄えのために分けたものなど、重要度が違うのでここで解説します。 最上部 ~~~~~~ :: nichiden-handover ├── Makefile ├── build │   ├── doctrees │   ├── html │   └── ... ├── build.sh ├── docs │   ├── _images │   ├── _sources │   ├── _static │   └── ... └── source - Makefile - Sphinxのビルドに必要なファイル。\ **編集不要です**\ 。 - [ディレクトリ]build - GitHubからクローンしてきた直後は空になっていると思います。 - Sphinxでビルドを実行すると、ここに結果が出力されます。 - 中身は基本的に\ **見なくていいです**\ 。 - build.sh - 日電引き継ぎのビルドのために書いたスクリプト。\ **あとで解説します**\ 。 - [ディレクトリ]docs - GitHub Pagesで公開するには、ここにHTMLなどを入れておく必要があります。 - ``build.sh``\ がファイルをコピーするので、\ **手動でいじる必要はありません**\ 。 - ただし、更新の都度ビルドを実行しないと\ ``docs``\ の内容が古いままになってしまうので要注意。 - [ディレクトリ]source - 記事のソースファイルなどが入ってます。\ **編集したいときに見るのはここ**\ 。 source以下 ~~~~~~~~~~ :: source ├── _media ├── _static │   └── css │   └── my_theme.css ├── _templates ├── begginers ├── bihin.md ├── conf.py ├── haisen-kagoshii.md ├── ... ├── honban.md ├── index.rst ├── main.md ├── management.md ├── mytheme │   ├── breadcrumbs.html │   ├── layout.html │   └── theme.conf ├── ... - \*.md - 各記事のソースファイル。Markdownで書いてある。 - [ディレクトリ]_media - 記事に入れる画像などを入れておく所です。 - **本当は画像はどこに置いてもいい**\ のですが、増えてくると目障りなので分けています。 - 記事に画像を入れたいときは、\ ``![画像の説明](_media/gazou.png)``\ みたいに書きましょう。 - [ディレクトリ]_static - 静的ファイルの置き場。現状CSSだけ入ってる。 - この下にある\ ``my_theme.css``\ を編集するとサイトの色を変えたりできるので、暇ならどうぞ。 - [ディレクトリ]_templates - 多分最初から用意されてたものだけど中に何もない。なんだこれ。 - conf.py - Sphinxの設定ファイルです。日電用に編集済みなのでそのままでもいいです。 - 著者名とかバージョンとかはここから変更できます。 - index.rst - 引き継ぎを開いたら横に出てくる\ **目次を定義**\ している部分。 - 記事を増やしたら忘れずにここに書き加えましょう! - [ディレクトリ]mytheme - Sphinxはサイトのデザインを「テーマ」という形で自由にいじれます。 - 今は\ `Read the Docs <https://github.com/rtfd/sphinx_rtd_theme>`__\ というテーマになってます。 - さらに、Read the Docsを\ **“mytheme”で一部上書き**\ して、自分好みのデザインにしました。 - 「\ `Sphinx: 既存のテーマをカスタマイズする <http://blog.amedama.jp/entry/2016/01/06/122931>`__\ 」を参考にしたので興味があれば読んでください。 - ここに出てこなかったディレクトリ - 同一カテゴリの記事を分類するためのものです。 - **一々ディレクトリに分けなくても別にいい**\ んですが、\ ``.md``\ のファイルが多すぎると見づらいので…… ビルド用スクリプト\ ``build.sh``\ でやっていることの解説 -------------------------------------------------------- - build.shがうまく動かない - build.shの動作を変更したい 方はここを読むと分かった気になれるかもしれません。 .. figure:: _media/running-build-script.gif :alt: build.shの動作 build.shの動作 build.shを実行すると、こんな感じの出力がずらずらと表示されるはずです。 今どの段階の作業をしているのか、数字付きで表示するようになってます。 呪文 ~~~~ - #/bin/bash - shebangって言います。ググれ。 - cd ``dirname $0`` - ``build.sh``\ が置いてあるディレクトリに移動します。 - これがないと、別の場所から\ ``build.sh``\ を読んだ時にうまく動きません。 第一段階 ^^^^^^^^ .. code-block:: bash find ./* -name '*.md' -print0 | while read -r -d '' file do echo "[1] Converting Markdown to reST : $file" pandoc -f markdown -t rst "$file" -o "${file%%.md}.rst" # translate Markdown to reST done ``.md``\ の付いたMarkdown形式のファイルをreST形式に変換します。 Pandocが必要なので入れておきましょう。 Markdownの文法にミスがあるとPandocがエラーを出します。 これ以降\ ``find``\ コマンドの結果でループを回す場面が多々ありますが、これはググると解説が山ほど出てくる基本技なので調べてみてください。 ``"${file%%.md}.rst"``\ の部分は、「拡張子.mdを削除して代わりに.rstを付ける」という意味です。これが終わると\ ``.rst``\ のファイルが一杯できます。 第二段階 ^^^^^^^^ .. code-block:: bash find ./* -name '*.rst' -print0 | while read -r -d '' file do echo "[2] Processing reST code : $file" sed -i .bak -e 's/\.\.\ code:: math/.. math::/g' "${file}" # substitution for code hilighting sed -i .bak -e 's/\.\.\ code::/.. code-block::/g' "${file}" # substitution for code hilighting done 今度は\ ``.rst``\ のファイルを加工します。\ ``sed``\ というコマンドで、全てのreST形式のファイルに一括で検索・置換をかけています。 ``sed``\ の書き方に慣れてないとよく分からないかもしれませんが、それぞれ次のようなことを行なっています。 1回目のsed ~~~~~~~~~~ ``.. math::``\ という記述を\ ``.. math::``\ に置き換えます(reSTではディレクティブと呼ばれる宣言)。 Sphinxの仕様の問題で、こうしないと\ :math:`\rm{\LaTeX}`\ の\ **数式が正常に変換されません**\ 。 .. _回目のsed-1: 2回目のsed ~~~~~~~~~~ ``.. code-block::``\ を\ ``.. code-block::``\ に置き換えます。 理由を忘れましたが、Pandocはコードブロック用の\ ``code-block``\ ディレクティブをなぜか\ ``code``\ に変換してしまいます。 コードを書いた部分の表示が崩壊するので、対策しました。 第3段階 ~~~~~~~ .. code-block:: bash find ./* -name '*.bak' -type f | xargs rm echo "[3] Building Documantation" make html いよいよSphinxのビルド本番ですが、コマンドは\ ``make html``\ だけです。数秒待つと、\ ``build/``\ の下にHTMLのファイルが作られます。 第4段階 ~~~~~~~ .. code-block:: bash echo "[4] Removing backup & reST files" find ./* -name '*.bak' -type f | xargs rm find ./* -name '*.md' -print0 | while read -r -d '' file do rm ${file%%.md}.rst done ``sed``\ の上書き時に発生したバックアップファイルを削除します。\ ``find``\ コマンドの結果を\ ``xargs``\ に渡して、\ ``rm``\ を実行します。 Sphinx用に生成したreSTのファイルを削除します。 しかし、単純に\ ``.rst``\ で検索して削除すると\ ``index.rst``\ が\ **巻き添えで消えてしまいます**\ 。 ``.md``\ で検索してから拡張子を付け替えることで、自動生成されたものだけが消えるようにしました。 第5段階 ~~~~~~~ .. code-block:: bash echo "[5] Copying all files to docs/" rm -r docs/* cp -r build/html/* docs/ touch docs/.nojekyll GitHub Pagesで公開するために、\ ``build/html/``\ にできたファイルを全部\ ``docs/``\ にコピーします。 最後に\ ``.nojekyll``\ を作成する理由ですが、これはGitHub Pagesで動いているJekyllによって\ **CSSが無効化されてしまうのを防ぐ**\ ためのものです。 (参考) `GitHub Pagesで普通の静的ホスティングをしたいときは .nojekyll ファイルを置く <https://qiita.com/sky_y/items/b96ae52c90457bcd7846>`__ <file_sep># 日周緯度変(日周緯度変換機構) - 書いた人: <NAME>(nichiden_27) - 更新: <NAME>(nichiden_28) - 更新日時: 2018/08/26 - 実行に必要な知識・技能: 歯車機構 - タスクの重さ: 5/準備だけで数ヶ月 - タスクの必須度: 2/たまにやるべき - 元資料 - `saitama.pdf` by 荒田 実樹(nichiden_23) ## 概要 日電の正式名称「日周緯度変・電源パート」から分かる通り、日電の本来の任務は日周緯度変装置を動作させることです。この記事では、日周緯度変装置自体に関しての情報をまとめます。 ## 構成 日周緯度変の役割は、プラネタリウムにおいて日周運動を再現する、あるいは(仮想的な)観測地の緯度を変更することである。なお、天文部の現在のプラネタリウムには歳差軸はない。 日周緯度変は大きく - 日周ギヤボックス - 緯度変ギヤボックス の2つに分かれ、それぞれに対応するステッピングモーターが搭載されている。 このステッピングモーターは一個数万円するものだが、本番中に劣化するので数年おきに買い換えられている。高価な割に**ケーブルが切れやすい**ので、取り扱う際は十分な注意を要する。 ギヤボックスはどちらも**10年以上前に製作された**ものである。製作年度に関して確かと言える情報は見つかっていないが、緯度は1994年の05主投、日周は2000年前後で製作されたようだ。 これほどの機構を再現できる技術が失われたため、かなりの長期間作り変えられていない。 ただし、いつかは必ず壊れてしまうものであり、**なるべく早期に予備を製作すべき**だろう。 日周緯度変の製作に成功すれば、天文部の歴史に名が残ることは間違いない。 特に緯度変に関しては27の時点で、軸が摩耗していたり、ギアの噛み合わせが悪かったりして、緯度を動かし続けるとある角度でかごしい全体が「揺れる」ことがある。 28のかごしいが軸を新しいものにしたためこの「揺れ」は大分改善された。 ただし、ギアなどは古いままなので、作り直しは必要だろう。 ギヤボックス周辺の可動部分には**定期的にグリスを塗るか、潤滑油を差しておく**ことが望ましい。 ただし2017年現在、機構部分の保守作業の大部分は、**かごしいの作業の過程で行われている。** ごきぶりやしいたけとの接続も彼らの方がより把握しているはずなので、任せておいて問題はないだろう。 ## 歯車機構と減速比 日周緯度変を自在に操るには各ギヤ比を知っておく事が必要である。 もちろん実物を見れば調べられるのだが、それなりに面倒だったので同じ手間を繰り返さないよう図に各ギヤの歯の数を載せておく。 また、「正の向き(時計回り)」にモーターを回した時に各ギヤがどちら向きに回るかも載せておく。 ![日周緯度変のギヤ構成](_media/nissyuuidohen_gear.png) 図に書いてあるギヤの歯の数からギヤ比を計算すると、 ```math \begin{aligned} \frac{1}{80}\times\frac{25}{80}\times\frac{18}{64}=\frac{9}{8192} &&\text{緯度変} \\ \frac{1}{50}\times\frac{20}{100}=\frac{1}{250} &&\text{日周}\end{aligned} ``` となる。なお、これらのギヤの歯の数は動かしながら手で数えたので、もしかすると数え間違いがあるかもしれない。あまり過信しないよう。 つまり、各軸をある角速度で回したい場合、緯度変の場合は`8192/9`を、日周の場合は`250`をそれぞれ掛ければモーターが出力すべき角速度が求まる。日周緯度変関連のソースコードで8192や250といった定数が登場するのは、この減速比の変換をするためである。 ## モーターの角速度 ステッピングモーターは速度を自由に設定できるが、もちろん上限はある。緯度変更モジュール単体で試したところ、緯度モーターの最高角速度は$3500 deg/s$程度であった。 この速度をかごしいの速度に換算すると $3500/(8192/9)=3.84 deg/s$ となる。1度動かすのに0.26秒、南北の反転に46.8秒ほどという計算だ。 ただし、この$3500 deg/s$という速度は速度を徐々に上げていった場合の最高速度であり、停止した状態から回転させる場合は$1800 deg/s$程度が限度だと思われる。この場合かごしいの速度は$1800/(8192/9)=1.98 deg/s$となり、1度動かすのに0.5秒、南北反転には1分半かかることになる。 また、実際にかごしいを載せた場合や、主投影機を全て設置した場合など、回すものの重量によってさらに実際の速度は低下するので注意すること。 <file_sep>配線(かごしい内) ================ - 書いた人: <NAME>(nichiden_27) - 更新: <NAME>(nichiden_28) - 更新日時: 2018/08/26 - 実行に必要な知識・技能: 端子のはんだ付けや圧着 - タスクの重さ: 2/数日かかる - タスクの必須度: 4/毎年やるべき 概要 ---- かごしいは、主投影機群を格納し回転させる機構です。 **組み立て・管理**\ はかごしいチームの仕事である一方、\ **内部配線**\ は複雑で手間がかかるので日電も手伝うことになります。 配線に関する引き継ぎはかごしいにもありますが、日電員が全体を把握できるようまとめて解説します。 用語解説 -------- かごしいの扱う器具には様々な愛称が付いている。実物を見るのが早いが、それぞれの役割について簡単に解説する。 かご・しいたけ ~~~~~~~~~~~~~~ 主投影機を搭載し、回転する台座。 そのうち半球状になっている部分をその形にちなみ\ **しいたけ**\ と呼んでいる。 .. figure:: _media/kago-shiitake.jpg :alt: かご・しいたけの外観 かご・しいたけの外観 アルミ合金製だが、無数の板材が組み合わされておりかなり重い。 日電のものを取り付ける際はこの板に括り付けることになるが、\ **結束バンド**\ が大変便利である。 ごきぶり ~~~~~~~~ かごしいたけの土台となる部分。 名称はその黒い塗装から。 塗装は所々剥げており、\ **しいたけと電気的に接続している**\ 。 そのため、主投影機群の事実上のアースとなっている(アースとして十分でないという指摘がある)。 緯度変 ~~~~~~ 緯度変のモータとギアボックスが一体となったもの。 かごしいがごきぶりに設置してくれる。 日周にも言えるが、モータのケーブルが頼りないので、\ **ごきぶりのどこかにテープで留めておく**\ こと。 日周 ~~~~ 日周モータとギアボックス。 同時にかごしいたけを支える回転台座でもあり、かなり大きく重い。 パンタグラフ ~~~~~~~~~~~~ 日周が回転していくと、電源ケーブルが巻きついて回転を妨げてしまう。 これを防ぐために、パンタグラフという円盤状の部品を日周とかごしいたけの間に挟む。 構造としてはボールベアリングだが、軸受けとしてではなく回転するボールを通して送電するために使っている。 外輪が地面に対して静止し、内輪が日周に合わせて回転する。 通電中に金属部分に触れると\ **感電することがある**\ ので要注意だ。 パンタグラフには接続用のケーブルが外輪・内輪に一本ずつ付いている。 パンタグラフ側は\ **丸型の圧着端子**\ をねじで軽く(回転するように)留めている。 圧着端子やねじは外れることがあるので気をつけよう。 圧着端子は部室のパーツケースに相当数のストックがあり、圧着工具も数本保管してあるので、部室が使える状況なら修理は容易だ(\ **本番では体育館に持ち込んでおく**\ と安心)。 なお、配線のうちの片方が本番後に断線したので、交換する必要がある。 頸動脈 ~~~~~~ **ケーブルを南北間で通す**\ ため、日周に開いている穴。 ここを通る線は少ないほどよい。 過去には本番直前にケーブルを増やした結果、それが絡まって断線したこともある。 地上からパンタグラフへ ---------------------- パンタグラフは、ベアリング全体が通電するため\ **一つの大きな端子**\ として使われている。 家庭用の交流100Vをしいたけ内部に送るには、当然端子が二つ必要になる。 南北それぞれのパンタグラフを巨大なコンセントのように使っていると理解してほしい。 二股ソケット ~~~~~~~~~~~~ 配線を南北に分離するため、\ **二股に分かれた電源ソケット(オス→メスx2)**\ がかごしいの備品に用意されている。 ケーブルはそれぞれ片側一本しかないので、正しい向きに刺さなければ通電しないことに注意。 わかりやすいようにテープが貼ってある。 外輪ケーブル ~~~~~~~~~~~~ 延長コードに二股ソケットを繋げたら、もう一方をパンタグラフの\ **外輪から伸びるケーブル**\ と接続する。 .. figure:: _media/pantograph.jpg :alt: パンタグラフの外観 パンタグラフの外観 写真にあるように、外輪のケーブルには\ **黒い角形の端子(メス)**\ がついており、二股ソケット側に差し込めば繋がる。 AC電源のソケットと違い、切り欠きによって向きが分かるため便利である。 ただ、この端子の名称が分からなくなっており、現状壊れた際の買い替えができない状況にある。 通るケーブルは一本なので、\ **DCジャック**\ などに交換しても機能は果たせるだろう。 (AC電源ソケットにしてしまうと、内輪と外輪の区別が付きづらくなるのでオススメしない) パンタグラフから頸動脈へ ------------------------ パンタグラフ内輪のケーブルには\ **AC電源ソケット(メス)**\ が繋がっている。 地上側とは逆に、南北二本の内輪ケーブルを二股ソケット(オスx2→メス)で一つに束ねよう。 ケーブルを合流させるには、南北どちらかの内輪ケーブルを反対側に持っていく必要がある。 これには、内輪ケーブルを\ **頸動脈**\ に通せばよい。 これで、しいたけと一緒に動くAC100Vのコンセントが完成する。 あとは複数口のある延長コードをつなぐだけである。 南北両方で電源が取れるようにするため、一方の\ **延長コードを頸動脈に通す**\ 。 太い延長コードは頸動脈を通りづらいので、必要に応じ緯度変を回しながら作業すると楽だ。 主投影機電源 ------------ 投影機の電源は直流なので、勿論コンセントにそのまま刺すわけではない。 また、投影機が一つならばACアダプタがあれば良いが、主投影機は数十個ある物が多い。 そこで、\ **【電源→各投影機の配電回路→(ケーブル)→各投影機】**\ という順番で接続することになる(数が少ないぎんとうは例外)。 ACアダプタ ~~~~~~~~~~ 直流を得るにはACアダプタを使うのが最も簡単である。 ただし、主投影機の\ **消費電力をまかなえるだけの個数を用意する**\ こと。 ACアダプタの定格を超えて使用すると、寿命を縮めてしまうことがあるので気をつけたい。 26主投時点では、しいたけ内に5V4A(2個)/12V5A(2個)の4つのACアダプタを、結束バンドで固定して給電していた。 28代では電源を12V150WのACアダプター1つにした。 これはPISCIUMやまたたき回路内でレギュレータを用いたため可能となった。 これによりしいたけ内の配線が簡単になり、ATX電源に比べてかなり軽くなったのでかごしい本体への負担も減った。 また、ATX電源より安定して電源を供給できるようになった。 ATX電源(参考) ~~~~~~~~~~~~~ 27主投では、ケーブルの多くなるACアダプタを廃止してPC用の\ **ATX電源**\ を使用した。 しかし、ちょっとした電流サージで停止してしまうというATX電源の仕様により活用は困難だった。 また、当初案ではしいたけに電源装置をねじ止めする予定だったものの、フレームのサイズが合わず断念した。 ATX電源は使い方にかなり難があるので、配電管理にコストを割けないのであればACアダプタを使う方が楽かもしれない。 そのため、28代では12VACアダプタに統一して三端子レギュレータで電圧を下げるという方針をとった。 なんにせよ、 - 配線の作業がしやすいこと - 本番で安定して電力供給できること を第一に考えて検討すべきだ。 投影機回路BOX ------------- しいたけ上でACアダプタと各投影機の間を繋ぐ回路が入った箱(実際はタッパー)。 **こうとうBOX・いっとうBOX・無線BOX**\ (Piscium)が存在する。 各投影機の備品を入れる箱も「**ボックス」と称するが別物である。 正直ややこしいので呼び方を変えるべきかもしれない。 こうとうBOX ~~~~~~~~~~~ 恒星投影機16個に電力を供給する回路。 27代まではDCジャックが18個繋がっているだけの簡単なものであったが、28代で\ `突入電流防止用のNTCサーミスタ <http://akizukidenshi.com/catalog/g/gP-12543/>`__\ を入力端子のところに直列で2つずつ取り付けた。 こうとうは一個あたり3Wを消費するので、過大な電流が流れないよう回路を半分の9個ずつに分けてある。 このNTCサーミスタは温度が低い(室温程度)の時は抵抗が1Ω程度だが、電流が流れて温度が高くなると抵抗がほぼ0になる。 そのため突入電流が防げるという仕組みだ。 27でこうとうのONOFFをやろうとしたところおそらく突入電流のせいでできなかったとのことだったので取り付けた。 もしかしたらATX電源をACアダプターに変えたことで突入電流に耐えられるようになっていたかもしれないが、サーミスタはつけたままでも問題ないだろう。 .. figure:: _media/koutou-box-appearance.jpg :alt: こうとうBOX外観 こうとうBOX外観 壊れる類のものではないので作り変えは例年行われないものの、27代では大電流を流せるよう基板の裏全体に銅箔を貼り付けた。28代ではNTCサーミスタをとりつけた。 取り付ける部分は、しいたけの下の四角い部分である(他の回路BOXも同様)。 養生テープなどでは剥がれるリスクがあるので、\ **結束バンドでフレームに固定する**\ とよさそうだ。 いっとうBOX ~~~~~~~~~~~ 中身は\ `またたき回路 <twinkle.html>`__\ 。使い方や仕組みはあちらの記事を参照いただきたい。 主投影機配線の要素の一つとして考えるときは、こちらの呼び方を使うことが多い。 .. figure:: _media/twinkle-appearance.jpg :alt: またたき回路の外観 またたき回路の外観 星座絵BOX ~~~~~~~~~ `Piscium <wireless/piscium.html>`__\ のこと。 26代までは無線は星座絵だけだったので、この呼び名が残る。 投影機ケーブル -------------- **回路BOXと投影機を繋ぐケーブル**\ は基本的に日電の管理下にある。 例外として、星座絵投影機は慣例的に本体とケーブルが一体なので製作は任せよう。 ただし、28主投において、正座絵のケーブルの部分でショートしてPisciumの一部が壊れるということが起きた(詳細は\ `Pisciumのページ <wireless/piscium.html>`__)。 ケーブルの制作は正座絵の負担にもなっているので、他の投影機と同様に正座絵も本体にDCジャックをつけるようにして、ケーブルは日電で制作した方が良いかもしれない。 ケーブルを日電で管理すればショートも防げるだろう。 また、現在使われている投影機ケーブルの太さは0.3sqである。 太い線を使うとDCジャック内でショートしやすくなってしまうので注意してほしい。 なお、正座絵のケーブルがショートした原因も太いケーブルを使ったことである可能性が高いので、日電が作るようにしなくても0.3sqの線(正座絵で持っているものではなく部室にある赤黒の線)を使うように指定すればいいかもしれない。 二色ケーブル ~~~~~~~~~~~~ 毎年使うものであり、必要本数は大抵部室にある。 とはいえ、もし足りなくなれば早めに増産しておこう。 適度な長さの二色ケーブルに、DCプラグを2個つけるだけで良い。 .. figure:: _media/syutou-cable.jpg :alt: 投影機ケーブルの一部 投影機ケーブルの一部 二分岐ケーブル ~~~~~~~~~~~~~~ ぎんとうは片方の半球に二つしかないため、BOXの代わりに\ **二つに分岐するケーブル**\ を挟む。 二分岐は自分で作ると耐久性に難があるので、既製品を使っている。 二つのぎんとうは距離をかなり離して設置されるので、分岐の後さらに\ **延長ケーブル**\ を挟まなくてはならない。 他のケーブルと違って一方がDCプラグ、他方がDCジャックとなるので混同しないように。 気をつけたいこと ~~~~~~~~~~~~~~~~ - 投影機の区別をつける - しいたけに取り付けると線が絡み合い、元を辿るのは困難を極める - **色付きのテープを巻く**\ など、どれがどの投影機かわかるようにする - 長さを確保する - こうとうやいっとうのケーブルは長くないと上まで届かない - 短くて届かないと言われたらすぐ\ **長いものと交換できる**\ ようにしておく - 導通チェックをする - 実際使う前に\ **断線・ショート・+-逆転**\ がないか確認する - 一本のショートでこうとうが半分つかなかったこともあり、甘く見てはいけない - テスターでチェックするのは大変なので、23代では下図のような回路を使っていた - 正常でなければ二つのLEDが同時に点灯しない仕組み - 非常に簡単なので、一つ作っておいてもいいかも(もしくはまだ部室にある??) .. figure:: _media/cablechecker-23.png :alt: 23代の簡易ケーブルチェッカ 23代の簡易ケーブルチェッカ しいたけ内部主投影機配線の全容 ------------------------------ 最後に、しいたけ内配線の様子をツリー上に示す。 記入してはいないが、こうとうBOXやいっとうBOXにももちろんそれぞれの投影機がつながっている。 Pisciumは全主投影機の電源を制御するので、27代から配線の構造がかなり変化した。 :: [26まで] 電源 ├── ACアダプタ12V-1 │   └── こうとうBOX-1 ├── ACアダプタ12V-2 │   └── こうとうBOX-2 ├── ACアダプタ5V-1 │   ├── いっとうBOX │   └── 二股DCケーブル │      └── (各ぎんとう) └── ACアダプタ5V-2    └── 星座絵BOX [27] 電源 ├── ATX電源装置+Piscium │   ├── (各星座絵) │   ├── 二股DCケーブル │   │   └── (各ぎんとう) │   ├── いっとうBOX │   ├── こうとうBOX1 │   └── こうとうBOX2 └── USB用ACアダプタ    └── Piscium(無線モジュール) [28] 電源 └── ACアダプタ12V+Piscium    ├── (各星座絵)    ├── 二股DCケーブル    │   └── (各ぎんとう)    ├── いっとうBOX    ├── こうとうBOX1    └── こうとうBOX2 <file_sep># マイコンをはじめよう - 書いた人: <NAME>(nichiden_27) - 更新日時: 2017/03/15 - 実行に必要な知識・技能: 特になし - 難易度: 2/少しやれば可能 - 情報の必須度: 2/知ってると楽 ## 概要 マイコンとは、小型のコンピュータシステムのことです。 和製英語なので注意。"microcomputer"だとパソコンも含んでしまうので、"microcontroller"と呼べば間違いはないかと。 最近では`Arduino`や`mbed`に代表される手軽なマイコンボードが増え、かなりの用途に対応できます。これらについても簡単に解説します。 ## マイコン比較 いろんな会社がいろんなシリーズを出している。 よく見るのだとPIC/AVR/H8/ARMなど。 - PIC + Microchip Technology Inc.が展開 + 日本で人気があり、情報も充実している + その昔アセンブラの開発環境のみ無料だった時代があり、先人たちが苦労していた + 今ではC原語で書ける[MPLAB X](http://www.microchip.com/ja/mplab/mplab-x-ide)というIDE(統合開発環境)が無償配布 + [秋月電子で山ほど売っている](http://akizukidenshi.com/catalog/c/cpicr/)ので入手性はおそらく日本一 + ライタ(書込み機)は[PICkit3](http://akizukidenshi.com/catalog/g/gM-03608/)や[AKI-PIC](http://akizukidenshi.com/catalog/g/gK-02018)など - AVR + Atmel Corporationのマイコン * だったが、2016年にMicrochipに買収された + Arduinoで゙使われている + 主にTinyシリーズ(下位)とMegaシリーズ(上位)に分かれる + [Atmel Studio](http://www.atmel.com/ja/jp/microsite/atmel-studio/default.aspx)というIDEを無償配布している + ライタはAVRISP mkIIなど(秋月のサイトから消えてる...) * 自作もできるらしい - H8 + 日立製作所→Renesas Electronics + よく知らないけど高性能らしい - ARM + ARM Holdingsによるマイコン + 消費電力が少なくスマートフォンでの採用が多い + mbedにも使われている プラネ用途であればPICかAVRで十分であろう。 以前は"C言語を使うならAVR"ということで、23-25の代でAVRが多数使われた。 しかしPICもC言語で開発できるようになり、27ではPICを使用していた。 今では、どちらを採用しても支障はないだろう。 ## マイコンボード比較 マイコンの多くは、ICチップと見た目が似ている。 ピンに自力で配線をつながなければプログラムを書き込むことすらできない。 これでは、初心者に優しくないのはもちろん、経験のある開発者にとっても手間が多くなってしまう。 最近人気となっているArduinoやmbedは、マイコンを載せた基板に電源や通信用のコネクタをあらかじめ実装しており、思い通りの機能を手軽に試すことが可能だ。 両者は厳密には言語や開発環境などを含めたシステム全体を指すため、マイコンそのものとは違う。 ただ、本記事では簡単のため**「マイコンボード」**と呼ぶことにする。 なお、Raspberry PiやIntel Edisonなども見た目が似ているが、これらはOSを動作させることが可能で、よりコンピュータに近い使い方ができる。 本記事ではマイコンとは区別し、詳しくは取り扱わない。 ### Arduino AVRマイコンを使ったマイコンボード。 イタリア発祥のため読み方に悩むが「あるでぃーの」みたいな感じらしい。 世界中で普及しており、日本においても解説記事、ブログ共にたいへん充実している。 シールドと呼ばれる拡張基板が充実しており、通信やインタフェースなどの機能を追加できる。 2015〜2016年にかけて運営会社が内部分裂を起こしていた経緯があり、公式サイトも[arduino.cc](http://www.arduino.cc)と[arduino.org](http://www.arduino.org)の二種類存在する。 混乱は製品ラインナップやIDEにまで及び、微妙に違う二バージョンが混在するという面倒な事態になっていたが、現在は和解、統合している。 公式サイトもどちらを使っても問題ないはず。筆者はarduino.ccしか見たことがないが不便を感じたことはない。 #### 購入 [秋月電子](http://akizukidenshi.com/catalog/c/carduino1/)や[千石電商](http://www.sengoku.co.jp/mod/sgk_cart/search.php?cid=4186)、[マルツ](http://www.marutsu.co.jp/GoodsListNavi.jsp?narrow1Cond=Arduino)といった有名な電子部品屋にはだいたい売っている。 ネットのみだが[スイッチサイエンス](https://www.switch-science.com/catalog/list/40/)でも買えるようだ。 価格は3000〜5000円程度。 安くはないので、一台を様々な用途に使い回すことが多くなるだろう。 ただ、Arduinoの設計は公開されていて、誰でも自前で作って販売することが可能だ。 従って本家との互換機が多数売られており、中には価格面で本家を大幅に下回るものも存在する。 例えば、国内で買うと3000円弱かかるArduino Nanoの互換機が、中国サイトなどで300円ちょっとで入手できてしまう(送料はかかる)。 信頼性が要求される場合や、初めてArduinoを使うときは避けるべきだが、沢山のArduinoを必要とする場面などでは検討してはいかがだろうか(クレカ情報を守るためpaypal推奨)。 安い互換機は、USBシリアル変換チップに`CH340G`という中国製品を使っていることが多々ある。 最近のWindowsなら刺せば認識するようだが、Macで初めて使う際はドライバを入れねばならない。[江苏沁恒股份有限公司のページ](http://www.wch.cn/download/CH341SER_MAC_ZIP.html)から落としてきてインストールしよう。 #### 開発環境 開発にはArduino IDEをPCにダウンロードする必要がある。2017年現在のバージョンは1.8系で、arduino.cc/arduino.orgのどちらでも同じものが入手できる。このIDEでスケッチと呼ばれるプログラムの作成からビルド、ボードへの書き込みまでを行う。 ...はずだったのだが、2016年夏に[Arduino Create](https://create.arduino.cc/)がリリースされ、mbedのようにブラウザからオンライン開発環境(`Arduino Web Editor`)を使えるようになった。 まだ普及している印象はないが、コミュニティ機能などが充実しているようだ。 使いこなせれば強い味方になるかもしれない。 ![Arduino Web Editorの画面](_media/arduino-web-editor.png) Arduino IDEの操作手順についてはWeb上に解説が数多くあるので述べない。 #### 言語 Arduinoは、ソフトウェアを専門としない層でも気軽に始められるようにとのコンセプトを持つ。 そのためか言語も独自のArduino言語を使用する。 C/C++風なので、経験者なら特に勉強しなくとも違和感なく書けるだろう。 それでいてArduinoで使う頻度の高い機能にはアクセスしやすくなっているので、とにかく初心者に優しい。 [本家のリファレンス](https://www.arduino.cc/en/Reference/)をはじめ資料も充実しており、ググれば大抵の問題は解決できるはずだ。 C++なので自分でクラスを作るのも自由。 ### mbed ARM社とNXP社が提供するマイコンボード。 公式推奨の読み方は「**エンベッド**」。 ブラウザで[developer.mbed.org](https://developer.mbed.org/)にある開発環境を使うというのが最大の特徴。 自分のマシンにいちいち開発環境を入れるよりも、通信環境さえあればどこからでも使えた方が良いという発想である。 アカウントを共有すればチーム開発ができてしまうなど便利さがある一方、ネット接続前提というのが足かせになってしまうこともある(最近になりオフライン開発が容易になった、後述)。 日本国内にはコアなファンが結構おり、[mbed祭り](https://mbed.doorkeeper.jp/)というユーザイベントが度々開催されるなど盛り上がっている。developer.mbed.org自体がユーザコミュニティ機能を備えており、開発と情報収集・発信が連続しているというのが強みだろう。 #### 購入 秋月電子やスイッチサイエンスなどで扱っている。 mbedの中で一番有名なのは`LPC1768`だ。 コンパクトで高性能だが、価格は6千〜7千円と安くはない。 低電圧版の`LPC11U24`でも5千円ほどはする。 そのためホイホイと買えなかったmbedだが、**mbed-enabled**プラットフォームの登場により状況は変わった。 ハードウェアの設計がオープンソースとなったことで、mbedの開発環境で使用できるボードが数多く生まれたのだ。 その全容は公式の[platforms](https://developer.mbed.org/platforms/)で確認できる。 なかでも、秋月電子などで容易に購入できるものにSTmicroの"`Nucleo Board`"がある。 搭載するマイコンの種類やフラッシュメモリの容量によって数十種が存在し、そのうち20種弱は[秋月電子](http://akizukidenshi.com/catalog/c/cstm32/)や[スイッチサイエンス](https://www.switch-science.com/catalog/list/615/)などから入手可能だ。 さらに、大部分が1500〜1900円程度と、本家mbedに比べて安価に購入できる。 `Nucleo Board`にはArduino UNOとピン配置の互換性があるため、Arduinoのシールドを流用できる場合もある。Arduinoに慣れている人にも触りやすいボードかもしれない。 また、変わったケースとして[LPC1114FN28](http://akizukidenshi.com/catalog/g/gI-06071/)というのもある。 これは、見た目は28ピンのマイコンだが、mbed対応だ。 USBでPCと繋いで他のmbedと同じ感覚で扱えるボードもあり、一個400円(110円の時代もあったらしい...)のマイコンを載せ替えれば使い回せる。 流石にボード型のものと比べて性能に制限はあるが、予算を抑えたい場合や多数のmbedを揃える場合に選択肢になりうる。 #### 開発環境 さきに述べた通り、mbedの開発環境はオンラインに存在する。 mbedを買ってアカウントを作成すれば早速使えるようになり、どこからでも保存したコードを閲覧できる。 開発環境自体も自動ヘルプ機能やライブラリのリファレンスを備えており、コードを書いていて特段不自由は感じない。 ビルドが成功すると拡張子`.bin`のファイルがダウンロードされる。 これをフラッシュメモリとして認識されるmbedのルートディレクトリに配置するだけで書き込み完了だ。 リセットボタンを押せば書き込んだプログラムが動作する。 どうしても、オフラインでコンパイルをしたい場合がある。 従来は、オンラインIDEの機能でプロジェクトを書き出した上で、自前で構築したARM向けの開発環境でビルドしていた。 2016年8月、`mbed OS 5`がリリースされる。 これは、それまでのいわゆるmbedである`mbed 2.0`と、IoT向けのOSである`mbed OS 3`を統合した新たなmbedのソフトウェア基盤だ。 これに伴い、コマンドラインの開発環境`mbed CLI`が使用可能になった。 `mbed CLI`は、`mbed 2.0`のコードをインポートしてビルドすることもできる。 本家ツールだけあってmbedとの親和性や機能性は優れているようなので、オフライン環境が欲しくなった際は使ってみてはいかがだろうか。 詳細は、[mbed オフラインの開発環境](https://developer.mbed.org/users/MACRUM/notebook/mbed-offline-development/)を確認されたい。 #### 言語 C++をベースとしている。 C++を書き慣れている開発者は違和感なく扱える一方、プログラム自体初心者だと意味を理解するのにしばらくかかるかもしれない。 Arduinoより後発のため、`=`などの演算子をクラスごとにオーバーロードするなど直感的に書くための工夫が進んでいる。 また、オンラインIDE自体にコミュニティ機能・コードの公開機能があり、他ユーザが公開している既存資源を簡単に自分のプロジェクトに取り込める。 mbedのシステムをフル活用すれば、かなり快適に開発を進められそうだ。 ## 結局何を選べばいいのか ここまで長々と書いてきたが、一体どのマイコン(ボード)を買いに行けばいいのだろう。 Arduinoやmbedといったマイコンボードの使い勝手は年々進化し続けており、従来のマイコンからは考えられない開発スピードを実現できる。 学生団体レベルの製作物ならば、無理に素のマイコンを使おうとせず、マイコンボードを採用して構わないだろう。 Arduinoとmbedには、双方に様々種類がある。 習得もそれほど大変でないので、それぞれの特徴を知った上で目的に合わせて選ぶのが良いだろう。 特に出力ピン数は、ボードを選ぶ際足りているかよくよく確認すべきである。 高性能のコアが全く必要ない用途や、電流サージの危険があり高価なボードを故障の危険に晒したくない場面では、PICやAVRといったマイコンの技術が生きてくる。 ひとたび動かし方を習得すれば、安くて小回りのきくマイコンは強い味方になってくれることだろう。 そうしたマイコンが実際に使われている機材の修理や、ソフトウェア改修を任されることもある。 幸いにも書き込み機や予備のマイコンがあらかじめ用意されているなら、PICやAVRの開発環境は出費なしで揃えられる。 先達の残したコードを解読していけば、あなたのマイコンの知識も深まるかもしれない。 <file_sep>マイコンをはじめよう ==================== - 書いた人: <NAME>(nichiden_27) - 更新日時: 2017/03/15 - 実行に必要な知識・技能: 特になし - 難易度: 2/少しやれば可能 - 情報の必須度: 2/知ってると楽 概要 ---- マイコンとは、小型のコンピュータシステムのことです。 和製英語なので注意。“microcomputer”だとパソコンも含んでしまうので、“microcontroller”と呼べば間違いはないかと。 最近では\ ``Arduino``\ や\ ``mbed``\ に代表される手軽なマイコンボードが増え、かなりの用途に対応できます。これらについても簡単に解説します。 マイコン比較 ------------ いろんな会社がいろんなシリーズを出している。 よく見るのだとPIC/AVR/H8/ARMなど。 - PIC - Microchip Technology Inc.が展開 - 日本で人気があり、情報も充実している - その昔アセンブラの開発環境のみ無料だった時代があり、先人たちが苦労していた - 今ではC原語で書ける\ `MPLAB X <http://www.microchip.com/ja/mplab/mplab-x-ide>`__\ というIDE(統合開発環境)が無償配布 - `秋月電子で山ほど売っている <http://akizukidenshi.com/catalog/c/cpicr/>`__\ ので入手性はおそらく日本一 - ライタ(書込み機)は\ `PICkit3 <http://akizukidenshi.com/catalog/g/gM-03608/>`__\ や\ `AKI-PIC <http://akizukidenshi.com/catalog/g/gK-02018>`__\ など - AVR - Atmel Corporationのマイコン - だったが、2016年にMicrochipに買収された - Arduinoで゙使われている - 主にTinyシリーズ(下位)とMegaシリーズ(上位)に分かれる - `Atmel Studio <http://www.atmel.com/ja/jp/microsite/atmel-studio/default.aspx>`__\ というIDEを無償配布している - ライタはAVRISP mkIIなど(秋月のサイトから消えてる…) - 自作もできるらしい - H8 - 日立製作所→Renesas Electronics - よく知らないけど高性能らしい - ARM - ARM Holdingsによるマイコン - 消費電力が少なくスマートフォンでの採用が多い - mbedにも使われている プラネ用途であればPICかAVRで十分であろう。 以前は“C言語を使うならAVR”ということで、23-25の代でAVRが多数使われた。 しかしPICもC言語で開発できるようになり、27ではPICを使用していた。 今では、どちらを採用しても支障はないだろう。 マイコンボード比較 ------------------ マイコンの多くは、ICチップと見た目が似ている。 ピンに自力で配線をつながなければプログラムを書き込むことすらできない。 これでは、初心者に優しくないのはもちろん、経験のある開発者にとっても手間が多くなってしまう。 最近人気となっているArduinoやmbedは、マイコンを載せた基板に電源や通信用のコネクタをあらかじめ実装しており、思い通りの機能を手軽に試すことが可能だ。 両者は厳密には言語や開発環境などを含めたシステム全体を指すため、マイコンそのものとは違う。 ただ、本記事では簡単のため\ **「マイコンボード」**\ と呼ぶことにする。 なお、Raspberry PiやIntel Edisonなども見た目が似ているが、これらはOSを動作させることが可能で、よりコンピュータに近い使い方ができる。 本記事ではマイコンとは区別し、詳しくは取り扱わない。 Arduino ~~~~~~~ AVRマイコンを使ったマイコンボード。 イタリア発祥のため読み方に悩むが「あるでぃーの」みたいな感じらしい。 世界中で普及しており、日本においても解説記事、ブログ共にたいへん充実している。 シールドと呼ばれる拡張基板が充実しており、通信やインタフェースなどの機能を追加できる。 2015〜2016年にかけて運営会社が内部分裂を起こしていた経緯があり、公式サイトも\ `arduino.cc <http://www.arduino.cc>`__\ と\ `arduino.org <http://www.arduino.org>`__\ の二種類存在する。 混乱は製品ラインナップやIDEにまで及び、微妙に違う二バージョンが混在するという面倒な事態になっていたが、現在は和解、統合している。 公式サイトもどちらを使っても問題ないはず。筆者はarduino.ccしか見たことがないが不便を感じたことはない。 購入 ^^^^ `秋月電子 <http://akizukidenshi.com/catalog/c/carduino1/>`__\ や\ `千石電商 <http://www.sengoku.co.jp/mod/sgk_cart/search.php?cid=4186>`__\ 、\ `マルツ <http://www.marutsu.co.jp/GoodsListNavi.jsp?narrow1Cond=Arduino>`__\ といった有名な電子部品屋にはだいたい売っている。 ネットのみだが\ `スイッチサイエンス <https://www.switch-science.com/catalog/list/40/>`__\ でも買えるようだ。 価格は3000〜5000円程度。 安くはないので、一台を様々な用途に使い回すことが多くなるだろう。 ただ、Arduinoの設計は公開されていて、誰でも自前で作って販売することが可能だ。 従って本家との互換機が多数売られており、中には価格面で本家を大幅に下回るものも存在する。 例えば、国内で買うと3000円弱かかるArduino Nanoの互換機が、中国サイトなどで300円ちょっとで入手できてしまう(送料はかかる)。 信頼性が要求される場合や、初めてArduinoを使うときは避けるべきだが、沢山のArduinoを必要とする場面などでは検討してはいかがだろうか(クレカ情報を守るためpaypal推奨)。 安い互換機は、USBシリアル変換チップに\ ``CH340G``\ という中国製品を使っていることが多々ある。 最近のWindowsなら刺せば認識するようだが、Macで初めて使う際はドライバを入れねばならない。\ `江苏沁恒股份有限公司のページ <http://www.wch.cn/download/CH341SER_MAC_ZIP.html>`__\ から落としてきてインストールしよう。 開発環境 ^^^^^^^^ 開発にはArduino IDEをPCにダウンロードする必要がある。2017年現在のバージョンは1.8系で、arduino.cc/arduino.orgのどちらでも同じものが入手できる。このIDEでスケッチと呼ばれるプログラムの作成からビルド、ボードへの書き込みまでを行う。 …はずだったのだが、2016年夏に\ `Arduino Create <https://create.arduino.cc/>`__\ がリリースされ、mbedのようにブラウザからオンライン開発環境(\ ``Arduino Web Editor``)を使えるようになった。 まだ普及している印象はないが、コミュニティ機能などが充実しているようだ。 使いこなせれば強い味方になるかもしれない。 .. figure:: _media/arduino-web-editor.png :alt: Arduino Web Editorの画面 Arduino Web Editorの画面 Arduino IDEの操作手順についてはWeb上に解説が数多くあるので述べない。 言語 ^^^^ Arduinoは、ソフトウェアを専門としない層でも気軽に始められるようにとのコンセプトを持つ。 そのためか言語も独自のArduino言語を使用する。 C/C++風なので、経験者なら特に勉強しなくとも違和感なく書けるだろう。 それでいてArduinoで使う頻度の高い機能にはアクセスしやすくなっているので、とにかく初心者に優しい。 `本家のリファレンス <https://www.arduino.cc/en/Reference/>`__\ をはじめ資料も充実しており、ググれば大抵の問題は解決できるはずだ。 C++なので自分でクラスを作るのも自由。 mbed ~~~~ ARM社とNXP社が提供するマイコンボード。 公式推奨の読み方は「\ **エンベッド**\ 」。 ブラウザで\ `developer.mbed.org <https://developer.mbed.org/>`__\ にある開発環境を使うというのが最大の特徴。 自分のマシンにいちいち開発環境を入れるよりも、通信環境さえあればどこからでも使えた方が良いという発想である。 アカウントを共有すればチーム開発ができてしまうなど便利さがある一方、ネット接続前提というのが足かせになってしまうこともある(最近になりオフライン開発が容易になった、後述)。 日本国内にはコアなファンが結構おり、\ `mbed祭り <https://mbed.doorkeeper.jp/>`__\ というユーザイベントが度々開催されるなど盛り上がっている。developer.mbed.org自体がユーザコミュニティ機能を備えており、開発と情報収集・発信が連続しているというのが強みだろう。 .. _購入-1: 購入 ^^^^ 秋月電子やスイッチサイエンスなどで扱っている。 mbedの中で一番有名なのは\ ``LPC1768``\ だ。 コンパクトで高性能だが、価格は6千〜7千円と安くはない。 低電圧版の\ ``LPC11U24``\ でも5千円ほどはする。 そのためホイホイと買えなかったmbedだが、\ **mbed-enabled**\ プラットフォームの登場により状況は変わった。 ハードウェアの設計がオープンソースとなったことで、mbedの開発環境で使用できるボードが数多く生まれたのだ。 その全容は公式の\ `platforms <https://developer.mbed.org/platforms/>`__\ で確認できる。 なかでも、秋月電子などで容易に購入できるものにSTmicroの“``Nucleo Board``”がある。 搭載するマイコンの種類やフラッシュメモリの容量によって数十種が存在し、そのうち20種弱は\ `秋月電子 <http://akizukidenshi.com/catalog/c/cstm32/>`__\ や\ `スイッチサイエンス <https://www.switch-science.com/catalog/list/615/>`__\ などから入手可能だ。 さらに、大部分が1500〜1900円程度と、本家mbedに比べて安価に購入できる。 ``Nucleo Board``\ にはArduino UNOとピン配置の互換性があるため、Arduinoのシールドを流用できる場合もある。Arduinoに慣れている人にも触りやすいボードかもしれない。 また、変わったケースとして\ `LPC1114FN28 <http://akizukidenshi.com/catalog/g/gI-06071/>`__\ というのもある。 これは、見た目は28ピンのマイコンだが、mbed対応だ。 USBでPCと繋いで他のmbedと同じ感覚で扱えるボードもあり、一個400円(110円の時代もあったらしい…)のマイコンを載せ替えれば使い回せる。 流石にボード型のものと比べて性能に制限はあるが、予算を抑えたい場合や多数のmbedを揃える場合に選択肢になりうる。 .. _開発環境-1: 開発環境 ^^^^^^^^ さきに述べた通り、mbedの開発環境はオンラインに存在する。 mbedを買ってアカウントを作成すれば早速使えるようになり、どこからでも保存したコードを閲覧できる。 開発環境自体も自動ヘルプ機能やライブラリのリファレンスを備えており、コードを書いていて特段不自由は感じない。 ビルドが成功すると拡張子\ ``.bin``\ のファイルがダウンロードされる。 これをフラッシュメモリとして認識されるmbedのルートディレクトリに配置するだけで書き込み完了だ。 リセットボタンを押せば書き込んだプログラムが動作する。 どうしても、オフラインでコンパイルをしたい場合がある。 従来は、オンラインIDEの機能でプロジェクトを書き出した上で、自前で構築したARM向けの開発環境でビルドしていた。 2016年8月、\ ``mbed OS 5``\ がリリースされる。 これは、それまでのいわゆるmbedである\ ``mbed 2.0``\ と、IoT向けのOSである\ ``mbed OS 3``\ を統合した新たなmbedのソフトウェア基盤だ。 これに伴い、コマンドラインの開発環境\ ``mbed CLI``\ が使用可能になった。 ``mbed CLI``\ は、\ ``mbed 2.0``\ のコードをインポートしてビルドすることもできる。 本家ツールだけあってmbedとの親和性や機能性は優れているようなので、オフライン環境が欲しくなった際は使ってみてはいかがだろうか。 詳細は、\ `mbed オフラインの開発環境 <https://developer.mbed.org/users/MACRUM/notebook/mbed-offline-development/>`__\ を確認されたい。 .. _言語-1: 言語 ^^^^ C++をベースとしている。 C++を書き慣れている開発者は違和感なく扱える一方、プログラム自体初心者だと意味を理解するのにしばらくかかるかもしれない。 Arduinoより後発のため、\ ``=``\ などの演算子をクラスごとにオーバーロードするなど直感的に書くための工夫が進んでいる。 また、オンラインIDE自体にコミュニティ機能・コードの公開機能があり、他ユーザが公開している既存資源を簡単に自分のプロジェクトに取り込める。 mbedのシステムをフル活用すれば、かなり快適に開発を進められそうだ。 結局何を選べばいいのか ---------------------- ここまで長々と書いてきたが、一体どのマイコン(ボード)を買いに行けばいいのだろう。 Arduinoやmbedといったマイコンボードの使い勝手は年々進化し続けており、従来のマイコンからは考えられない開発スピードを実現できる。 学生団体レベルの製作物ならば、無理に素のマイコンを使おうとせず、マイコンボードを採用して構わないだろう。 Arduinoとmbedには、双方に様々種類がある。 習得もそれほど大変でないので、それぞれの特徴を知った上で目的に合わせて選ぶのが良いだろう。 特に出力ピン数は、ボードを選ぶ際足りているかよくよく確認すべきである。 高性能のコアが全く必要ない用途や、電流サージの危険があり高価なボードを故障の危険に晒したくない場面では、PICやAVRといったマイコンの技術が生きてくる。 ひとたび動かし方を習得すれば、安くて小回りのきくマイコンは強い味方になってくれることだろう。 そうしたマイコンが実際に使われている機材の修理や、ソフトウェア改修を任されることもある。 幸いにも書き込み機や予備のマイコンがあらかじめ用意されているなら、PICやAVRの開発環境は出費なしで揃えられる。 先達の残したコードを解読していけば、あなたのマイコンの知識も深まるかもしれない。 <file_sep># 日周緯度変(さいたま) - 書いた人: <NAME>(nichiden_27) - 更新日時: 2017/02/26 - 実行に必要な知識・技能: AVRマイコン、電子回路 - タスクの重さ: 3/数週間 - タスクの必須度: 3/年による - 元資料 - `日周・緯度変資料.pdf` by 岩滝宗一郎(nichiden_22) - `saitama.pdf` by 荒田 実樹(nichiden_23) ## 概要 <pre style="font-family:IPAMonaPGothic,'MS Pゴシック',sans-serif;">                 \ │ /<br>                  / ̄\   / ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄<br>                ─( ゚ ∀ ゚ )< さいたまさいたま!<br>                  \_/   \_________<br>                 / │ \<br>                     ∩ ∧ ∧  / ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄<br>  ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄\∩ ∧ ∧ \( ゚∀゚)< さいたまさいたまさいたま!<br> さいたま~~~!   >( ゚∀゚ )/ |    / \__________<br> ________/ |    〈 |   |<br>               / /\_」 / /\」<br>                ̄     / /<br> </pre> 日周緯度変コントローラ「さいたま」の使い方や仕組みなどを説明します。壊れて部品交換が必要になった・新しいさいたまを作りたい際に参照してください。 ## 沿革 日周緯度変のステッピングモーターを回すには、モータドライバという回路が必要になる。駒場祭プラネではモータドライバと制御基板を内蔵した専用コントローラーを使っており、2002年の[13日周以降](http://twitter.com/fujita_d_h/status/254087988882046976)今日に至るまで**「さいたま」** と呼ばれている。 「さいたま」や他の回路に使用するマイコンは長らくPICであったが、22日電で**AVR** が採用され、23日電、24日電でもこれを踏襲した。PIC時代はほとんどのプログラムがアセンブラで書かれていたが、AVRを使うようになってからはC言語が使われるようになった。 さいたまはたびたび作り変えられてきたが、現在使用しているのは22が製作した**さいたま6號** である。23は、さいたまをPCから制御するための装置「Ikebukuro」を導入した(Ikebukuroの資料参照)。24では基板を作り直し、その際マイコンを**ATmega** に変更したようだ。 ## 使い方 ![さいたま6號と電源装置を接続している様子](_media/saitama_connection.jpg) 背面に日周・緯度用に二つのコネクタがあるので、専用ケーブル※を使ってそれぞれのモータに繋ぐ。次に、モータの電力を確保するため、電源装置から**24V** を右面のDCジャックから供給しよう。 ※コネクタはELコネクタ(日本圧着)6極、ケーブルはVCTF0.5sq 5芯 ![さいたま6號のボタン配置図](_media/saitama_buttons.png) コントローラ前面には6つのスイッチがある。現在では[外部制御](ikebukuro.md)でPCから動かす方がはるかに便利だが、PCが使えない緊急時や急いでいるときはこのスイッチを使えばよい。 ラベルを参照すれば大体の意味は分かることだろう。回転のON/OFFと方向はそれぞれの軸で独立しているが、回転速度は2軸で変えることはできない。`外部制御ON/OFF`スイッチは、PCから操作したい場合にONにする。これがONになっているときは、さいたま側のスイッチに反応しなくなるので気をつけよう。 ## 電装 ケースの両側に付いているねじを全て外すと、さいたまの中身を確認できる。 ![さいたま6號の内部](_media/saitama_internal.jpg) - メイン基板 - **画像は23引き継ぎのものだが、この翌年に作り変えられているので注意** - マイコンがスイッチの状態を読取り、モータードライバにCW・CCWパルスを送信する - 基板に付いていたスイッチはあまり重要でなかったため、基板作り変えの際取り除かれた模様 - 2×3のピンヘッダは、AVRマイコンにプログラムを書き込むためのもの - モータードライバ基板 - CW・CCWパルスに応じてステッピングモータに電流を流す - 既製品。割と高価だが、部室に未使用の買い置きがある - スイッチ基板 - トグルスイッチが配置されている - 普通に使っている場合一番壊れやすい部分なのでたまに異常がないか見てあげよう ## プログラム 23代が`nissyuido`ディレクトリ以下に使用したソースコードを残している。`WinAVR`環境があれば`default`ディレクトリに移動して`make`コマンドを打てばビルドされるとのことだ。 ただし、前述の通り**24代でマイコンをATmega328Pに変更**しており、以前のコードを使用できるかは定かでない。作り変えをする際は、24代の方に問い合わせてみることも検討されたい。 以下のプログラム解説は、23荒田氏の作成されたドキュメントと同内容である。必要なら氏のPDFや、コード中のコメントなども併せて確認すると良いだろう。 ### main.c ![プログラムの流れ](_media/saitama_program_flow.png) プログラムの起点となる `main` 関数が入っている。 プログラムの大まかな流れは図を参照。 プログラムは初期化(`main.c`の`init`関数)の後、メインループ(無限ループ)に入る。ただ、初期化の時にタイマ割り込みを設定しているため、100マイクロ秒ごとに現在メインループで実行されている内容に関係なく「タイマ割り込み」の内容が実行される。 メインループの処理内容は`main.c`を、「タイマ割り込み」の処理内容は`motordrive.c`を参照されたい。 外部制御コマンドのフォーマットはここで処理している。 ### motordrive.c ここが最も重要な部分である。 ステッピングモーターのドライブ回路に定期的にパルスを送り、指定した速度でモーターを回す。 モーターを角速度$Speed$(コード中ではm->current_speed $[deg/s]$)で回すにはどうすればよいか考えてみよう。 一回のパルスでモーターが回転する角度はモーターとドライブ回路によって決まっており、$\mathrm{MotorStep}=0.72 \mathrm{deg}$(コード中ではMOTOR_STEP $[10^{-2}deg]$)である。 AVRのタイマ機能により、`motordrive`関数は$\mathrm{ControlPeriod}=100 \mu\mathrm{s}$(コード中ではCONTROL_PERIOD $[\mu\mathrm{s}]$)間隔で呼ばれる。 前回パルスを送ってからの経過時間を$n\cdot\mathrm{ControlPeriod}$とする(前回パルスを送ってから$n$回目の`motordrive`の呼び出し; $n$はコード中ではm->count)。 このとき、簡単な考察により、$n\cdot\mathrm{ControlPeriod}\cdot\mathrm{Speed}\ge\mathrm{MotorStep}$の時に次のパルスを送ればよいことが分かる。 実際には、速度指定モード・角度指定モードがあったり、速度を徐々に変化させる処理を行っているので、もう少し複雑なプログラムになっている。 「速度を徐々に変化させる処理」であるが、今のところ、現在の速度と目標速度が一致しなければ一定の加速度を加えるという、比較的単純な制御になっている。 時間と速度をグラフで表すと図のようになる。赤線が指定した速度、青線が実際の速度である。 このように速度を徐々に変化させるようにプログラムの改修を行ったので、もはや**「一旦回転を停止してから回転方向を変更する」必要はない。** ![速度変化](_media/saitama_program_speed.png) 角度指定モードの、速度を下げ始めるタイミングについて。 プログラムが実行されている時点を時刻$t_0$とし、時刻$t_1$にモーターが停止するとする。 モーターの$t_0$における角速度を$\omega_0$とする。単位時間当たりのモーターの角速度の変化を$\alpha$とする。 現在のプログラムでは、`motordrive`が呼ばれるたびに速度を$1\mathrm{deg/s}$ずつ増減するので、 ```math \alpha=\pm\frac{1 \mathrm{deg/s}}{\mathrm{ControlPeriod}} ``` である。モーターの時刻$t$における角度(位置)を$\theta(t)$とする。 時刻$t$におけるモーターの角速度と角度はそれぞれ ```math \begin{aligned} \omega(t)&=\omega_0+\alpha(t-t_0) \\ \theta(t)&=\theta(t_0)+\omega_0(t-t_0)+\frac{1}{2}\alpha(t-t_0)^2 \end{aligned} ``` となる。 時刻$t_1$にモーターが停止、すなわち$\omega(t_1)=0$より、 ```math t_1-t_0=-\frac{\omega_0}{\alpha} ``` である。これを$\theta(t_1)$に代入すると、 ```math \begin{aligned} \theta(t_1)&=\theta(t_0)-\frac{\omega_0^2}{\alpha} +\frac{1}{2}\alpha\left(-\frac{\omega_0}{\alpha}\right)^2 \\ %&=\theta(t_0)+\left(-\frac{1}{\alpha}+\frac{1}{2\alpha}\right)\omega_0^2 \\ &=\theta(t_0)-\frac{1}{2\alpha}\omega_0^2 \end{aligned} ``` を得る。 求めたい量は、現在角がどういう値になったら速度を下げ始めるか、その角度である。 つまり、$\theta(t_1)-\theta(t_0)$の値である: ```math \begin{aligned} \theta(t_1)-\theta(t_0)&=-\frac{1}{2\alpha}\omega_0^2 \\ &=\frac{1}{2\left(\frac{1 \mathrm{deg/s}}{\mathrm{ControlPeriod}}\right)}\omega_0^2 \\ &=\frac{\mathrm{ControlPeriod}}{2(1 \mathrm{deg/s})}\omega_0^2 \end{aligned} ``` ステップ数に換算するために両辺を$\mathrm{MotorStep}$で割ると、 ```math \frac{\theta(t_1)-\theta(t_0)}{\mathrm{MotorStep}} =\frac{\mathrm{ControlPeriod}}{2(1 \mathrm{deg/s})\mathrm{MotorStep}}\omega_0^2 ``` を得る。 なお、コード中では$\frac{\mathrm{MotorStep}}{\mathrm{ControlPeriod}}$に`MOTOR_MAX_SPEED`という名前を与えている。 ### uart.c 外部とシリアル通信するための関数が記述されている。通信データのバッファリングを行っているが、この仕組みが正常に動いているかは検討の余地がある。 ### timer.c `motordrive`関数を$100\mu s$間隔で呼び出すための設定を行う。 ぶっちゃけ、`motordrive`関数をそのままタイマ割り込みハンドラにし ても良い気がする。 ### コンパイルするには ソースコードを編集したら、書き込む前にコンパイルする必要がある。`default`ディレクトリ以下に`Makefile`が入っているので、`Makefile`の意味が分かる人は利用すると良いだろう。 Makefileの意味が分からない人は、Atmel Studioだか何だか知らないが、適当にプロジェクトを作ってファイルを放り込んでコンパイルすればよろしい。その際、 - マイコンの種類は ATmega328P - クロック周波数は 16MHz: プリプロセッサの設定をいじって、`F_CPU=16000000UL`がpredefinedになるようにする。(コンパイラオプションとして`-DF_CPU=16000000UL`が渡されればOK) - 言語規格はC99+GNU拡張(コンパイラオプションとして`-std=gnu99`が渡されればOK) となるように注意する。 ## 今後の展望 もしもさいたまを作り替えるようなら、もう少し強力なマイコンを搭載すること、センサー(後述)対応にすること、**通信経路**についてもっとしっかり考えること(`RS-485`にするのか、全部`RS-232`とUSBシリアル通信で統一するのか)が望ましい。 23代で相対角度指定が実装されたが(現在使われていない)、**絶対角度指定**があると良いだろう。つまり、投影される星空を見ながら日周緯度変を操作するのではなく、「緯度は何度、日周は何月何日何時」という形で指定できるようにする。 絶対角度指定のためには、角度センサーを設置して現在位置を取得するか、一ヶ所にフォトインタラプタなどを設置して初期位置を判別できるようにして、後はステッピングモーターのステップ数で現在位置を把握する、などの方法が考えられる。 いずれにせよ、さいたまを作り直す際に日周緯度変に設置したセンサーを接続することを考慮しておくとよいだろう。 PC側のソフトウエアだが、PCで操作する以上何らかのメリットが欲しい。 速度を柔軟に調節できるようにはなったが、操作性にはまだまだ改善の余地がある。 リアルタイムで操作するには、マウスよりもキーボード、欲を言えばタッチパネルでの操作の方がいい。いろいろ工夫してみると良いだろう。 もう一つの方向性として、操作の記録・再生が考えられる。 ボタン一つで一本のソフトをまるまる上映できると楽だろう。ただし、ソフトウエアを実装する手間、操作を記録しておく手間に見合うメリットがあるかよく考える必要がある。 <file_sep># またたき回路 - 書いた人: <NAME>(nichiden_27) - 更新: <NAME>(nichiden_28) - 更新日時: 2017/10/4 - 実行に必要な知識・技能: 電子回路、AVRマイコン - タスクの重さ: 3/数週間 - タスクの必須度: 2/たまにやるべき - 元資料 + `一等星投影機付属またたき回路仕様書.docx` by 西村陽樹(nichiden_23) ## 概要 いっとうはただ明るいだけでなく、またたいているように見える効果が付いています。 そのための「またたき回路」の開発は日電に委託されており、遅くとも20主投の頃から存在していました。 現行のプログラム、回路は23が作ったもので、プログラムは27で改造、回路は28で改造して作り直したものです。 ## 原理 またたきの再現には様々な方法が考えられるが、ここでは20代から現在まで使われている「**1/fゆらぎ**」と「**間欠カオス法**」による方法を解説する。 ### 自然のゆらぎ またたきのパターンは周期的ではなく、ランダムであるべきだということは直感的にわかるだろう。 ただし、日電が用いたのは完全な乱数ではなく、自然の「ゆらぎ」を擬似的に再現したものである。 恒星のまたたきは、大気の「ゆらぎ」による光の強弱の変化と説明できる。 ゆらぎ(fluctuation)とは、ある量が平均値からずれる現象である。 なかでも、**1/fゆらぎ** は自然現象によくみられ、星のまたたきもこれに分類される。 電子回路などにおけるゆらぎはノイズとして表れる。 ノイズは周波数特性(パワースペクトルと周波数の関係)によって分類されているが、1/fゆらぎによるノイズは**ピンクノイズ** と呼ばれる。 ピンクノイズはパワーと周波数が反比例しており、高周波成分であるほど弱い。 これを可視光に当てはめると波長の長い色が残り、ピンク色に見えるというわけだ。 ### 間欠カオス法 従って、いっとうの明るさを1/fゆらぎに近いパターンで変化させればまたたきが再現できる。 1/fゆらぎをプログラムで生成する方法はいくつかあるが、またたき回路では処理の軽い「**間欠カオス法**」が用いられてきた。 これは、漸化式によって擬似乱数を作り出す方法である。 以下に基本となる式を示す。 ```math \begin{aligned} \begin{cases} X(t+1)=X(t)+2X(t)^{2} & (X(t)<0.5)\\ X(t+1)=X(t)-2(1-X(t))^{2} & (X(t)\geqq 0.5 ) \end{cases} \end{aligned} ``` ただし、実はこのままではこの式はあまり実用的でない。 まず、`X(t)=0.5`の場合、以降のXの値は0に張り付いてしまう。 また、0と1の近傍では値の変化が小さくなりすぎる問題もある。 そこで、実際のプログラムでは上限と下限の付近で若干値をいじるようになっている。 また10進数の浮動小数点演算はマイコンでは時間がかかりすぎるので、実際には`double`型ではなく`unsigned long`型(32bit長整数)の値としてある。 ## 回路 北天用と南天用の二つが現存する。 回路は全く同じで、プログラムだけが違う。 **電源電圧は12V**である。 いっとうのユニットやマイコンの電源は5Vであるが、他の主投の電源が12Vであるためそれに合わせて12Vになっている。 それを3端子レギュレータで5Vに降圧して利用している。 もともと27までのまたたき回路は電源電圧が5Vで、12Vを刺し間違えても壊れないように過電圧保護回路が入っていた。 しかし、他の主投と電圧を統一するために28で回路を変更した。 ただし、**いっとうのユニット自体の電源電圧自体は5V**なので、またたき回路を通さずにいっとうを光らせたい場合は12Vをつながないように注意しよう。 ![またたき回路の回路図](_media/twinkle-circuit28.png) 回路図を掲載する。 **電源部**(変圧部)、**またたき制御部**(マイコン)、**またたき出力部**(トランジスタアレイ、DCジャック)が主だった構成である。 ### スイッチ類 ![またたき回路の外観](_media/twinkle-appearance.jpg) トグルスイッチ(`SW2`)が、**またたきのON/OFFスイッチ** である。 OFFにすると消灯するわけではなく、またたきの効果のない常時点灯となる。 いっとうユニット自体のテストやデバッグに使用することを想定している。 スイッチの近くに設置されたLEDはまたたきの確認用である。 横のジャンパピンを外すと消灯するので、上映中は外しておくとよい。 タクトスイッチは**リセットスイッチ**で、押すとマイコンが再起動する。 ### またたき制御部 `ATTiny861A`を使用している。 `SW2`がpin9(`INT0/PB6`)に繋がれており、INT0割り込みを使用してまたたきON/OFFを切り替える。 INT割り込みはI/Oポートが出力設定になっていても機能するので、プログラムでは`PB6`が出力設定になっていても問題ない。 また、ON/OFFの制御をするだけのスイッチであるためチャタリング除去はなされていない。 `PB0`、`PA0`に確認用LEDが接続されている。 ### またたき出力部 `TD62003`トランジスタアレイを使用する。 `ATTiny861A`の`PA0-PA5`/`PB0-PB5`の12本が出力ピンとなる。 いっとうとの接続部はφ2.5の基板用DCジャックを使っている。 各出力ピンが`HIGH`になると、対応したDCジャックのGNDが導通して電流が流れる仕組みである。 ### 電源部 三端子レギュレータを用いて12Vの電源電圧を5Vに降圧している。 三端子レギュレータの使い方は[このサイト](http://radio1ban.com/bb_regu/)を参考にするとよい。 なお、降圧した7V分は熱として放出される。 放熱効率を上げるために[放熱器](http://akizukidenshi.com/catalog/g/gP-00429/)を取り付けている。 放熱器と接触する面に[放熱用シリコングリス](http://akizukidenshi.com/catalog/g/gT-04721/)を塗ってとりつけよう。 ## プログラム 27でプログラムを改修した際、Arduino IDEを使用してビルドと書き込みを行った。 Arduino IDEではメインのソースファイルは.inoという拡張子のファイルになる。 ただし、ベースはC++なので.cppや.hのファイルに分割して記述しても問題ない。 23日電のまたたき回路のプログラムでは**マイコンを実際に動作させる部分**と**またたきパターンを生成する部分**が混在していた。 可読性を高める目的で、前者を`Twinkle.ino`に、後者を`Twinkle.cpp`及び`Twinkle.h`と分けることにした。 `Twinkle.h`で宣言している`Twinkle`クラスがパターン生成のライブラリのように使えることを目指したが、完全なブラックボックスにはできていないので適宜改善が必要。 ### Twinkle.h プログラム中で使う変数・関数の宣言があるファイル。 `NORTH_HEMISPHERE`や`SOUTH_HEMISPHERE`がdefineされているが、これは北天・南天で数値を切り替えるために用いる。 書き込み前によく確かめて、不要な方をコメントアウトすること(片方をコメントにしていないと、変数宣言が二重となりエラーが出る)。 使っている変数や配列の注釈を箇条書きしておこう。 - public変数 + int bit_num[6]: パターンの番号とマイコン側のピンの順番の対応を示す + unsigned int on[12]: 27で追加した、またたきをピンごとに無効化するための配列。1か0 + unsigned int on_duration[12]: 一周期のうちLEDが点灯している時間(=またたきパターン)を格納する - private変数 + unsigned long shift_chaos: ピン同士を入れ替える際に使う乱数値 + unsigned long chaos[12]: またたきパターン用の乱数値 + unsigned int min_duration[12]: on_durationの最小値。大きくするとまたたき効果が強くなる + unsigned int refresh_rate/rr_count/shift_rate/sr_count: (後述) ### Twinkle.cpp 冒頭でいくつか記号定数が宣言されている。 コメントを読めば概ね理解できるであろう。 結局`Twinkle`クラスの内部処理で使うだけなので、ヘッダファイルのクラス宣言の方に書いても問題なかったかも。 ```cpp #define CHAOS_DIV 256 // chaos_gen()で生成される乱数は1~32768の幅であるが、このままではタイマ0割込に使用できないので適当な2の乗数で割る #define ON_DURATION_MAX 160 // LEDの点灯時間の最大値を決定するパラメーター(タイマ割込の間隔によって決まっているのでオシロスコープで波形を見ながら調整のこと) #define TWINKLE_RATE 2 // またたき用の乱数値の更新レート、nを設定するとn回のタイマ割込に1回の割合で値が更新する #define TWINKLE_SHIFT 100 // 乱数の周期性問題を解決するために、乱数とそれに対応する信号出力ビットをport_shift()で変更している。nを設定するとn回の乱数更新に1回の割合で出力がビットシフトする ``` 次に、コンストラクタがある。 と言っても変数の初期化をしているだけである。 ここで、`refresh_rate`や`shift_rate`などを設定する。 ```cpp Twinkle::Twinkle():refresh_rate(TWINKLE_RATE), rr_count(TWINKLE_RATE), shift_rate(TWINKLE_SHIFT), sr_count(TWINKLE_SHIFT){}; ``` #### port_shift() 間欠カオス法はあくまで擬似乱数なので、周期性が目立つことがある(らしい)。 定期的にまたたきパターンと各出力ピンの対応を変えることで、これを防ぐ。 **ただし、このメソッドは現在使用していない。** 23では12のピンを強弱2種類にしか分けていなかったが、27で惑星(またたかない)を追加したのでこれが3種類に増えた。 当初それに気づかず実験したところ、またたき強・弱・惑星が数秒で入れ替わってしまう。 修正の時間も限られており、本番ではポートの入れ替えを使わずに投影をすることとなった。 見ていた限りでは特に不自然には感じなかったが、この仕様が必要かどうかは更なる検証を待ちたい。 参考のためにピンを入れ替える仕組みを解説する。 ```cpp for(int i=0;i<6;i++) bit_num[i] = (bit_num[i] + (shift_chaos >= 12000 ? 1 : 4)) % 6; // 6要素の数列を左に回転シフト ``` 回転シフトは、配列の中身を押し出して溢れた分を逆側に追加するものだ。 円環状に並んだ数字を回転させるイメージである。 アルゴリズムとしてはある数字(6要素なら1~5)を足し、6以上になった要素からは6を引くというものだ。 6で割った余りを保ったまま6を下回ればいいので、**実は割り算して余りをとるだけでもいい。** なお、23の計測によるこの処理の実行時間は100μsだが、割り算の方法で処理を簡略化したので短くなったかもしれない。 #### refresh() またたきパターンの更新を行う。 `chaos`の12個の要素それぞれに、新たな乱数値を格納している。 ```cpp void Twinkle::refresh(void){ // 乱数値を更新する。所要時間は12変数で1ms for(int i=0;i<SIZE_OF(on_duration);i++){ chaos[i] = chaos_gen(chaos[i]); on_duration[i] = min((int)(chaos[i] / CHAOS_DIV + min_duration[i]), ON_DURATION_MAX); } } ``` 実際のまたたきパターンで使う`on_duration`には、`chaos`から二つの変化を加える。 まず、最大32768の出力を`CHAOS_DIV`で除した上で、`min_duration`という数を加えている。 `min_duration`が大きいほど、**LEDが点灯している時間が増え、またたきの効果が薄まる**。 また、`on_duration`は160を超えてはいけないので、`ON_DURATION_MAX`と比較して小さい方を採用する。 実行時間は1msらしい。 #### chaos_gen(y) 入力yに対して間欠カオス法による擬似乱数を一個出力する。 元の漸化式にアレンジを加え、yの変化が微小になることがないよう調整してある。 ```cpp unsigned long Twinkle::chaos_gen(unsigned long y){ // Max == 32768までの整数値を返す疑似乱数(1/fゆらぎ) if(y < 1638) y += 2 * pow(y, 2) / 32768 + 1966; else if(y < 16384) y += 2 * pow(y, 2) / 32768; else if(y > 31129) y -= 2 * pow(32768 - y, 2) / 32768 + 1310; else y -= 2 * pow(32768 - y, 2) / 32768; return y; } ``` #### generate() またたき生成や出力ピンの入れ替えを制御する。 タイマ割り込みで毎回呼ばれることを想定している。 割り込みが入るたびに`rr_count`と`sr_count`が1ずつ減少し、0になると`port_shift()`や`refresh()`を実行する。 ただし、27の仕様変更で`port_shift()`は不使用としたので、その部分はコメントになっている。 ```cpp void Twinkle::generate(void){ // またたきをつかさどる部分 rr_count--; //乱数更新時期の判定と実行をする if(!rr_count){ sr_count--; //ビットシフト更新時期の判定と実行をする if(!sr_count){ //port_shift(); sr_count = shift_rate; }else _delay_us(100); refresh(); rr_count = refresh_rate; }else _delay_us(1100); //それらの操作をしない場合でも、同じだけの時間waitして調整する } ``` ### Twinkle.ino AVRマイコンの制御に直接関連するコードはこちらにまとめた。 #### ISR(INT0_vect) INT0割り込みで呼ばれる。 PORTAとPORTBをすべてH、つまり常時点灯・またたきなしの状態にする。 ```cpp ISR(INT0_vect){ //またたきOFF(スイッチで切り替え) PORTA = 0xFF; PORTB = 0xFF; } ``` #### ISR(TIMER0_COMPA_vect) タイマ0割り込みで呼ばれる。 PORTAとPORTBをすべてHにしてから、Twinkleクラスの`generate()`関数を呼んでパターンの更新処理をする。 ```cpp PORTA = 0xFF; PORTB = 0xFF; twinkle.generate(); unsigned int c_up = 0; ``` 以降は、実際にピンから出力するコードになる。 `pattern_count`は出力ピンの数(現状12)を表す。 forループ内では、7μsごとに`c_up`をインクリメント(コメントに`twinkle.c_up`とあるがこれはミス)していく。 `twinkle.on_duration[i]`と一致したら`pattern_count`を一つ減らして、`twinkle.on[i]`が0でなければLEDを消灯する。 `i`とピン番号の対応は`twinkle.bit_num`に書いてある。 ```cpp unsigned int pattern_count = SIZE_OF(twinkle.on_duration); while(pattern_count){ //twinkle.on_durationの値とtwinkle.c_up(カウントアップ)の値を比較し、一致するまではON、一致したらLEDをOFFにする。全部OFFになったらループを抜けてmainに戻る。 c_up++; for(int i=0;i<SIZE_OF(twinkle.on_duration);i++){ if(twinkle.on_duration[i] == c_up){ pattern_count--; if(!twinkle.on[i]) continue; if(i < 6) PORTA ^= 1 << twinkle.bit_num[i]; else PORTB ^= 1 << twinkle.bit_num[i-6]; } } _delay_us(7); } ``` 出力ポートの制御であるが、マイコンボードのデジタル出力のようには便利でなく、**出力レジスタというものを使う**。 `PORTA`や`PORTB`とあるのが出力レジスタで、ピンの状態が二進数で保存されている。 これを書き換えることで出力がなされる仕組みだ。 例えば、`PORTA = 0xFF(11111111)`の時に、6番目のピンを`LOW`にしたいとする。 `^=`演算子はXOR代入といい、右の数との排他的論理和を代入する。 XORは二つの数が違えば1、同じなら0を返すので、`PORTA`の6桁目と1のXORを取ればそこだけが0になる。 n桁目が1の数は1を(n-1)ビット左にビットシフトすると作れるので、コードはこうなる。 ```cpp PORTA ^= 1 << 5 ``` #### main() 初期設定とメインルーチン。 I/Oポートの設定・タイマ0(CTCモード)とプリスケーラの設定・タイマ0割り込みの設定・INT0割り込みの設定を行っているらしい。 ここを変更したければAVRの勉強をしよう。 `sei()`は割り込みを許可する組み込み関数である。 設定終了後にこれを呼んで無限ループに入り、割り込みを待つことになる。 ```cpp int main(void){ /*** 初期設定(TIMER0_CTC、TIMER割込、INT0割込) ***/ _delay_ms(100); DDRA = 0xFF; //PORTA0~7を出力に設定 DDRB = 0xFF; /*タイマ0 CTCモード、タイマ0_Compare_A割込*/ TCCR0A = 0x01; //CTC0をHに TCCR0B = 0x00 | 1<<CS02 | 0<<CS01 | 0<<CS00; OCR0A = 180; //CTCのMAX値の設定(180、プリスケーラ256の設定でタイマ割込間隔は7.5msec) TIMSK |= 1<<OCIE0A | 0<<TOIE0; //タイマ0CompA割込有効 GIMSK |= 1<<INT0; //INT0割り込み有効 MCUCR |= 0<<ISC01 | 0<<ISC00; //INTピンのLowで割り込み発生 PORTA = 0x00; PORTB = 0x00; /*************************************************/ sei(); for(;;){} } ``` ### 書き込むには 書き込みの際、Fuseビットの`DIVCLK8`を`Disable`する必要がある(内部クロックを1MHzではなく8MHzで使用するため)。 27では、書き込みにArduino IDEを使った。 Arduinoの中身はAVRマイコンなので、マイコン(ボード)の定義を読み込む事で書き込み可能になる。 ボードマネージャで[設定ファイルのURL](http://drazzy.com/package_drazzy.com_index.json)を指定すると各種設定が選べるので、`ATTiny861A`を選択して書き込もう。 手順の詳細は[Arduino IDE に ATtiny45/85/2313 他の開発環境を組み込む](http://make.kosakalab.com/make/electronic-work/arduino-ide/attiny-dev/)など参照。 ## 改善点 現在のまたたき回路は起動に時間がかかるため、いっとうも無線制御にしようとしても、どうしてもONにしてから点灯するまでにラグが生じてしまう。 現在の間欠カオス法による1/fゆらぎの再現は現実に近いものなのかもしれないが、再現性を少し犠牲にしてでも、処理が軽く起動の速い新しいまたたき回路を作ることを考えてもいいかもしれない。 もしくは、またたき回路自体を無線制御できるようにするという手も考えられる。<file_sep>日周緯度変(さいたま) ==================== - 書いた人: <NAME>(nichiden_27) - 更新日時: 2017/02/26 - 実行に必要な知識・技能: AVRマイコン、電子回路 - タスクの重さ: 3/数週間 - タスクの必須度: 3/年による - 元資料 - ``日周・緯度変資料.pdf`` by 岩滝宗一郎(nichiden_22) - ``saitama.pdf`` by 荒田 実樹(nichiden_23) 概要 ---- .. raw:: html <pre style="font-family:IPAMonaPGothic,'MS Pゴシック',sans-serif;">                 \ │ /<br>                  / ̄\   / ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄<br>                ─( ゚ ∀ ゚ )< さいたまさいたま!<br>                  \_/   \_________<br>                 / │ \<br>                     ∩ ∧ ∧  / ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄<br>  ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄\∩ ∧ ∧ \( ゚∀゚)< さいたまさいたまさいたま!<br> さいたま~~~!   >( ゚∀゚ )/ |    / \__________<br> ________/ |    〈 |   |<br>               / /\_」 / /\」<br>                ̄     / /<br> </pre> 日周緯度変コントローラ「さいたま」の使い方や仕組みなどを説明します。壊れて部品交換が必要になった・新しいさいたまを作りたい際に参照してください。 沿革 ---- 日周緯度変のステッピングモーターを回すには、モータドライバという回路が必要になる。駒場祭プラネではモータドライバと制御基板を内蔵した専用コントローラーを使っており、2002年の\ `13日周以降 <http://twitter.com/fujita_d_h/status/254087988882046976>`__\ 今日に至るまで\ **「さいたま」** と呼ばれている。 「さいたま」や他の回路に使用するマイコンは長らくPICであったが、22日電で\ **AVR** が採用され、23日電、24日電でもこれを踏襲した。PIC時代はほとんどのプログラムがアセンブラで書かれていたが、AVRを使うようになってからはC言語が使われるようになった。 さいたまはたびたび作り変えられてきたが、現在使用しているのは22が製作した\ **さいたま6號** である。23は、さいたまをPCから制御するための装置「Ikebukuro」を導入した(Ikebukuroの資料参照)。24では基板を作り直し、その際マイコンを\ **ATmega** に変更したようだ。 使い方 ------ .. figure:: _media/saitama_connection.jpg :alt: さいたま6號と電源装置を接続している様子 さいたま6號と電源装置を接続している様子 背面に日周・緯度用に二つのコネクタがあるので、専用ケーブル※を使ってそれぞれのモータに繋ぐ。次に、モータの電力を確保するため、電源装置から\ **24V** を右面のDCジャックから供給しよう。 ※コネクタはELコネクタ(日本圧着)6極、ケーブルはVCTF0.5sq 5芯 .. figure:: _media/saitama_buttons.png :alt: さいたま6號のボタン配置図 さいたま6號のボタン配置図 コントローラ前面には6つのスイッチがある。現在では\ `外部制御 <ikebukuro.md>`__\ でPCから動かす方がはるかに便利だが、PCが使えない緊急時や急いでいるときはこのスイッチを使えばよい。 ラベルを参照すれば大体の意味は分かることだろう。回転のON/OFFと方向はそれぞれの軸で独立しているが、回転速度は2軸で変えることはできない。\ ``外部制御ON/OFF``\ スイッチは、PCから操作したい場合にONにする。これがONになっているときは、さいたま側のスイッチに反応しなくなるので気をつけよう。 電装 ---- ケースの両側に付いているねじを全て外すと、さいたまの中身を確認できる。 .. figure:: _media/saitama_internal.jpg :alt: さいたま6號の内部 さいたま6號の内部 - メイン基板 - **画像は23引き継ぎのものだが、この翌年に作り変えられているので注意** - マイコンがスイッチの状態を読取り、モータードライバにCW・CCWパルスを送信する - 基板に付いていたスイッチはあまり重要でなかったため、基板作り変えの際取り除かれた模様 - 2×3のピンヘッダは、AVRマイコンにプログラムを書き込むためのもの - モータードライバ基板 - CW・CCWパルスに応じてステッピングモータに電流を流す - 既製品。割と高価だが、部室に未使用の買い置きがある - スイッチ基板 - トグルスイッチが配置されている - 普通に使っている場合一番壊れやすい部分なのでたまに異常がないか見てあげよう プログラム ---------- 23代が\ ``nissyuido``\ ディレクトリ以下に使用したソースコードを残している。\ ``WinAVR``\ 環境があれば\ ``default``\ ディレクトリに移動して\ ``make``\ コマンドを打てばビルドされるとのことだ。 ただし、前述の通り\ **24代でマイコンをATmega328Pに変更**\ しており、以前のコードを使用できるかは定かでない。作り変えをする際は、24代の方に問い合わせてみることも検討されたい。 以下のプログラム解説は、23荒田氏の作成されたドキュメントと同内容である。必要なら氏のPDFや、コード中のコメントなども併せて確認すると良いだろう。 main.c ~~~~~~ .. figure:: _media/saitama_program_flow.png :alt: プログラムの流れ プログラムの流れ プログラムの起点となる ``main`` 関数が入っている。 プログラムの大まかな流れは図を参照。 プログラムは初期化(\ ``main.c``\ の\ ``init``\ 関数)の後、メインループ(無限ループ)に入る。ただ、初期化の時にタイマ割り込みを設定しているため、100マイクロ秒ごとに現在メインループで実行されている内容に関係なく「タイマ割り込み」の内容が実行される。 メインループの処理内容は\ ``main.c``\ を、「タイマ割り込み」の処理内容は\ ``motordrive.c``\ を参照されたい。 外部制御コマンドのフォーマットはここで処理している。 motordrive.c ~~~~~~~~~~~~ ここが最も重要な部分である。 ステッピングモーターのドライブ回路に定期的にパルスを送り、指定した速度でモーターを回す。 モーターを角速度\ :math:`Speed`\ (コード中ではm->current_speed :math:`[deg/s]`)で回すにはどうすればよいか考えてみよう。 一回のパルスでモーターが回転する角度はモーターとドライブ回路によって決まっており、\ :math:`\mathrm{MotorStep}=0.72 \mathrm{deg}`\ (コード中ではMOTOR_STEP :math:`[10^{-2}deg]`)である。 AVRのタイマ機能により、\ ``motordrive``\ 関数は\ :math:`\mathrm{ControlPeriod}=100 \mu\mathrm{s}`\ (コード中ではCONTROL_PERIOD :math:`[\mu\mathrm{s}]`)間隔で呼ばれる。 前回パルスを送ってからの経過時間を\ :math:`n\cdot\mathrm{ControlPeriod}`\ とする(前回パルスを送ってから\ :math:`n`\ 回目の\ ``motordrive``\ の呼び出し; :math:`n`\ はコード中ではm->count)。 このとき、簡単な考察により、\ :math:`n\cdot\mathrm{ControlPeriod}\cdot\mathrm{Speed}\ge\mathrm{MotorStep}`\ の時に次のパルスを送ればよいことが分かる。 実際には、速度指定モード・角度指定モードがあったり、速度を徐々に変化させる処理を行っているので、もう少し複雑なプログラムになっている。 「速度を徐々に変化させる処理」であるが、今のところ、現在の速度と目標速度が一致しなければ一定の加速度を加えるという、比較的単純な制御になっている。 時間と速度をグラフで表すと図のようになる。赤線が指定した速度、青線が実際の速度である。 このように速度を徐々に変化させるようにプログラムの改修を行ったので、もはや\ **「一旦回転を停止してから回転方向を変更する」必要はない。** .. figure:: _media/saitama_program_speed.png :alt: 速度変化 速度変化 角度指定モードの、速度を下げ始めるタイミングについて。 プログラムが実行されている時点を時刻\ :math:`t_0`\ とし、時刻\ :math:`t_1`\ にモーターが停止するとする。 モーターの\ :math:`t_0`\ における角速度を\ :math:`\omega_0`\ とする。単位時間当たりのモーターの角速度の変化を\ :math:`\alpha`\ とする。 現在のプログラムでは、\ ``motordrive``\ が呼ばれるたびに速度を\ :math:`1\mathrm{deg/s}`\ ずつ増減するので、 .. math:: \alpha=\pm\frac{1 \mathrm{deg/s}}{\mathrm{ControlPeriod}} である。モーターの時刻\ :math:`t`\ における角度(位置)を\ :math:`\theta(t)`\ とする。 時刻\ :math:`t`\ におけるモーターの角速度と角度はそれぞれ .. math:: \begin{aligned} \omega(t)&=\omega_0+\alpha(t-t_0) \\ \theta(t)&=\theta(t_0)+\omega_0(t-t_0)+\frac{1}{2}\alpha(t-t_0)^2 \end{aligned} となる。 時刻\ :math:`t_1`\ にモーターが停止、すなわち\ :math:`\omega(t_1)=0`\ より、 .. math:: t_1-t_0=-\frac{\omega_0}{\alpha} である。これを\ :math:`\theta(t_1)`\ に代入すると、 .. math:: \begin{aligned} \theta(t_1)&=\theta(t_0)-\frac{\omega_0^2}{\alpha} +\frac{1}{2}\alpha\left(-\frac{\omega_0}{\alpha}\right)^2 \\ %&=\theta(t_0)+\left(-\frac{1}{\alpha}+\frac{1}{2\alpha}\right)\omega_0^2 \\ &=\theta(t_0)-\frac{1}{2\alpha}\omega_0^2 \end{aligned} を得る。 求めたい量は、現在角がどういう値になったら速度を下げ始めるか、その角度である。 つまり、\ :math:`\theta(t_1)-\theta(t_0)`\ の値である: .. math:: \begin{aligned} \theta(t_1)-\theta(t_0)&=-\frac{1}{2\alpha}\omega_0^2 \\ &=\frac{1}{2\left(\frac{1 \mathrm{deg/s}}{\mathrm{ControlPeriod}}\right)}\omega_0^2 \\ &=\frac{\mathrm{ControlPeriod}}{2(1 \mathrm{deg/s})}\omega_0^2 \end{aligned} ステップ数に換算するために両辺を\ :math:`\mathrm{MotorStep}`\ で割ると、 .. math:: \frac{\theta(t_1)-\theta(t_0)}{\mathrm{MotorStep}} =\frac{\mathrm{ControlPeriod}}{2(1 \mathrm{deg/s})\mathrm{MotorStep}}\omega_0^2 を得る。 なお、コード中では\ :math:`\frac{\mathrm{MotorStep}}{\mathrm{ControlPeriod}}`\ に\ ``MOTOR_MAX_SPEED``\ という名前を与えている。 uart.c ~~~~~~ 外部とシリアル通信するための関数が記述されている。通信データのバッファリングを行っているが、この仕組みが正常に動いているかは検討の余地がある。 timer.c ~~~~~~~ ``motordrive``\ 関数を\ :math:`100\mu s`\ 間隔で呼び出すための設定を行う。 ぶっちゃけ、\ ``motordrive``\ 関数をそのままタイマ割り込みハンドラにし ても良い気がする。 コンパイルするには ~~~~~~~~~~~~~~~~~~ ソースコードを編集したら、書き込む前にコンパイルする必要がある。\ ``default``\ ディレクトリ以下に\ ``Makefile``\ が入っているので、\ ``Makefile``\ の意味が分かる人は利用すると良いだろう。 Makefileの意味が分からない人は、Atmel Studioだか何だか知らないが、適当にプロジェクトを作ってファイルを放り込んでコンパイルすればよろしい。その際、 - マイコンの種類は ATmega328P - クロック周波数は 16MHz: プリプロセッサの設定をいじって、\ ``F_CPU=16000000UL``\ がpredefinedになるようにする。(コンパイラオプションとして\ ``-DF_CPU=16000000UL``\ が渡されればOK) - 言語規格はC99+GNU拡張(コンパイラオプションとして\ ``-std=gnu99``\ が渡されればOK) となるように注意する。 今後の展望 ---------- もしもさいたまを作り替えるようなら、もう少し強力なマイコンを搭載すること、センサー(後述)対応にすること、\ **通信経路**\ についてもっとしっかり考えること(\ ``RS-485``\ にするのか、全部\ ``RS-232``\ とUSBシリアル通信で統一するのか)が望ましい。 23代で相対角度指定が実装されたが(現在使われていない)、\ **絶対角度指定**\ があると良いだろう。つまり、投影される星空を見ながら日周緯度変を操作するのではなく、「緯度は何度、日周は何月何日何時」という形で指定できるようにする。 絶対角度指定のためには、角度センサーを設置して現在位置を取得するか、一ヶ所にフォトインタラプタなどを設置して初期位置を判別できるようにして、後はステッピングモーターのステップ数で現在位置を把握する、などの方法が考えられる。 いずれにせよ、さいたまを作り直す際に日周緯度変に設置したセンサーを接続することを考慮しておくとよいだろう。 PC側のソフトウエアだが、PCで操作する以上何らかのメリットが欲しい。 速度を柔軟に調節できるようにはなったが、操作性にはまだまだ改善の余地がある。 リアルタイムで操作するには、マウスよりもキーボード、欲を言えばタッチパネルでの操作の方がいい。いろいろ工夫してみると良いだろう。 もう一つの方向性として、操作の記録・再生が考えられる。 ボタン一つで一本のソフトをまるまる上映できると楽だろう。ただし、ソフトウエアを実装する手間、操作を記録しておく手間に見合うメリットがあるかよく考える必要がある。 <file_sep>過電圧保護回路 ============== - 書いた人: <NAME>(nichiden_28) - 更新日時: 2018/09/28 - 実行に必要な知識・技能: 電子回路の知識 - 難易度: 2/少しやれば可能 - 情報の必須度: 3/必要な場合がある - 元資料 - ``27日電引き継ぎドキュメント またたき回路`` by Kenichi Ito(nichiden_27) 概要 ---- 27代までのまたたき回路についていた回路です。 27代まではまたたき回路の電源が5Vであったため、誤って12Vを刺しても壊れないように使っていました。 28代でまたたき回路の電源を12Vに変更したため必要なくなりましたが、あくとうコントローラーなど他の電源が5Vの回路に組み込むなどの利用方法があります。 回路 ---- .. figure:: _media/protection.png :alt: 過電圧保護回路 過電圧保護回路 閾値の検出に使用しているのは\ **ツェナーダイオード**\ である。 ダイオードには、逆方向に電圧をかけるとある閾値以上の電位差で逆向きに電流が流れ、それ以上電位差が大きくならない効果がある。 その閾値をツェナー電圧という。 通常のダイオードでは非常に高いツェナー電圧だが、ツェナーダイオードは不純物を混ぜることでツェナー電圧を下げている。 またたき回路で使用した\ ``HZ5B1``\ のツェナー電圧は4.6-4.8V。 カソード側の200Ωの抵抗により、回路全体としての閾値を\ **5.1-5.2V**\ としてある。 ``VCC_IN``\ が約5.1V以下の場合、ツェナーダイオードには電流が流れず、\ ``2SA1015GR``\ はOFFの状態になる。 ``2SA1015GR``\ のコレクタはプルダウンされているので0Vに落ち、FET(\ ``2SJ471``)にはゲート・ソース間電圧が発生する。 従って、FETのソース・ドレイン間に電流が流れ、\ ``VCC_OUT``\ に入力電圧がそのまま出てくる。 ``VCC_IN``\ が約5.2Vを超えると、ツェナーダイオードに逆向きの電流が流れ始める。 ``2SA1015GR``\ にエミッタ・ベース電流が流れることで、コレクタに電流が流れて\ ``2SJ471``\ のゲート電圧が\ ``VCC_IN``\ とほぼ等しくなる。 結果、ゲート・ソース間電圧はほぼ0Vとなり、FETがOFFの状態になって電源が遮断される。 この回路の耐圧はツェナーダイオードの許容損失による。 入力が約15Vを越えると許容損失を超え、ダイオードが焼き切れる可能性がある。 仮に焼ききれた場合、ツェナーダイオードに電流が流れない状態と同じになり、入力電圧が\ ``VCC_OUT``\ に出力されてしまう。 大変危険なので、\ **高電圧の電源を接続しないよう注意すべきだ**\ 。 保護回路の閾値は、ツェナーダイオードのツェナー電圧やカソード側の抵抗値を調整することで変更できる。 <file_sep>無線制御 ======== - 書いた人:<NAME>(nichiden_27) - 更新:<NAME>(nichiden_28) - 更新日時:2018/10/4 - 実行に必要な知識・技能:電子回路、マイコン - タスクの重さ: 5/準備だけで数ヶ月 - タスクの必須度:4/毎年やるべき 概要 ---- 星座絵は、プラネのにとって重要な要素ですが、常に点けたままというわけにはいきません。 解説やソフトの流れに合わせてたくさんの星座絵をリアルタイムでオンオフできる必要があるのです。 ただ、星座絵投影機の本体は、他の主投影機同様日周緯度変装置により回転します。 そのため有線での制御は困難です。 そこで、日電では星座絵の制御に無線を採用してきました。 沿革 ---- 16-21主投 ~~~~~~~~~ データとして共有されている限りの資料では、16日電が\ **FM変調方式** の電波を採用していた。 FMとは周波数変調方式のことで、ある周波数を閾値として0か1かのデジタル信号を表すというわけだ。 ただし、高周波のノイズが紛れ込むと0が1に反転してしまう問題があり、誤り訂正の工夫をしていたようだ。 この頃の情報は不完全で、不明なことも多い。 19日電の資料には、北天側で信号を受信し、南天側のサブ機に有線で信号を送ったとの記述がある。 送信機・受信機にはPICマイコンを使っていたようだ。 .. _主投-1: 22主投 ~~~~~~ 22では、AM変調の無線モジュールとAVRマイコンを採用した。 英RF Solutions社の\ ``AM-RT``/``AM-HRR``\ というモジュールを使用していたようだ。 22星座絵は16個あり、16bit(2byte)のデータでオンオフを表現できる。 送信側はトグルスイッチ16個を並べた基板と接続しており、スイッチの状態を読み取って電波信号に換える。 南北の受信機の区別にも工夫があった。 ジャンパピンの位置で、上位・下位それぞれ8bitのどちらを読み取るか切り替えられる。 これにより、送信側からは南北まとめて信号を送り、受信側で南北を区別する仕組みだ。 .. figure:: _media/wireless-22.jpg :alt: 22星座絵受信機に貼られていたラベル 22星座絵受信機に貼られていたラベル しかし、通信のエラーは排除しきれず、タイムラグも大きいものだった。 .. _主投-2: 23主投 ~~~~~~ 23日電になり、\ ``XBee``\ **が初めて採用された。** ``Xbee``\ は、\ ``ZigBee``\ というプロトコルを使用した無線モジュールだ。 買ってきて設定するだけで、手軽に無線通信を使用できる。 ロボットやCanSat(模擬人工衛星)の大会でも多数のチームが採用しており、性能は折り紙つきである。 ``XBee``\ にはシリアル通信のように扱えるATモードと、\ ``XBee``\ 自体を制御に使うAPIモードがある。 23で使ったのは前者で、送信側1台をPCに、受信側2台を南北それぞれの受信機回路に接続していた。 23では、これまでのように一方的にコマンドを送るだけでなく、\ **受信側の状態をフィードバック** することでエラー検出・修正を試みた。 しかし、回路の不備で正しい応答が返らず、星座絵の操作はできたもののフィードバックは実現しなかった。 受信機の回路には22同様AVRマイコンが使われていた。 さらに、過電圧保護回路やトランジスタアレイでのポート制御など、以降の星座絵受信機の基本となる設計がこの時期に生み出されたと言える。 .. figure:: _media/wireless-23-circuit.png :alt: 23星座絵受信機回路図 23星座絵受信機回路図 .. _主投-3: 24主投 ~~~~~~ 24日電では23の設計を受け継ぎ、受信機を作り替えた。 また、PC操作用のソフト\ ``Constellation Picture Transmitter``\ が開発された。 黒基調のUIが採用され、「黄道十二星座」「夏の大三角」といった星座グループの一括オンオフにも対応している。 ただ、受信側からのフィードバックで表示を修正する機能はうまく動作しなかった模様である。 .. figure:: _media/constellation-picture-transmitter.png :alt: Constellation Picture Transmitterの画面 Constellation Picture Transmitterの画面 .. _主投-4: 25主投 ~~~~~~ 25日電はPC側アプリケーションの改良を進め、\ ``Funabashi``\ を開発した。 しかし、不具合により本番で動かず、24の\ ``Constellation Picture Transmitter``\ に切り替えたという。 ``Fuinabashi``\ では24と同じように星座一覧から選ぶモードと、ソフトやライブ解説の指示に沿ってボタンが並ぶモードが用意された。 .. figure:: _media/funabashi.png :alt: Funabashiのソフト指示画面 Funabashiのソフト指示画面 .. _主投-5: 26主投 ~~~~~~ 26でも\ ``Fuinabashi``\ の開発が続けられ、完成に至った。 一方、リハーサルの頃に予備も含めて受信機の故障が相次ぎ、本番時点で北天用一台しか使えない事態に発展した。 急遽解説で使用する星座を14個まで減らし、公演ごとに配線を繋ぎかえる方針で投影を試みた。 しかし、公演間の準備の手間が増えた上、イレギュラーな南北配線により電源喪失が数回発生してしまった。 このため、星座絵の全点灯は最終日になってようやく達成されたのだった。 .. _主投-6: 27主投 ~~~~~~ 26までの受信機が全て故障していたことから、再生産が急務となった。 ソフトの要望により、こうとうの無線によるオンオフにも挑戦した。 最終的に、\ ``XBee``\ からWi-Fi規格のモジュールに変更し、全主投影機をオンオフする能力を備えた\ ``Piscium``\ が新たな受信機として登場した。 また、Wi-Fi採用により送信側はPC単体で済むようになり、操作用Webアプリ\ ``Acrab``\ が作られた。 .. figure:: _media/acrab-main.png :alt: Acrabのメイン画面 Acrabのメイン画面 星座絵一覧から選ぶ方式は変わっていないが、内部処理が大きく変容している。 クリックでボタンのオンオフを切り替えるのではなく、受信機からの応答によって全ボタンの表示を更新する仕組みだ。 これにより、必ず実際の投影機と\ ``Acrab``\ の表示が同期する。 23から続いていた受信機からのフィードバック機能を初めて実用化したと言えるだろう。 また、「公演用」画面においてソフトの指示をファイルから読み込み、進む/戻るボタンで簡単に操作できるようにした。 本番中の負担が大きく軽減され、星座絵のメンバーにも操作を手伝って頂くことができた。 .. figure:: _media/acrab-scenario.png :alt: Acrabの公演用画面 Acrabの公演用画面 実装など詳細は\ ``Piscium``\ ・\ ``Acrab``\ の個別記事に掲載する。 .. _主投-7: 28主投 ~~~~~~ 28では基本的に27の星座絵受信機\ ``Piscium``\ とWebアプリ\ ``Acrab``\ を使いまわした。 27の\ ``Piscium``\ は電源が不安定であるという問題があったため、そこを改善した。 27で全投影機の制御が実装されていたが、実際には電源が突入電流に耐えられず機能しなかった。 28で電源を改善したため、調整中には実際に全投影機の制御が可能であることが確認できた。 しかし、本番では問題が発生して星座絵以外の制御は使用しなかった。(詳しくは個別の記事で書く。) 無線通信の要件 -------------- 無線通信を実現する技術は、プラネの歴史を見ればわかるように様々である。 しかし、手法によらず達成しておくべき機能がいくつかある。 27の\ ``Piscium``\ や\ ``Acrab``\ 固有の反省点については個別記事内で触れる。 どの投影機を制御するか ~~~~~~~~~~~~~~~~~~~~~~ 無線制御装置は、元より星座絵を遠隔で点灯させるために始まった。 しかし27でその対象を全投影機に広げた。 ソフトの「星空が急に現れる」という演出の都合上、こうとうが確実に消える必要があったための措置である。 ところが本番での検証の結果、こうとうはあおとうで確実に搔き消え、しるとうのみの状態でも2等星が見えるか見えないかという状態だった。 そのため、実際はこうとうのONOFF制御はいらなかったかもしれない。 一方で、あおとうの全点灯時にもいっとうだけは見えていた。 ドーム内が「昼間」の状態でも一等星の位置が分かるのは日周の位置合わせに便利だったが、昼間に星が見えるのは本来正しくない。 星空を再現するのであれば、\ **夕日が沈むのに合わせて一等星を少しずつ点灯させるのがベストだろう。** 一等星を個別に操作※するのは難しいにしても、いっとう全体をオンオフする演出を取り入れる価値はあるだろう。 ソフトや他の投影機と一度話し合っておいてほしい。 ※とはいえ、いっとうと電源の間には既に「またたき回路」が挟まっている。またたき機能と無線機能を兼ね備えた新たな回路を作れば一等星を個別に操れるかもしれない。 送信側と受信側の同期 ~~~~~~~~~~~~~~~~~~~~ エアコンの赤外線リモコンを操作していて、障害物などで信号が届かなかった経験があるだろう。 こうした場合、リモコンの表示は「オン」なのに実際はオフ、といった食い違いが起こる。 ここからエアコンを起動するには、ボタンをさらに数回押してやらねばならない。 このように、操作対象と操作画面の状態がずれてしまうと混乱が生じやすい。 特に、数十の星座を番組進行に合わせてタイミングよく切り替えるプラネの現場ではなるべく避けたい事態だ。 これを解決するには、受信機が信号を受け取るたびに送信側に結果を通知する仕組みが有効である。 送信側の結果更新には受信機から受け取ったデータを使えば、\ **受信機の状態と画面の表示が必ず同期する。** この手法にもデメリットはあり、送受信に時間がかかるような環境ではボタンを押してから表示が変化するまでにラグが発生してしまう。 現在使われるような高性能のモジュールではほぼ問題はなさそうだが、遅延が無視できない対策が必要だ。 冗長化 ~~~~~~ 無線制御装置が本番で突然故障し、予備もないとしよう。 その瞬間から、星座絵は一つも点灯できず、星座絵メンバーの努力が水の泡となる。 このような恐ろしい事態を避けるために、二重・三重の対策が必要だ。 確実かつ思いつきやすいのが、\ **予備の受信機** を用意しておくことだ。 23〜25代の星座絵受信機は、ほぼ同じ設計のものが最終的に4台作られた。 これで、急に故障しても丸ごと交換してしまえば復旧できそうだ(故障原因を特定して潰せていればだが)。 全く同じものを作るのが難しくても、\ **壊れやすい部品の予備** を手に届くところに用意しておくだけでもいい。 無線モジュールやマイコンが破損し、買いに行こうにも部品屋はもう閉まっている…といった最悪の事態を回避できる。 また、予備部品は不具合があった際の問題の切り分けにも役立つ。 別の方針として、\ **手動スイッチの追加** というのがある。 無線通信が絶たれても、受信機のところまで行って手で操作すれば投影機が点灯するというものだ。 回路が余計に複雑になるので27では見送ったが、検討の余地はありそうだ。 電流管理 ~~~~~~~~ 投影機の光源は旧来の電球からLEDにシフトしつつある。 なかでも、強力な光源を必要とする主投影機が昨今相次いで採用しているのが、「パワーLED」だ。 パワーLEDは、一個で1Wや3Wといった大電力を消費する。 それを複数まとめて点灯させると、突入電流はかなりのものになることだろう。 過去の星座絵受信機の故障の原因の多くは、\ **想定を超えた過電流による端子の故障** と考えられる。 27の\ ``Piscium``\ で、あえてトランジスタアレイを使わずFETを採用したのも、万一問題が起きても故障が高価な部品にまで及ばないようにするためだ。 すぐに目に見える故障が起きないとしても、大電流が流れる回路であることを意識して、アースの確保や導線の太さの選定などに気をつけてほしい。 法令遵守 ~~~~~~~~ 今や、電波は我々の文明にとって欠かせない資源である。 わが国では、その利用について「電波法」で定めている。 無線局は誰でも勝手に設置して良いものではなく、原則として免許を受けねばならない。 ただし、無線LAN機器などはその例外にあたり、「\ **技適マーク**\ 」が付いていれば国内で使用してよい。 国内の部品屋などで買える無線モジュールには大概技適マークが付いているので、気にせずに使っても構わない。 しかし、技適マークは日本国内でしか通用しないので、海外の端末やモジュールにはないことも多い。 海外通販で部品を買う場合は、日本の技適を通っているかよく確認するのが望ましい。 <file_sep># 無線制御(PISCIUM) - 書いた人:眞木俊弥(nichiden_27) - 更新:<NAME>(nichiden_28) - 更新日時:2018/10/4 - 実行に必要な知識・技能:電子工作の経験、電子回路について一通りの知識、マイコン(Arduino, PIC)、インターネットの仕組み - タスクの重さ: 4/一月はかかる - タスクの必須度:5/しないとプラネ終了 ## 概要 ※とりあえず使えるようにするだけだったら、**概要**と**使い方**の部分を理解すれば大丈夫です。ブラックボックスになるように設計しました。ただ、故障した…とかいうことになったら、頑張って**技術仕様**のところを理解するか、いっそのこと全部作り直してください。 プラネタリウムの公演と、外で星をぼんやりみている時の差とは何でしょうか? それは、ずばり、分かりやすい解説やワクワクするストーリーがあるないかです! そして、その演出をサポートしてくれるものは何と言っても様々な神話や逸話に彩られた星座でしょう。 ただ、一般の人には満天の星空の中から星座を見つけ出すことは至難の技なので、プラネタリウムでは、「星座絵」を投影します。 そのため、ナレーションに合わせて星座絵を点灯・消灯する必要があります。 ただ、投影機からたくさん線を引き出してしまうと、日周・緯度の変化の際の回転で絡まってしまうため、我々のプラネタリウムでは、無線制御を行っています。 27代では、新たに無線制御装置を作り直しました。 その名も、`PISCIUM`(Planetarium Integrated Stars and Constellation Images Utility Module)です!! `PISCIUM`を使うことで、みなさんよくお世話になっているWi-Fiネットワークを介して、パソコン、スマホ、タブレットなどWi-Fiの接続可能な端末から星座絵などのかごしい内部の投影機を無線で制御できます。 28代で電源回りを設計し直し、細かいところを修正して作り直しました。 ## 使い方 `PISCIUM`はそのほかのボックス類と同じように、(百均)タッパーを加工したケースに収められています。 かごしいの側面に固定して使うことを想定しています。 また、事前に部室にあるはずの無線Wi-Fiルーターの電源を入れておきましょう。 ![](_media/router_photo.jpg) 使用するには、電源を接続し、出力用の側面のDCジャックに星座絵などの投影機を接続してください。 使用している電源は、[12V150WのACアダプター](http://akizukidenshi.com/catalog/g/gM-09089/)です。 `PISCIUM`を上から見たときに、DCジャックが見えていない方を下側面としたときに、 - 上側面の一番左以外と右側面が星座絵(12V)。全部で16ポート。ポート1からポート16まで。 - 左側面が、下から、こうとうONOFFなし(12V、2つ)、こうとうONOFFあり(12V、2つ)、いっとう(12V)、上側面の一番左がぎんとう(12V) となっています。 こうとうのポートだけは他と仕様が違うので注意してください。 また、いっとうとぎんとうは星座絵と仕様が全く同じなので入れ替えることができます。 無線Wi-Fiルーターに自動的に接続されるので、ブラウザで特定のURLにアクセスすることで制御が可能になります。 ブラウザでの制御に関しては、Webアプリケーション`Acrab`があるので、[そちらの説明](acrab.html)を参照してください。 また、基本的に給電は上記のように12V150WのACアダプターを電源用のコネクタに刺して行いますが、軽くテストしたいだけなのにかごしいに固定してある電源を利用するのは大変だと思います。 そのようなときは、ONOFFなしのこうとうのポートのどちらかに12Vの普通のACアダプター(端子がDCプラグのもの)を刺すと`PISCIUM`に給電ができます。 ただし、これはあくまでもテスト用の給電なので、星座絵を何個も同時に点灯させたい場合や、こうとうをつけたい場合など大電力を使う場合(ACアダプターの定格電力を超える場合)は正しい給電方法を行ってください。 また、**2つ以上の電源から同時に給電しない**ようにしてください。 ### 使用上の注意点 - 電源がついた状態での各投影機の抜き差しは故障の原因になるのでやめてください。 - ATX電源からACアダプターに変えたため電源が落ちることはなくなりましたが、万が一電源が落ちて再起動した場合、Wi-Fiモジュールも再起動します。 Wi-Fiモジュールが再起動した後、設定を送り直すため`Acrab`のページを再読み込みする必要あります(これは欠陥なので改善されるべき)。 - かごしいのグラウンドが弱いため、稼働している間に全体が帯電してしまうようです。 27代の公演でも、公演中に火花が飛び散り、空中放電して一瞬ブラックアウトしたことがあります。 **かごしいのアース接続を何とかする必要があります。** そうでないと最悪の場合、火花放電により出火します。 かごしい本体とは導通していることは確認しているので、かごしいか、それと導通しているごきぶりをアースしてください。 アースするときは、より線ではなく、単芯の太めの導線を使用し、体育館の柱など地面に突き刺さっている大きい金属に接続してください。 アースしただけで治るのかはよくわかりませんが、アースしてないのはまずいです。 28代ではその指摘を受けて、赤黒の太い線(より線ではあるが)を使って、片側はごきぶりの下の方にあるボルトに挟み、もう片側をバレーボールの支柱を立てる土台に固定してアースをしました。 そのおかげか28代では火花が散ることはありませんでした。 ただし、かごしいを触ると静電気のようなものを感じることは何度もあったので、帯電はしていたようです。 27代よりも頻繁に(毎公演の前に)調整を行っていたので、アースのおかげではなく、人間を通じて放電していただけなのかもしれないです。 - また、グラウンドが弱く、サージに耐えられないので、こうとうの制御は27代の時点では不可能(電源が落ちてしまう)でしたが、28代で電源を変えたのと、こうとうboxに突入電流防止用のサーミスタをつけたことで、こうとうの制御が可能になりました。 しかし、本番直前にPICのこうとうの制御をしているピンが壊れてしまい、本番はこうとうはONOFFなしのポートに接続し、常時つけっぱなしにしていました。 単純に経年劣化の可能性もありますが、こうとうをONOFFする際のサージにPICが耐えられなかった可能性があります。 実際、こうとうはあおとうやしるとうの光で見えなくなるので、公演の際にONOFFをいじる手間を考えると常時ONにするという選択肢もあるでしょう。 - いっとうの制御は可能ですが、いっとうボックスのまたたき回路の起動に時間がかかり、点灯までにタイムラグが生じるので、現時点では行える状況にありません。 またたき回路のプログラムを変更して、すぐに起動できるようにする、またはまたたき回路に無線の機能をつければいっとうの制御もできるようになるでしょう。 ## 技術仕様 27代、28代で作成したファイルは全て[Githubレポジトリ](https://github.com/Triangulum-M33/nichiden28)においてあります。 ### 回路 主な部品としては、Wi-Fiの制御を行う`ESP8266`というSoC(System on Chip: マイコン、通信制御回路などが一つのチップの中に収まっているもの)の開発ボード、`ESP8266`からのシリアル通信を受信して各DCジャックを制御するPICマイコン、DCジャックの電流をスイッチングするFETから構成されています。 ![回路図](_media/PISCIUM_circuit28.jpg) こうとう以外のポートには、DCジャックの付け根に2.2Ωの抵抗(定格1W)が入っています。 これは、27代において、各投影機をONにした際の突入電流によって電源が落ちるということが何度も起きたため、その突入電流を制限するために28代出つけました。 これで理論上突入電流は最大でも(12/2.2=)5.5Aまでしか流れないです。 こうとうに関しては特に大電流を流すので、こうとうbox側で別途突入電流対策をしています。 しかし、実際は28代でATX電源をACアダプターに変えたことで電源が落ちるという問題は解決されていた可能性もあり、この抵抗の意味があるのかはいまいち不明です。 さらに、28代で実際にあった事例として、星座絵のユニットの部分でショートしていたことがあり、電流を流しすぎてこの抵抗が焼き切れた(見た目上はわからないが電流が流れなくなる)ことがあります。 これは一度だけでなく何度も起きた事例で、抵抗を交換する手間がかかりました。 ただし、これは一概に悪いこととは言えず、もし抵抗がなかったらFETやもっと大事な部分が壊れていた可能性もあり、ヒューズのような役割を果たしていたともいえます。 かごしいに固定したままでも抵抗を交換できるような機構を作るのが一番良いのかもしれません。 ### ESP8266の開発ボード周りのソフトウェア (中華製の安物の)Wi-Fi入りマイコンボードを利用しています。 この`ESP8266`は、`Xtensa`というアーキテクチャを採用していますが、有志により、Arduino IDEで開発できるようになっていて、Wi-Fiサーバーなどの高度なプログラムもライブラリとして整備されていて、我々素人にとっては非常に開発のしやすいモジュールです。 また、今回使用しているボードには、すでに書き込み用の回路も付いているので、USBでパソコンに接続するだけで開発できます。 ただ、USB-シリアル変換素子はArduino純正のものとは違うので、ドライバをインストールする必要があります。 USB-シリアル変換素子の型番は、`CH340g`です。Githubとか製造元のサイトからドライバ落としてきてインスコしてください。 また、ボードの書き込み設定などは、[このサイト](http://trac.switch-science.com/wiki/esp_dev_arduino_ide)などを参照してください。 "ESP8266 書き込み"とかでググるとわんさか出てくるはずです。 27代が開発したプログラムは、`ESP8266`上でwebサーバー(のようなもの)を動かし、特定のURIのGETリクエストを受け取ると、シリアル通信でPICマイコンに点灯状況を送信する形になっています。 IPアドレスは、固定IPで、北天が192.168.11.100、南天が192.168.11.101になっています。 #### 使い方 [Wikiへのリンク](https://github.com/macv35/nichiden27/wiki/Piscium#usage) >Send GET request to certain url. >1. **Refresh Confirm** >(example) http://(ip)/refresh_confirm/status.json >1. **Set Port** >Set ON/OFF of each port. >(example) http://(ip)/setPort/status.json?P01=0&P02=1 >1. **Set Constellation Name** >Change names of pin used in communication. >(example) >http://(ip)/setConstellationName/status.json?p01=And&p02=Aql... >1. **All Set** >Set all port ON. >(example) http://(ip)/allSet/status.json >1. **All Clear** >Set all port OFF. >(example) http://(ip)/allClear/status.json 以上の5種類のコマンドが用意されています。 通常の公演時は、`Acrab`がこの辺のことはやってくれるはずですが、回路関係のデバッグをする際には、手持ちのスマホとかでこれらのURIにアクセスしながらやると楽です。 `ESP8266`が正しくURIをパーズすると、シリアル通信(UART)でPICマイコンにコマンドが送られます。 "NS"の2文字を送ったあとに、各DCジャック(ポート)20個分の点灯状況を点灯の時"1"、消灯の時"0"として、20文字分送ったあとに、23文字目に"\\n"(改行)をパケットとして送るプロトコルを使用しています。 名付けてNS(Nichiden Seizae)プロトコル…雑です、はい、すみません。 まあ、どうせUARTなんだし、こんな雑なプロトコルでも問題は起きていませんのでご安心を。 また、UARTでPICにパケットが送られるのと同時に、GETリクエストに対して、現在のステータスを表したjsonを返します。 参考までに、ソースコードのリンクをつけておきます。 (汚いのであんまり見ないでー。URIパーザーの部分とかは他のクラスに分けるとかするべきだった。) [Arduinoのスケッチ](https://github.com/macv35/nichiden27/blob/master/PISCIUM/PISCIUMServer/PISCIUMServer.ino) ### PICマイコンのソフトウェア `ESP8266`から送られてきたシリアル通信をデコードして各ポートのFETをオンオフするだけの子なので、大したことはしてないです。 `ESP8266`は3.3V駆動なのに対して、PICは5Vで駆動しているので、間にシリアルレベル変換素子は入れてあります。 MPLAB Xのプロジェクトファイルが引き継ぎ資料の`/pic_decoder/`ディレクトリに入っています。 もし万が一、PICが壊れたりした場合は、`PICkit3`を差し込めるピンヘッダを用意しておいた(28で作り替えた際に書き込み用のピンヘッダを省略して作りました。必要に応じて追加してください)ので、PICを交換して書き込み直してください。 書き込み方は、[PICkit3の使い方](http://ww1.microchip.com/downloads/jp/DeviceDoc/52010A_JP.pdf)をみてください。 <file_sep>【直前特集】本番で気をつけたい三箇条 ==================================== - 書いた人: <NAME>(nichiden_27) - 更新日時: 2017/11/22 - 実行に必要な知識・技能: 特になし - 難易度: 1/常識の範囲 - 情報の必須度: 5/全員必須 概要 ---- いよいよ本番が近づいてきました。 本番は準備期間とは違う動き方になるので、気をつけてほしいことをいくつか書きます。 新機能を諦める勇気 ------------------ 準備期間中は新しい機能を作り、改善するために努力してきたことでしょう。 ただ、本番ではこれまで表に出なかった問題が出現し、うまく動かないこともやはり多いです。 そうした時に、\ **新機能を捨てる判断**\ が素早くできることが大切です。 せっかく作ったものだから、何とか修理して使いたいというのは当たり前の心情でしょう。 ただ、\ **お客様や他の投影機の人**\ にとって何が最善かをぜひ考えて下さい。 お客様は日電の最新技術を楽しみに来場している訳ではありません(OB/OGや他団体の偵察は別)。 お客様は「東大天文部の星空」を体験するために来場されます。 **一回でも多くの公演を正常に行う**\ ことを最優先に、新要素を撤廃する、予備の方法に変えるなど柔軟に対応するのがよいと思います。 また、本番夜の時間帯には各主投影機の位置調整が行われます。 日電が設備の修理やテストを行えば、主投調整がそれだけ遅れてしまいます。 主投が本来の力を発揮できるよう、日電は安定した電源を提供することを重視してください。 人に頼る -------- 日電は人数が少なく、やることの多い本番では休む暇もなく動き続けるようなことが起きます。 休養が十分でないと視野が狭くなり、本来のパフォーマンスを発揮できません。 他の日電メンバーはもちろん、\ **その辺にいる天文部員に積極的に相談**\ してください。 手を動かす人が一人から二人に増えるだけで、作業効率はなんと(約)2倍なのです。 記録を残す ---------- **本番中に起きたことの記録**\ は、備品の故障部位の特定や次年度以降の改善にとても役立ちます。 忙しい中きちんとした記録など残せるはずもないですが、断片的なメモや、チャットのログなど後から経過を辿れるような心がけをしてみてはどうでしょうか。 駒場祭が終わると改善点などを報告するよう要請がありますし、駒場祭回顧号の執筆もあるわけですから、本番で頭に浮かぶちょっとしたことのメモは決して無駄にはなりません。 おわりに -------- 最後に、本番の成功と皆様の健康を祈念します。 (平成29年11月22日 27日電) <file_sep># 回路設計のためのソフトウェア - 書いた人: <NAME>(nichiden_27) - 更新日時: 2017/08/02 - 実行に必要な知識・技能: 基本的な電子部品の知識 - 難易度: 3/練習・勉強が必要 - 情報の必須度: 2/知ってると楽 ## 概要 電子回路の設計は手書きでもできますが、 - 回路図をチームで共有する - 後から配線などを整理する - 基板の配置を考える といった場合は**専用ソフトウェアで回路図を描く**のが便利です。 回路設計ソフトは多数存在し、それぞれに特色があります。 本稿では、よく名前の挙がるものや最近注目されているものを独断で選んで解説します。 ## BSch3V 開発 | 価格 | 拡張子 -------|-------|------- 水魚堂 | フリー | .CE3 - [公式](http://www.suigyodo.com/online/schsoft.htm) - [マニュアル](http://www.suigyodo.com/online/manual/) Windows(7/8/10)専用の回路図エディタ(macOS向けには[Qt-BSch3V Modified](#qt-bsch3v-modified)が存在する)。 ![BSch3Vの画面](_media/bsch3v.png) 構成は至ってシンプルだが、**軽快な動作と簡単な操作**に定評があり、小規模な回路であれば十分な機能を備えている。 **部品のライブラリをいくつでも導入できる**ため自由に拡張ができるのもポイントだ。 標準でも基本的な部品は用意されているが、マイコンなどのライブラリが多数のサイトで配布されているので、欲しい部品があればググってみよう(ソフトの古さ故**リンク切れ**も多いので、手に入らない場合は諦めること)。 また、部品エディタ「**LCoV**」が同梱されており、欲しい部品を自作したり(例: [BSch3V 向け Arduino MEGA 部品ライブラリつくった](https://blog.shiftky.net/bsch3v-arduino-mega/))、BSch3V側から編集したりもできる。 開発元の水魚堂では、プリント基板編集ソフト「[Minimal Board Editor](http://www.suigyodo.com/online/mbe/mbe.htm)」も配布している。 ### 操作/Tips - **ドラッグツール**は、範囲選択により回路の一部を移動できる。 * 配線の片方だけを動かすと簡単に**斜めの線**が作れる。 * 斜め線のアイコンは「エントリー」ツールで、配線の引き出しを表す。斜めの線として使わないこと。 - **太い線と細い線のツール**があるが、太い線は複数の線をまとめた「バス線」。 * 通常は細い方を使っていれば問題ない。 - レイヤ機能が存在し、右のツールバーから操作できる。 * 編集するレイヤを選択したり、可視/不可視の切り替えが可能。 * 選択レイヤ以外に配置したものは**クリックしても反応しない**。 + 不具合ではないので、慌てないこと! * 多くの情報を書き込む場合に、コメント・ラベルを別レイヤにするなどの使い道が考えられる。 - 他のPCやモバイルからの閲覧用に、**PDFファイルを用意しておく**とよい。 * BSch3V自体にPDF書き出し機能はないが、印刷メニューからPDFに変換できる。 ## Qt-BSch3V Modified 開発 | 価格 | 拡張子 -----------------|-------|------- informationsea | フリー | .CE3 - [公式](https://informationsea.info/apps/qtbsch3v/) QtというGUIフレームワークで[BSch3V](#bsch3v)をクロスプラットフォームに書き直した「Qt-BSch3V」というソフトが水魚堂で配布されている。 informationsea氏がQt-BSch3Vを最近のmacOS向けにさらに改造したのが、「Qt-BSch3V Modified」である。 これのお陰で、MacユーザでもCE3ファイルを開くことができる。 ![Qt-BSch3Vの画面](_media/qtbsch3v.png) BSch3V(及び同梱ソフト)の機能の多くが使用できるが、**日本語が表示できない**など問題もあるようだ。 ## Eagle 開発 | 価格 | 拡張子 ----------|--------------|------------ AutoDesk | フリー(学生版) | .sch, .brd - [公式](https://www.autodesk.com/products/eagle/overview) - [サポートトップ](https://knowledge.autodesk.com/ja/support/eagle?sort=score) 元々ドイツのCadSoft社が開発していたものを、[AutoDeskが2016年に買収した](http://makezine.jp/blog/2016/08/the-autodesk-family-grows-with-new-eagle-acquisition.html)。 Windows / Mac / Linuxで使用可能。 ![Eagleの画面](_media/eagle.png) 商用のプリント基板CADであり本来は数万円だが、基板サイズなどに制限付きの無料版が存在する。 さらに、AutoDeskの傘下に入ったことで**AutoDeskの学生プログラムの対象となった**。 [教育機関限定版および学生版](https://knowledge.autodesk.com/ja/search-result/caas/sfdcarticles/sfdcarticles/JPN/Eagle-Education.html)を使用することで、Premiumバージョン同等の機能を3年間使用できる(商用利用は不可)。 学生からすれば、**事実上の利用制限解除**である。 商用ソフトウェアなので機能は豊富であるが、そのぶん操作を覚えるのが大変でもある。 ## KiCad 開発 | 価格 | 拡張子 -----------------------|-------|----------------- KiCad Developers Team | フリー | .sch, .kicad_pcb - [公式](http://kicad-pcb.org/) **オープンソース**の回路CADソフト。 OSSなので当然全機能を無料で使用でき、商用利用に関する制限もない。 Eagle同様、各種OSに対応している。 kicadについてツイートすると、国内コミュニティ[\@kicad_jp](https://twitter.com/kicad_jp)の中の人がエゴサしてふぁぼってくれるらしい。 ![Kicadの画面](_media/kicad.png) 回路図やプリント基板の設計が可能で、非常に多機能。 チュートリアルをこなしてから使うことをお勧めする。 国内コミュニティの方々の努力により、現行バージョンでは**日本語版のマニュアルとチュートリアル**が同梱されるようになった。 メニューの `ヘルプ` から選択できる。 また、トラ技編集部から[Kicad本](https://www.amazon.co.jp/dp/4789849279/)も出版されているので、紙のチュートリアルが欲しければこちらを購入するのもいいだろう。 ## Fritzing 開発 | 価格 | 拡張子 ---------------------|-------|------ Friends of Fritzing | フリー | .fzz - [公式](http://fritzing.org/home/) オープンソースの回路図ソフト。ドイツのthe University of Applied Sciences Potsdamで開発され、現在は開発チームにより更新が行われている。 **部品の形状をそのまま表示して配置**するという独特のインターフェースを持ち、[メイカー](https://ja.wikipedia.org/wiki/メイカーズムーブメント)界隈で人気が高い。 Arduino関連のブログ記事などで、Fritzingにより生成された回路図を見る機会も多いだろう。 ![Fritzingの画面](_media/fritzing.png) 基本的には、右パネルに表示されたパーツをドラッグして配置していくだけで回路図ができてしまう。 新規ファイルを開いた状態では**ブレッドボード**が表示されるが、**ユニバーサル基板もパーツの一つとして用意されている**ためユニバーサル基板の配置を考えるときにも使える。 上メニューから「**回路図**」「**プリント基板**」などにも切り替えができる。 いずれかを編集すると残りも自動生成されるが、残念ながら見るに堪えない配置になることが多い。 面倒ではあるが、自分で配置を修正しよう。 「Fritzing Fab」というサービスにプリント基板のデータを送ると、ドイツ国内で基板を製作して送ってくれる。 また、他のプリント基板業者向けにデータを書き出すこともできる。 ## まとめ 手軽さを取るならBSch3VやFritzing、ある程度複雑な作業をするならKiCad、AutoDeskのファンならEagle……といったところだろうか。 最近はプリント基板を安価で製作してくれる業者が増え、**アマチュアの世界でもプリント基板の使用が拡大**しつつある。 プリント基板を使った製作を視野に入れるのであれば、KiCadやEagleを使えるようになることは決して損ではなさそうだ。<file_sep>東京大学地文研究会天文部 日電引き継ぎ ===================================== - 更新: 2017/03/04 <NAME>(nichiden_27) 日電の引き継ぎ文書です。ソースは全て公開しますので、ご自由に修正・追記してください。 .. figure:: _media/88x31.png :alt: Creative Commons Attribution-ShareAlike 3.0 Unported License Creative Commons Attribution-ShareAlike 3.0 Unported License 冒頭部の情報について -------------------- 各資料の冒頭部分には、「書いた人」「更新日時」「実行に必要な知識・技能」「タスクの重さ or 難易度」「タスクの必須度 or 情報の必須度」といった項目が示されています。 実行に必要な知識・技能 ---------------------- 資料で解説しているタスクや知識を実践するのに必要な知識などです。 自分が理解できそうな資料を探したり、作業をするために何を身につけるべきか判断したりする際に参考にしてください。 タスクの重さ ------------ タスク関連の記事に付いています。 - 1: 数時間で可能 - 2: 数日かかる - 3: 数週間 - 4: 一月はかかる - 5: 準備だけで数ヶ月 の5段階です。作業計画を立てる際などにご覧ください。 ただし、各代の方針によって、個々のタスクの重さは変動することに注意しましょう。 難易度 ------ 技術情報などをまとめた記事に付いています。 - 1: 常識の範囲 - 2: 少しやれば可能 - 3: 練習・勉強が必要 - 4: 分野に慣れてればできる - 5: 得意分野ならどうぞ 学んでおきたい分野の大枠を掴むのに利用してください。 タスクの必須度 -------------- タスク関連の記事に付いています。 - 1: よほど暇なら - 2: たまにやるべき - 3: 年による - 4: 毎年やるべき - 5: しないとプラネ終了 今年の日電で何をやるか決める手助けになるかもしれません。 情報の必須度 ------------ 技術情報などをまとめた記事に付いています。 - 1: 趣味レベル - 2: 知ってると楽 - 3: 必要な場合がある - 4: 担当者には必須 - 5: 全員必須 <file_sep># 備品管理 - 書いた人: <NAME>(nichiden_27) - 更新: <NAME>(nichiden_28) - 更新日時: 2018/08/26 - 実行に必要な知識・技能: 特になし - タスクの重さ: 1/数時間で可能 - タスクの必須度: 2/たまにやるべき ## 概要 日電は、日電自体の備品の他に電子部品や工具なども管理することになっています。 各投影機が備品を有効活用できるよう、日頃から備品の状態に気を配りましょう。 ## 日電カゴ ![日電カゴの外観](_media/basket.jpg) 部室の机がある側の区画に入って左側の棚の一番下に、黒色で持ち手が黄色のカゴと蓋つきの半透明のケースがある。 この二つが日電のカゴとなっている。 また、本番で入りきらなかったものはダンボールに入れてある。 なお、画像は27代のときのものなので2つともカゴだが、28代で片方はケースに買い替えた。 内容は代によって変化するものの、日周緯度変や無線送受信機、主投影機の配線など重要物品が入っている。 このカゴは基本的に他投影機の人は触らないので、**壊れたり無くなったりすると困るもの**を入れておこう。 ## 延長コード 部室の機材がある側の棚に延長コードのたくさん入ったケースと少し古そうな延長コードの入ったカゴ(ダンボールになっているかもしれない)がある。 これも日電の備品だ。 ケースに入っている延長コードは基本的に**本番ですべて使う**ので、本数などを確認したらあまり使わないほうがいいだろう(駒場祭の片付けで使わないものも混ざった可能性があるので要確認)。 他の投影機にも延長コードを使いたいときはカゴの方から持っていくように伝えておこう。 なお、延長コードのたくさん入ったケースは想像以上に重いので持ち運びの際は注意しよう。 ## 部室の部品及び工具 日電のカゴがあるのと同じ区画の棚には、電子部品や工具などが収納されている。 これらは基本的に日電の管轄で、勝手に使わないようになどと引き継ぎに書いてある投影機もある。 ただし、部室にある部品は基本的に過去に購入して余らせているものなので、各投影機で再利用してもらう方がむしろ有益である。 そのため、27代で部品の一斉調査を行い、機長向けに公開した。 また、部品・工具の使用に関しては以下のガイドラインに従えば自由に可能とした。 > - 使用にあたって特に許可を得る必要はありません(何かあれば日電へ)。 > - 学生会館の外には持ち出さず、使い終わったらすぐに部室に返してください。 > - 箱やカゴごと持ち出されると他の投影機が困りますので、工具や部品はなるべく 必要な数だけ持ち出すようにお願いします。 > - 部品については当該棚の一段目~三段目は余った在庫なので使用できますが、 それ以外の他投影機の箱やカゴのものは勝手に使わないでください。 > - 多くの投影機が電気関係の作業をするため、工具等が足りなくなることがあります。主投・補助投とも必ずないと困る工具は各自持ち込んでください。 28代ではここまで丁寧な告知はしておらず、この棚にあるものは自由に使って良いということだけ伝えた。 これで特にトラブルは起きなかったが、使う頻度の高い投影機の機長には個別に何があるか等も伝えた方が良いかもしれない。 部品の在庫調査は毎年行う必要は全くないが、各ケースの内容を軽く見ておくと突然部品が必要になっても対処できるようになるだろう。 箱の大部分にはラベルが付してあり、種類別にある程度分類されている。 ![部品ボックスの内容例](_media/partsbox-example.jpg) 27日電がパーツケースの中身を調査した際の資料を以下に示す。 ()内以外の部分はケースのラベルと対応している。 1. ヒューズ 2. トランジスタ・IC・マイコン(トライアック) 3. ピンヘッダ・ソケット・コネクタ 4. 力強い抵抗たちなど(大電力抵抗) 5. ミノ虫クリップ(ジャンパ線) 6. DCジャック・プラグ(トライアック) 7. スイッチ(トグル・プッシュ・タクト・マイクロ・ロータリー) 8. コンデンサ(集合抵抗・インダクタ) 9. あわれなレジスタンスたち(袋入り抵抗) 10. LED 11. 線材 12. 線材2 13. 調光器(トライアック万能調光器キット) 14. リレー 15. 放射板(ヒートシンク) 16. 電池ボックス 17. ボリウム(ツマミ) 18. ACソケット・その他コネクタ(大きめのもの中心) 19. ケース・基板・ブレッドボード 20. その他電球・モータなど 21. コネクタ1, 2 22. ネジ1, 2, 3 ただし、28代で整理をしたため内容が少し変わっているはずである。 また、作業が進むにつれて本来あるべき場所と違う場所にある部品もあるはずだ。 何があるかの把握にもなるので軽く整理するといいかもしれない。 工具に関しては十分な量が用意してあるが、特にハンダ付け関連のものは消耗しやすいので注意しておこう。 コテ台が足りなかったり、コテ先やスポンジが劣化したりしていた場合は買い出しの際に補充すると良い。 <file_sep>プロジェクト マネジメント ========================= - 書いた人: <NAME>(nichiden_27) - 更新日時: 2017/02/18 - 実行に必要な知識・技能: 特になし - タスクの重さ: 3/数週間 - タスクの必須度: 4/毎年やるべき 概要 ---- 日電長向けの内容です。日電の仕事をどう進めていくかなどを書きます。 チーム編成 ---------- 連絡手段を決める ~~~~~~~~~~~~~~~~ 27ではSlackを使用した。日電は作業内容が多岐にわたるため、一つのチャットグループでは話題が混乱してしまう。 LINEでも多数のグループを立てることで対応はできるが、管理が困難になるので最初からチームチャットを導入しておくことをお勧めする。 以下は27Slackの最終的なチャンネル構成である。 :: #acrab ... 星座絵アプリ #dome ... ドームコンソール #general ... 総合 #ginga ... ぎんとう #haisen ... 配線 #hojyotou ... 補助投 #ittou ... いっとう #log ... 活動記録 #nissyu-idohen ... 日周緯度変 #notifications ... 通知を流す用 #parts ... 部品管理 #piscium ... 星座絵無線機 #random ... 雑談 #seizae ... 星座絵 Slackの特徴の一つに、他のWebサービスとの豊富な連携がある。 27では、ToDoリストを共有できるTrelloやGitHubを使用した。通知がSlackで一覧できるので、進捗の共有が簡単になる。 余裕があれば、進捗を煽るBotなどを作成しても面白いかもしれない。 目標を設定する ~~~~~~~~~~~~~~ 日電のやることは毎年そう変わらないが、できれば先年までと違うことに挑戦するとよい。 ただし、新しい製品や機能には不具合や故障が付き物 であり、早期に目標を設定して動き始めることが重要だ。 前年度までに壊れてしまったものや、部員・観客へのインタビューで不満が多く寄せられた部分などが、新たな目標の候補となるだろう。 担当を決める ~~~~~~~~~~~~ 日電の仕事の特質は、\ **種類が多く、それぞれの作業は個人作業になりやすい** ことである。 また人数も限られているので、各自の責任感を高める意味でも早期に担当を振っておくべきだろう。 これには、日電員が作業に向けて勉強するにあたり、個々の課題を明確にするという利点もある。 スケジュールを決める ~~~~~~~~~~~~~~~~~~~~ 進捗は必ず遅れるものだが、だからと言ってスケジュールを切らずに闇雲に進めるのは大変危険である。 最低限、どの期間に何をするかの大枠は示しておきたい。27日電での例は以下の通り。 - 準備期間 〜8/1(Sセメ試験) - 試作期間 8/2〜9/25(夏休み終了) - 製作期間 9/26〜10/31 - 動作試験 11/1〜11/24(駒場祭前日) もちろん、実際の作業に入った後の進捗の把握や再検討は、日電長が随時やっておく必要がある。 作業が始まったら ---------------- 夜間 ~~~~ 日電は個人プレーが多いので夜間への参加は必須ではないが、他の投影機は随時日電のサポートを必要とするので最低一人は出ておくのが望ましい。 また、作業で得られた進捗は、\ **箇条書きなどにまとめて日電全員に報告** するとよい。 作業に参加していないメンバーが現状を把握できる上、日電長自身も進捗を目に見える形で確認できる。 卒検・リハ ~~~~~~~~~~ 卒検やリハでは、ドームを膨らませて投影機を配置し、点灯させる。 この間の配線は日電が全て行うので、大変仕事が多くかつ責任が重い。 この二日間だけは **日電メンバーを全員揃える** のが重要だ。 前々から日程は判明しているはずなので、各自の予定を確認しておこう。 <file_sep> <!DOCTYPE html> <!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]--> <head> <meta charset="utf-8"> <meta name="ROBOTS" content="NOINDEX,NOFOLLOW,NOARCHIVE"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>主投影機との連携 &mdash; Nichiden 0.9 RC ドキュメント</title> <link rel="stylesheet" href="_static/css/my_theme.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <link rel="index" title="索引" href="genindex.html"/> <link rel="search" title="検索" href="search.html"/> <link rel="top" title="Nichiden 0.9 RC ドキュメント" href="index.html"/> <link rel="next" title="補助投影機との連携" href="hojotou.html"/> <link rel="prev" title="備品管理" href="bihin.html"/> <script src="_static/js/modernizr.min.js"></script> <!-- Google Analytics --> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-102450326-2', 'auto'); ga('send', 'pageview'); </script> </head> <body class="wy-body-for-nav" role="document"> <div class="wy-grid-for-nav"> <nav data-toggle="wy-nav-shift" class="wy-nav-side"> <div class="wy-side-scroll"> <div class="wy-side-nav-search"> <a href="index.html" class="icon icon-home"> Nichiden </a> <div class="version"> 0.9 </div> <div role="search"> <form id="rtd-search-form" class="wy-form" action="search.html" method="get"> <input type="text" name="q" placeholder="Search docs" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation"> <p class="caption"><span class="caption-text">最近更新した記事</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="twinkle.html">またたき回路</a></li> <li class="toctree-l1"><a class="reference internal" href="nissyu-idohen/pc-software.html">日周緯度変(外部制御アプリ)</a></li> <li class="toctree-l1"><a class="reference internal" href="nissyu-idohen/pc-software-code.html">日周緯度変(Ogoseの実装解説)</a></li> <li class="toctree-l1"><a class="reference internal" href="wireless/piscium.html">無線制御(PISCIUM)</a></li> <li class="toctree-l1"><a class="reference internal" href="wireless/wireless.html">無線制御</a></li> <li class="toctree-l1"><a class="reference internal" href="protect.html">過電圧保護回路</a></li> </ul> <p class="caption"><span class="caption-text">目次</span></p> <ul class="current"> <li class="toctree-l1"><a class="reference internal" href="main.html">東京大学地文研究会天文部 日電引き継ぎ</a></li> <li class="toctree-l1"><a class="reference internal" href="management.html">プロジェクト マネジメント</a></li> <li class="toctree-l1"><a class="reference internal" href="nissyu-idohen/kikou.html">日周緯度変(日周緯度変換機構)</a></li> <li class="toctree-l1"><a class="reference internal" href="nissyu-idohen/saitama.html">日周緯度変(さいたま)</a></li> <li class="toctree-l1"><a class="reference internal" href="nissyu-idohen/ikebukuro.html">日周緯度変(Ikebukuro)</a></li> <li class="toctree-l1"><a class="reference internal" href="nissyu-idohen/pc-software.html">日周緯度変(外部制御アプリ)</a></li> <li class="toctree-l1"><a class="reference internal" href="nissyu-idohen/pc-software-history.html">日周緯度変(外部制御アプリの歴史)</a></li> <li class="toctree-l1"><a class="reference internal" href="nissyu-idohen/pc-software-code.html">日周緯度変(Ogoseの実装解説)</a></li> <li class="toctree-l1"><a class="reference internal" href="wireless/wireless.html">無線制御</a></li> <li class="toctree-l1"><a class="reference internal" href="wireless/piscium.html">無線制御(PISCIUM)</a></li> <li class="toctree-l1"><a class="reference internal" href="wireless/acrab.html">無線制御(Acrab)</a></li> <li class="toctree-l1"><a class="reference internal" href="wireless/acrab-code.html">無線制御(Acrabの実装解説)</a></li> <li class="toctree-l1"><a class="reference internal" href="wireless/graffias.html">無線制御(GRAFFIAS)</a></li> <li class="toctree-l1"><a class="reference internal" href="twinkle.html">またたき回路</a></li> <li class="toctree-l1"><a class="reference internal" href="protect.html">過電圧保護回路</a></li> <li class="toctree-l1"><a class="reference internal" href="haisen.html">配線</a></li> <li class="toctree-l1"><a class="reference internal" href="haisen-kagoshii.html">配線(かごしい内)</a></li> <li class="toctree-l1"><a class="reference internal" href="bihin.html">備品管理</a></li> <li class="toctree-l1 current"><a class="current reference internal" href="#">主投影機との連携</a><ul> <li class="toctree-l2"><a class="reference internal" href="#id2">概要</a></li> <li class="toctree-l2"><a class="reference internal" href="#id3">こうとう</a></li> <li class="toctree-l2"><a class="reference internal" href="#id4">いっとう</a></li> <li class="toctree-l2"><a class="reference internal" href="#id5">ぎんとう</a></li> <li class="toctree-l2"><a class="reference internal" href="#id6">星座絵</a></li> <li class="toctree-l2"><a class="reference internal" href="#id7">ドーム</a></li> <li class="toctree-l2"><a class="reference internal" href="#id8">ソフト</a></li> <li class="toctree-l2"><a class="reference internal" href="#id9">かごしい</a></li> <li class="toctree-l2"><a class="reference internal" href="#id10">展示</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="hojotou.html">補助投影機との連携</a></li> <li class="toctree-l1"><a class="reference internal" href="begginers/buy_parts.html">部品の買い方</a></li> <li class="toctree-l1"><a class="reference internal" href="begginers/electronic-design.html">回路設計のためのソフトウェア</a></li> <li class="toctree-l1"><a class="reference internal" href="begginers/microcontroller.html">マイコンをはじめよう</a></li> <li class="toctree-l1"><a class="reference internal" href="begginers/editor.html">テキストエディタを使ってみよう</a></li> <li class="toctree-l1"><a class="reference internal" href="begginers/visualstudio.html">Visual Studioをはじめよう</a></li> <li class="toctree-l1"><a class="reference internal" href="begginers/windows.html">無料でWindowsを手に入れる</a></li> <li class="toctree-l1"><a class="reference internal" href="handover.html">引き継ぎ資料の作成方法</a></li> <li class="toctree-l1"><a class="reference internal" href="honban.html">【直前特集】本番で気をつけたい三箇条</a></li> </ul> </div> </div> </nav> <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap"> <nav class="wy-nav-top" role="navigation" aria-label="top navigation"> <i data-toggle="wy-nav-top" class="fa fa-bars"></i> <a href="index.html">Nichiden</a> </nav> <div class="wy-nav-content"> <div class="rst-content"> <div role="navigation" aria-label="breadcrumbs navigation"> <ul class="wy-breadcrumbs"> <li><a href="index.html">Nichiden</a> &raquo;</li> <li>主投影機との連携</li> <li class="wy-breadcrumbs-aside"> <a href="_sources/syutou.rst.txt" rel="nofollow"> View page source</a> </li> </ul> <hr/> </div> <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article"> <div itemprop="articleBody"> <div class="section" id="id1"> <h1>主投影機との連携<a class="headerlink" href="#id1" title="このヘッドラインへのパーマリンク">¶</a></h1> <ul class="simple"> <li>書いた人: <NAME>(nichiden_27)</li> <li>更新: Kenta Suda(nichiden_28)</li> <li>更新日時: 2018/08/26</li> <li>実行に必要な知識・技能:</li> <li>タスクの重さ: 2/数日かかる</li> <li>タスクの必須度: 3/年による</li> </ul> <div class="section" id="id2"> <h2>概要<a class="headerlink" href="#id2" title="このヘッドラインへのパーマリンク">¶</a></h2> <p>駒場祭プラネでは、ほぼ全ての主投が電気に関わる作業をすることになります。 残念ながら、電子回路の知識が不十分なまま主投の作業を進めてしまう例も過去にありました。 主投の回路にミスがあると卒検やリハで上手く動かないのはもちろん、最悪の場合<strong>日電側の重要機器が壊れる</strong> こともあり得ます。</p> <p>忙しくなってから無用な手間をかけずに済むよう、早めに各主投の機長と情報交換を行いましょう。</p> </div> <div class="section" id="id3"> <h2>こうとう<a class="headerlink" href="#id3" title="このヘッドラインへのパーマリンク">¶</a></h2> <p>こうとうのモジュールは年々改良が進んでおり、引き継ぎも十分に行われている。 とりわけ26代で再設計されたユニットは、LEDの放熱も考慮されており、耐久性にも優れている。 3WのパワーLEDを光らせるだけの回路なので、特に頼まれない限り日電が補助する必要はないだろう。</p> <p>ただし、32個のユニットを全点灯すると、南北合わせて100W近く消費することになる。 こうとうへの電力を供給する回路やケーブルは、<strong>大電流に耐えられる</strong> ものにするよう注意されたい。</p> <p><em>主な使用部品</em></p> <ul class="simple"> <li><a class="reference external" href="http://akizukidenshi.com/catalog/g/gI-08956/">放熱基板付3W白色パワーLED</a></li> <li><a class="reference external" href="http://akizukidenshi.com/catalog/g/gM-04487/">定電流方式ハイパワーLEDドライバモジュール(3W1個点灯)</a></li> </ul> </div> <div class="section" id="id4"> <h2>いっとう<a class="headerlink" href="#id4" title="このヘッドラインへのパーマリンク">¶</a></h2> <p>いっとうは星の色を再現するため多様な色のLEDを用いる。 引き継ぎ資料が充実しており、LEDの抵抗計算も解説されている。</p> <p>使用しているLEDの型番などは確認していないが、秋月で売っている5mmの砲弾型LEDを利用している。 パワーLEDではないため、電力についてはそれほど気にしなくていいはず。 28代で実測してみたところ、いっとうをすべてつないだいっとうboxに対して最大でも500mAは超えなかった。</p> <p>またたき回路の開発は基本的に日電に一任されている。 頃合いを見て、またたき具合や種類の希望がないか機長に聞き取りをしておこう。</p> </div> <div class="section" id="id5"> <h2>ぎんとう<a class="headerlink" href="#id5" title="このヘッドラインへのパーマリンク">¶</a></h2> <p>消滅と復活を繰り返していたが、最近はクオリティが上がっている投影機。 光源は1Wの白色パワーLED。</p> <p>27代で<strong>調光機能</strong> が新設された。 投影された天の川が明るすぎ、恒星をかき消してしまう事態を避けるためである。 位置調整の時は明るくするなどの応用もできる。</p> <p>調光には、あくとう・しるとうと同様「定電流方式ハイパワーLEDドライバモジュール」に載っている<code class="docutils literal notranslate"><span class="pre">CL6807</span></code>の機能を用いる。 あくとうではPWMを利用しているが、ぎんとうはしるとうと同じ電位による調光を利用している(補助投の記事参照)。 抵抗二つと可変抵抗一つで調光できるので、PWMに比べて部品点数やサイズが大幅に減る。</p> <p>以下に調光の回路図を掲載する。 VCCやGNDはLEDと共通である。 なお、抵抗値は変更した可能性があるので実物で確認してほしい。</p> <div class="figure" id="id11"> <img alt="銀投調光回路図" src="_images/gintou_choukou.png" /> <p class="caption"><span class="caption-text">銀投調光回路図</span></p> </div> <p><em>主な使用部品</em></p> <ul class="simple"> <li><a class="reference external" href="http://akizukidenshi.com/catalog/g/gI-03709/">放熱基板付1W白色パワーLED</a></li> <li><a class="reference external" href="http://akizukidenshi.com/catalog/g/gM-04486/">定電流方式ハイパワーLEDドライバモジュール(1W1個点灯)</a></li> <li>抵抗(240Ω/4.7kΩ)</li> <li>可変抵抗(1kΩ)</li> </ul> </div> <div class="section" id="id6"> <h2>星座絵<a class="headerlink" href="#id6" title="このヘッドラインへのパーマリンク">¶</a></h2> <p>星座絵は、1W白色パワーLEDを使用している。 過去にLEDを抵抗なしで回路に繋ぐ、極性を間違えるなどの事象があり、<strong>無線受信機の故障原因を作った可能性もある。</strong></p> <p>代によって知識に差があるのは当然なので、日電側からも基本的な知識については確認しておこう。</p> <p>また、<a class="reference external" href="haisen-kagoshii.html">配線(かごしい内)</a>に書いたとおり、正座絵のコードでショートが何回か起きた。 そのため正座絵のコードも日電で作るもしくは使うコードを指定した方が良いかもしれない。</p> <p><em>主な使用部品</em></p> <ul class="simple"> <li><a class="reference external" href="http://akizukidenshi.com/catalog/g/gI-03709/">放熱基板付1W白色パワーLED</a></li> <li><a class="reference external" href="http://akizukidenshi.com/catalog/g/gM-04486/">定電流方式ハイパワーLEDドライバモジュール(1W1個点灯)</a></li> </ul> </div> <div class="section" id="id7"> <h2>ドーム<a class="headerlink" href="#id7" title="このヘッドラインへのパーマリンク">¶</a></h2> <p>ドームを膨らませる際に使う<strong>ドームコンソール</strong>(ダクトコントローラー)のメンテナンスは日電管轄である。 ドームを直立させるため、3つのダクトそれぞれの風量を調節できるようになっている。</p> <div class="figure" id="id12"> <img alt="ドームコンソールの外観" src="_images/ductcontroller.jpg" /> <p class="caption"><span class="caption-text">ドームコンソールの外観</span></p> </div> <p>中には秋月電子の<a class="reference external" href="http://akizukidenshi.com/catalog/g/gK-00098/">トライアック万能調光器キット</a>が3つ入っている。 交流の波形を変えることで出力パワーを変更するキットである。</p> <p>破損の可能性があるのは基本的にトライアックなので、万一故障してもトライアックを替えれば復活するかもしれない。 大電流から回路を保護するためヒューズがついているので、切れた場合は部室の予備と交換しよう。</p> <p>上側のスイッチでFULL/OFF/CONTROLの切り替え、下側のツマミで風量調節をする。 内部を見ればわかるが、FULLは入力・出力を直接繋ぐので、キットが使えなくなったとしても送風を継続できる。</p> <div class="figure" id="id13"> <img alt="ドームコンソールの使い方" src="_images/ductcontroller-instruction.png" /> <p class="caption"><span class="caption-text">ドームコンソールの使い方</span></p> </div> <p>2017年現在、24のドームコンソールが現役である。 以下は当時使用した部品。</p> <ul class="simple"> <li>タカチ MB-6 W140 H75 D200 ¥1,092</li> <li>マル信無線 MSR-6#7 中点OFFロッカスイッチ ¥158</li> <li>ロッカスイッチ 秋月AJ8221B ¥100</li> <li>ベターキャップ WH4015PK ¥115 マルツ</li> <li>ベターコネクタ</li> <li>トライアック調光器40A ¥800</li> <li>ユニバーサル基板 48 mm * 72 mm</li> <li>ヒューズホルダ(パネル取り付け・ミゼット用) ¥84</li> </ul> </div> <div class="section" id="id8"> <h2>ソフト<a class="headerlink" href="#id8" title="このヘッドラインへのパーマリンク">¶</a></h2> <p>早いうちに連絡を取っておくべきである。 代ごとのソフトの方針によって、日周緯度変や無線制御などに手を加えるべきか否かが左右されるためだ。</p> </div> <div class="section" id="id9"> <h2>かごしい<a class="headerlink" href="#id9" title="このヘッドラインへのパーマリンク">¶</a></h2> <p>主投を組み立てる際には日電と一体になって動くことが多い。 かごしいは機構部分、日電は回路部分との暗黙の住み分けがある。</p> <p>かごしい内のAC100Vケーブルの配線はかごしいに引き継がれているが、実際は日電が行うこともあるので資料を見せてもらうと良いだろう。 かごしい内配線については別記事で詳しく扱う。</p> </div> <div class="section" id="id10"> <h2>展示<a class="headerlink" href="#id10" title="このヘッドラインへのパーマリンク">¶</a></h2> <p>展示は、電気を使った模型を製作したこともあるが、基本的には電気と関わりのない唯一の主投と言っていい。 27代では、無線制御システムの解説ポスターを作成し、印刷と展示を依頼した。</p> </div> </div> </div> <div class="articleComments"> </div> </div> <footer> <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation"> <a href="hojotou.html" class="btn btn-neutral float-right" title="補助投影機との連携" accesskey="n" rel="next">Next <span class="fa fa-arrow-circle-right"></span></a> <a href="bihin.html" class="btn btn-neutral" title="備品管理" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left"></span> Previous</a> </div> <hr/> <div role="contentinfo"> <p> &copy; Copyright 2017, Nichiden Project. </p> </div> Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/rtfd/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>. </footer> </div> </div> </section> </div> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT:'./', VERSION:'0.9 RC', COLLAPSE_INDEX:false, FILE_SUFFIX:'.html', HAS_SOURCE: true, SOURCELINK_SUFFIX: '.txt' }; </script> <script type="text/javascript" src="_static/jquery.js"></script> <script type="text/javascript" src="_static/underscore.js"></script> <script type="text/javascript" src="_static/doctools.js"></script> <script type="text/javascript" src="_static/translations.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/javascript" src="_static/js/theme.js"></script> <script type="text/javascript"> jQuery(function () { SphinxRtdTheme.StickyNav.enable(); }); </script> </body> </html><file_sep>日周緯度変(日周緯度変換機構) ============================ - 書いた人: <NAME>(nichiden_27) - 更新: <NAME>(nichiden_28) - 更新日時: 2018/08/26 - 実行に必要な知識・技能: 歯車機構 - タスクの重さ: 5/準備だけで数ヶ月 - タスクの必須度: 2/たまにやるべき - 元資料 - ``saitama.pdf`` by 荒田 実樹(nichiden_23) 概要 ---- 日電の正式名称「日周緯度変・電源パート」から分かる通り、日電の本来の任務は日周緯度変装置を動作させることです。この記事では、日周緯度変装置自体に関しての情報をまとめます。 構成 ---- 日周緯度変の役割は、プラネタリウムにおいて日周運動を再現する、あるいは(仮想的な)観測地の緯度を変更することである。なお、天文部の現在のプラネタリウムには歳差軸はない。 日周緯度変は大きく - 日周ギヤボックス - 緯度変ギヤボックス の2つに分かれ、それぞれに対応するステッピングモーターが搭載されている。 このステッピングモーターは一個数万円するものだが、本番中に劣化するので数年おきに買い換えられている。高価な割に\ **ケーブルが切れやすい**\ ので、取り扱う際は十分な注意を要する。 ギヤボックスはどちらも\ **10年以上前に製作された**\ ものである。製作年度に関して確かと言える情報は見つかっていないが、緯度は1994年の05主投、日周は2000年前後で製作されたようだ。 これほどの機構を再現できる技術が失われたため、かなりの長期間作り変えられていない。 ただし、いつかは必ず壊れてしまうものであり、\ **なるべく早期に予備を製作すべき**\ だろう。 日周緯度変の製作に成功すれば、天文部の歴史に名が残ることは間違いない。 特に緯度変に関しては27の時点で、軸が摩耗していたり、ギアの噛み合わせが悪かったりして、緯度を動かし続けるとある角度でかごしい全体が「揺れる」ことがある。 28のかごしいが軸を新しいものにしたためこの「揺れ」は大分改善された。 ただし、ギアなどは古いままなので、作り直しは必要だろう。 ギヤボックス周辺の可動部分には\ **定期的にグリスを塗るか、潤滑油を差しておく**\ ことが望ましい。 ただし2017年現在、機構部分の保守作業の大部分は、\ **かごしいの作業の過程で行われている。** ごきぶりやしいたけとの接続も彼らの方がより把握しているはずなので、任せておいて問題はないだろう。 歯車機構と減速比 ---------------- 日周緯度変を自在に操るには各ギヤ比を知っておく事が必要である。 もちろん実物を見れば調べられるのだが、それなりに面倒だったので同じ手間を繰り返さないよう図に各ギヤの歯の数を載せておく。 また、「正の向き(時計回り)」にモーターを回した時に各ギヤがどちら向きに回るかも載せておく。 .. figure:: _media/nissyuuidohen_gear.png :alt: 日周緯度変のギヤ構成 日周緯度変のギヤ構成 図に書いてあるギヤの歯の数からギヤ比を計算すると、 .. math:: \begin{aligned} \frac{1}{80}\times\frac{25}{80}\times\frac{18}{64}=\frac{9}{8192} &&\text{緯度変} \\ \frac{1}{50}\times\frac{20}{100}=\frac{1}{250} &&\text{日周}\end{aligned} となる。なお、これらのギヤの歯の数は動かしながら手で数えたので、もしかすると数え間違いがあるかもしれない。あまり過信しないよう。 つまり、各軸をある角速度で回したい場合、緯度変の場合は\ ``8192/9``\ を、日周の場合は\ ``250``\ をそれぞれ掛ければモーターが出力すべき角速度が求まる。日周緯度変関連のソースコードで8192や250といった定数が登場するのは、この減速比の変換をするためである。 モーターの角速度 ---------------- ステッピングモーターは速度を自由に設定できるが、もちろん上限はある。緯度変更モジュール単体で試したところ、緯度モーターの最高角速度は\ :math:`3500 deg/s`\ 程度であった。 この速度をかごしいの速度に換算すると :math:`3500/(8192/9)=3.84 deg/s` となる。1度動かすのに0.26秒、南北の反転に46.8秒ほどという計算だ。 ただし、この\ :math:`3500 deg/s`\ という速度は速度を徐々に上げていった場合の最高速度であり、停止した状態から回転させる場合は\ :math:`1800 deg/s`\ 程度が限度だと思われる。この場合かごしいの速度は\ :math:`1800/(8192/9)=1.98 deg/s`\ となり、1度動かすのに0.5秒、南北反転には1分半かかることになる。 また、実際にかごしいを載せた場合や、主投影機を全て設置した場合など、回すものの重量によってさらに実際の速度は低下するので注意すること。 <file_sep>補助投影機との連携 ================== - 書いた人: <NAME>(nichiden_27) - 更新: <NAME>(nichiden_28) - 更新日時: 2018/09/26 - 実行に必要な知識・技能: 電子回路、マイコン、Arduino - タスクの重さ: 2/数日かかる - タスクの必須度: 3/年による 概要 ---- 補助投影機は主に1年生で構成されており、電気回路の知識が十分とは言えません(例外もある)。 そのため\ **補助投の電気関連の作業のサポート**\ も日電の仕事になっています。 主投影機関連ほどの労力はかからないので、随時進捗を見ながら助けになってあげましょう。 以下では、各投影機の\ **コントローラー**\ について書きます。 それ以外にも、投影機自体の回路や部品について聞かれることもありますが、臨機応変に対応してください。 あおとう -------- 現状、電球を毎年利用する唯一の投影機。 全投影機を\ **同時に調光**\ できる必要がある。 電球はAC100Vなので、交流のまま\ **調光回路だけを挟めばコントローラーになる**\ 。 使用しているのは、ドームコンソールでも採用している秋月電子の\ `トライアック万能調光器キット <akizukidenshi.com/catalog/g/gK-00098/>`__\ 。 このコントローラーをあおとうに使っている延長コードの根元に入れればよい。 電球の調光であればキットを一個そのまま使うだけでよく、故障も極めて起きにくいので、数年前のものを毎年使っている。 なお、同キットには秋月電子によるやたら詳しい説明書が付いているので、念のため一度は目を通しておきたい。 気をつけたい点としては、アルミケース上面に付いている\ **ボリュームの取り付けが緩む**\ ことくらいだ。 ツマミがぐらついていたら締めておこう。 *主な使用部品* - `トライアック万能調光器キット <http://akizukidenshi.com/catalog/g/gK-00098/>`__ - アルミケース あくとう -------- あくとうは、多色のLEDの明るさを制御する。 本体の回路製作自体が複雑で工数もかかるので、\ **コントローラの仕事は日電に回ってくることが多い**\ 。 あくとうの場合は特に、投影機のコンセプトとコントローラの機能が密接に関わってくる。 コンセプトの\ **聞き取りをしっかり行う**\ こと、投影機自体に関わる意思決定は\ **なるべくあくとうメンバーに委ねる**\ ことを心がけよう。 あくとうコントローラの歴史 ~~~~~~~~~~~~~~~~~~~~~~~~~~ 砲弾型LEDの調光 ^^^^^^^^^^^^^^^ LEDの明るさは電流や電圧などに対して線形には変わらないので、一般には\ **PWM(パルス幅変調)**\ という方式を使う(ここでは特に解説しない)。 LEDの電源自体を高速でオンオフする手法が用いられた。 16~17主投の代で、ロジックICなどを駆使して自前のPWM回路を作成していた記録が残っている。 22日電の時に作られたコントローラには、「\ **メモリ機能**\ 」というものが実装されていた。 これは、\ **発光パターンを記録しボタン一つで再生**\ しようという意欲的なものであったが、翌年には使用できなくなってしまった。 24日電では、メモリ機能を取り除き基板とプログラムの改修を実施した。 この時期のあくとうは、通常のLEDを大きな平板に付けたものを並べるという方式(LEDの個数は144個にのぼったという)を採っていた。 そのため、コントローラの他に東西切り替え器(信号を東西に分ける)・分配器(信号を各板に分ける)などの周辺機器も存在した。 .. figure:: _media/akutou_24.jpg :alt: 24主投当時のあくとうコントローラ 24主投当時のあくとうコントローラ パワーLEDの調光 ^^^^^^^^^^^^^^^ 25主投(26補助投)の時、あくとうが\ **パワーLEDを採用した**\ 。 パワーLEDは大電流を制御する必要があり運用が難しいが、秋月電子などが販売する「\ **定電流方式ハイパワーLEDドライバモジュール**\ 」を使用すれば、12Vを供給するだけで点灯する。 このドライバモジュールには\ ``CL6807``\ (`データシートPDF <http://akizukidenshi.com/download/ds/chiplink/CL6807_p.pdf>`__)という制御ICが搭載されているが、このICが調光機能を持っている。 ``ADJ``\ というピンに以下のような入力を与えることで明るさを制御できるのだ。 1. 0.4V未満: 消灯 2. 0.5V ~ 2.5V: 電位による調光 3. 6Vまで: PWMによる調光 25日電は、\ **これまでのコントローラを流用**\ できる3番目の方法を使用した。 これまではコントローラから直接LEDに電力を供給していたが、26あくとうで別電源になったため、新たにプルアップ回路を追加して対応したという。 自動化の試み ^^^^^^^^^^^^ 27あくとうでは、コントローラ自体を全面的に作り替えた。 投影機の目標が\ **操作の自動化**\ であったこと、東西切り替え器などの周辺回路をコントローラ自体にまとめようとしたことがその理由である。 自動モードか手動モードかを数字で区別できる\ **7セグメントLED**\ や、東西切り替えをコントローラ内で行う\ **ロータリスイッチ**\ が新たに追加された。 マイコンは製作者が慣れていたためPICを使用した。 .. figure:: _media/akutou_27.jpg :alt: 26主投当時のあくとうコントローラ 26主投当時のあくとうコントローラ 製作の遅れや単純なミスによる不具合は多々あったが、設計自体の大きな問題点を以下に列挙する。 1. 自動モードは停止やスピード変更ができず、\ **他投影機とタイミングが合いにくい** - (必ずしもすべてを自動にするのが最良とは言えない例である) 2. ロータリスイッチがノンショートタイプ(回す際回路が一度切れる)であり、東西切り替え時に信号が途切れる(=\ **投影機が全点灯**) - 本番では、東西切り替え前に一度投影機の電源を落とす対応をした 3. 調光でパワーLEDを消灯させた後、\ **電源ケーブルを抜くと一瞬LEDが光る** - ドライバモジュールのコンデンサに溜まった電荷が解放されるためと推測される 4. アルミケースのメンテナンス性が悪い - 堅牢だが開けにくく、導電性があることによる誤動作も起きた - **タッパを使おう!** 5. PICを使用した - 不具合対応できる人員が実質一人しかいなかった - 無理に素のマイコンを使っても苦しむだけではなかろうか 現在のあくとうコントローラ ~~~~~~~~~~~~~~~~~~~~~~~~~~ 現在、最新のあくとうコントローラは27日電が2016年に製作し、28日電が変更を加えたものである。 問題の多い全自動モードを廃止し、専用の\ **つまみを回すことで時間を進める**\ 半自動モードを実装した。 時間の進み方を担当者が調節することでタイミングを合わせやすく、しかも4色を別々に操作するよりはるかに手間が少ない。 .. figure:: _media/akutou_28.jpg :alt: 28あくとうコントローラ外観 28あくとうコントローラ外観 27あくとうの反省から、制御にはマイコンボードの\ **Arduino Nano**\ を使用し、\ **ケースはタッパ**\ として修理・デバッグを容易にした。 また\ **PWM機能が生きているかその場で確認**\ できるデバッグ用LEDを装着できるスペースも追加した。 回路 ^^^^ 回路図を掲載する。 .. figure:: _media/akutou_29_circuit.png :alt: 29あくとうコントローラ回路図 29あくとうコントローラ回路図 基本の構成はこれまで同様、ボリュームの抵抗値をマイコンが読み、出力端子からPWMを発生させるというものだ。 出力端子は10個使用し、\ **東西切り替えをソフトウェアで実現する**\ こととした。 使用する側の5本からはPWM信号が送られ、残り5本は電位が0Vに落ちる仕様だ。 回路図左上のCN1/CN2が投影機に接続するコネクタ、左下のLED群はデバッグ用LED(実際は取り外し可能)。 本体と違い、\ **電源電圧が5Vなので注意する**\ こと。 間違えて12VをつなげるとArduinoが壊れてしまうので\ **絶対にやってはいけない**\ 。 プログラム ^^^^^^^^^^ `AkutouController29.ino <https://github.com/Triangulum-M33/nichiden28/blob/master/akutou/AkutouController29/AkutouController29.ino>`__\ をArduino IDEで書き込んでいる。 なお、このコードは27日電の作成した\ `AkutouController28.ino <https://github.com/macv35/nichiden27/blob/master/akutou/AkutouController28/AkutouController28.ino>`__\ を加筆修正したものである。 全ては解説しないので、必要に応じコードを読んで理解していただきたい。 なお、言語はC++である。 Arduino NanoにはPWM用の端子が6本ある。 しかし、東西切り替えスイッチを物理的に作ると配線が面倒なので、\ **10本の端子からPWMが出せる**\ ようにした。 当然標準のライブラリでは対応できないので、マイコンの機能に頼らずにPWMを発生させねばならない。 幸い先人が作成したライブラリがいくつかあり、今回は\ `bhagman/SoftPWM <https://github.com/bhagman/SoftPWM>`__\ を使用した。 ``SoftPWMSet(ピン番号, 0~255までの整数)``\ という関数で、デジタル出力ピンからPWM信号を出力できる。 28のあくとうは4色だったので出力ピンが8本であったが、29のあくとうで5色になったので、出力ピンが10本になった。 そのため、シリアル通信のTX用のピン(D1)をPWMの出力用に使うようにしたので、実行中に\ **パソコンとのシリアル通信ができなく**\ なっている。 28あくとうの時はシリアルプリントによるデバッグができるようになっていたが、D1を使ったことでそれができなくなった。 シリアルプリントをしようとすると挙動がおかしくなる可能性があるので、すべてコメントアウトしてある。 また、29のあくとうで色を5色に増やしたことでRAM不足のエラーが出た。 これを解決するために発光パターンの配列を\ **フラッシュメモリに保存**\ するようにした。 フラッシュメモリに関しては\ `「Arduino 日本語リファレンス」の該当ページ <http://www.musashinodenpa.com/arduino/ref/index.php?f=0&pos=1830>`__\ を参考にするとよいだろう。 コード中で\ ``HC4511``\ というクラスを定義しているが、これは\ `74HC4511 <http://akizukidenshi.com/catalog/g/gI-11905/>`__\ という7セグLEDドライバIC用に作ったものである。 ``write(int value)``\ で数字を表示できるようにしてあり、さらに\ ``=``\ 演算子をオーバーロードして数字を代入するだけで使える仕様としている。 プログラム自体は、初期化→loop関数でPWM発生→ボタンが押されたら割り込みでモード変更 という流れになっている。 発光パターンを変えるだけであれば、\ ``PROGMEM const unsigned char LightPattern[3][5][120]``\ という配列の中身を書き換えるだけで良い。 こうしたカンマ区切りの整数列は、\ **Excelのオートフィルで数字を自動入力**\ した後カンマを付け足してコピペすることで容易に生成できる。 *主な使用部品* - Arduino Nano - `7セグメントドライバ HD74HC4511P <http://akizukidenshi.com/catalog/g/gI-11905/>`__ - `7セグメントLED(カソードコモン) <http://akizukidenshi.com/catalog/g/gI-00640/>`__ - 他スイッチ・ボリューム・コネクタなど しるとう -------- しるとうは消滅していた時代もあったが、23主投の代で復活し発展を続けている。 近年では街明かりの再現も兼ねており、消灯する場面をよりドラマティックにするため\ **調光機能**\ が必要とされる。 25代しるとうまでは電球を使用し、あおとうコントローラと同じ仕組みで調光できたが、26代からパワーLEDに切り替えた。 PWM信号をドライバモジュールに送ることで調光を試みたが、ドーム内ではうまく動かず、二年連続で断念している。 原因は確定していないが、あくとうより遥かに\ **ケーブルが長く(30m程度)PWM信号が減衰してしまう**\ ためと考えられている。 27日電の時に、パワーLEDモジュールの調光ICを\ **電位変化(0.5V~2.5V)で制御する方法**\ が確立され、本番で調光に成功した。 電位を変化させるだけならば、\ **抵抗二つと可変抵抗二つ**\ で作れてしまう。 原理はぎんとうの調光と全く同じであるのでそちらの回路図を参考にすること。 ただし、ぎんとうと違い、調光用には5Vの別電源を用いている。 **グラウンドの共通化**\ を忘れないようにしよう。 *主な使用部品(数値は電源が5Vの場合の例)* - 抵抗(1.2kΩ/240Ω) - 可変抵抗(1kΩ) 理論上この抵抗値でよいはずなのが、これだと完全に消灯しなかったため抵抗値を調整してある。 実物を見て確認すること。 また、電源の電圧がLEDは12Vであるが、\ **コントローラーの電圧は5V**\ であるので注意すること。 りゅうとう ---------- りゅうとうは毎回機構が大きく変化するため、コントローラの類も自分たちで製作することが多い(25日電がモータ制御用の回路を製作した事例はあるが)。 質問を受けたら答える程度で構わないだろう。 あゆとう -------- あゆとうは1WのパワーLEDを1つ使っているのみである。 必要な部品や配線の仕方を聞かれたら答える程度で大丈夫だろう。 <file_sep># 日周緯度変(Ogoseの実装解説) - 書いた人: <NAME>(nichiden_27) - 更新: <NAME>(nichiden_28) - 更新日時: 2018/10/08 - 実行に必要な知識・技能: Windows GUI開発、C#、WPF、Visual Studioの操作 - 難易度: 3/練習・勉強が必要 - 情報の必須度: 3/必要な場合がある ## 概要 [日周緯度変(外部制御アプリ)](pc-software.html)から`Ogose`の実装解説を分離した記事です。 `Ogose`のソースコードを読む、あるいは書き換える際に参考にしてください。 ## ファイル構成 `Ogose`のソースファイル等は、`Ogose`フォルダ内に入っている。以下にファイル・ディレクトリ構成の抜粋を示す。 ``` Ogose ├── Ogose │ ├── App.config │ ├── App.xaml │ ├── App.xaml.cs │ ├── MainWindow.xaml │ ├── MainWindow.xaml.cs │ ├── NisshuidohenController.cs │ ├── Ogose.csproj │ ├── Properties │ | └── (省略) │ ├── bin │ │ ├── Debug │ │ │ ├── Ogose.exe │ | │ └── (省略) │ │ └── Release │ │ ├── Ogose.exe │ | └── (省略) │ ├── main_projector_27_w.png │ └── obj │ └── (省略) └── Ogose.sln ``` 一見複雑で身構えてしまうかもしれない。 ただ、`Visual Studio(以下VS)`でプロジェクトを作成すると自動で生成されるファイルがほとんどで、実際に開発者が触るべきファイルは多くない。 `Ogose`直下には`Ogose.sln`がある。これは「ソリューション(開発プロジェクトをまとめたもの)」の状態を管理している。 slnファイルをダブルクリックするか、VS内の読み込みメニューで選択してあげれば`Ogose`の各ファイルを閲覧できる。 `Ogose`の下に更に`Ogose`ディレクトリがあり、この中にソースコードなどが収められている。 このうち、開発で実際に触ったのは`App.xaml` `MainWindow.xaml` `MainWindow.xaml.cs` `NisshuidohenController.cs`の四つのみである。 `Ogose/Ogose/bin/`以下には、ビルドで生成された`.exe`ファイルが格納される。 `Debug`と`Release`は適当に使い分ければいい。exeの他にも様々なファイルが吐き出されるが、基本的には`Ogose.exe`単体で動作する。 以下、ソースコードを簡単に解説する。WPF開発の基本的な知識全てに触れるとは限らないので、よく理解できない部分はググるなどして補完してもらいたい。 ## App.xaml `App.xaml`や`App.xaml.cs`の内容は、GUIのみならずアプリケーション全体に適用される。 何も書かなくても問題ないが、`Ogose`ではコントロールの外見に関する記述をこちらに分離した。[MainWindow.xaml](#mainwindow-xaml)が長くなりすぎないようにするのが目的である。 XAML(ざむる)は、XMLをベースとしたGUIの記述言語である。XMLのタグを用いて階層状に指示を書けるようになっている。 なお、`<>`で囲まれた単位は「タグ」とも「要素」とも言うが、GUIの要素と混同する危険があるので、ここでは「タグ」に統一する。 `<Application>`タグには色々とおまじないが書いてあるが、気にする必要はない。その下の`<Application.Resources>`内からがコードの本番だ。 ### ブラシ ```xml <!-- App.xaml --> <SolidColorBrush x:Key="WindowBackground" Color="#FF111111"/> <SolidColorBrush x:Key="ButtonNormalBackground" Color="#AA444444"/> <SolidColorBrush x:Key="ButtonHoverBackground" Color="#FF334433"/> <SolidColorBrush x:Key="ButtonNormalForeground" Color="White"/> <SolidColorBrush x:Key="ButtonDisableBackground" Color="#AA222222"/> <SolidColorBrush x:Key="ButtonDisableForeground" Color="SlateGray"/> <SolidColorBrush x:Key="ButtonNormalBorder" Color="#FF707070"/> <LinearGradientBrush x:Key="TextBoxBorder" EndPoint="0,20" MappingMode="Absolute" StartPoint="0,0"> <GradientStop Color="#ABADB3" Offset="0.05"/> <GradientStop Color="#E2E3EA" Offset="0.07"/> <GradientStop Color="#E3E9EF" Offset="1"/> </LinearGradientBrush> ``` **ブラシ**は、色などのデザインに名前(`x:Key`)をつけて使い回せるようにしたものである。各色の役割が明確になるし、後からの変更も楽なので積極的に利用した。 `SolidColorBrush`は単色のブラシ、`LinearGradientBrush`はグラデーションのブラシである。 配色が気に入らなければ、ここの色指定を変えれば良い。 色は名称で指定しても良いし([色一覧](http://www.atmarkit.co.jp/fdotnet/dotnettips/1071colorname/colorname.html#colorsample))、Webなどでお馴染みの16進数で更に細かく決めることもできる。 ここでは`ARGB`というRGBに加えアルファ値(透過度)も指定する方式で書いているので注意。例えば`#FF111111`なら、不透明で{R,G,B} = {17,17,17}の色を指す。 ### コントロールテンプレート **コントロールテンプレート**は、コントロール(ボタンやテキストエリアなど)のテンプレートである。 この中にボタンなどの見た目を書いておくと使い回しが効く。今あるコントロールテンプレートとその用途は以下の通り。 - "NormalToggleButton" ... 日周緯度変回転用のトグルボタン - "ComboBoxToggleButton" ... 接続するシリアルポートを選択するコンボボックス また、`<ControlTemplate.Triggers>`タグ内で「トリガー」を指定できる。 トリガーは、特定のイベントが起きたら動的にコントロールの見た目を変更する機能だ。 マウスでポイントした時やクリックした時に色が変わると、操作の結果がユーザーに視覚的に伝わる。 ```xml <!-- App.xaml --> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="true"> <Setter TargetName="InnerBackground" Property="Fill" Value="#FF222288" /> </Trigger> <Trigger Property="IsChecked" Value="true"> <Setter Property="Content" Value="停止" /> <Setter TargetName="InnerBackground" Property="Fill" Value="#FF111144"/> </Trigger> <Trigger Property="IsEnabled" Value="false"> <Setter TargetName="Content" Property="TextBlock.Foreground" Value="{StaticResource ButtonDisableForeground}" /> <Setter TargetName="InnerBackground" Property="Fill" Value="{StaticResource ButtonDisableBackground}" /> </Trigger> </ControlTemplate.Triggers> ``` 例として、`"NormalToggleButton"`のトリガー定義を紹介する。 マウスポインタが乗った時、Checked(ON)状態になった時でそれぞれ"InnerBackground"の色を変更するようになっている。 `Property="IsEnabled"`は、ボタンが有効(=操作できる)かを示しており、これが`false`の時は、文字・背景の色をグレー調にしてクリックできないことをアピールする。 ### スタイル **スタイル**には、要素の外観を定義できる。 前項のコントロールテンプレートに比べ機能が制限され、より個別の要素に対して用いる。 スタイルの適用の仕方はいくつかある。`TargetType`**に要素の種類を入れると、同じ種類の要素全てに適用される**。 以下は`Window`の見た目を指定している例。 ```xml <!-- App.xaml --> <Style TargetType="Window"> <Setter Property="Background" Value="{StaticResource WindowBackground}" /> <Setter Property="Height" Value="600" /> <Setter Property="MinHeight" Value="600" /> <Setter Property="Width" Value="700" /> <Setter Property="MinWidth" Value="700" /> </Style> ``` `<Setter>`タグはプロパティを操作するために使う。`Property`にプロパティの名前、`Value`に値を入れるだけである。 `Value`は実際の値でもいいし、ブラシなど他で定義したリソースを与えてもよい。 `<Setter>`の中には更に様々な機能を持ったタグを入れられる。`<ControlTemplate>`が入っていることもあるし、`<Style.Triggers>`タグでトリガーを設定することもできる。 複雑な使い方は筆者もよく把握していないので、頑張ってググって貰いたい。 もう一つのスタイル適用方法は、`x:Key`**プロパティ**を用いることだ。`<Style>`タグに`x:Key="hogefuga"`のように分かりやすい名前をつけておく。 ```xml <!-- App.xaml --> <Style x:Key="DiurnalPlusButton" TargetType="ToggleButton" BasedOn="{StaticResource ToggleButton}"> <Setter Property="Content" Value="日周戻す" /> <Setter Property="FontSize" Value="18" /> </Style> <Style x:Key="DiurnalMinusButton" TargetType="ToggleButton" BasedOn="{StaticResource DiurnalPlusButton}"> <Setter Property="Content" Value="日周進める" /> </Style> ``` そして、適用したいボタンなどに`Style="{StaticResource hogefuga}"`などと指定すれば該当する`x:Key`を持つスタイルが適用される。 ```xml <!-- MainWindow.xaml --> <ToggleButton x:Name="diurnalPlusButton" Style="{StaticResource DiurnalPlusButton}" Grid.Row="2" Grid.Column="0" Command="{x:Static local:MainWindow.diurnalPlusButtonCommand}" /> ``` 上の`App.xaml`のコードでは、**スタイルの継承**という機能も活用している。 `BasedOn`プロパティに基にしたいスタイルの`x:Key`を指定すると、そのスタイルの中身を引き継いだり、部分的に書き換えたりできる。 例えば、`"DiurnalMinusButton"`スタイルは`"DiurnalPlusButton"`スタイルを継承したので、`FontSize`について再度記述する必要がない。 一方で、ボタンに表示する文字は変更したいので、`Content`を書き換えている。 ## MainWindow.xaml メインのウィンドウの構造を記述する。 といっても`Ogose`には一つしかウィンドウがないので、配置を変えたい場合はこれを編集すればいい。 UIのデザインについてもこの中に書けるが、たいへん長いので[App.xaml](#app-xaml)に移した。 ### 編集方法について ウィンドウの見た目はXAMLのコードだけで自在に操れるが、VSではより便利に、実際の画面をプレビューしながらドラッグ&ドロップで編集することもできる。 ![Visual Studioの画面プレビュー編集](_media/mainwindow-xaml.png) GUIでの編集は手軽で初心者にも扱いやすいが、コードが自動生成されるので手で書くよりも読みにくくなりがちだ。 また、数値を細かく決めたい場合はコードを直接編集した方が早い。 図のように画面プレビューとコードは並べて表示できるので、双方の利点を使い分けるとよかろう。 ### グリッド WPFのレイアウト要素はいくつかあるが、`Ogose`では`<Grid>`タグを使ってレイアウトしている。 **グリッド**は、画面を格子状に分割してその中に要素を配置していくことができる。 いちいち行や列を定義せねばならず面倒だが、サイズを相対的に決められるので、ウィンドウを大きくしたときボタンも拡大されるというメリットがある。 ```xml <!-- MainWindow.xaml --> <Grid x:Name="MainGrid"> <Grid.RowDefinitions> <RowDefinition Height="1*"/> <RowDefinition Height="30"/> <RowDefinition Height="40*"/> <RowDefinition Height="2*"/> <RowDefinition Height="1*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="1*"/> <ColumnDefinition Width="60*"/> <ColumnDefinition Width="20*"/> <ColumnDefinition Width="20*"/> <ColumnDefinition Width="1*"/> </Grid.ColumnDefinitions> <Grid x:Name="HeaderGrid" Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="3"> <Grid.ColumnDefinitions> <ColumnDefinition Width="9*"/> <ColumnDefinition Width="1*"/> <ColumnDefinition Width="13*"/> <ColumnDefinition Width="7*"/> </Grid.ColumnDefinitions> ``` 上のコード片は、グリッドを定義している例である。 一意の`x:Name`を付けて`<Grid>`を宣言したら、`<Grid.RowDefinitions>`で行を、`<Grid.ColumnDefinitions>`で列を定義する。 #### グリッドの使い方 それぞれの中に行・列を欲しいだけ並べれば良いのだが、**高さや幅の指定**にポイントがある。 数値のみを書くとピクセル数を表すが、`数値*`とすると相対サイズを表せるのだ。 例えば、`Height="1*"`の行と`Height="2*"`の行だけがある場合、グリッドは1:2の比率で分割される。 また、コード例では使っていないが`Auto`を指定すると、中に配置した子要素のサイズに合わせてくれる。 ピクセル指定、相対指定、Auto指定は混ぜて書いても問題ない。 画面プレビューで行や列を分割した場合、サイズが単純な数値にならないので適宜コード側で修正するといいだろう。 **グリッドの中に要素を置く**時は、画面プレビュー上で設置したい場所に動かすだけで良い。 ただし、グリッドは入れ子にすることもでき(コード例では`MainGrid`の下に`HeaderGrid`を入れてある)、意図した階層に置けないことも多々ある。 その場合は、望みの階層に要素の定義をコピペした上で、`Grid.Row`と`Grid.Column`プロパティに何行何列目かを指定する。 両プロパティは**0始まり**なので要注意。`Grid.Row="1" Grid.Column="1"`なら2行2列目だ。 要素が横に長く、**複数の列に渡って配置**したいーそんな時は、`Grid.RowSpan`や`Grid.ColumnSpan`を使おう。 それぞれに指定した数だけ要素が占める場所が下方向・右方向に伸びる。 これは、画面プレビューで操作している時に勝手に追加されていることもあるので、やはりコード側で直してあげよう。 ### UI要素 個別のUI要素については実際にコードを見ていただく方が早い。 `Ogose`では`ComboBox`、`ToggleButton`、`RadioButton`、`CheckBox`などを使い分けている。 それぞれの動作を規定するコードについては、[MainWindow.xaml.cs](#mainwindow-xaml-cs)の項で扱う。 少し説明が必要なのは、`RadioButton`についてだ。 **ラジオボタン**というと、 ``` ◎ 選択肢1 ◎ 選択肢2 ``` のようなデザインが普通だ。 しかし、`Ogose`では縦に並べたり横に並べたりするので、横の二重丸がなく/普通のボタンと同じ見た目で/全体がクリック可能 である方が都合がよい。 実は、これには複雑なコーディングは必要なく、トグルボタン用のスタイルを適用してやるだけで済む。 ```xml <!-- App.xaml --> <Style TargetType="RadioButton" BasedOn="{StaticResource ToggleButton}"> ``` これは、`RadioButton`クラスが`ToggleButton`クラスを継承しているため、共通のスタイル指定が使えることによる (参考にした記事: [RadioButtonなToggleButtonを実現する](http://neareal.net/index.php?Programming%2F.NetFramework%2FWPF%2FRadioToggleButton))。 ## MainWindow.xaml.cs `MainWindow.xaml`のコードビハインドである。C#で書かれている。 日電のWindowsアプリケーションは代々C#なので、宗教上やむを得ない事情がなければC#を読み書きできるようになろう。 とはいえ、VSのコード補完(`IntelliSense`)が凄く優秀なので、コードを書いていて苦労することはあまりなさそうだ。 筆者もC#経験はないが、言語使用についてはfor文を少しググったくらいで不便を感じることは少なかった。 コード中にやたら`<summary></summary>`で囲まれたコメントを目にすると思うが、これはVSのドキュメント自動生成機能の推奨XMLタグらしい。 ドキュメントを作るかは別として、面倒でなければこの形式のコメントにして損はなさそうだ。 400行近いコードの全てを解説することはしないので、コードだけでは分かりにくいと思われる項目のみを以下に掲載する。 ### コマンド **コマンド**とは、ユーザの操作を抽象化したものである。 例えば、Wordで編集していてペースト操作をしたいとき、どうするか考えてみよう。 ショートカットキーを知っていれば`Ctrl(Command)`+`V`を叩くだろうし、右クリックしてペーストを選ぶ人もいるだろう。 メニューバーからペーストメニューを選択してもペーストできる。 操作はいろいろだが、結果として呼ばれる処理は同一なのだ。 この仕組みがコマンドで、WPFでは`ICommand`というインターフェースで実現される。 無理にコマンドを使わずともアプリは作れるのだが、`Ogose`のキーボード操作を実装する際、必要に迫られて導入した。 これまでと違い`Ogose`の回転/停止ボタンはトグル式で、色やラベルが状態により変化する。 25までClickイベントを用いる方式では上手く行かなくなったのである(キー操作だと、外観を変えるべきボタンの名称を関数内で取得できないため...だった気がする)。 そこで、`ICommand`を使うようにプログラムを書き直した。 時間がない中でやったので、かなり汚いコードになってしまった。 今後書き換える際はぜひ何とかして欲しい。 #### コマンドの使い方 コマンドは高機能の代わりに難解なので、使い始めるときは[この記事](http://techoh.net/wpf-make-command-in-5steps/)あたりを参考にした。 まず、`RoutedCommand`クラスを宣言する。絶賛コピペなので意味はよく知らない。 `diurnalPlus`は日周を進めるという意味だ。 ```c# /// <summary> RoutedCommand </summary> public readonly static RoutedCommand diurnalPlusButtonCommand = new RoutedCommand("diurnalPlusButtonCommand", typeof(MainWindow)); ``` この状態ではまだコマンドとボタン・処理が結びついていない。 CommandBindingという操作でこれらを紐付けする。これもコピペ。 ```c# /// <summary> /// MainWindowに必要なコマンドを追加する。コンストラクタで呼び出して下さい /// </summary> private void initCommandBindings() { diurnalPlusButton.CommandBindings.Add(new CommandBinding(diurnalPlusButtonCommand, diurnalPlusButtonCommand_Executed, toggleButton_CanExecuted)); /// (省略) } ``` これをボタンの数だけ書き連ねる。 `new CommandBinding()`に与えている引数は順に、コマンド・実行する関数・実行可能かを与える関数である。 三番目のコマンド実行可否は、コマンドを実行されては困る時のための仕組みだ。 ```c# /// <summary> 各ボタンが操作できるかどうかを記憶 </summary> private Dictionary<string, bool> isEnabled = new Dictionary<string, bool>() { {"diurnalPlusButton", true}, {"diurnalMinusButton", true}, {"latitudePlusButton", true}, {"latitudeMinusButton", true} }; ``` ``` c# private void toggleButton_CanExecuted(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isEnabled[((ToggleButton)sender).Name]; } ``` 上手い方法が全然思いつかなかったので、`isEnabled`という連想配列を作っておいて、呼び出し元ボタンの名前をもとに参照するようにした。 呼び出し元は、引数`sender`に与えられて、`ToggleButton`など元々のクラスに型変換するとプロパティを見たりできる。 さて、`private void initCommandBindings()`をプログラム開始時に実行しなければバインディングが適用されない。 `MainWindow`のコンストラクタ内で呼び出しておく。 ```c# public MainWindow() { InitializeComponent(); initCommandBindings(); } ``` 考えてみれば大したことはしてないので、コンストラクタの中に直接書いてしまっても良かったかもしれない。 あとはXAML側でコマンドを呼び出せるようにするだけである。 `<Window>`タグ内にローカルの名前空間(`xmlns:local="clr-namespace:Ogose"`)がなければ追加しておこう。 各コントロールの`Command`プロパティにコマンドをコピペする。 ```xml <!-- MainWindow.xaml --> <ToggleButton x:Name="diurnalPlusButton" Style="{StaticResource DiurnalPlusButton}" Grid.Row="2" Grid.Column="0" Command="{x:Static local:MainWindow.diurnalPlusButtonCommand}" /> ``` これでクリック操作でコマンドが使えるようになる。 #### キー操作でコマンドを実行する(※28日電では誤操作防止のため使用せず) ここまできたら、キー操作でもコマンドが実行されるようにしたい。 XAMLで`<KeyBinding>`タグを使えば実現できるのだが、なんとこれではボタンが`sender`にならない。 色々調べても対処法が見つからないので、結局キー操作イベントから無理やりコマンドを実行させるしかなかった。 ```c# private void Window_KeyDown(object sender, KeyEventArgs e) { var target = new ToggleButton(); switch (e.Key) { case Key.W: latitudePlusButtonCommand.Execute("KeyDown", latitudePlusButton); break; case Key.A: diurnalPlusButtonCommand.Execute("KeyDown", diurnalPlusButton); break; case Key.S: latitudeMinusButtonCommand.Execute("KeyDown", latitudeMinusButton); break; case Key.D: diurnalMinusButtonCommand.Execute("KeyDown", diurnalMinusButton); break; } ``` `(コマンド名).Execute()`メソッドの第一引数は`ExecutedRoutedEventArgs e`の`Parameter`、第二引数は`object sender`として渡される。 結局、`sender`は第二引数に人力で指定した。 `e.Parameter`というのは、仕様では「コマンドに固有の情報を渡す」とされていて、要は自由に使っていいようだ。 キーボード操作によるものかどうか、コマンドの処理で判定するために"KeyDown"という文字列(勝手に決めた)を渡している。 ※28代でメモ欄を設置したことにより、キー操作による誤操作の可能性が高まったことと、皆結局マウスで操作していることからいったん`MainWindow.xaml`の`Keydown`イベントを削除し、キー操作でのコマンド実行を無効にした。 #### コマンドで呼ばれる処理 最後に、CommandBindingでコマンドと紐付けた関数について書く。 日周を進めるボタンのものは以下のようになっている。 ```c# private void diurnalPlusButtonCommand_Executed(object sender, ExecutedRoutedEventArgs e) { if (e.Parameter != null && e.Parameter.ToString() == "KeyDown") { ((ToggleButton)sender).IsChecked = !((ToggleButton)sender).IsChecked; } if (sender as ToggleButton != null && ((ToggleButton)sender).IsChecked == false) { emitCommand(nisshuidohenController.RotateDiurnalBySpeed(0)); } else { emitCommand(nisshuidohenController.RotateDiurnalBySpeed(diurnal_speed)); } if (sender as ToggleButton != null) toggleOppositeButton((ToggleButton)sender); } ``` どうしてこのような汚いコードになったのか弁解しておこう。 この関数は、三箇所から呼び出される可能性がある。 まず、対応するボタンがクリックされた場合。 クリックした時点でボタンの`IsChecked`プロパティが反転するので、falseならモータを停止させ、trueなら動かせば良い。 ところが、キー操作イベントから呼ばれた場合、ボタンの状態は変わらない。 最初のif文で、`e.Parameter.ToString() == "KeyDown"`であるときだけ、ボタンの`IsChecked`を反転させることで対応した。 もう一つの可能性は、速度を切り替えたときだ。 日周の速度を管理している`diurnalRadioButton`がクリックされたとき実行されるコードを見てみよう。 ```c# private void diurnalRadioButton_Checked(object sender, RoutedEventArgs e) { var radioButton = (RadioButton)sender; if (radioButton.Name == "diurnalRadioButton1") diurnal_speed = SPEED_DIURNAL["very_high"]; else if (radioButton.Name == "diurnalRadioButton2") diurnal_speed = SPEED_DIURNAL["high"]; else if (radioButton.Name == "diurnalRadioButton3") diurnal_speed = SPEED_DIURNAL["low"]; else if (radioButton.Name == "diurnalRadioButton4") diurnal_speed = SPEED_DIURNAL["very_low"]; if (diurnalPlusButton.IsChecked == true) diurnalPlusButtonCommand.Execute(null, diurnalPlusButton); if (diurnalMinusButton.IsChecked == true) diurnalMinusButtonCommand.Execute(null, diurnalMinusButton); } ``` 前半は、`sender`がどの項目かによって速度を変更しているだけなので問題ないだろう。 後半で、「日周進める」か「日周戻す」がCheckedになっていれば、新しい設定をさいたまに送るためコマンドを実行している。 このときボタンの`IsChecked`プロパティはすでにtrueなので、二重に変更されないよう`e.Parameter`をnullとしている。 だが、考えてみればさいたまと通信さえすればいいので、**ボタンなど経由せず直接**`emitCommand()`**(さいたまにコマンドを送る関数)を呼べばいいだけである。** 総じて、コマンドを使うことにこだわりすぎて酷いコードになってしまった。 バグの原因になっている可能性もあるので、後任の方は綺麗に書き直してやって頂きたい。 ### シリアル通信 `MainWindow.xaml.cs`のうちシリアル通信に関する記述の大部分は、24の`Fujisawa`から受け継いでいる。 この項では、通信を行うためのコードを読み、必要に応じて解説を加える。 #### ポート一覧の取得 ```c# /// <summary> /// シリアルポート名を取得し前回接続したものがあればそれを使用 ボーレートの設定 /// </summary> /// <param name="ports[]">取得したシリアルポート名の配列</param> /// <param name="port">ports[]の要素</param> private void Window_Loaded(object sender, RoutedEventArgs e) { var ports = SerialPort.GetPortNames(); foreach (var port in ports) { portComboBox.Items.Add(new SerialPortItem { Name = port }); } if (portComboBox.Items.Count > 0) { if (ports.Contains(Settings.Default.LastConnectedPort)) portComboBox.SelectedIndex = Array.IndexOf(ports, Settings.Default.LastConnectedPort); else portComboBox.SelectedIndex = 0; } serialPort = new SerialPort { BaudRate = 2400 }; } ``` `Window_Loaded`は、ウィンドウが描画されるタイミングで実行される。 処理としては、シリアルポート一覧を取得して`portComboBox`に候補として追加し、さらに前回の接続先と照合するというものだ。 また、`SerialPort`クラスのオブジェクト`serialPort`を宣言し、ボーレートを2400に設定している。 foreach文の中で使用している`SerialPortItem`は自作クラスで、`ToString()`をオーバーライドしている。 何の為のものかは理解していないので、興味があればソースコードを確認してほしい。 #### ポートへの接続 接続ボタンがクリックされると、`ConnectButton_IsCheckedChanged()`が呼ばれる。 その中身はこうだ。 ```c# /// <summary> /// PortComboBoxが空でなくConnectButtonがチェックされている時にシリアルポートの開閉を行う シリアルポートの開閉時に誤動作が発生しないよう回避している /// </summary> private void ConnectButton_IsCheckedChanged(object sender, RoutedEventArgs e) { var item = portComboBox.SelectedItem as SerialPortItem; if (item != null && ConnectButton.IsChecked.HasValue) { bool connecting = ConnectButton.IsChecked.Value; ConnectButton.Checked -= ConnectButton_IsCheckedChanged; ConnectButton.Unchecked -= ConnectButton_IsCheckedChanged; ConnectButton.IsChecked = null; if (serialPort.IsOpen) serialPort.Close(); if (connecting) { serialPort.PortName = item.Name; try { serialPort.WriteTimeout = 500; serialPort.Open(); } catch (IOException ex) { ConnectButton.IsChecked = false; MessageBox.Show(ex.ToString(), ex.GetType().Name); return; } catch (UnauthorizedAccessException ex) { ConnectButton.IsChecked = false; MessageBox.Show(ex.ToString(), ex.GetType().Name); return; } Settings.Default.LastConnectedPort = item.Name; Settings.Default.Save(); } ConnectButton.IsChecked = connecting; ConnectButton.Checked += ConnectButton_IsCheckedChanged; ConnectButton.Unchecked += ConnectButton_IsCheckedChanged; portComboBox.IsEnabled = !connecting; } else { ConnectButton.IsChecked = false; } } ``` かなり長いが、順番に見ていこう。 最初のif文はポートが選択されているかチェックしているだけだ。 `bool connecting`はポートを開くのか閉じるのかの分岐に使われている。 後はtry-catch文でポートを開き、エラーが出れば警告を出すのだが、このブロックの上下に変な記述がある。 ```c# ConnectButton.Checked -= ConnectButton_IsCheckedChanged; ConnectButton.Unchecked -= ConnectButton_IsCheckedChanged; ConnectButton.IsChecked = null; /// (省略) ConnectButton.IsChecked = connecting; ConnectButton.Checked += ConnectButton_IsCheckedChanged; ConnectButton.Unchecked += ConnectButton_IsCheckedChanged; ``` これはおそらくコメントの言う「シリアルポートの開閉時に誤動作が発生しないよう回避している」部分であろう。 `MainWindow.xaml`の、`ConnectButton`に関する部分を見てみよう。 ```xml <!-- MainWindow.xaml --> <ToggleButton x:Name="ConnectButton" Checked="ConnectButton_IsCheckedChanged" Unchecked="ConnectButton_IsCheckedChanged" Margin="0"> ``` `Checked`と`Unchecked`は、いずれもボタンがクリックされた時に発生するイベントだ。 `ConnectButton.Checked -= ConnectButton_IsCheckedChanged;`などとしておくことで、ポートへの接続を試行している間ボタンのクリックを無効化しているようだ。 このコードを削除した状態でボタンを連打しても特に問題はなかったので効果のほどは分からないが、あっても害にはならないだろう。 #### ポート一覧の更新 ポート一覧のコンボボックスは、開くたびにシリアルポートを取得し直している。 `portComboBox_DropDownOpened()`に処理が書かれているが、`Window_Loaded()`と同じようなことをしているだけなので省略する。 #### コマンド送信 `emitCommand()`は、コマンド文字列を与えて実行すると接続しているポートに送信してくれる。 `serialPort.IsOpen`がfalseの時は、警告とともにコマンド文字列をMessageBoxに表示する。 ```c# /// <summary> /// シリアルポートが開いている時にコマンドcmdをシリアルポートに書き込み閉じている時はMassageBoxを表示する /// </summary> /// <param name="cmd"></param> private void emitCommand(string cmd) { if (serialPort.IsOpen) { var bytes = Encoding.ASCII.GetBytes(cmd); serialPort.RtsEnable = true; serialPort.Write(bytes, 0, bytes.Length); Thread.Sleep(100); serialPort.RtsEnable = false; } else { MessageBox.Show("Error: コントローラと接続して下さい\ncommand: "+ cmd, "Error", MessageBoxButton.OK, MessageBoxImage.Warning); } } ``` ### 公演モード(誤操作防止モード) `checkBox2`は公演モードのON/OFFを管理している。 公演モードは、日周を進める以外の機能を制限して誤操作を防ぐ為のものだ。 一応28で目立ったバグは修正したつもりだが、何らかの不具合が確認された場合は適宜修正してもらいたい。 ```c# private void checkBox2_Checked(object sender, RoutedEventArgs e) { var result = new MessageBoxResult(); result = MessageBox.Show("公演モードに切り替えます。\n日周を進める以外の動作はロックされます。よろしいですか?", "Changing Mode", MessageBoxButton.YesNo); if(result == MessageBoxResult.No) { checkBox2.IsChecked = false; return; } isPerfMode = true; List<string> keyList = new List<string>(isEnabled.Keys); // isEnabled.Keysを直接見に行くとループで書き換えてるので実行時エラーになる foreach (string key in keyList) { if(key != "diurnalMinusButton") isEnabled[key] = !isPerfMode; } latitudeRadioButton1.IsEnabled = latitudeRadioButton2.IsEnabled = latitudeRadioButton3.IsEnabled = latitudeRadioButton4.IsEnabled = !isPerfMode; notepadCombobox.IsEnabled = Savebutton1.IsEnabled = !isPerfMode; textBox1.Focusable = !isPerfMode; } private void checkBox2_Unchecked(object sender, RoutedEventArgs e) { var result = new MessageBoxResult(); result = MessageBox.Show("公演モードを終了します。", "Finish PerfMode", MessageBoxButton.OK); isPerfMode = false; List<string> keyList = new List<string>(isEnabled.Keys); // isEnabled.Keysを直接見に行くとループで書き換えてるので実行時エラーになる foreach (string key in keyList) { if (key != "diurnalMinusButton") isEnabled[key] = !isPerfMode; } latitudeRadioButton1.IsEnabled = latitudeRadioButton2.IsEnabled = latitudeRadioButton3.IsEnabled = latitudeRadioButton4.IsEnabled = !isPerfMode; notepadCombobox.IsEnabled = Savebutton1.IsEnabled = !isPerfMode; textBox1.Focusable = !isPerfMode; } ``` 他の関数等で公演モードかどうかいちいち判定する必要が出てきたので、`isPerfMode`というbool値に記録するようにした。 たいへん紛らわしいが、`diurnalMinusButton`が「日周進める」ボタンである。 実機で運用した際に、かごしいの実際の動きを合わせてラベルだけ交換したため逆になっている。 28でもかごしいに合わせ何度かラベル交換したので、29のかごしいの動きではそれぞれのボタンを押したときにどのような動きをするのかしっかりと確認し、変更してほしい。 ### メモ帳機能 `notepadCombobox_DropDownOpened`は、メモ帳を読み込むときに使われる。コンボボックスを開いた時も閉じたときもこの処理が行われるようになっているが、 この仕様のせいで妙に重い等の不具合がもしあれば修正したほうがいいのかもしれない。 メモ帳に加えた変更の保存は、`Savebutton1_Click`の方で行っている。 ```c# private void notepadCombobox_DropDownOpened(object sender, EventArgs e) { var item = notepadCombobox.SelectedItem; notepadCombobox.SelectedIndex = -1; notepadCombobox.Items.Clear(); string[] files = Directory.GetFiles( @"..\..\WorkInstructions", "*.txt", SearchOption.AllDirectories); Array.Sort(files); foreach (var file in files) notepadCombobox.Items.Add(file); if (item != null) { textblock1.Text = Path.GetFileName(item.ToString()); notepadCombobox.SelectedIndex = Array.IndexOf(files, item.ToString()); using (FileStream fs = new FileStream(item.ToString(), FileMode.Open, FileAccess.ReadWrite)) { using (StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("shift_jis"), true)) { try { textBox1.Text = sr.ReadToEnd(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } } } ``` 構文は[こちらのリンク](https://divakk.co.jp/aoyagi/csharp_tips_using.html)を見て書いた部分が大きい。 読み込むファイルについては、`Directory.GetFiles`を使って`WorkInstructions`ディレクトリ内の.txtファイルを読み込むようにしている…のだが、 そのファイルのパスがそのままコンボボックスに表示されてしまうため見栄えが悪い。28日電の知識ではどうにもならなかったが、修正できる人がいれば修正してほしいところだ。 ## NisshuidohenController.cs さいたまに送るコマンド文字列を生成するための`NisshuidohenController`クラスが実装されている。 27では、24が書いたものをほぼそのまま利用した。 一点のみ、日周・緯度のギヤ比の換算もこちらでやってしまうように変更した。 これで、クラスの外側からはかごしいを回したい角速度(1 deg/sなど)を指定すればいいようになった。 使うだけなら`RotateDiurnalBySpeed()`や`RotateLatitudeBySpeed()`をブラックボックスとして利用するだけでいいだろう。 ただし、23や25が使っていた角度指定メソッドは残してあるだけで一切触っていないので、使いたい場合はしっかりデバッグしてほしい。 <file_sep>日周緯度変(外部制御アプリの歴史) ================================ - 書いた人: <NAME>(nichiden_27) - 更新日時: 2017/03/04 - 実行に必要な知識・技能: 特になし - 難易度: 2/少しやれば可能 - 情報の必須度: 2/知ってると楽 - 元資料 - ``引き継ぎと技術的補足:日周緯度変外部制御ユーザインタフェース.docx`` by 紺野雄介(nichiden_23) - ``ふじさわreadme.docx`` by 池下 氏(nichiden_24) - ``25の日周・緯度変について.docx`` by 伊藤太陽(nichiden_25) 概要 ---- `日周緯度変(外部制御アプリ) <pc-software.html>`__\ から歴代外部制御アプリケーションの紹介を分離した記事です。 現在は実装されていない機能があったりと、それぞれに特徴があるので、把握しておくと今後の改善に繋がるかもしれません。 Tokyo Terminal(2012) -------------------- .. figure:: _media/tokyoterminal.png :alt: Tokyo Terminalの画面 Tokyo Terminalの画面 23代荒田氏が制作した。外部制御は23代で初使用されたが、\ ``Tokyo Terminal``\ はそのテスト用に書かれたものである。 氏の環境がMac OSだったため、Macでしか動作しない。23代の作業データの\ ``日周緯度変外部制御/Saitama6Brain/``\ 以下にソースファイルやアプリ本体があるが、最新のMac OSでは対応していない旨が表示され起動しなかった。 これ以降の外部制御アプリは全てWindows向けに開発されたものだ。Mac向けに開発する必要に迫られることがもしあれば、\ ``Tokyo Terminal``\ のコードが参考になるかもしれない(Mac開発の経験があれば一から書いた方が早い可能性も大いにあるが…)。 NisshuidohenController2(2012) ----------------------------- .. figure:: _media/nisshuidohencontroller2.png :alt: NisshuidohenController2の画面 NisshuidohenController2の画面 23代紺野氏の作。\ ``Tokyo Terminal``\ がMac専用だったため、Windows版として開発された。開発言語はC#で、Windows Formアプリケーション(\ ``System.Windows.Forms``\ 名前空間を使用)である。 ``Tokyo Terminal``\ と共通の機能が多いが、大きな違いは\ **操作の記録・再生ができる**\ ことである。「速度指定」か「角度指定」かを選択して「記録」ボタンを押すと右のスペースに送るコマンドが表示され、同時に\ ``Instruction.txt``\ というファイルにも保存される。 あらかじめ必要なコマンドを記録しておいて面倒な操作なしに再実行できる画期的な機能である…と言いたいところだが、\ **表示されるのはコマンドだけ**\ (数値は16進数)なので、肝心の再生部分が手軽に利用できるとは言い難い。 「高速」「低速」のボタンで出る角速度は以下の数値に固定されている。なお、上半分で入力する角速度はモーターのもの、以下の角速度はギアによる減速後のかごしいのものなので注意。 - 日周高速ボタン: 4 deg/s - 日周低速ボタン: 1 deg/s - 緯度高速ボタン: 1 deg/s - 緯度低速ボタン: 0.5 deg/s この数値は後発の\ ``Fujisawa``\ 、\ ``Chichibu``\ でも同じものが使われている。 当時の日周緯度変は相応のスキルのある日電員が操作しており、自分たちで使うための最小限の機能を盛り込んだという印象だ。実際、本番中に使用したのは「高速」などのボタンだけだったという。 将来これを使うことはなさそうだが、速度・角度・方向に対応するコマンドを表示してくれるので、デバッグ用の計算機にはなるかもしれない。 Fujisawa(2013) -------------- .. figure:: _media/fujisawa.png :alt: Fujisawaの画面 Fujisawaの画面 24池下氏によるもの。引き続きC#によるWindowsアプリだが、UIのフレームワークに\ ``Windows Presentation Foundation(WPF)``\ を使用している。 WPFの詳細についてはググって欲しいが、デザインとコードを分けて書くことができるというのが大きな利点である。つまり、内部の動作を崩さずに見た目だけをいじり倒せるのだ。その甲斐あってか、23のUIに比べデザイン面が大きく改善した。コマンド文字列を生成するコードは\ ``fujisawa/NisshuidohenController.cs``\ でクラスにまとめて定義されている。 日周緯度変にPCを使うとき、一番問題になるのは画面が光ることだ。PCは画面も大きいし、そのために星がかき消されてしまいかねない。\ ``Fujisawa``\ は、\ **黒基調の画面**\ にすることでPCの光害を抑制している。 使い方は見れば分かると思うが、「びゅーん」が高速回転、「のろのろ」が低速回転だ。また、本番で画面を暗くしているとマウス操作が大変なので、日周はキーボードでも操作できる。\ ``C``: 高速逆転、\ ``V``: 低速逆転、\ ``B``: 停止、\ ``N``: 低速順回転、\ ``M``: 高速順回転 である。 総じて24日電の雰囲気がよく出ており大変分かりやすいものの、回転方向が少し把握しにくい。なお、アプリ名称は往時の天文部の「備品などに駅名をつける」習慣に則ったもので、「ふじさわ」は制作者の地元であるらしい。 Chichibu(2014) -------------- .. figure:: _media/chichibu.png :alt: Chichibuの画面 Chichibuの画面 25伊藤氏が開発したアプリ。他にない特色として、25ソフト専用のモードが用意され、ボタンを押すだけでシナリオで要求された動きを実現できることがある。 また、23の\ ``NisshuidohenController2``\ と24の\ ``Fujisawa``\ の画面もそのまま移植され、それぞれの機能が利用できる。本番でも、ライブ解説時には\ ``Fujisawa``\ を使っていたようだ。 .. figure:: _media/chichibu_2.png :alt: Chichibuに移植されたNisshuidohenController2 Chichibuに移植されたNisshuidohenController2 フルスクリーン状態で起動することで、以前より更に画面の光漏れを抑えている。ただし、ソフト内に終了ボタンがないうえタイトルバーも見えないので、プログラムを終了させる際は\ ``Alt``\ +\ ``F4``\ を押すなどショートカットキーを使うしかない。 Ogose(2016) ----------- .. figure:: _media/ogose.png :alt: Ogoseの画面(画像は28日電使用時) Ogoseの画面(画像は28日電使用時) 27日電の伊東が開発した。これまでのUIの問題点を洗い出した上で、改善すべく様々な変更を加えている。デザイン部分(\ ``MainWindow.xaml``)は一から作り直したが、コマンド文字列生成は\ ``NisshuidohenController.cs``\ を継続使用した。 指定できる速度が各軸4段階に増えたことで、多彩な演出が可能となった。また、速度指定のボタンを回転スタート/ストップボタンとは別に用意したため、回転を止めずとも速度を変更できる。 ウィンドウモードとフルスクリーンモードをボタンで切り替えられる機能も実装した。また、フルスクリーンボタンの横にある「公演モード」ボタンは、使用できる機能を「日周進める」に限定し誤操作を防止する機能である。キーボード操作などにより意図しない状態になるバグが存在するので注意。 思いがけないことに、ボタンを十字に配置したことで、ゲームコントローラーのボタンと同様の配置となった。本番ではゲームコントローラーを実際に使用し、慣れていない人でも操作ができるという恩恵があった。 実装についてなど、詳細は\ `外部制御アプリの記事 <pc-software.html>`__\ に示すこととする。 <file_sep># プロジェクト マネジメント - 書いた人: <NAME>(nichiden_27) - 更新日時: 2017/02/18 - 実行に必要な知識・技能: 特になし - タスクの重さ: 3/数週間 - タスクの必須度: 4/毎年やるべき ## 概要 日電長向けの内容です。日電の仕事をどう進めていくかなどを書きます。 ## チーム編成 ### 連絡手段を決める 27ではSlackを使用した。日電は作業内容が多岐にわたるため、一つのチャットグループでは話題が混乱してしまう。 LINEでも多数のグループを立てることで対応はできるが、管理が困難になるので最初からチームチャットを導入しておくことをお勧めする。 以下は27Slackの最終的なチャンネル構成である。 ``` #acrab ... 星座絵アプリ #dome ... ドームコンソール #general ... 総合 #ginga ... ぎんとう #haisen ... 配線 #hojyotou ... 補助投 #ittou ... いっとう #log ... 活動記録 #nissyu-idohen ... 日周緯度変 #notifications ... 通知を流す用 #parts ... 部品管理 #piscium ... 星座絵無線機 #random ... 雑談 #seizae ... 星座絵 ``` Slackの特徴の一つに、他のWebサービスとの豊富な連携がある。 27では、ToDoリストを共有できるTrelloやGitHubを使用した。通知がSlackで一覧できるので、進捗の共有が簡単になる。 余裕があれば、進捗を煽るBotなどを作成しても面白いかもしれない。 ### 目標を設定する 日電のやることは毎年そう変わらないが、できれば先年までと違うことに挑戦するとよい。 ただし、新しい製品や機能には不具合や故障が付き物 であり、早期に目標を設定して動き始めることが重要だ。 前年度までに壊れてしまったものや、部員・観客へのインタビューで不満が多く寄せられた部分などが、新たな目標の候補となるだろう。 ### 担当を決める 日電の仕事の特質は、**種類が多く、それぞれの作業は個人作業になりやすい** ことである。 また人数も限られているので、各自の責任感を高める意味でも早期に担当を振っておくべきだろう。 これには、日電員が作業に向けて勉強するにあたり、個々の課題を明確にするという利点もある。 ### スケジュールを決める 進捗は必ず遅れるものだが、だからと言ってスケジュールを切らずに闇雲に進めるのは大変危険である。 最低限、どの期間に何をするかの大枠は示しておきたい。27日電での例は以下の通り。 - 準備期間 〜8/1(Sセメ試験) - 試作期間 8/2〜9/25(夏休み終了) - 製作期間 9/26〜10/31 - 動作試験 11/1〜11/24(駒場祭前日) もちろん、実際の作業に入った後の進捗の把握や再検討は、日電長が随時やっておく必要がある。 ## 作業が始まったら ### 夜間 日電は個人プレーが多いので夜間への参加は必須ではないが、他の投影機は随時日電のサポートを必要とするので最低一人は出ておくのが望ましい。 また、作業で得られた進捗は、**箇条書きなどにまとめて日電全員に報告** するとよい。 作業に参加していないメンバーが現状を把握できる上、日電長自身も進捗を目に見える形で確認できる。 ### 卒検・リハ 卒検やリハでは、ドームを膨らませて投影機を配置し、点灯させる。 この間の配線は日電が全て行うので、大変仕事が多くかつ責任が重い。 この二日間だけは **日電メンバーを全員揃える** のが重要だ。 前々から日程は判明しているはずなので、各自の予定を確認しておこう。 <file_sep>回路設計のためのソフトウェア ============================ - 書いた人: <NAME>(nichiden_27) - 更新日時: 2017/08/02 - 実行に必要な知識・技能: 基本的な電子部品の知識 - 難易度: 3/練習・勉強が必要 - 情報の必須度: 2/知ってると楽 概要 ---- 電子回路の設計は手書きでもできますが、 - 回路図をチームで共有する - 後から配線などを整理する - 基板の配置を考える といった場合は\ **専用ソフトウェアで回路図を描く**\ のが便利です。 回路設計ソフトは多数存在し、それぞれに特色があります。 本稿では、よく名前の挙がるものや最近注目されているものを独断で選んで解説します。 BSch3V ------ +--------+--------+--------+ | 開発 | 価格 | 拡張子 | +========+========+========+ | 水魚堂 | フリー | .CE3 | +--------+--------+--------+ - `公式 <http://www.suigyodo.com/online/schsoft.htm>`__ - `マニュアル <http://www.suigyodo.com/online/manual/>`__ Windows(7/8/10)専用の回路図エディタ(macOS向けには\ `Qt-BSch3V Modified <#qt-bsch3v-modified>`__\ が存在する)。 .. figure:: _media/bsch3v.png :alt: BSch3Vの画面 BSch3Vの画面 構成は至ってシンプルだが、\ **軽快な動作と簡単な操作**\ に定評があり、小規模な回路であれば十分な機能を備えている。 **部品のライブラリをいくつでも導入できる**\ ため自由に拡張ができるのもポイントだ。 標準でも基本的な部品は用意されているが、マイコンなどのライブラリが多数のサイトで配布されているので、欲しい部品があればググってみよう(ソフトの古さ故\ **リンク切れ**\ も多いので、手に入らない場合は諦めること)。 また、部品エディタ「\ **LCoV**\ 」が同梱されており、欲しい部品を自作したり(例: `BSch3V 向け Arduino MEGA 部品ライブラリつくった <https://blog.shiftky.net/bsch3v-arduino-mega/>`__)、BSch3V側から編集したりもできる。 開発元の水魚堂では、プリント基板編集ソフト「\ `Minimal Board Editor <http://www.suigyodo.com/online/mbe/mbe.htm>`__\ 」も配布している。 操作/Tips ~~~~~~~~~ - **ドラッグツール**\ は、範囲選択により回路の一部を移動できる。 - 配線の片方だけを動かすと簡単に\ **斜めの線**\ が作れる。 - 斜め線のアイコンは「エントリー」ツールで、配線の引き出しを表す。斜めの線として使わないこと。 - **太い線と細い線のツール**\ があるが、太い線は複数の線をまとめた「バス線」。 - 通常は細い方を使っていれば問題ない。 - レイヤ機能が存在し、右のツールバーから操作できる。 - 編集するレイヤを選択したり、可視/不可視の切り替えが可能。 - 選択レイヤ以外に配置したものは\ **クリックしても反応しない**\ 。 - 不具合ではないので、慌てないこと! - 多くの情報を書き込む場合に、コメント・ラベルを別レイヤにするなどの使い道が考えられる。 - 他のPCやモバイルからの閲覧用に、\ **PDFファイルを用意しておく**\ とよい。 - BSch3V自体にPDF書き出し機能はないが、印刷メニューからPDFに変換できる。 Qt-BSch3V Modified ------------------ +----------------+--------+--------+ | 開発 | 価格 | 拡張子 | +================+========+========+ | informationsea | フリー | .CE3 | +----------------+--------+--------+ - `公式 <https://informationsea.info/apps/qtbsch3v/>`__ QtというGUIフレームワークで\ `BSch3V <#bsch3v>`__\ をクロスプラットフォームに書き直した「Qt-BSch3V」というソフトが水魚堂で配布されている。 informationsea氏がQt-BSch3Vを最近のmacOS向けにさらに改造したのが、「Qt-BSch3V Modified」である。 これのお陰で、MacユーザでもCE3ファイルを開くことができる。 .. figure:: _media/qtbsch3v.png :alt: Qt-BSch3Vの画面 Qt-BSch3Vの画面 BSch3V(及び同梱ソフト)の機能の多くが使用できるが、\ **日本語が表示できない**\ など問題もあるようだ。 Eagle ----- +----------+----------------+------------+ | 開発 | 価格 | 拡張子 | +==========+================+============+ | AutoDesk | フリー(学生版) | .sch, .brd | +----------+----------------+------------+ - `公式 <https://www.autodesk.com/products/eagle/overview>`__ - `サポートトップ <https://knowledge.autodesk.com/ja/support/eagle?sort=score>`__ 元々ドイツのCadSoft社が開発していたものを、\ `AutoDeskが2016年に買収した <http://makezine.jp/blog/2016/08/the-autodesk-family-grows-with-new-eagle-acquisition.html>`__\ 。 Windows / Mac / Linuxで使用可能。 .. figure:: _media/eagle.png :alt: Eagleの画面 Eagleの画面 商用のプリント基板CADであり本来は数万円だが、基板サイズなどに制限付きの無料版が存在する。 さらに、AutoDeskの傘下に入ったことで\ **AutoDeskの学生プログラムの対象となった**\ 。 `教育機関限定版および学生版 <https://knowledge.autodesk.com/ja/search-result/caas/sfdcarticles/sfdcarticles/JPN/Eagle-Education.html>`__\ を使用することで、Premiumバージョン同等の機能を3年間使用できる(商用利用は不可)。 学生からすれば、\ **事実上の利用制限解除**\ である。 商用ソフトウェアなので機能は豊富であるが、そのぶん操作を覚えるのが大変でもある。 KiCad ----- +-----------------------+--------+------------------+ | 開発 | 価格 | 拡張子 | +=======================+========+==================+ | KiCad Developers Team | フリー | .sch, .kicad_pcb | +-----------------------+--------+------------------+ - `公式 <http://kicad-pcb.org/>`__ **オープンソース**\ の回路CADソフト。 OSSなので当然全機能を無料で使用でき、商用利用に関する制限もない。 Eagle同様、各種OSに対応している。 kicadについてツイートすると、国内コミュニティ\ `@kicad_jp <https://twitter.com/kicad_jp>`__\ の中の人がエゴサしてふぁぼってくれるらしい。 .. figure:: _media/kicad.png :alt: Kicadの画面 Kicadの画面 回路図やプリント基板の設計が可能で、非常に多機能。 チュートリアルをこなしてから使うことをお勧めする。 国内コミュニティの方々の努力により、現行バージョンでは\ **日本語版のマニュアルとチュートリアル**\ が同梱されるようになった。 メニューの ``ヘルプ`` から選択できる。 また、トラ技編集部から\ `Kicad本 <https://www.amazon.co.jp/dp/4789849279/>`__\ も出版されているので、紙のチュートリアルが欲しければこちらを購入するのもいいだろう。 Fritzing -------- +---------------------+--------+--------+ | 開発 | 価格 | 拡張子 | +=====================+========+========+ | Friends of Fritzing | フリー | .fzz | +---------------------+--------+--------+ - `公式 <http://fritzing.org/home/>`__ オープンソースの回路図ソフト。ドイツのthe University of Applied Sciences Potsdamで開発され、現在は開発チームにより更新が行われている。 **部品の形状をそのまま表示して配置**\ するという独特のインターフェースを持ち、\ `メイカー <https://ja.wikipedia.org/wiki/メイカーズムーブメント>`__\ 界隈で人気が高い。 Arduino関連のブログ記事などで、Fritzingにより生成された回路図を見る機会も多いだろう。 .. figure:: _media/fritzing.png :alt: Fritzingの画面 Fritzingの画面 基本的には、右パネルに表示されたパーツをドラッグして配置していくだけで回路図ができてしまう。 新規ファイルを開いた状態では\ **ブレッドボード**\ が表示されるが、\ **ユニバーサル基板もパーツの一つとして用意されている**\ ためユニバーサル基板の配置を考えるときにも使える。 上メニューから「\ **回路図**\ 」「\ **プリント基板**\ 」などにも切り替えができる。 いずれかを編集すると残りも自動生成されるが、残念ながら見るに堪えない配置になることが多い。 面倒ではあるが、自分で配置を修正しよう。 「Fritzing Fab」というサービスにプリント基板のデータを送ると、ドイツ国内で基板を製作して送ってくれる。 また、他のプリント基板業者向けにデータを書き出すこともできる。 まとめ ------ 手軽さを取るならBSch3VやFritzing、ある程度複雑な作業をするならKiCad、AutoDeskのファンならEagle……といったところだろうか。 最近はプリント基板を安価で製作してくれる業者が増え、\ **アマチュアの世界でもプリント基板の使用が拡大**\ しつつある。 プリント基板を使った製作を視野に入れるのであれば、KiCadやEagleを使えるようになることは決して損ではなさそうだ。 <file_sep>配線 ==== - 書いた人: <NAME>(nichiden_27) - 更新: <NAME>(nichiden_28) - 更新日時: 2018/09/25 - 実行に必要な知識・技能: 特になし - タスクの重さ: 2/数日かかる - タスクの必須度: 5/しないとプラネ終了 概要 ---- 配線には、特別な知識や技能は不要です。 ただし、プラネの大部分には電源が欠かせません。 配線のミスはプラネ全体に響きます。特に入念に準備をするようにしてください。 配線を行うタイミング -------------------- 配線を実際に行うのは、 - 卒検 - リハーサル - 本番前日準備 の三回。 卒検・リハと本番では、ドームの展開場所が屋外か屋内かという大きな違いがある。 卒検段階では投影機は一部しか運用されないので、全てを配線する必要はない。 ただし、リハ以降の練習ができる唯一の機会でもあり、大した負担でもないので全て配線してしまってもいいだろう。 リハでは、補助投の設置状態などがほぼ確定している。 補助投の仕様変更などを把握し、本番同様の状態を構築できるのが望ましい。 また、卒検やリハは天気などにより短時間で必要最低限の調整のみを行うことになる可能性がある。 実際、28代の卒検では昼前から雨の予報が出ていたためドームの確認と最低限の主投調整のみを行った。 そのような場合、本番の配線の確認はできなくなってしまうが、電気が必要な場所になるべくはやく電源を供給できるように臨機応変に対応しよう。 前日準備はとにかく時間との戦いになる。 配線の遅れが投影機調整の遅れ、公演開始の遅れと連鎖してしまうこともある。 コードをつなぐだけなので、手の空いた補助投の人に協力してもらっても構わない。 配線計画 -------- 電力計算 ~~~~~~~~ 体育館には、使用できる電力に制限がある。 ブレーカーが落ちないよう、館内で個人的な充電等をしないよう注意されたのを覚えているかもしれない。 実際には滅多に起きないことだが、もし起こしてしまえば即企画停止である。 各投影機が使用する電力を把握し、負担を分散させることは大変重要だ。 各投影機の消費電力は、白熱球やハロゲンランプからLEDへの移行によって減少傾向にある。 ただ、あおとうやソフトなど大電力を要求する投影機があるため、急激に上下することはない。 毎年3000W前後であり、大学側への申請は更に余裕をみて\ **3500W**\ としてある。 参考までに、27で計算した電力(28で修正)を掲載する。数値は概略である。 投影機仕様に大幅な変更があれば、必要に応じて再計算して欲しい。 +------------+----------------+--------+----------+---------+ | 投影機 | 種別 | 使用数 | 電力[W] | 電圧[V] | +============+================+========+==========+=========+ | こうとう | パワーLED3W | 32 | 100 | 12 | +------------+----------------+--------+----------+---------+ | いっとう | LED | 24 | 5 | 12 | +------------+----------------+--------+----------+---------+ | 星座絵 | パワーLED1W | 32 | 32 | 12 | +------------+----------------+--------+----------+---------+ | ぎんとう | パワーLED1W | 4 | 4 | 12 | +------------+----------------+--------+----------+---------+ | ドーム | ダクト用ファン | 3 | 200 | 交流100 | +------------+----------------+--------+----------+---------+ | ソフト | スピーカーなど | ~ | 1000 | 交流100 | +------------+----------------+--------+----------+---------+ | 日周緯度変 | モータ | 2 | 100 | 24 | +------------+----------------+--------+----------+---------+ | あおとう | 白熱球 | 8 | 1000 | 交流100 | +------------+----------------+--------+----------+---------+ | あくとう | パワーLED1W | 30 | 40 | 12 | +------------+----------------+--------+----------+---------+ | あゆとう | 白熱球 | 1 | 100 | 交流100 | +------------+----------------+--------+----------+---------+ | しるとう | パワーLED1W | 8 | 24 | 12 | +------------+----------------+--------+----------+---------+ | りゅうとう | ? | ? | 100 | ? | +------------+----------------+--------+----------+---------+ | **合計** | ~ | ~ | **2700** | ~ | +------------+----------------+--------+----------+---------+ 電力配分 ~~~~~~~~ 以下に書く内容は28代までの内容なので第二体育館での配線の話である。 29代以降実施場所が変わるので、あくまで参考として読んでもらいたい。 第二体育館の電源系統は一つではなく、4つに分かれている。 一つの系統に負担が集中しすぎると、落ちてしまうというわけだ。 .. figure:: _media/haisen-gym.jpg :alt: 体育館配線 体育館配線 この画像は、23代の頃作成されたもので出典不明だが、日電の配電計画はここに書かれた数字を元に決定されてきた。 しかし、配線の根元となる **コードリールの定格が1500W**\ であり、1500Wを目安とするのが安全だろう。 二体の南と東向きの壁面がA系統、西側がB系統、女子更衣室前とトイレ前がそれぞれC系統とD系統となっている。 現在の配分では、用途別に四系統に振り分けている。 - A系統: ダクト・かごしい(主投)・スピーカーアンプ - B系統: その他(ドーム外の作業や充電用) - C系統: 補助投 - D系統: 日周緯度変・PC・ミキサ ソフト関連は、PCのノイズが影響しないようアンプとそれ以外を分ける慣例となっている。 また、主投と補助投は別電源にするなどリスクを抑える工夫がある。 ただし、28代においてA系統を取っているコンセントから安定して電力が供給されていないことが確認された。(そのため前日準備でドームを膨らませていた際にダクトが止まるという危険な状況が発生した。) 前日に急遽わかったことだったので詳細は忘れてしまったが、他の系統に分散させて三系統で使用していた。 なお、会場が変わるため新しい体育館の各コンセントの電気容量を確認しておくとよいだろう。 その際、かごしいのアースを取れる場所も調べておくとよい。 配線図 ~~~~~~ 電力配分が決まったら、配線図を作成する。 配線図は毎年作成されているものではなく、実際数年で大きくは変わらないので流用してもいい。 ただし、配線の様子を頭に入れるには、実際に図を書いてみるのが有効だろう。 27で更新した配線図を掲載しておく。 28でも同じ配線図を使用した。 配線図はドーム内で作業中に繰り返し参照することになるので、各自の端末にすぐ表示できるようにしておくと良い。 .. figure:: _media/haisen-27.jpg :alt: 27配線図 27配線図 以下、28代で配線を担当した芝田のコメントを載せる。 - 配線図の「照」とは「青くないあおとう」です。 - 必要なものから順に配線してください。 - 28では29のしるとうが優秀で、方位投の配線をする必要がありませんでした。 来年も様子を見て必要であれば配線をお願いします。 - 27の配線図ではしる・あおの位置が簡略化されています。 実際にはメインドア・スタッフドア・長机を避けてだいたい45°ずつ配置されます。 ドームドアが南側、スタッフドアが北側、PCなどの長机がスタッフドアの両側に設置されます。 リハの際に確認してください。 コードの管理 ------------ 在庫調査 ~~~~~~~~ 卒検やリハの前に、人数が集まる機会を狙ってコードの在庫調査をしておきたい。 込み入った作業ではないので、数時間かければ終わる。 部室の機材などがある側に、延長コードが入った大きなケースがある。 大量の金属が入っているのでかなり重いので運ぶときは注意。 27まではダンボールに入っていたが、中身の重さで破れてしまうのでプラスチックのケースに変更した。 山ほどコードがあるように見えるが、プラネがフル稼働するとギリギリの数しかないので必ず全てあるか確認すること。 コードには、番号を書いたテープが付いている(番号がないものは予備である)。 適切な長さや口数のものが使えるよう、通し番号で管理されているのだ。 27で長さや口数の調査をしたので、結果を掲載する。 +-----------------------+-----------------------+-----------------------+ | 通し番号 | 用途 | | +=======================+=======================+=======================+ | 1-8 | C(to22)あおとう配線 | 1:3m (分岐用) | | | | 2-6:5m | | | | 7,8:5m(端っこ) | +-----------------------+-----------------------+-----------------------+ | 9-16 | C(to22)しるとう配線 | 9:3m(分岐用) | | | | 10-14:5m | | | | 15,16:5m(端っこ) | +-----------------------+-----------------------+-----------------------+ | 17-21 | C方位とう配線 | 17:3m(3) 18,19:10m(1) | | | | 20:5m(1) 21:5m(3) | +-----------------------+-----------------------+-----------------------+ | 22 | Cあお、しる、方位コントローラ用 | 3m 4口 | +-----------------------+-----------------------+-----------------------+ | 23 | Dプロジェクター用 | 5m 1口 | +-----------------------+-----------------------+-----------------------+ | 24 | A(to32)かごしい用 | 2m 1口 | +-----------------------+-----------------------+-----------------------+ | 26-30 | C補助用 | 30:タップ 26-28:2m(3) | | | | 29:2m(1) | +-----------------------+-----------------------+-----------------------+ | 31 | Dさいたま、PC | タップ | +-----------------------+-----------------------+-----------------------+ | 32 | A分岐アンプかごしい | 4m(1) | +-----------------------+-----------------------+-----------------------+ | 33 | A(to32)アンプ | 2m(3) | +-----------------------+-----------------------+-----------------------+ | 34 | A(to24)かごしい本体 | 3m(4) | +-----------------------+-----------------------+-----------------------+ | 35-37 | A ダクト | 35:4m(1) 36:14m(1) | | | | 37:15m(1) | +-----------------------+-----------------------+-----------------------+ | 外1-4 | 外 | 20m,20m,15m,15m | +-----------------------+-----------------------+-----------------------+ 毎年長さを測る必要はなく、直近で調査がなされているなら全部の番号があるかだけ調べれば良さそうだ。 28ではこれらがすべてそろっていることを確認した。 しかし、\ **31番のタップの接触が絶望的に悪い**\ ことが本番で発覚した。 そのため、本番中にあくとうが点滅するなどの不具合が発生した。 これは\ **必ず買い替えるべき**\ である。 スイッチが光るタイプはドームを暗くした時に邪魔なので、光らないものにするといいだろう。 これとは別に、コンセントが四口あるコードリールが部室に5つある。 また、古い延長コードは予備として別のかごで保管してある。 (ただし、**28の駒場祭本番で混ざってしまっている**\ 。) 普段の作業で延長コードを使う場合はこの予備から使ってもらうようにして、本番用のコードは紛失しないようにしっかりとしまっておこう。 コードの買い増し ~~~~~~~~~~~~~~~~ 延長コードは既製品で、簡単に切れたりはしないので買い替えのスパンは長い。 また、現状の量で本番に対応できているのでこれ以上増やす必要性はあまりない。 古かったり汚れが気になるものを適宜買い換える程度で大丈夫だろう。 パソコン用の電源タップは予備も何個か買ってもいいかもしれない。 ドーム外配線 ------------ 卒検・リハ ~~~~~~~~~~ 卒検やリハ時のドーム外配線は、本番にはない屋外作業となる。各投影機が予定通り調整できるよう、確実に配線しておきたい。 タイムスケジュール ^^^^^^^^^^^^^^^^^^ ドームを膨らませる前に\ **ダクトの配線**\ だけは完成していなければならないので、機長会議で予定時刻を確認して計画を立てよう。 早朝から開始となるので、前日の夜間に最低限二人は参加しておくのが望ましい。 なお、日電はドームの展開(40人必要)などドーム作業の人数がどうしても足りない時以外は\ **配線を優先**\ しよう。 トレ体 ^^^^^^ 当日、電源は\ **トレーニング体育館(トレ体)と第一体育館(一体)**\ から取っていいことになっている。 トレ体が5:00に開くので、まずはトレ体からドームの場所までコードを引っ張ろう。 入り口から入り、左の廊下に曲がってすぐの場所にコンセントがある。 ただし、これは28までの話であり、29以降は卒検・リハの会場が変わり、電源をとる場所も変わるだろう。 必ず\ **朝早くからとれる電源を確保**\ しておこう。 ここで注意だが、人が通る場所では **引っかからないようコードを固定しなければならない。** 養生テープを用意し、一定間隔に貼っておこう。これは卒検やリハに限らず、本番でも必要なことだ(しかし、地面が濡れていて固定が難しいこともあるので臨機応変に)。 .. figure:: _media/haisen-tape.jpg :alt: テープでコードを固定した例 テープでコードを固定した例 一体 ^^^^ ドームが膨らみ終わる頃には一体が開いているので、一体からもコードを引いてこよう。 一体のコンセントは差込みがゆるく抜けてしまうことがあったので、テープで念入りに固定しておくと良い。 危険箇所 ^^^^^^^^ 配線が切れてしまいがちな場所と、対策を列挙する。 - コンセント: テープで固定する - ドア(開閉で引っ張られる): ドアの下をくぐらせるか、コードをたるませる - コード同士の接合部: テープを巻いて補強 本番 ~~~~ 屋内でコードを引っ張るだけなので、卒検やリハよりは楽なはずだ。 かなり床が冷える中二体中を歩き回るので、スリッパの用意があると幸せになれる。 二体のコンセントも、グラグラしているものや壊れているものがある。コンセント周辺は抜けないように念入りに固定し、できれば注意書きもあるとなおよい。 コードはなるべく段ボールパネルの裏側などのお客さんの通らない場所を通し、お客さんの通る場所を通す場合は特に念入りにテープで固定しよう。 28代の本番、公演と公演の間におそらくお客さんの足に引っかかってコードの根元が抜けたことがあり、日周緯度変が動かなくなり、主投が消えたことがあった。 公演中でなかったため大惨事にはならなかったが、しっかりと固定をしておこう。 ドーム内配線 ------------ ドーム内配線は、本番までやることがそう変わらない。 星潰しが終わる頃にコードを搬入し、配線図を見ながらコードを繋げていこう。 ソフトには、どのコンセントを使っていいか伝えておけば音響の配線を進めてくれる。 ドーム外周のあお・しる・方位については、日電で配線してしまっても補助投に任せてもいい。 任せる場合は\ **どれがどの投影機の配線かわかるよう、置き方などを工夫**\ しよう。 ドーム内は末端の投影機の線が抜けても繋ぎ直せばいいだけだが、\ **コードリールの根元**\ などは余裕があるときに固定をしておく方が良い。 **ドームのダクトコンソール**\ も、線が抜けるとドームがしぼんで慌てることになるので、テープを巻いておくべきだ。 本番では、ドーム内にお客様が大勢入られるので、対策が必要だ。 ケーブル類はできるだけスタッフ席側を通るべきだが、その上で銀マットなどを敷いて隠すようにする。 <file_sep>.. Nichiden documentation master file, created by sphinx-quickstart on Thu Feb 16 23:09:56 2017. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. 日電引き継ぎドキュメント ======================== .. toctree:: :maxdepth: 1 :caption: 最近更新した記事 twinkle nissyu-idohen/pc-software nissyu-idohen/pc-software-code wireless/piscium wireless/wireless protect .. toctree:: :maxdepth: 2 :caption: 目次 main management nissyu-idohen/kikou nissyu-idohen/saitama nissyu-idohen/ikebukuro nissyu-idohen/pc-software nissyu-idohen/pc-software-history nissyu-idohen/pc-software-code wireless/wireless wireless/piscium wireless/acrab wireless/acrab-code wireless/graffias twinkle protect haisen haisen-kagoshii bihin syutou hojotou begginers/buy_parts begginers/electronic-design begginers/microcontroller begginers/editor begginers/visualstudio begginers/windows handover honban <file_sep># 【直前特集】本番で気をつけたい三箇条 - 書いた人: <NAME>(nichiden_27) - 更新日時: 2017/11/22 - 実行に必要な知識・技能: 特になし - 難易度: 1/常識の範囲 - 情報の必須度: 5/全員必須 ## 概要 いよいよ本番が近づいてきました。 本番は準備期間とは違う動き方になるので、気をつけてほしいことをいくつか書きます。 ## 新機能を諦める勇気 準備期間中は新しい機能を作り、改善するために努力してきたことでしょう。 ただ、本番ではこれまで表に出なかった問題が出現し、うまく動かないこともやはり多いです。 そうした時に、**新機能を捨てる判断**が素早くできることが大切です。 せっかく作ったものだから、何とか修理して使いたいというのは当たり前の心情でしょう。 ただ、**お客様や他の投影機の人**にとって何が最善かをぜひ考えて下さい。 お客様は日電の最新技術を楽しみに来場している訳ではありません(OB/OGや他団体の偵察は別)。 お客様は「東大天文部の星空」を体験するために来場されます。 **一回でも多くの公演を正常に行う**ことを最優先に、新要素を撤廃する、予備の方法に変えるなど柔軟に対応するのがよいと思います。 また、本番夜の時間帯には各主投影機の位置調整が行われます。 日電が設備の修理やテストを行えば、主投調整がそれだけ遅れてしまいます。 主投が本来の力を発揮できるよう、日電は安定した電源を提供することを重視してください。 ## 人に頼る 日電は人数が少なく、やることの多い本番では休む暇もなく動き続けるようなことが起きます。 休養が十分でないと視野が狭くなり、本来のパフォーマンスを発揮できません。 他の日電メンバーはもちろん、**その辺にいる天文部員に積極的に相談**してください。 手を動かす人が一人から二人に増えるだけで、作業効率はなんと(約)2倍なのです。 ## 記録を残す **本番中に起きたことの記録**は、備品の故障部位の特定や次年度以降の改善にとても役立ちます。 忙しい中きちんとした記録など残せるはずもないですが、断片的なメモや、チャットのログなど後から経過を辿れるような心がけをしてみてはどうでしょうか。 駒場祭が終わると改善点などを報告するよう要請がありますし、駒場祭回顧号の執筆もあるわけですから、本番で頭に浮かぶちょっとしたことのメモは決して無駄にはなりません。 ## おわりに 最後に、本番の成功と皆様の健康を祈念します。 (平成29年11月22日 27日電)<file_sep># 主投影機との連携 - 書いた人: <NAME>(nichiden_27) - 更新: <NAME>(nichiden_28) - 更新日時: 2018/08/26 - 実行に必要な知識・技能: - タスクの重さ: 2/数日かかる - タスクの必須度: 3/年による ## 概要 駒場祭プラネでは、ほぼ全ての主投が電気に関わる作業をすることになります。 残念ながら、電子回路の知識が不十分なまま主投の作業を進めてしまう例も過去にありました。 主投の回路にミスがあると卒検やリハで上手く動かないのはもちろん、最悪の場合**日電側の重要機器が壊れる** こともあり得ます。 忙しくなってから無用な手間をかけずに済むよう、早めに各主投の機長と情報交換を行いましょう。 ## こうとう こうとうのモジュールは年々改良が進んでおり、引き継ぎも十分に行われている。 とりわけ26代で再設計されたユニットは、LEDの放熱も考慮されており、耐久性にも優れている。 3WのパワーLEDを光らせるだけの回路なので、特に頼まれない限り日電が補助する必要はないだろう。 ただし、32個のユニットを全点灯すると、南北合わせて100W近く消費することになる。 こうとうへの電力を供給する回路やケーブルは、**大電流に耐えられる** ものにするよう注意されたい。 *主な使用部品* - [放熱基板付3W白色パワーLED](http://akizukidenshi.com/catalog/g/gI-08956/) - [定電流方式ハイパワーLEDドライバモジュール(3W1個点灯)](http://akizukidenshi.com/catalog/g/gM-04487/) ## いっとう いっとうは星の色を再現するため多様な色のLEDを用いる。 引き継ぎ資料が充実しており、LEDの抵抗計算も解説されている。 使用しているLEDの型番などは確認していないが、秋月で売っている5mmの砲弾型LEDを利用している。 パワーLEDではないため、電力についてはそれほど気にしなくていいはず。 28代で実測してみたところ、いっとうをすべてつないだいっとうboxに対して最大でも500mAは超えなかった。 またたき回路の開発は基本的に日電に一任されている。 頃合いを見て、またたき具合や種類の希望がないか機長に聞き取りをしておこう。 ## ぎんとう 消滅と復活を繰り返していたが、最近はクオリティが上がっている投影機。 光源は1Wの白色パワーLED。 27代で**調光機能** が新設された。 投影された天の川が明るすぎ、恒星をかき消してしまう事態を避けるためである。 位置調整の時は明るくするなどの応用もできる。 調光には、あくとう・しるとうと同様「定電流方式ハイパワーLEDドライバモジュール」に載っている`CL6807`の機能を用いる。 あくとうではPWMを利用しているが、ぎんとうはしるとうと同じ電位による調光を利用している(補助投の記事参照)。 抵抗二つと可変抵抗一つで調光できるので、PWMに比べて部品点数やサイズが大幅に減る。 以下に調光の回路図を掲載する。 VCCやGNDはLEDと共通である。 なお、抵抗値は変更した可能性があるので実物で確認してほしい。 ![銀投調光回路図](_media/gintou_choukou.png) *主な使用部品* - [放熱基板付1W白色パワーLED](http://akizukidenshi.com/catalog/g/gI-03709/) - [定電流方式ハイパワーLEDドライバモジュール(1W1個点灯)](http://akizukidenshi.com/catalog/g/gM-04486/) - 抵抗(240Ω/4.7kΩ) - 可変抵抗(1kΩ) ## 星座絵 星座絵は、1W白色パワーLEDを使用している。 過去にLEDを抵抗なしで回路に繋ぐ、極性を間違えるなどの事象があり、**無線受信機の故障原因を作った可能性もある。** 代によって知識に差があるのは当然なので、日電側からも基本的な知識については確認しておこう。 また、[配線(かごしい内)](haisen-kagoshii.html)に書いたとおり、正座絵のコードでショートが何回か起きた。 そのため正座絵のコードも日電で作るもしくは使うコードを指定した方が良いかもしれない。 *主な使用部品* - [放熱基板付1W白色パワーLED](http://akizukidenshi.com/catalog/g/gI-03709/) - [定電流方式ハイパワーLEDドライバモジュール(1W1個点灯)](http://akizukidenshi.com/catalog/g/gM-04486/) ## ドーム ドームを膨らませる際に使う**ドームコンソール**(ダクトコントローラー)のメンテナンスは日電管轄である。 ドームを直立させるため、3つのダクトそれぞれの風量を調節できるようになっている。 ![ドームコンソールの外観](_media/ductcontroller.jpg) 中には秋月電子の[トライアック万能調光器キット](http://akizukidenshi.com/catalog/g/gK-00098/)が3つ入っている。 交流の波形を変えることで出力パワーを変更するキットである。 破損の可能性があるのは基本的にトライアックなので、万一故障してもトライアックを替えれば復活するかもしれない。 大電流から回路を保護するためヒューズがついているので、切れた場合は部室の予備と交換しよう。 上側のスイッチでFULL/OFF/CONTROLの切り替え、下側のツマミで風量調節をする。 内部を見ればわかるが、FULLは入力・出力を直接繋ぐので、キットが使えなくなったとしても送風を継続できる。 ![ドームコンソールの使い方](_media/ductcontroller-instruction.png) 2017年現在、24のドームコンソールが現役である。 以下は当時使用した部品。 - タカチ MB-6 W140 H75 D200 ¥1,092 - マル信無線 MSR-6#7 中点OFFロッカスイッチ ¥158 - ロッカスイッチ 秋月AJ8221B ¥100 - ベターキャップ WH4015PK ¥115 マルツ - ベターコネクタ - トライアック調光器40A ¥800 - ユニバーサル基板 48 mm * 72 mm - ヒューズホルダ(パネル取り付け・ミゼット用) ¥84 ## ソフト 早いうちに連絡を取っておくべきである。 代ごとのソフトの方針によって、日周緯度変や無線制御などに手を加えるべきか否かが左右されるためだ。 ## かごしい 主投を組み立てる際には日電と一体になって動くことが多い。 かごしいは機構部分、日電は回路部分との暗黙の住み分けがある。 かごしい内のAC100Vケーブルの配線はかごしいに引き継がれているが、実際は日電が行うこともあるので資料を見せてもらうと良いだろう。 かごしい内配線については別記事で詳しく扱う。 ## 展示 展示は、電気を使った模型を製作したこともあるが、基本的には電気と関わりのない唯一の主投と言っていい。 27代では、無線制御システムの解説ポスターを作成し、印刷と展示を依頼した。 <file_sep>日周緯度変(Ikebukuro) ===================== - 書いた人: <NAME>(nichiden_27) - 更新: <NAME>(nichiden_28) - 更新日時: 2018/08/26 - 実行に必要な知識・技能: 電子回路 - タスクの重さ: 2/数日かかる - タスクの必須度: 3/年による - 元資料 - ``日周・緯度変資料.pdf`` by 岩滝宗一郎(nichiden_22) - ``saitama.pdf`` by 荒田 実樹(nichiden_23) 概要 ---- .. figure:: _media/ikebukuro.jpg :alt: 池袋 池袋 さいたま6號には、外部機器(PCなど)を接続して制御することが可能です。これをさいたまの「\ **外部制御**\ 」と呼んでいます。 埼玉6號の外部制御端子は\ ``RS-485/Mini-DIN6``\ という規格・形状ですが、残念ながらこのままではPCに直接挿して外部制御することはできません。そこで、\ ``RS-485/Mini-DIN6``\ と\ ``USB``\ の変換を行うために製作されたのが、\ **変換モジュール\ ``Ikebukuro``**\ (埼玉と繋がっているかららしい…)です。 実際に日周緯度変を動かす際に関わりの多い部分なので、使い方や構造などを解説します。 沿革 ---- 外部制御は、埼玉6號を製作した22代の時点で既に仕様に盛り込まれていた。ただし使用はされておらず、テストもされていない状態だった。続く23代で\ ``Ikebukuro``\ が導入され、\ **PCを使用しての日周緯度変制御を初めて行った**\ 。 その後の24〜27代では日周緯度変を操作するアプリの開発を行なっており、通信には\ ``Ikebukuro``\ が使われ続けている。 使い方 ------ さいたま6號側面に通信用の端子(\ ``Mini-DIN6``)があるので、ケーブルで\ ``Ikebukuro``\ の同じ端子に接続する。次に、\ ``Ikebukuro``\ のUSB端子(miniB)とPCのUSB端子をUSBケーブルで接続すれば準備完了である。 さいたま6號の外部制御スイッチをONにすれば、PCからの信号を待ち受ける状態になる。あとは日周緯度変用のアプリなどを起動してシリアルポートに接続すれば良い。 電装 ---- 通信方式 ~~~~~~~~ 埼玉6號の外部制御端子は、電気的には\ ``RS-485``\ という規格に従っている。 ``RS-485``\ では、3本の線(A,B,GND)で半二重通信(双方向の通信ができるが、同時に両方向の通信は不可)ができる。ノイズに強く、長距離にも耐えられるらしい。 埼玉6號の側部にあるMini-DIN6コネクタのピンとの対応は、図のようになっている。 .. figure:: _media/ikebukuro-rs485.png :alt: 外部制御端子の配線 外部制御端子の配線 のはずなのだが、28代で中身を見たところ、この配線は実際のものと違うことが確認された。 作り直す際などはよく調べてほしい。 内部基板 ~~~~~~~~ ``Ikebukuro``\ の中身は単なる変換モジュールであり、\ ``RS-485``\ と\ ``UART``\ の変換を行うIC(\ ``LTC485``)と、USBとUARTの変換を行うモジュール(\ ``AE-UM232R``)が載っているだけである。 ``AE-UM232R``\ に搭載されているUSB-UART変換チップ(FTDI社の\ ``FT232R``\ という、定番チップ)の関係で、利用するにはPC側にドライバが必要な場合がある。\ `FTDI社のWebページ <http://www.ftdichip.com/Drivers/VCP.htm>`__\ から入手できるので、必要なら使用するPCにインストールしておこう。 自動インストールされることが多いようだが、手動でインストールする必要がある場合もある。 Ogoseでポートを選択できない場合はドライバがインストールできていないことが原因である可能性がある。 また、このチップは初期状態から設定が書き換えられており、\ ``InvertRTS=1``\ となっている。この設計はFTDI社謹製の\ ``FT_PROG``\ (Windows用)というツールで設定できる。 ``RS-485``\ は半二重なので、通信方向の切り替えが必要である。これは、シリアルポートのRTSピンを使用して行っている。 ``Ikebukuro``\ の基板の配線を図に載せる。なお、図には反映していないが、RTSの状態確認用にLEDを実装している。 .. figure:: _media/ikebukuro-circuit.png :alt: Ikebukuro基板の配線 Ikebukuro基板の配線 ``AE-UM232R``\ はICソケットに差さっているので、容易に\ ``Ikebukuro``\ から取り外すことができる。他の回路のテストでUSBシリアル変換モジュールを使いたい時は、\ ``Ikebukuro``\ から\ ``AE-UM232R``\ を取り外して使うと良いだろう(実際、23代で惑星投影機の基板のテストに利用した。最終的にはXBeeで通信するのだが、デバッグ時は「信頼と安定の」FT232Rを利用しようというわけだ)。 ただし、容易に取り外せるのは良いのだが、USBケーブルに変な力がかかると抜けてしまう可能性がある。 28代では1日目の最終公演後日周緯度変がPCから動かせなくなった。 原因はこのモジュールがソケットから外れかけていることであった。 PCと接続しているUSBケーブルに変な力がかかると抜ける可能性があるということを覚えておこう。 プロトコルとコマンド -------------------- 外部制御モードではPCからさいたま6號に指令(コマンド)を送る。ここでは、コマンドを表す文字列のフォーマットを述べる。 このフォーマットを変更したいと思ったら、さいたま側のプログラムの\ ``main.c``\ とPC側のプログラムをいじればよい。 各コマンドに共通するフォーマット ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +------+-------+-------+--------+-------+-------+---+ | 位置 | 0 | 1 | 2 | 3 | 4 | … | +======+=======+=======+========+=======+=======+===+ | 内容 | ``$`` | ``W`` | *addr* | *len* | *cmd* | … | +------+-------+-------+--------+-------+-------+---+ -------------- - *addr*: 機器のアドレス (16進1桁; ‘``0``’〜‘``9``’, ‘``A``’〜‘``F``’) - メイン基板上のディップスイッチで設定した値と一致させる - 現在は\ ``0``\ が使われている - 複数の機器を繋いだ時用のアドレスだが、使うことはないだろう - *len*: 以降のバイト数 (16進1桁; ‘``0``’〜‘``9``’, ‘``A``’〜‘``F``’) - *cmd*: コマンドの種類 速度指定コマンド ~~~~~~~~~~~~~~~~ +------+---+-------+-------+---------+-------+---------+---+ | 位置 | … | 3 | 4 | 5 | 6 | 7..10 | … | +======+===+=======+=======+=========+=======+=========+===+ | 内容 | … | ``7`` | ``V`` | *motor* | *dir* | *speed* | … | +------+---+-------+-------+---------+-------+---------+---+ -------------- - *len*: 以降のバイト数 = ‘``7``’ (7 byte) - *cmd*: コマンドの種類 = ‘``V``’ - *motor*: モーター (日周:‘``D``’, 緯度:‘``L``’) - *dir*: 回転方向 (時計回り:‘``+``’, 反時計回り‘\ ``-``\ ’) - *speed*: 回転速度[deg/s] (16進4桁; ‘``0``’〜‘``9``’, ‘``A``’〜‘``F``’) 角度指定コマンド ~~~~~~~~~~~~~~~~ +------+---+-------+-------+---------+-------+---------+---------+ | 位置 | … | 3 | 4 | 5 | 6 | 7…12 | 13…16 | +======+===+=======+=======+=========+=======+=========+=========+ | 内容 | … | ``D`` | ``P`` | *motor* | *dir* | *angle* | *speed* | +------+---+-------+-------+---------+-------+---------+---------+ -------------- - *len*: 以降のバイト数 = ‘``D``’ (13 byte) - *cmd*: コマンドの種類 = ‘``P``’ - *motor* モーター (日周:‘``D``’, 緯度:‘``L``’) - *dir* 回転方向 (時計回り:‘``+``’, 反時計回り‘\ ``-``\ ’) - *angle* 回転角度[\ ``$10^{-2}$``\ deg] (16進6桁; ‘``0``’〜‘``9``’, ‘``A``\ 〜‘\ ``F``’) - *speed* 回転速度[deg/s] (16進4桁; ‘``0``’〜‘``9``’, ‘``A``’〜‘``F``’) コマンド実例集 ~~~~~~~~~~~~~~ 以上がさいたま外部制御コマンドの仕様だが、これだけでは少々分かりにくいはずなのでいくつか実例を挙げておく。 - 緯度モーターを3000deg/sで時計回りに回す -> ``$W07VL+0BB8`` - 日周モーターを1800deg/sで時計回りに90000deg回す -> ``$W0DPD+8954400708`` PC側のプログラム ~~~~~~~~~~~~~~~~ PC側からは、Ikebukuroが仮想COMポートに見えるので、そのCOMポートに対して上に述べたコマンドを書き込めば良い。この辺りの具体的な話は\ `外部制御アプリの資料 <pc-software.html>`__\ に譲る。 <file_sep>無線制御(Acrab) =============== - 書いた人: <NAME>(nichiden_27) - 更新: <NAME>(nichiden_28) - 更新日時: 2017/05/06 - 実行に必要な知識・技能: Web制作、JavaScript - タスクの重さ: 3/数週間 - タスクの必須度: 4/毎年やるべき 概要 ---- ``Acrab``\ は、27代で開発した投影機無線操作用Webアプリケーションです。 最新のブラウザ(Chrome推奨)があれば、どんな環境でも使うことができます。 名称は、ブラウザで星座絵などを操れることからApplication for Constellation Remote controlling Assistance on Browserの頭文字をとりました。 さそり座β星の固有名でもあります。 使い方 ------ 下準備 ~~~~~~ まず、\ `Acrabの各種ファイル <https://github.com/Triangulum-M33/nichiden28/tree/master/ACRAB>`__\ を同じフォルダに配置する。 ファイルの読み込みにAjaxを使っているので、index.htmlをそのまま開いただけ(file:///)では機能が使えない。 回避方法は「Ajax ローカル」などとググれば複数出てくるが、ローカルにWebサーバを立てる方法を解説する。 Windowsでローカルホストを立てるには、\ `XAMPP <https://www.apachefriends.org/jp/index.html>`__\ を使うのが簡単だ。 GUIなので、操作も分かりやすいだろう。XAMPPの設定については\ `xamppでローカル作業環境構築をしよう <http://creator.aainc.co.jp/archives/6388>`__\ や\ `XAMPPで任意のディレクトリをバーチャルホストにする方法 <https://qiita.com/nbkn/items/e72b283c54403a30b2e1>`__\ 等が参考になるだろう。 MacならApacheが標準で入っているはずなので、\ ``sudo apachectl start``\ を打てば\ ``httpd``\ が動き出す。 設定については、ググれば役に立つ情報が得られる。 起動と接続 ~~~~~~~~~~ localhostにアクセスすれば以下のような画面が表示されるはずだ。 もしボタンに日本語が表示されない場合、設定ファイルの読み込みに失敗しているので再読み込みすること。 .. figure:: _media/acrab-main.png :alt: Acrabのメイン画面(※画像は27代のもの) Acrabのメイン画面(※画像は27代のもの) 次に、\ ``Piscium``\ との接続を確認する。 ``Piscium``\ の電源が入っていて、Wi-Fiネットワークに接続していれば、画面上の「受信状況」が緑色に変わるはずだ。 もし「接続なし」のままなら、PCと\ ``Piscium``\ が同じLANに接続しているか(PCが別のルーターに接続してしまうミスは結構ある)、受信モジュールのIPアドレスが正しいかなどを確認しよう。 「受信状況」欄右の更新ボタンを押すと、\ ``Piscium``\ へのリクエストが再送される。 無事接続できたら下に並ぶボタンを押して投影機をオンオフさせてみよう。 投影機を繋いでいなくても、コマンド自体は送ることができる。 ``Piscium``\ から応答が来なかった場合はボタンの色が変わらないので、不具合に気づける。 公演用画面 ~~~~~~~~~~ ソフトの指示を次へ・前へのボタンで実行できるモード。 画面上に「\ **公演用**\ 」ボタンがあり、押すと画面が切り替わる。 .. figure:: _media/acrab-scenario.png :alt: Acrabの公演用画面 Acrabの公演用画面 左上のメニューから番組名を選べるので、選んでから「\ **開始**\ 」ボタンを押すと一番初めのコマンドが送信される。 下にタイミングが表示されるので、緑色の「\ **次へ**\ 」ボタンを押して番組を進行する。 「\ **前へ**\ 」ボタンでは、直前と逆の指示を送信できる。 「\ **Skip**\ 」ボタンでは、番組は進行するが、指示は送信されない。番組進行者が「次へ」ボタンをうっかり押し忘れた時等に使う。 「開始」した後は左のボタンが「\ **停止**\ 」「\ **再開**\ 」に変化するが、これは右上のタイマーが止まるだけで深い意味はない。 「\ **リセット**\ 」ボタンを押すと、タイマーと番組の進行状況が最初に戻る。 誤操作防止のため、「リセット」は「停止」状態でないとできない。 また、番組選択メニューは「リセット」しなければ操作できない。 プログラム ---------- ``Acrab``\ はWebの技術を使って通信や画面表示を行っている。 画面の情報はHTML、デザインはCSS、内部処理や画面の書き換えはJavaScript(以下JS)という構成だ。 ファイル構成 ~~~~~~~~~~~~ 以下のようなディレクトリ構成になっている。 ファイルを動かす際はリンク切れに注意すること。 :: ACRAB ├── acrab_conf.json ├── img │   ├── acrab-banner.svg │   ├── main_01.png │   ├── main_02.png │   └── (省略) ├── index.html ├── js │   ├── acrab_main.js │   ├── acrab_scenario.js │   └── jquery-3.1.0.js ├── scenario │   ├── 0.json │   ├── 1.json │   ├── (省略) │   └── csv │   └── (省略) ├── style.css └── testscript.json ``index.html``\ がAcrabのメインページである。 デザイン関連の記述は\ ``style.css``\ に分離した。 ``acrab_conf.json``\ には、各種設定が格納されている。 ``img/``\ 以下にはページで使用した画像、\ ``js/``\ 以下にはJavaScriptのコードが入っている。 ``scenario/``\ 内は、番組の指示書を指定形式で入力したデータ。 技術要素 ~~~~~~~~ HTMLとCSS ^^^^^^^^^ 最近のWebアプリは、サーバ側でHTMLファイルを動的に生成して送ってくることが多い。 しかし、\ ``Acrab``\ は\ **静的なHTMLファイルを準備し、クライアント(ブラウザ)側で書き換える**\ 方式を採っている。 単に開発が楽であること、サーバ側で作業する必要がないこと、多数のユーザに後悔するような規模でないことがその理由である。 ``Acrab``\ の\ **ページ構成**\ を変えたければ\ ``index.html``\ を、\ **色やサイズ**\ なら\ ``style.css``\ を編集すれば良い。 どちらもググれば分かる程度の機能しか使っていないつもりなので、Webの経験がなくても対応できるだろう。 それぞれの内容についてはここでは触れないが、JS部分と連動する箇所は都度解説する。 jQuery ^^^^^^ プログラムにはJSを用いていると書いたが、素のJSだけで書くと記述が長くなってしまう。 そこで、jQueryというライブラリを採用している。 動的なページの書き換えやAjaxによるファイル取得などを簡単に書けるようになり、コードを読みやすくできる。 近頃のWebアプリはサーバ側が急速に発展し、jQueryは不要な存在となりつつあるが、\ ``Acrab``\ はクライアントサイドだけで動作する仕様のためあえて採用した。 数年前の流行りとはいえネット上に解説記事が充実しており、学習が容易であることも採用の理由だ。 jQueryは単一のjsファイルにまとめて配布されるので、最新版をダウンロードして\ ``js/``\ 内に入れておけば使えるようになる。 わざわざダウンロードしておくのは、ネットに接続できない本番ドーム内などでもjQueryを取得できるようにするため。 jQueryの機能は解説しないのでググって補完されたい。 ``acrab_main.js``\ や\ ``acrab_scenario.js``\ 内に頻繁に登場する\ ``$``\ という文字は、jQueryを呼び出すためのものである。 ``$.(メソッド名)``\ といった形式で各種メソッドを使用できる。 JSON ^^^^ ``Acrab``\ では、各種設定を個別ファイルに分離している。 投影する星座の名称を変えたい、指示書を編集したいと言った要求はいつ来てもおかしくない。 こうした変更に迅速に対応できるよう\ **JSON**\ 形式の設定ファイルを読み込む方式とした。 JSON(JavaScript Object Notation)は、JavaScriptのオブジェクトの形式でデータを記述するものである。 「JavaScriptのオブジェクト」というのは配列や連想配列を入れ子にした構造を指す。 .. code-block:: js { "hoge": [ 1, null ], "fuga": { "one": [ true, "tenmon" ], "two": "nichiden" } } 上の例のように、項目にラベルを付ける、入れ子にするといったことが比較的シンプルな記述で可能になる。 また、オブジェクトなので\ ``.``\ でラベル名を繋ぐだけでデータを取り出せる(例: ``fuga.one[1]``\ は\ ``"tenmon"``)。 文法がJavaScriptからの流用なので親和性がよく、読み込みが簡単なのも嬉しい。 ただ、文法がたいへん厳しくかつ目で眺めてもミスに気づきにくいので、パースエラーが出ないことを確かめてから使うよう心がけたい。 `JSONLint <http://jsonlint.com/>`__\ など、JSONの文法ミスを検出してくれるサービスが存在する。 また、\ ``Acrab``\ では、JSON形式の指示書の一覧を\ ``scenario_list.json``\ というJSONファイルにして、\ ``ACRAB``\ ディレクトリ内に配置している。 これは、\ ``Acrab_scenario.js``\ が指示書の個数やタイトルを読み込むのに必要なファイルであり、\ ``GRAFFIAS``\ によって簡単に生成することができる。 指示書の検討 ~~~~~~~~~~~~ PCで投影機を操作する場合、指示書の内容が表示されていると便利なのは言うまでもない。 しかし、コードに直接書き込むような方式では、翌年にはもう使えなくなってしまう。 そこで、\ ``Acrab``\ が\ **外部の指示書ファイルを読み込む**\ 方式を検討した。 指示書をどう表現するか ^^^^^^^^^^^^^^^^^^^^^^ ソフトの指示書には様々な情報が書かれているが、主投影機に限れば必要な情報は - 順番 - セリフ - タイミング - 指示 - どの投影機を - 点灯する/消灯する となる。 一公演に対して普通は多数のセリフが存在し、また一つのセリフに複数の投影機への指示がつくこともある。 つまり、「番組」→「セリフ(タイミング)」→「指示」と\ **階層的に表現**\ できればとても嬉しい。 ソフトは指示書をExcel(xlsxファイル)で作成している。 xlsxファイルはかなり複雑で、プログラムから読むのは大変なので、テキスト形式のデータに変換したい。 エクセルならCSVが扱えるが、CSVは表形式のデータとなり階層構造が表現できない。 階層状にできるXMLかJSONのうち、XMLは扱いづらそうだったため\ **JSON**\ を採用した。 JSONならばJavaScriptの\ ``Acrab``\ との親和性もある。 具体的にどのような構造のJSONかについては、ソースコード解説の記事にゆずる(概ね上の箇条書きの通りと思ってよい)。 エクセルからJSONデータへ ^^^^^^^^^^^^^^^^^^^^^^^^ 指示書のデータはソフトが持っているので貰ってくるとして、一発でJSONに変換できる訳ではない。 日本語の指示を\ **プログラム用の形式にする**\ 作業が待っている。 とはいえ、JSONを手で書くのは非常に面倒で、しかもミスがあるとパースができない。 そこで28では\ ``GRAFFIAS``\ という、JSON作成を補助するGUIを作成・使用した。 ``GRAFFIAS``\ の使用法・解説については長くなるので、\ `GRAFFIASの記事 <graffias.html>`__\ に分離する。 ソースコード解説 ~~~~~~~~~~~~~~~~ たいへん長くなるので、\ `Acrabの実装解説 <acrab-code.html>`__\ に分離する。 今後の展望 ---------- 既知の問題 ~~~~~~~~~~ 同時多数点灯対策でごちゃごちゃしている ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 27の本番近くになり、星座絵の突入電流で電源が不安定化するのを避けるため\ ``each_slice()``\ や\ ``sleep_ms()``\ を急遽追加した。 これでも動作はするが、こういった処理はマイコン側でする方が簡単である(sleep関数も用意されている)。 直前に追加したことでコードが読みにくくなっているので、\ **無線受信機側で小分けにして点灯**\ するような対策に切り替えるのが良いだろう。 星座のグループが正しく点灯・消灯しない ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 28の公演中、公演用画面で夏の大三角・冬のダイヤモンドと言った星座グループについて点灯・消灯を指定してもこれが反映されない問題が発生した。 後にこれは\ ``acrab_scenario.js``\ でのコードのミスだと判明したが、修正する時間が足りなかったのでJSONを書き換えて星座グループを使用しないことで無理矢理対応した。 詳しくは\ `Acrabの実装解説 <acrab-code.html>`__\ で説明しているので、修正をお願いしたい。 画面レイアウトの改善 ^^^^^^^^^^^^^^^^^^^^ 28では、27に比べ表示する星座絵の数が増えたため、ボタンの幅を狭めるなどしてこれに対処したが、これを別PCの画面で見ると表示ずれが起きることがあった。 これはおそらくPCの画面サイズの違いが原因だと思われるので、余裕があれば他のPCでも表示テストをしてみるといいかもしれない。 また、「前へ」・「次へ」ボタンは中のテキストによって横幅が変わる仕様(\ ``Flexbox``\ による)だが、これにより「次へ」ボタンの一部が画面からはみ出すことがある。 cssを調整する、\ ``GRAFFIAS.php``\ を弄って改行コードを有効にする等して対応してほしい。(MacとWindowsでも表示異なる可能性あり…?要検証) Skipボタンについても、とりあえず「次へ」ボタンの右側に配置してみたが、本番で一度押し間違いがあったようなので配置を変更した方がいいかもしれない。(そもそも担当者が本番中に寝落ちしなければ不要説も…) 求むデザインセンス。 フルスクリーン機能について ^^^^^^^^^^^^^^^^^^^^^^^^^^ 28の公演中に\ ``Acrab``\ 画面外のアドレスバーの光が漏れていたことがあったので、プログラム的に弄るべきところはないがここに記載しておく。 ``Acrab``\ は\ ``Google Chrome``\ 上で動かすことを前提としたアプリであるため、\ ``Google Chrome``\ の\ **フルスクリーン**\ 機能が使える。 Windowsでは\ ``F11``\ 、Macでは\ ``shift+command+F``\ でフルスクリーンにできる。当日、公演用のPCを持ってきてくれた人に伝えておくといいだろう。 あと、\ ``Acrab``\ はマウスを使うと操作しやすいので、誰がマウスを持ってくるかをちゃんと割り当てておこう。 追加機能案 ~~~~~~~~~~ 設定画面の改善・機能追加 ^^^^^^^^^^^^^^^^^^^^^^^^ ``Acrab``\ は、メンテナンス性・拡張性を高めるために各種設定をプログラムとは別のファイルに保存している。 しかし、設定ファイル自体の読み書きがプログラマにしかできないようでは、その変更は結局日電メンバの仕事となる。 そこで28日電では指示書のJSONファイル作成補助として\ ``GRAFFIAS``\ を製作した。 ローカルにWebサーバを立てると、大体の場合\ **PHPも動く**\ ようになる。 PHPならサーバのファイルに書き込めるので、設定用のJSONファイルを読み込んで画面に表示し、修正して書き込むということが可能だ。 JSONの入出力については\ `PHPでJSONのデータを処理する方法 <https://syncer.jp/how-to-use-json>`__\ など詳しい記事を参照のこと。 現状では指示書用JSONの作成補助と、作成したJSONファイルの一覧を作る機能しかない簡素なものだが、今後は、\ ``acrab_conf.json``\ の書き換えにも対応した設定画面を作る、受信機や投影機の数の増減にも対応できるよう、行の追加・削除ができる表のような仕掛けを用意するなどしてもいい。 色々と工夫の余地がありそうなところだ。 デスクトップアプリ化 ^^^^^^^^^^^^^^^^^^^^ 最近Web界で流行っている\ ``Electron``\ という技術を使うと、Webの作法を使ってクロスプラットフォーム(Win/Mac/Linux)のアプリが組める。 ``Acrab``\ は基本的にサーバサイドで処理をしないので、移植しようと思えばできるだろう。 Web技術が大好きor勉強してみたいのであれば、やってみてはいかがだろうか。 参考: `WebアプリをElectronに乗せる <https://www.slideshare.net/hiroyukianai/webelectron>`__ <file_sep># 日周緯度変(外部制御アプリ) - 書いた人: <NAME>(nichiden_27) - 更新: <NAME>(nichiden_28) - 更新日時: 2018/10/08 - 実行に必要な知識・技能: シリアル通信、C# - タスクの重さ: 3/数週間 - タスクの必須度: 4/毎年やるべき ## 概要 日周緯度変の[外部制御](ikebukuro.html)には、大きな可能性があります。PCを使える以上かなり複雑な操作も自動化できるためです。 ただし、本番で日周緯度変を動かすのは人間である部員たち。 それも、プログラムの挙動を知っている日電員だけが操作するとは限りません(26-28と、かごしいにも日周緯度変操作を手伝って貰っています)。 誰にでも使いやすい日周緯度変外部制御アプリを作るために注意すべきことを書きます。 ## 沿革 **過去に開発されたアプリケーションが多数にのぼるため、**[外部制御アプリの歴史](pc-software-history.html)**に分離する。** ## Ogoseの特徴と使い方 `Ogose`は、27代日電で作成した、2017/03/01現在最新の外部制御アプリである。 特徴は[沿革](pc-software-history.html)の方に文章で書いたので、ここでは簡単に箇条書きするにとどめる。 ![Ogoseの画面](_media/ogose.png) - 各軸4段階で速度を指定 - 回転中の速度変更が可能 - 回転の開始/停止はトグルボタン(押すたびにON/OFFが切り替わる) - フルスクリーン切り替えボタン - 誤操作防止用の「公演モード」 - メモ帳を表示・編集可能 - フリーソフトを使ってゲームコントローラに操作を割り当て可能 ### 基本操作 起動したら、まずは最上部からシリアルポートを選んで**接続ボタン**を押す。 さいたまを`Ikebukuro`を介して繋いだだけの状態ならポートは一つしか出ないことがほとんどだが、複数出たとしても一つずつ試してモーターが動くかどうかで判断すればよい。 未接続のままコマンドを送る操作をした場合は、エラーメッセージとともに送信するコマンドが表示される。 接続していないことに気づけるようにする一方、わざと未接続にすることでコマンド送信のデバッグも可能だ。 実際に日周緯度変を動かすときは、左側と上側にある**速度切り替えボタン**から速度を選び、動かしたい方向のボタンをクリックする。 起動後に一度も速度を選んでいないときは、各軸とも「速い」速度が選択される。 回転開始ボタンは押すと「停止」に表示が切り替わり、再度押すと回転が停止する。 反対方向のボタンは「停止」するまでグレーアウトしてクリックに反応しない。これは、ボタンの表示がおかしくなるのを防ぐためである。 **フルスクリーンボタン**にチェックするとフルスクリーンになる。 画面全体が黒背景になるので、本番中はフルスクリーンが望ましい。 **公演モード**ボタンは、ONにすると警告が表示され日周を進めることしかできなくなる。 画面の右側には.txtファイルを表示する欄がある。あまり機会はないかもしれないが、Ogoseの画面上で編集して保存することも可能。新規作成はできない。 表示する.txtファイルは`Ogose/Ogose/WorkInstructions`ディレクトリ内のものなので、.txtファイルの追加・削除・変更等はここから行えばよい。 この.txtファイルはOgose操作時の指示書として使うことがほとんどだと思うので、本番前に忘れずに準備しておこう。 `Ogose`のコードの解説は、たいへん長いので別記事とする。 -> [Ogoseの実装解説](pc-software-code.html) ## 通信プログラム ### シリアル通信の基本 [Ikebukuroの記事](ikebukuro.html)にある通り、パソコン側からは`Ikebukuro`はシリアルポートとして見える。 よって、シリアルポートにアクセスするプログラムを書けばよい。 ポート名は、Windowsであれば`COM1`や`COM4`のように、「'`COM`'+数字」の形式である。 Mac OS XやLinuxのようなUNIX環境であれば、`/dev/tty.usbserial-A5017ABT`である。 シリアルポートの設定は、さいたま6號側のプログラム中に記述してある設定と一致させなければならない。 現時点での設定は、 - baud rate: 2400 - parity: none - char bits: 8 - stopbit: 1 である。baud rateはこの値である必然性はないので、変えても良い(さいたま6號のプログラムも一緒に変更すること!)。 通信経路の途中で`RS485`を使っている関係上、シリアルポートには読み取りと書き込みのいずれか一方しかできない。 `RS485`の通信方向の切り替えには、シリアルポートのRTS端子を使う。 RTSが`HIGH`になるとパソコン側から日周緯度変側への通信ができ、`LOW`になると逆方向の通信ができる。 コマンドを送信する直前にRTSを`HIGH`にし、終了したら`LOW`に戻すといいだろう。 ### .Netでのシリアル通信 `.Net Framework`を使う場合は、`System.IO.Ports`名前空間以下にある`SerialPort`クラスを利用すると便利である。 Mac OS XやLinuxでは`.Net`のオープンソース実装である`Mono`を利用できるが、`Mono`においても同様である。 以下ではC#のコード例を示す。 まず、ソースコードの冒頭に以下の文を書いておくと便利であろう: ```c# using System.IO.Ports; ``` 通信を開始する前に、まずポートを開く: ```c# SerialPort port = new SerialPort( portName:portName, baudRate:2400, parity:Parity.None, dataBits:8, stopBits:StopBits.One ); port.Open(); ``` この後、`port.IsOpen`により、ポートを開くのに成功したか確認しておこう。 実際に通信するには`SerialPort.Write`メソッドを使う。プログラムを終了する際には、`port.Close()`によりポートを閉じておく。 ### 他の言語でのシリアル通信 日電では23からC#で外部制御アプリを開発してきたが、他の各種の言語でもシリアル通信を扱えるので記しておく。 - C, Lua: [librs232](https://github.com/ynezz/librs232/) - Lua: LuaSys - Python: [pySerial](http://pyserial.sourceforge.net/) - Ruby: [ruby-serialport](http://ruby-serialport.rubyforge.org/) - Java: Java Communications API / RXTX(Windows) - JavaScript(Node.js): [serialport](https://www.npmjs.com/package/serialport) それぞれの使い方やインストール方法についてはググって欲しい。 ### 仮想シリアルポート 開発中、きちんとコマンド文字列が送れているか確認したくなることがあるだろう。 **仮想シリアルポート**は、シリアルポートとして振る舞い、自分自身にデータを送信するループバックテストを可能にするソフトウェアだ。 Windows用だが、[com0com](https://sourceforge.net/projects/com0com/)を紹介する。 ![com0comの設定画面](_media/com0com.png) セットアップすると、互いに繋がった二つのCOMポートを用意してくれる。 番号は、他と被らないよう大きめにしておけば大丈夫だろう。 あとは、一方に作ったアプリから接続し、他方に`Tera Term`などのターミナルソフトで接続すれば、送っている内容が見えるようになる。 ## 今後の展望 ### GUIフレームワーク 日周緯度変をある程度誰でも動かせるようにするには、GUIは欠かせない。 歴代日電では、GUI開発にWindows FormアプリケーションやWPFを用いてきた。 もちろん他にもGUIのフレームワークは山ほどあるが、時間も限られている以上、定番で枯れた技術を使っておくのが無難ではなかろうか。 一つの可能性としては、最近イケイケのWebアプリがある。 ChromeとJavaScriptをベースにデスクトップアプリを実現する`Electron`など、ここ最近急速にシェアを伸ばしている技術もある。 もしあなたがそういった技術を得意としているなら、乗り換える価値はあるかもしれない。 ### 入力機器 本番でアプリの操作性にはまだまだ改善の余地がある。 暗い画面ですばやく操作をするには、マウスよりもキーボードがいいし、タッチパネルやゲームコントローラーといった馴染みのある操作系も役に立つだろう。 ゲームコントローラーは、27プラネではフリーソフトでキー操作と無理やり関連付けしたが、`DirectInput`を使えば単体でも利用できる。 入力機器として完成されているし、操作に慣れている人も多いので、案外自前のボタン配置に凝るよりコスパがいいかもしれない。 ![27本番の日周緯度変スタッフ席の様子](_media/honban-nichiden.jpg) …28プラネでは、マウス操作一本に絞った。メモ帳をつけたために、キーやコントローラーの割り当てが難しくなったためである。 また、メモ帳を作ったことでボタン⇔メモ帳欄でのフォーカス変更が難しくなったのもある。キーボード、ゲームコントローラーを使いたい場合、このあたりの問題をクリアする必要が出てくるだろう。 マウスを使う場合、PCを操作する人の間で、本番ではマウスを誰が持ち込むかの割り当てを決めておいた方がいいだろう。 ### 機能追加 機能の追加案としては、**操作の記録・再生**が考えられる。 23や25で行ってきたことを発展させ、ボタン一つで一本のソフトをまるまる上映できるようになれば楽だろう。 ただし、当然ソフトの指示は毎年変わるので、開発の負担は増加する。 ライブ解説ではタイミングを人力で判断せねばならず、想定外の事態も起こりうる以上、全自動化への道は平坦ではない。 コストに見合うメリットが得られるような仕組みを、ぜひ考案してほしい。 ### メモ帳欄の改良 28でメモ帳の表示機能をつけてみたはいいものの、メモ帳を開くコンボボックスの表示がゴチャゴチャしてしまう点をどうしても解決できなかった。 また、メモ帳のレイアウトも、現状は取り敢えず右に置いてみただけとなっているので、さらに使いやすいレイアウト案があったら改良していってほしい。 また、28でOgoseを実際に使った人からは、メモ欄に原稿の抜粋ではなく、原稿を全部表示して、操作があるところだけ強調or改行を挟んではどうかという意見があった。 表示に使っているのがtxtファイルである以上、強調のためにハイライトを入れるのは難しいが、改行を挟むことや強調のための記号等を入れることくらいならささっとできるので検討してみてもいいかと思う。<file_sep>主投影機との連携 ================ - 書いた人: <NAME>(nichiden_27) - 更新: <NAME>(nichiden_28) - 更新日時: 2018/08/26 - 実行に必要な知識・技能: - タスクの重さ: 2/数日かかる - タスクの必須度: 3/年による 概要 ---- 駒場祭プラネでは、ほぼ全ての主投が電気に関わる作業をすることになります。 残念ながら、電子回路の知識が不十分なまま主投の作業を進めてしまう例も過去にありました。 主投の回路にミスがあると卒検やリハで上手く動かないのはもちろん、最悪の場合\ **日電側の重要機器が壊れる** こともあり得ます。 忙しくなってから無用な手間をかけずに済むよう、早めに各主投の機長と情報交換を行いましょう。 こうとう -------- こうとうのモジュールは年々改良が進んでおり、引き継ぎも十分に行われている。 とりわけ26代で再設計されたユニットは、LEDの放熱も考慮されており、耐久性にも優れている。 3WのパワーLEDを光らせるだけの回路なので、特に頼まれない限り日電が補助する必要はないだろう。 ただし、32個のユニットを全点灯すると、南北合わせて100W近く消費することになる。 こうとうへの電力を供給する回路やケーブルは、\ **大電流に耐えられる** ものにするよう注意されたい。 *主な使用部品* - `放熱基板付3W白色パワーLED <http://akizukidenshi.com/catalog/g/gI-08956/>`__ - `定電流方式ハイパワーLEDドライバモジュール(3W1個点灯) <http://akizukidenshi.com/catalog/g/gM-04487/>`__ いっとう -------- いっとうは星の色を再現するため多様な色のLEDを用いる。 引き継ぎ資料が充実しており、LEDの抵抗計算も解説されている。 使用しているLEDの型番などは確認していないが、秋月で売っている5mmの砲弾型LEDを利用している。 パワーLEDではないため、電力についてはそれほど気にしなくていいはず。 28代で実測してみたところ、いっとうをすべてつないだいっとうboxに対して最大でも500mAは超えなかった。 またたき回路の開発は基本的に日電に一任されている。 頃合いを見て、またたき具合や種類の希望がないか機長に聞き取りをしておこう。 ぎんとう -------- 消滅と復活を繰り返していたが、最近はクオリティが上がっている投影機。 光源は1Wの白色パワーLED。 27代で\ **調光機能** が新設された。 投影された天の川が明るすぎ、恒星をかき消してしまう事態を避けるためである。 位置調整の時は明るくするなどの応用もできる。 調光には、あくとう・しるとうと同様「定電流方式ハイパワーLEDドライバモジュール」に載っている\ ``CL6807``\ の機能を用いる。 あくとうではPWMを利用しているが、ぎんとうはしるとうと同じ電位による調光を利用している(補助投の記事参照)。 抵抗二つと可変抵抗一つで調光できるので、PWMに比べて部品点数やサイズが大幅に減る。 以下に調光の回路図を掲載する。 VCCやGNDはLEDと共通である。 なお、抵抗値は変更した可能性があるので実物で確認してほしい。 .. figure:: _media/gintou_choukou.png :alt: 銀投調光回路図 銀投調光回路図 *主な使用部品* - `放熱基板付1W白色パワーLED <http://akizukidenshi.com/catalog/g/gI-03709/>`__ - `定電流方式ハイパワーLEDドライバモジュール(1W1個点灯) <http://akizukidenshi.com/catalog/g/gM-04486/>`__ - 抵抗(240Ω/4.7kΩ) - 可変抵抗(1kΩ) 星座絵 ------ 星座絵は、1W白色パワーLEDを使用している。 過去にLEDを抵抗なしで回路に繋ぐ、極性を間違えるなどの事象があり、\ **無線受信機の故障原因を作った可能性もある。** 代によって知識に差があるのは当然なので、日電側からも基本的な知識については確認しておこう。 また、\ `配線(かごしい内) <haisen-kagoshii.html>`__\ に書いたとおり、正座絵のコードでショートが何回か起きた。 そのため正座絵のコードも日電で作るもしくは使うコードを指定した方が良いかもしれない。 *主な使用部品* - `放熱基板付1W白色パワーLED <http://akizukidenshi.com/catalog/g/gI-03709/>`__ - `定電流方式ハイパワーLEDドライバモジュール(1W1個点灯) <http://akizukidenshi.com/catalog/g/gM-04486/>`__ ドーム ------ ドームを膨らませる際に使う\ **ドームコンソール**\ (ダクトコントローラー)のメンテナンスは日電管轄である。 ドームを直立させるため、3つのダクトそれぞれの風量を調節できるようになっている。 .. figure:: _media/ductcontroller.jpg :alt: ドームコンソールの外観 ドームコンソールの外観 中には秋月電子の\ `トライアック万能調光器キット <http://akizukidenshi.com/catalog/g/gK-00098/>`__\ が3つ入っている。 交流の波形を変えることで出力パワーを変更するキットである。 破損の可能性があるのは基本的にトライアックなので、万一故障してもトライアックを替えれば復活するかもしれない。 大電流から回路を保護するためヒューズがついているので、切れた場合は部室の予備と交換しよう。 上側のスイッチでFULL/OFF/CONTROLの切り替え、下側のツマミで風量調節をする。 内部を見ればわかるが、FULLは入力・出力を直接繋ぐので、キットが使えなくなったとしても送風を継続できる。 .. figure:: _media/ductcontroller-instruction.png :alt: ドームコンソールの使い方 ドームコンソールの使い方 2017年現在、24のドームコンソールが現役である。 以下は当時使用した部品。 - タカチ MB-6 W140 H75 D200 ¥1,092 - マル信無線 MSR-6#7 中点OFFロッカスイッチ ¥158 - ロッカスイッチ 秋月AJ8221B ¥100 - ベターキャップ WH4015PK ¥115 マルツ - ベターコネクタ - トライアック調光器40A ¥800 - ユニバーサル基板 48 mm \* 72 mm - ヒューズホルダ(パネル取り付け・ミゼット用) ¥84 ソフト ------ 早いうちに連絡を取っておくべきである。 代ごとのソフトの方針によって、日周緯度変や無線制御などに手を加えるべきか否かが左右されるためだ。 かごしい -------- 主投を組み立てる際には日電と一体になって動くことが多い。 かごしいは機構部分、日電は回路部分との暗黙の住み分けがある。 かごしい内のAC100Vケーブルの配線はかごしいに引き継がれているが、実際は日電が行うこともあるので資料を見せてもらうと良いだろう。 かごしい内配線については別記事で詳しく扱う。 展示 ---- 展示は、電気を使った模型を製作したこともあるが、基本的には電気と関わりのない唯一の主投と言っていい。 27代では、無線制御システムの解説ポスターを作成し、印刷と展示を依頼した。 <file_sep>無線制御(PISCIUM) ================= - 書いた人:眞木俊弥(nichiden_27) - 更新:<NAME>(nichiden_28) - 更新日時:2018/10/4 - 実行に必要な知識・技能:電子工作の経験、電子回路について一通りの知識、マイコン(Arduino, PIC)、インターネットの仕組み - タスクの重さ: 4/一月はかかる - タスクの必須度:5/しないとプラネ終了 概要 ---- ※とりあえず使えるようにするだけだったら、\ **概要**\ と\ **使い方**\ の部分を理解すれば大丈夫です。ブラックボックスになるように設計しました。ただ、故障した…とかいうことになったら、頑張って\ **技術仕様**\ のところを理解するか、いっそのこと全部作り直してください。 プラネタリウムの公演と、外で星をぼんやりみている時の差とは何でしょうか? それは、ずばり、分かりやすい解説やワクワクするストーリーがあるないかです! そして、その演出をサポートしてくれるものは何と言っても様々な神話や逸話に彩られた星座でしょう。 ただ、一般の人には満天の星空の中から星座を見つけ出すことは至難の技なので、プラネタリウムでは、「星座絵」を投影します。 そのため、ナレーションに合わせて星座絵を点灯・消灯する必要があります。 ただ、投影機からたくさん線を引き出してしまうと、日周・緯度の変化の際の回転で絡まってしまうため、我々のプラネタリウムでは、無線制御を行っています。 27代では、新たに無線制御装置を作り直しました。 その名も、\ ``PISCIUM``\ (Planetarium Integrated Stars and Constellation Images Utility Module)です!! ``PISCIUM``\ を使うことで、みなさんよくお世話になっているWi-Fiネットワークを介して、パソコン、スマホ、タブレットなどWi-Fiの接続可能な端末から星座絵などのかごしい内部の投影機を無線で制御できます。 28代で電源回りを設計し直し、細かいところを修正して作り直しました。 使い方 ------ ``PISCIUM``\ はそのほかのボックス類と同じように、(百均)タッパーを加工したケースに収められています。 かごしいの側面に固定して使うことを想定しています。 また、事前に部室にあるはずの無線Wi-Fiルーターの電源を入れておきましょう。 |image0| 使用するには、電源を接続し、出力用の側面のDCジャックに星座絵などの投影機を接続してください。 使用している電源は、\ `12V150WのACアダプター <http://akizukidenshi.com/catalog/g/gM-09089/>`__\ です。 ``PISCIUM``\ を上から見たときに、DCジャックが見えていない方を下側面としたときに、 - 上側面の一番左以外と右側面が星座絵(12V)。全部で16ポート。ポート1からポート16まで。 - 左側面が、下から、こうとうONOFFなし(12V、2つ)、こうとうONOFFあり(12V、2つ)、いっとう(12V)、上側面の一番左がぎんとう(12V) となっています。 こうとうのポートだけは他と仕様が違うので注意してください。 また、いっとうとぎんとうは星座絵と仕様が全く同じなので入れ替えることができます。 無線Wi-Fiルーターに自動的に接続されるので、ブラウザで特定のURLにアクセスすることで制御が可能になります。 ブラウザでの制御に関しては、Webアプリケーション\ ``Acrab``\ があるので、\ `そちらの説明 <acrab.html>`__\ を参照してください。 また、基本的に給電は上記のように12V150WのACアダプターを電源用のコネクタに刺して行いますが、軽くテストしたいだけなのにかごしいに固定してある電源を利用するのは大変だと思います。 そのようなときは、ONOFFなしのこうとうのポートのどちらかに12Vの普通のACアダプター(端子がDCプラグのもの)を刺すと\ ``PISCIUM``\ に給電ができます。 ただし、これはあくまでもテスト用の給電なので、星座絵を何個も同時に点灯させたい場合や、こうとうをつけたい場合など大電力を使う場合(ACアダプターの定格電力を超える場合)は正しい給電方法を行ってください。 また、\ **2つ以上の電源から同時に給電しない**\ ようにしてください。 使用上の注意点 ~~~~~~~~~~~~~~ - 電源がついた状態での各投影機の抜き差しは故障の原因になるのでやめてください。 - ATX電源からACアダプターに変えたため電源が落ちることはなくなりましたが、万が一電源が落ちて再起動した場合、Wi-Fiモジュールも再起動します。 Wi-Fiモジュールが再起動した後、設定を送り直すため\ ``Acrab``\ のページを再読み込みする必要あります(これは欠陥なので改善されるべき)。 - かごしいのグラウンドが弱いため、稼働している間に全体が帯電してしまうようです。 27代の公演でも、公演中に火花が飛び散り、空中放電して一瞬ブラックアウトしたことがあります。 **かごしいのアース接続を何とかする必要があります。** そうでないと最悪の場合、火花放電により出火します。 かごしい本体とは導通していることは確認しているので、かごしいか、それと導通しているごきぶりをアースしてください。 アースするときは、より線ではなく、単芯の太めの導線を使用し、体育館の柱など地面に突き刺さっている大きい金属に接続してください。 アースしただけで治るのかはよくわかりませんが、アースしてないのはまずいです。 28代ではその指摘を受けて、赤黒の太い線(より線ではあるが)を使って、片側はごきぶりの下の方にあるボルトに挟み、もう片側をバレーボールの支柱を立てる土台に固定してアースをしました。 そのおかげか28代では火花が散ることはありませんでした。 ただし、かごしいを触ると静電気のようなものを感じることは何度もあったので、帯電はしていたようです。 27代よりも頻繁に(毎公演の前に)調整を行っていたので、アースのおかげではなく、人間を通じて放電していただけなのかもしれないです。 - また、グラウンドが弱く、サージに耐えられないので、こうとうの制御は27代の時点では不可能(電源が落ちてしまう)でしたが、28代で電源を変えたのと、こうとうboxに突入電流防止用のサーミスタをつけたことで、こうとうの制御が可能になりました。 しかし、本番直前にPICのこうとうの制御をしているピンが壊れてしまい、本番はこうとうはONOFFなしのポートに接続し、常時つけっぱなしにしていました。 単純に経年劣化の可能性もありますが、こうとうをONOFFする際のサージにPICが耐えられなかった可能性があります。 実際、こうとうはあおとうやしるとうの光で見えなくなるので、公演の際にONOFFをいじる手間を考えると常時ONにするという選択肢もあるでしょう。 - いっとうの制御は可能ですが、いっとうボックスのまたたき回路の起動に時間がかかり、点灯までにタイムラグが生じるので、現時点では行える状況にありません。 またたき回路のプログラムを変更して、すぐに起動できるようにする、またはまたたき回路に無線の機能をつければいっとうの制御もできるようになるでしょう。 技術仕様 -------- 27代、28代で作成したファイルは全て\ `Githubレポジトリ <https://github.com/Triangulum-M33/nichiden28>`__\ においてあります。 回路 ~~~~ 主な部品としては、Wi-Fiの制御を行う\ ``ESP8266``\ というSoC(System on Chip: マイコン、通信制御回路などが一つのチップの中に収まっているもの)の開発ボード、\ ``ESP8266``\ からのシリアル通信を受信して各DCジャックを制御するPICマイコン、DCジャックの電流をスイッチングするFETから構成されています。 |回路図| こうとう以外のポートには、DCジャックの付け根に2.2Ωの抵抗(定格1W)が入っています。 これは、27代において、各投影機をONにした際の突入電流によって電源が落ちるということが何度も起きたため、その突入電流を制限するために28代出つけました。 これで理論上突入電流は最大でも(12/2.2=)5.5Aまでしか流れないです。 こうとうに関しては特に大電流を流すので、こうとうbox側で別途突入電流対策をしています。 しかし、実際は28代でATX電源をACアダプターに変えたことで電源が落ちるという問題は解決されていた可能性もあり、この抵抗の意味があるのかはいまいち不明です。 さらに、28代で実際にあった事例として、星座絵のユニットの部分でショートしていたことがあり、電流を流しすぎてこの抵抗が焼き切れた(見た目上はわからないが電流が流れなくなる)ことがあります。 これは一度だけでなく何度も起きた事例で、抵抗を交換する手間がかかりました。 ただし、これは一概に悪いこととは言えず、もし抵抗がなかったらFETやもっと大事な部分が壊れていた可能性もあり、ヒューズのような役割を果たしていたともいえます。 かごしいに固定したままでも抵抗を交換できるような機構を作るのが一番良いのかもしれません。 ESP8266の開発ボード周りのソフトウェア ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (中華製の安物の)Wi-Fi入りマイコンボードを利用しています。 この\ ``ESP8266``\ は、\ ``Xtensa``\ というアーキテクチャを採用していますが、有志により、Arduino IDEで開発できるようになっていて、Wi-Fiサーバーなどの高度なプログラムもライブラリとして整備されていて、我々素人にとっては非常に開発のしやすいモジュールです。 また、今回使用しているボードには、すでに書き込み用の回路も付いているので、USBでパソコンに接続するだけで開発できます。 ただ、USB-シリアル変換素子はArduino純正のものとは違うので、ドライバをインストールする必要があります。 USB-シリアル変換素子の型番は、\ ``CH340g``\ です。Githubとか製造元のサイトからドライバ落としてきてインスコしてください。 また、ボードの書き込み設定などは、\ `このサイト <http://trac.switch-science.com/wiki/esp_dev_arduino_ide>`__\ などを参照してください。 “ESP8266 書き込み”とかでググるとわんさか出てくるはずです。 27代が開発したプログラムは、\ ``ESP8266``\ 上でwebサーバー(のようなもの)を動かし、特定のURIのGETリクエストを受け取ると、シリアル通信でPICマイコンに点灯状況を送信する形になっています。 IPアドレスは、固定IPで、北天が192.168.11.100、南天が192.168.11.101になっています。 .. _使い方-1: 使い方 ^^^^^^ `Wikiへのリンク <https://github.com/macv35/nichiden27/wiki/Piscium#usage>`__ Send GET request to certain url. .. 1. **Refresh Confirm** (example) http://(ip)/refresh_confirm/status.json 2. **Set Port** Set ON/OFF of each port. (example) http://(ip)/setPort/status.json?P01=0&P02=1 3. **Set Constellation Name** Change names of pin used in communication. (example) >http://(ip)/setConstellationName/status.json?p01=And&p02=Aql… 4. **All Set** Set all port ON. (example) http://(ip)/allSet/status.json 5. **All Clear** Set all port OFF. (example) http://(ip)/allClear/status.json 以上の5種類のコマンドが用意されています。 通常の公演時は、\ ``Acrab``\ がこの辺のことはやってくれるはずですが、回路関係のデバッグをする際には、手持ちのスマホとかでこれらのURIにアクセスしながらやると楽です。 ``ESP8266``\ が正しくURIをパーズすると、シリアル通信(UART)でPICマイコンにコマンドが送られます。 “NS”の2文字を送ったあとに、各DCジャック(ポート)20個分の点灯状況を点灯の時“1”、消灯の時“0”として、20文字分送ったあとに、23文字目に“\\n”(改行)をパケットとして送るプロトコルを使用しています。 名付けてNS(Nichiden Seizae)プロトコル…雑です、はい、すみません。 まあ、どうせUARTなんだし、こんな雑なプロトコルでも問題は起きていませんのでご安心を。 また、UARTでPICにパケットが送られるのと同時に、GETリクエストに対して、現在のステータスを表したjsonを返します。 参考までに、ソースコードのリンクをつけておきます。 (汚いのであんまり見ないでー。URIパーザーの部分とかは他のクラスに分けるとかするべきだった。) `Arduinoのスケッチ <https://github.com/macv35/nichiden27/blob/master/PISCIUM/PISCIUMServer/PISCIUMServer.ino>`__ PICマイコンのソフトウェア ~~~~~~~~~~~~~~~~~~~~~~~~~ ``ESP8266``\ から送られてきたシリアル通信をデコードして各ポートのFETをオンオフするだけの子なので、大したことはしてないです。 ``ESP8266``\ は3.3V駆動なのに対して、PICは5Vで駆動しているので、間にシリアルレベル変換素子は入れてあります。 MPLAB Xのプロジェクトファイルが引き継ぎ資料の\ ``/pic_decoder/``\ ディレクトリに入っています。 もし万が一、PICが壊れたりした場合は、\ ``PICkit3``\ を差し込めるピンヘッダを用意しておいた(28で作り替えた際に書き込み用のピンヘッダを省略して作りました。必要に応じて追加してください)ので、PICを交換して書き込み直してください。 書き込み方は、\ `PICkit3の使い方 <http://ww1.microchip.com/downloads/jp/DeviceDoc/52010A_JP.pdf>`__\ をみてください。 .. |image0| image:: _media/router_photo.jpg .. |回路図| image:: _media/PISCIUM_circuit28.jpg <file_sep>#/bin/bash cd `dirname $0` find ./* -name '*.md' -print0 | while read -r -d '' file do echo "[1] Converting Markdown to reST : $file" pandoc -f markdown -t rst "$file" -o "${file%%.md}.rst" # translate Markdown to reST done find ./* -name '*.rst' -print0 | while read -r -d '' file do echo "[2] Processing reST code : $file" sed -i.bak -e 's/\.\.\ code:: math/.. math::/g' "${file}" # substitution for code hilighting sed -i.bak -e 's/\.\.\ code::/.. code-block::/g' "${file}" # substitution for code hilighting done echo "[3] Building Documantation" make html echo "[4] Removing backup & reST files" find ./* -name '*.bak' -type f | xargs rm find ./* -name '*.md' -print0 | while read -r -d '' file do rm ${file%%.md}.rst done echo "[5] Copying all files to docs/" rm -r docs/* cp -r build/html/* docs/ touch docs/.nojekyll echo "[6] Done." <file_sep># 過電圧保護回路 - 書いた人: <NAME>(nichiden_28) - 更新日時: 2018/09/28 - 実行に必要な知識・技能: 電子回路の知識 - 難易度: 2/少しやれば可能 - 情報の必須度: 3/必要な場合がある - 元資料 + `27日電引き継ぎドキュメント またたき回路` by <NAME>(nichiden_27) ## 概要 27代までのまたたき回路についていた回路です。 27代まではまたたき回路の電源が5Vであったため、誤って12Vを刺しても壊れないように使っていました。 28代でまたたき回路の電源を12Vに変更したため必要なくなりましたが、あくとうコントローラーなど他の電源が5Vの回路に組み込むなどの利用方法があります。 ## 回路 ![過電圧保護回路](_media/protection.png) 閾値の検出に使用しているのは**ツェナーダイオード**である。 ダイオードには、逆方向に電圧をかけるとある閾値以上の電位差で逆向きに電流が流れ、それ以上電位差が大きくならない効果がある。 その閾値をツェナー電圧という。 通常のダイオードでは非常に高いツェナー電圧だが、ツェナーダイオードは不純物を混ぜることでツェナー電圧を下げている。 またたき回路で使用した`HZ5B1`のツェナー電圧は4.6-4.8V。 カソード側の200Ωの抵抗により、回路全体としての閾値を**5.1-5.2V**としてある。 `VCC_IN`が約5.1V以下の場合、ツェナーダイオードには電流が流れず、`2SA1015GR`はOFFの状態になる。 `2SA1015GR`のコレクタはプルダウンされているので0Vに落ち、FET(`2SJ471`)にはゲート・ソース間電圧が発生する。 従って、FETのソース・ドレイン間に電流が流れ、`VCC_OUT`に入力電圧がそのまま出てくる。 `VCC_IN`が約5.2Vを超えると、ツェナーダイオードに逆向きの電流が流れ始める。 `2SA1015GR`にエミッタ・ベース電流が流れることで、コレクタに電流が流れて`2SJ471`のゲート電圧が`VCC_IN`とほぼ等しくなる。 結果、ゲート・ソース間電圧はほぼ0Vとなり、FETがOFFの状態になって電源が遮断される。 この回路の耐圧はツェナーダイオードの許容損失による。 入力が約15Vを越えると許容損失を超え、ダイオードが焼き切れる可能性がある。 仮に焼ききれた場合、ツェナーダイオードに電流が流れない状態と同じになり、入力電圧が`VCC_OUT`に出力されてしまう。 大変危険なので、**高電圧の電源を接続しないよう注意すべきだ**。 保護回路の閾値は、ツェナーダイオードのツェナー電圧やカソード側の抵抗値を調整することで変更できる。 <file_sep>無線制御(Acrabの実装解説) ========================= - 書いた人: <NAME>(nichiden_27) - 更新: Hanaka Satoh(nichiden_28) - 更新日時: 2018/08/26 - 実行に必要な知識・技能: Web制作、JavaScript - 難易度: 3/練習・勉強が必要 - 情報の必須度: 4/担当者には必須 概要 ---- `無線制御(Acrab) <acrab.html>`__\ から\ ``Acrab``\ の具体的な実装の解説を分離した記事です。 ``Acrab``\ のソースコードを読む、あるいは書き換える際に参考にしてください。 acrab_conf.json --------------- ``Acrab``\ の設定ファイルである。 JSONファイルのため構造の概略のみ示す。 :: ├── "ip" [Pisciumとの通信用] │   ├── "N" [北天受信機のIPアドレス] │   └── "S" [南天受信機のIPアドレス] ├── "port" [出力ポート用] │   ├── "And" [星座or投影機名の三文字コード] │   │   ├── "name" [ボタンに表示する名前] │   │   ├── "box" [北天なら"N"/南天なら"N"/両方なら"NS"] │   │   └── "pin" [投影機とピン番号の対応] │   └── (以下同様) └── "group" [星座や投影機のグループを定義]    ├── "Set" [全点灯の三文字コード]    │   └── "name" [ボタンに表示する名前]    ├── "Cle" [全消灯の三文字コード]    │   └── "name" [ボタンに表示する名前]    ├── "Spc" [グループ名の三文字コード]    │   ├── "name" [ボタンに表示する名前]    │   └── "value" [配列: グループに属する星座or投影機を列挙]    └── (以下同様) 三文字コードというのは、プログラム中で\ **星座・投影機・そのグループ**\ を区別するため一意に割り振った三文字を指す。 星座にはもともと\ `この形式の略符が用意されている <http://www.nao.ac.jp/new-info/constellation2.html>`__\ こともあり、文字数を統一して可読性を高めることを目指した。 また、\ ``ACRAB``\ ディレクトリ内に\ ``88星座+略符一覧.txt``\ を用意してみたので、良ければ参考にしてほしい。 例えば星座絵のピン番号を入れ替える際には、\ ``port.(星座名).pin``\ を書き換えれば良い。(※北天、南天それぞれでpin番号が重複しないようにする) ``Piscium``\ 側に設定を反映させるためページをリロードすること。 acrab_main.js ------------- ``Acrab``\ 全体に関わるコードや、「メイン」画面で使用するコードを記述した。 読み込み時の処理 ~~~~~~~~~~~~~~~~ ページを読み込んだ後に一度だけ実行したい処理がある。 JSはスクリプト言語なので、main関数のようなものはなくコードの頭から順に読み込まれる。 通常は関数を定義しても呼び出されるまで何も起こらないが、\ ``(function(){})()``\ の形式のものは読み込んだ時点で実行される。 これを\ **即時関数**\ といい、初期設定の適用などに使える。 また、コード中に\ ``$(function(){})``\ もあるが、これは即時関数ではない。 $がついたものはjQueryの\ **readyイベント**\ といい、\ **HTMLが全てロードされた時点で実行される**\ 。 ページを書き換えるような処理ではページが読み込まれていないと意味がないので、こちらを使うようにしよう。 即時関数・readyイベントで行っている処理は以下の通り。 冒頭の\ ``acrab_conf.json``\ の取得とパースだけはreadyイベントでは上手くいかなかったので即時関数を使用している。 - ``acrab_conf.json``\ の取得とパース - ``$.getJSON()``\ を使うだけ - ``port``\ と\ ``group``\ の\ ``name``\ をボタンに表示 - ``$.each()``\ で配列の全要素にループ処理できる - ピン番号の設定を\ ``Piscium``\ に送信(\ ``pinSettingSend()``) - 各ボタンにclickイベントを追加 - ``.main_button``\ というクラスの要素を取得して\ ``$.each()`` - HTMLに手作業で書くのが面倒なので、クラスからボタンの種類を判定して最適な関数を実行する仕組み - 更新ボタン、明るさスライダーの処理を追加 - タブの切り替え - 各タブの画面はそれぞれ\ ``.content``\ クラスに入っている - 一度全てを非表示にした後、押したタブの順番と同じ順番の画面のみ表示する 開発の途中に順次追加したのでかなりグチャグチャになっている。 自由に読みやすく変更して構わない。 getRequest(address, data) ~~~~~~~~~~~~~~~~~~~~~~~~~ ``address``\ にURLパラメータとして\ ``data``\ を付けて送信する関数。 jQueryの\ ``get()``\ や\ ``Deferred``\ を使用している。 .. code-block:: js data = data || {} console.info(address + ': ' + JSON.stringify(data)); var deferred = $.Deferred(); // 非同期通信なので完了時にデータを渡す処理 $.get({ url: address, dataType: 'json', timeout: 1000, data: data }).done(function(res) { console.debug(res); if(address.match(ip.N)) $('#wifi-icons #north').text('正常受信中').removeClass('error'); else if(address.match(ip.S)) $('#wifi-icons #south').text('正常受信中').removeClass('error'); deferred.resolve(res); }).fail(function(xhr) { console.error(xhr.status+' '+xhr.statusText); if(address.match(ip.N)) $('#wifi-icons #north').text('接続なし').addClass('error'); else if(address.match(ip.S)) $('#wifi-icons #south').text('接続なし').addClass('error'); deferred.reject; }); return deferred; ``$.get()``\ は、指定したURLにGETリクエストを送信する。 ``data``\ に連想配列を指定するとURLパラメータに整形してくれる嬉しい機能付きだ。 また、通信が切れている時に固まらないよう、1500msのタイムアウトを設定している。(1000msだと通信失敗することが多かった。) その後の\ ``.done()``\ や\ ``.fail()``\ にはそれぞれ通信成功時・失敗時の処理を書く。 ここでは通信するたびにブラウザコンソールに結果を出力し、受信状況の欄を更新するようになっている。 さて、\ ``Piscium``\ にコマンドを送ると、\ **各ポートの状態を0か1で表したjsonデータ**\ が返る。 ``dataType: 'json'``\ としておけばパースまでやってくれるようだ。 これを関数の戻り値としたいが、これには工夫が必要になる。 ``$.get()``\ のようなAjax通信は\ **非同期処理**\ を採用しており、リクエストを送った後応答を待たずに関数が終了してしまう。 そのため、送られてくるはずのデータを戻り値に入れることができない。 そこで、\ ``$.Deferred``\ を利用する。 ググれば出てくるため詳細は省くが、Deferredオブジェクトを一旦返し\ **通信が終了してからデータを格納する**\ ことができる。 また、通信が失敗した場合\ ``deferred.reject``\ すると以上終了させることもできる。 checkStatus(stat) ~~~~~~~~~~~~~~~~~ ``Piscium``\ から送られてくるjsonをパースしたオブジェクトから\ **各星座絵・投影機のオンオフ状況を確認する**\ 。 基本的に\ ``getRequest()``\ で通信した後はこれを呼ぶようにして、表示を常に最新に保つべきである。 ``getRequest()``\ は非同期関数なので、以下のコード片のように\ ``.done()``\ を使う。 .. code-block:: js getRequest(address, data).done(function(res){checkStatus(res)}); ボタンはHTML側で以下のように三文字コードのIDが振られている。 .. code-block:: html <!-- index.html --> <button class="main_button constellation" id="And">And</button> 三文字コードは\ ``port``\ や\ ``group``\ に入っているので、\ ``$.each()``\ ループを回して巡回する。 各ボタンに\ ``on``\ クラスを追加すると色などが変わる仕組みだ。 .. code-block:: js $.each(port, function(key){ // 星座|投影機ごと if(stat[key] === 1) $('[id='+key+']').addClass('on'); else if(stat[key] === 0) $('[id='+key+']').removeClass('on'); }); ``group``\ に関しても基本は変わらないが、こちらは\ **属している星座絵全てが点灯していなければオンにならない**\ 。 例えば、「夏の大三角」ボタンを押すと「こと/わし/はくちょう」が点灯するが、このうち一つでも消すと「夏の大三角」もオフの表示になる。 .. code-block:: js $.each(group, function(key){ // 星座グループごと if(!this.value) return; var isOn = true; $.each(this.value, function(){isOn &= $('#'+this).hasClass('on');}); // 各星座がオンかどうかのANDをとる if(isOn) $('[id='+key+']').addClass('on'); else $('[id='+key+']').removeClass('on'); }); return; } pinSettingSend() ~~~~~~~~~~~~~~~~ ``Piscium``\ には、\ ``(ip)/setConstellationName/status.json``\ にアクセスすることでピンごとに名前を設定する機能がある。 これで\ ``(ip)/setPort/status.json?And=0``\ のように三文字コードをURLに使えるようになり、ユーザが見てもわかりやすい。 ``acrab_conf.json``\ が読み込まれた後のタイミングで実行される。また、受信状況の「更新」ボタンを押しても実行される。(北天・南天とも) これは\ ``PISCIUM``\ の再起動時に、ページを再読み込みしなくても、「更新」ボタンを押せば\ ``PISCIUM``\ にピン名称を送れるようにするためである。 ``port.(三文字コード).pin``\ の中身を順に取得して\ ``getRequest()``\ に渡すという流れである。 buttonオブジェクト ~~~~~~~~~~~~~~~~~~ メイン画面のボタンは、\ **星座絵/投影機/全点(消)灯/グループ**\ の四種類ある。 それぞれに合った処理をするため、\ ``button``\ オブジェクトを作成し必要なメソッドをまとめるようにした。 星座絵: button.constellation(obj) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 星座絵は南天か北天に分かれている。 南北は\ ``port[(三文字コード)].box``\ から判定し、受信機のアドレスを\ ``ip[(NかS)]``\ で取得する。 また、ボタンのオンオフ状態と逆の真偽値を\ ``data``\ に入れておく。 後は\ ``getRequest()``\ を呼んで終了する。 .. code-block:: js var address = ip[port[obj.id].box] + 'setPort/status.json'; var data = {} data[obj.id] = button.stat(obj); getRequest(address, data).done(function(res){checkStatus(res)}); return; 投影機: button.projector(obj) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 星座絵以外の投影機は南北両方に付いているのが普通である。 そのため\ **受信機の数だけ同じリクエストを送る**\ 必要がある。 ``ip``\ の各要素について\ ``$.each()``\ を回すことでこれを実現する。 .. code-block:: js $.each(ip, function(){ var address = this + 'setPort/status.json'; var data = {}; data[obj.id] = button.stat(obj); getRequest(address, data).done(function(res){checkStatus(res)}); }); return; 全点(消)灯: button.all(obj) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ ``Piscium``\ 側の全点灯(allSet)・全消灯(allClear)を使う場合。 コードは\ ``button.projector(obj)``\ と似ているので省略。 ``Piscium``\ 側の負荷の関係で、今のところ全点灯は使うべきでないようだ。 グループ: button.group(obj) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ 「夏の大三角」「黄道十二星座」と言った星座のグループ。 実はこれが一番面倒である。 理由は\ **各星座絵が南北にばらけていることがある**\ ため。 そのため、 1. ``ip``\ からIPアドレスを取得してURLを作成 2. ``group[(三文字コード).value]``\ で\ ``$.each()``\ を回し、南北判定していずれかの\ ``data``\ に追加 3. ``req``\ オブジェクトに南北それぞれのデータを入れ、\ ``getRequest()`` という手順を踏んでいる。 実は、本番前にさらに一段階手順を増やした。 星座絵を10個弱同時に点灯すると電源が不安定化する事象を確認したため、回避のため\ **少数ずつ分けて点灯する**\ よう変更したのである。 このため新たに\ ``each_slice()``\ と\ ``sleep_ms()``\ という関数を定義した。 これらの詳細は後述する。 ボタンの状態を取得する: button.stat(obj) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ボタンがオンかオフかは、\ ``on``\ クラスを持っているかどうかで分かる。 ``stat()``\ にボタンのオブジェクトを渡すと、現在の状態の逆の値を返す。 .. code-block:: js return ($(obj).hasClass('on') ? 0 : 1); each_slice(obj, n) ~~~~~~~~~~~~~~~~~~ 投影機を複数点灯・消灯する際一回あたりの数を抑えるのに使用する。 ``obj``\ にオブジェクトを、\ ``n``\ に最大数を指定すると\ ``obj``\ をn要素ごとに切り分けたオブジェクトの配列を返す。 .. code-block:: js each_slice({"Ari":1,"Cnc":1,"Gem":1,"Leo":1,"Aqr":1,"Cap":1,"Psc":1},3) -> [{"Ari":1,"Cnc":1,"Gem":1},{"Leo":1,"Aqr":1,"Cap":1},{"Psc":1}] ただし、例外として“St1”と“St2”をキーにもつ場合は1要素のオブジェクトに分ける。 これは、こうとうの負荷があまりに大きいため他の投影機と同時に点灯することを避けるためである。 アルゴリズムとしては、n要素ずつ切ったものをfor文内でオブジェクトに追加していくだけなのでコードは省略する。 sleep_ms(T) ~~~~~~~~~~~ ``getRequest()``\ が\ ``each_slice()``\ により複数回に別れる場合に、間隔を十分取るための関数。 これがマイコンならば\ ``delay()``\ のような関数が標準で用意されるところだが、ブラウザにはそんなものはないので作るしかない。 下のコードを見れば分かるように、ひたすら時刻を取得して最初との差が\ ``T``\ を超えたら抜けるという作戦になっている。 .. code-block:: js var d = new Date().getTime(); var dd = new Date().getTime(); while(dd < d+T) dd = new Date().getTime(); 遅らせる時間だが、100 msとした。 LEDの突入電流が流れる時間は数ms程度なので、十分大きくかつ人間には長すぎない程度と判断している。 scenarioディレクトリ -------------------- ``scenario/``\ 以下には、番組の指示書を\ ``Acrab``\ から読み取れるようJSON形式に変換したJSONファイルが入っている。 \*.json JSONファイルの構造を簡単に示す。 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :: ├── "info" [番組情報] │   ├── "day" [(ライブ解説の場合)何日目か] │   ├── "title" [番組名] │   └── "name" [担当者名] └── "script" [配列: 指示が入る部分]    ├── 0    │   ├── "word" [セリフ: 0番目は空欄にする]    │   ├── "timing" [タイミング: 0番目は空欄にする]    │   └── "projector" [投影機]    │      ├── "(三文字コード)" [点灯なら1/消灯なら0]    │      └── (以下同様)    ├── 1    │   ├── "word" [セリフ]    │   ├── "timing" [タイミング]    │   └── "projector" [投影機]    │      ├── "(三文字コード)" [点灯なら1/消灯なら0]    │      └── (以下同様)    └── (以下同様) ``info``\ オブジェクト内には、番組のメタデータに相当する情報が入っている。 番組選択画面で番組を選びやすくする為、\ ``day``\ に\ **公演日**\ の情報も入れるようにした。 なお、ソフトは駒場祭を通じて上演されるので実際には(ソフト,一日目,二日目,三日目)の四つに分かれる。 ``script``\ 以下が\ **セリフやタイミング**\ を格納する部分である。 配列の形で並べてあり、上から順番に時系列で並んでいる必要がある。 配列の0番目は特別な部分で、公演の\ **開始前から点灯**\ したい投影機に使用する。 このため、先頭のセリフとタイミングは空欄にする必要がある。 ``timing``\ に\ ``pre``\ を指定すると「(セリフ)の\ **言い始め**\ 」、\ ``post``\ を指定すると「(セリフ)の\ **言い終り**\ 」と画面に表示される。 セリフの前後以外のタイミングを指定したければ、「〜の」につながる形で\ **自由に書けばそのまま表示**\ される。 最後に、JSONファイルの例を示しておく。 .. code-block:: json { "info": { "day": "sample", "title": "とてもわかりやすい星座解説", "name": "星見太郎" }, "scenario":[ { "timing": "", "word": "", "projector": { "Fst": 1, "Gxy": 1 } }, { "timing": "post", "word": "プラネタリウムはいかがでしょう", "projector": { "St1": 1, "St2": 1 } } ] } 28で使ったJSONファイルは一旦そのまま残してあるので、\ ``Acrab``\ の動作テスト用やJSONファイルの書き方例として参考にしてほしい。 scenario_list.json ------------------ 後述する\ ``acrab-scenario.js``\ で、\ ``Acrab``\ にサーバの指示書ファイルの数を渡すための指示書ファイルのリスト。 ``GRAFFIAS``\ で生成できる。作り方は\ `無線制御(GRAFFIAS) <graffias.html>`__\ 参照のこと。 acrab-scenario.js ----------------- 「公演用画面」のためのコード。 分量が多くなったためmainと分けることにした。 ページの初期化関連 ~~~~~~~~~~~~~~~~~~ 前述の通り、指示書は番組ごとのJSONファイルに分けて\ ``scenario/``\ 以下に保存されている。 ``acrab_main.js``\ と同様に、jQueryの\ ``$.getJSON()``\ を用いて取得とパースを行っている。 | ``Acrab``\ はブラウザ側だけで動作しているため、サーバにいくつの指示書ファイルがあるかを直接取得できない。 | このため、先述した\ ``scenario_list.json``\ をjQueryの\ ``$.ajax()``\ を用いることで取得・パースし、配列の要素数から指示書ファイルの数を得る方式にした。 | ``$.ajax()``\ は本来非同期通信に用いるものであるが、非同期のままだと\ ``scenariolist``\ にデータが入らなかったため\ ``async: false``\ にすることで無理矢理対応した。 | 本当は非同期通信のまま\ ``$.Deferred``\ などを使った方がいい気がするが、ページ読み込み時のみの処理なので妥協してしまったところ。読み込み時に気になるようなら書き直してほしい。 .. code-block:: js $.ajax({ type: "GET", url: "scenario_list.json", async: false, success: function(data){ scenariolist = data.scenariolist; } }); for(var i=0;i< scenariolist.length;i++){ scenario_file[i] = $.getJSON(scenariolist[i]); } 指示書ファイルを取得したら、番組選択メニューにタイトルと担当者名を追加する。 ``<option>``\ や\ ``<optgroup>``\ というのはHTMLのセレクトボックス用のタグで、前者が選択項目、後者が項目をまとめる見出しだ。 特に工夫したわけではないので解説はしない。 ググりながらコードを読んで理解してほしい。 最後の\ ``$('select#select').change()``\ は、セレクトボックスが更新された際に呼ばれるメソッドを指定している。 ``getScenarioData()``\ を使うと、該当する番号の指示書ファイルを読み込む。 .. code-block:: js /*** Initialize select box ***/ $.when.apply($, scenario_file).done(function(){ // シナリオファイルが全部取得できたら<option>と<optgroup>追加 $.each(arguments, function(index){ // argumentsに取得したjsonが全部入ってるのでそれぞれ読む var init_info = this[0].info; var $dayGroup = $('#select > optgroup[label='+init_info.day+']'); // <option>を入れる<optgroup> if(!$dayGroup[0]){ $('#select').append($('<optgroup>', {label: init_info.day})); $dayGroup = $('#select > optgroup[label='+init_info.day+']'); } $dayGroup.append($('<option>', { value: index, text: init_info.name + ' - ' + init_info.title })); }); $('select#select').change(function(){ getScenarioData($(this).val()); }); }).fail(function(xhr){console.error(xhr.status+' '+xhr.statusText);}); getScenarioData(0); 指示書データの取得と表示 ~~~~~~~~~~~~~~~~~~~~~~~~ getScenarioData(num) ^^^^^^^^^^^^^^^^^^^^ ``num``\ 番目の\ **指示書ファイルを取得**\ し、JSONとしてパースする。 取得を終えたら、\ ``scenarioInit()``\ を呼び出す。 .. code-block:: js function getScenarioData(num){ console.debug('getScenarioData called. num: '+num); $.when($.getJSON('scenario/'+ num +'.json')).done(function(data){ info = data.info; scenario = data.scenario; scenarioInit(); }); } scenarioInit() ^^^^^^^^^^^^^^ 取得された\ **指示書のデータ**\ (``scenario``)\ **を画面に表示**\ する。 情報が表示される要素にはHTML側で該当するタグを付与してある。 各要素に何番目の指示が表示されるかを管理するため、\ ``scenario{数字}``\ という名称のクラスを\ ``scenario0``\ から順に追加するようになっている。 .. code-block:: js function scenarioInit(){ $('#scenario_prev').html('(前のシーンが表示されます)').addClass('scenario0').attr('onclick', 'goPrev();').prop('disabled', true); viewScript('#scenario_now', 0); $('#scenario_now').addClass('scenario1').prop('disabled', true); viewScript('#scenario_next', 1); $('#scenario_next').addClass('scenario2').attr('onclick', 'goNext();').prop('disabled', true); $('#scenario_skipnext').html('Skip').prop('disabled', true); $('#scenario_skipnext').addClass('scenario2').attr('onclick','skipNext();').prop('disabled',true); $('#scenario_number').html('1/' + scenario.length); $('#progress_bar progress').attr('pass_time', '00:00:00'); } viewScript(id, index) ^^^^^^^^^^^^^^^^^^^^^ ``id``\ のIDを持つ要素に、 ``index``\ 番目の\ **セリフ・タイミング・指示**\ を表示する。 タイミング等の表記を変えたければ、ここを編集すれば良い。 .. code-block:: js function viewScript(id, index){ if($(id).is(':disabled'))$(id).prop('disabled', false); $(id).html(function(){ var res = '' if(!scenario[index].word) res += '開始直後' else { res += '「'+scenario[index].word+'」の'; switch(scenario[index].timing){ case 'pre': res += '前'; break; case 'post': res += '後'; break; default: res += scenario[index].timing; break; } } $.each(scenario[index].projector, function(key){ res += '<br>' + port[key].name + 'を' + (this == 1 ? '点灯' : '消灯'); }); return res; }); } timer_buttonオブジェクト ~~~~~~~~~~~~~~~~~~~~~~~~ ボタン関連 ^^^^^^^^^^ **「開始」「停止」「再開」「リセット」**\ の四つのボタンの動きを管理する。 ``timer_button``\ には四つのメンバ関数が用意されており、それぞれが各ボタンが押された際に呼ばれる。 なお画面ではボタンは二つに見えるが、内部的には四つのボタンの表示/非表示を切り替えて内容が変わるように見せている。 以下にそれぞれの動作内容を簡単に記す(「」内はボタン名称)。 - timer_button.start() - 投影機に0番目(番組開始前)の指示を送信 - **セレクトボックス**\ を無効化・「\ **次へ**\ 」を有効化 - **タイマー**\ を動かす - 「\ **開始**\ 」を「\ **停止**\ 」に、「\ **リセット**\ 」を無効化 - timer_button.stop() - **タイマー**\ を止める \*「\ **停止**\ 」を「\ **再開**\ 」に、「\ **リセット**\ 」を有効化 - timer_button.restart() - **タイマー**\ を動かす - 「\ **再開**\ 」を「\ **停止**\ 」に、「\ **リセット**\ 」を無効化 - timer_button.reset() - **タイマー**\ と\ **指示書表示**\ の初期化 - **セレクトボックス**\ を有効化 - 「\ **再開**\ 」を「\ **開始**\ 」に、「\ **リセット**\ 」を無効化 - セリフ・指示表示エリアから\ ``scenario{数字}``\ のクラスを除去 「停止」ボタンは意図せぬリセットを防ぐ意味合いで設置したため、押しても「次へ」などは有効のままである。 コード例として、\ ``timer_button.start()``\ を掲載しておく。 .. code-block:: js this.start = function(){ sendComm(0, 0); $('#select').prop('disabled', true); $('#scenario_next').prop('disabled', false); timer = setInterval(function(){pass_time++; readTime();}, 1000); $('#timer_start').hide(); $('#timer_stop').show(); $('#timer_reset').prop('disabled', true); }; タイマー関連 ^^^^^^^^^^^^ 画面には、\ **「開始」が押されてからの時間経過**\ を表示するタイマーがある。 特にタイマーが必須だったわけではなく、遊びでつけてしまったものである。 ボタン操作と連動するので、\ ``timer_button``\ のメンバとなっている。 ``pass_time``\ が経過時間で、単位は秒。 ``readTime()``\ を呼び出すと、\ ``pass_time``\ を\ **“時:分:秒”のフォーマット**\ に直した上で表示する。 「開始」または「再開」が押されると\ ``setInterval()``\ によって\ ``readTime()``\ が\ **1秒おきに実行**\ されるようになる。 また、タイマーが表示される部分は\ **プログレスバー**\ (進行状況を示す棒グラフ)であり、``value``\ に0~1の値を入れることができる。 ここでは、公演の標準的な時間を25分として、進行の目安を確認できるようにした(本番で活用されてはいなかったようだが…)。 .. code-block:: js var pass_time = 0; var readTime = function(){ var hour = toDoubleDigits(Math.floor(pass_time / 3600)); var minute = toDoubleDigits(Math.floor((pass_time - 3600*hour) / 60)); var second = toDoubleDigits((pass_time - 3600*hour - 60*minute)); $('#progress_bar progress').attr('pass_time', hour + ':' + minute + ':' + second); var progress = Math.min(pass_time / 1500.0, 1); // 25 minutes $('#progress_bar progress').attr('value', progress); return; }; var toDoubleDigits = function(num){return ('0' + num).slice(-2);}; // sliceで時刻要素の0埋め 指示の送信 ~~~~~~~~~~ ``acrab_main.js``\ に実装がある\ ``getRequest()``\ と\ ``checkStatus()``\ を利用する。 しかし、メイン画面と違いユーザが\ **進む・戻る**\ の動作をするので、それに対応した。 ``scenario``\ オブジェクトから\ ``index``\ 番目の指示を読み取り、\ ``reverse``\ がtrue(=「前へ」ボタンがクリックされている)なら真偽値の部分を反転させる。 後は完成した指示を送信するだけだが、前に書いたように同時点灯の問題が出たため、ここでも\ ``each_slice()``\ した上で送るようにした。 実はこの部分、\ **グループに対応していない**\ 。\ ``acrab_main.js``\ の\ ``button.group(obj)``\ では、「夏の大三角」等のボタンがクリックされると、 1. ``ip``\ からIPアドレスを取得してURLを作成 2. ``group[(三文字コード).value]``\ で\ ``$.each()``\ を回し、南北判定していずれかの\ ``data``\ に追加 3. ``req``\ オブジェクトに南北それぞれのデータを入れ、\ ``getRequest()`` という手順によって「夏の大三角」の星座が光るシステムだが、指示の送信\ ``sendComm()``\ では、 1. ``ip``\ からIPアドレスを取得してURLを作成 2. ``getRequest()`` という流れになってしまっているため、折角指示書でグループを指定しても\ **光らない**\ 。 グループ関連の指示(Wnd等)が来た時には処理を分岐させるなど、何らかの工夫が必要だろう。 なお、画面右に表示されている星座名付きのグリッドは、メイン画面と同じIDにしてあり\ **オンになったものに色が付く**\ 。 同一ページ内でIDが被るのはHTMLの規格上間違いであるが、\ ``Acrab``\ ではどちらかが常に非表示になるため不具合は出ないと判断した。 .. code-block:: js function sendComm(index, reverse){ var data = $.extend(true, {}, scenario[index].projector); if(reverse) $.each(data, function(key){ data[key] = this == 1 ? 0 : 1; }); $.each(ip, function(){ address = this + 'setPort/status.json'; sliced_data = each_slice(data, 5); $.each(sliced_data, function(){ getRequest(address, this).done(function(res){checkStatus(res)}); sleep_ms(100); }); }); } 前へ/次へ/スキップボタン ~~~~~~~~~~~~~~~~~~~~~~~~ 指示の送信は\ ``sendComm()``\ に番号を渡せば済むので、ここでは\ **何番目の指示を次に送るべきかを管理**\ する。 前述の通り、現状を挟んで三つの指示が表示される領域には\ ``scenario{数字}``\ なるクラスが付与されているので、そこから数字を取り出して利用する。 実装については\ ``goNext()``\ のコード例を読んで頂くとして、処理の流れのみ解説しておく。 - クラス名から\ **数字を取得**\ し、\ ``num``\ に格納 - クラスを一旦削除し、数字を増やし(減らし)て再追加 - 次のnumが0以下か最終番号を超えるか - true: 指示が存在しないので\ **ボタンを無効化**\ して\ **メッセージ表示** - false: ``#scenario_now``\ の処理中なら\ **指示を送信**\ (スキップの場合は指示を送信しない) - ``#scenario_number``\ に\ ``#scenario_now``\ の番号を表示 .. code-block:: js function goNext(){ $.each(['scenario_prev', 'scenario_now', 'scenario_next','scenario_skipnext'], function(){ var num = $('#'+this).get(0).className.match(/\d/g).join('') / 1; // 数字だけ取り出して渡す(型変換しないとうまくいかなかった) $('#'+this).removeClass($('#'+this).get(0).className).addClass('scenario' + (num+1)); if(num+1 > scenario.length){ if(this == 'scenario_skipnext') $('#'+this).html('---').prop('disabled', true); else $('#'+this).html('(原稿の最後です)').prop('disabled', true); } else{ if(this == 'scenario_now') sendComm(num, 0); if(this != 'scenario_skipnext') viewScript('#'+this, num); } }); $('#scenario_number').html($('#scenario_now').get(0).className.match(/\d/g).join('') + '/' + scenario.length); } <file_sep># 無料でWindowsを手に入れる - 書いた人: <NAME>(nichiden_27) - 更新日時: 2017/05/30 - 実行に必要な知識・技能: 特になし - 難易度: 1/常識の範囲 - 情報の必須度: 3/必要な場合がある ## 概要 夢のあるタイトルですね。 ん? 買うと1万円もするWindowsが無料のはずない? 普通の人ならばそうでしょう。 しかし、これを読んでいる皆さんは(おそらく)学生のはず。 Microsoftの学生向けプログラム「**Microsoft Imagine**」を使えば、Windowsを無料で使えてしまうんです。 Mac(Linux)ユーザーだけどWindowsも使いたいという方、新しいPCを組んでOSが欲しい方など、ぜひお試しください。 ## 注意点 Microsoft Imagineで配布されているのは通常のWindowsではなく、"Windows Embedded 8.1 Industry Pro"。 これは、Windows 8.1に**組み込み機器向けの機能を追加**したものである。 専用機器向けの機能を持ってはいるが、普通のPC用のWindowsとしても十分使用できる。 Windows Embedded 8.1に限らず、提供されたソフトウェアを**営利目的で使用することは原則禁止**である。 作ったソフトウェアを販売するなどという事はできないので気をつけよう。 また、当然ではあるが発行されるライセンスは**一人につき1ライセンス**までとなる。 複数のコンピュータで使うことはできない。 Macの場合は、仮想マシンに入れるかBoot Campを使うかよく考えておくべきだろう。 ## Microsoft Imagineに登録する ※Microsoft Imagineまたは旧DreamSparkに登録済みの場合、この手順は不要 ### サインイン まずは、Microsoft Imagineの[アカウント作成ページ](https://imagine.microsoft.com/ja-jp/account)にアクセスしよう。 **Microsoft Imagine**は、以前はDreamSparkと呼ばれていたもので、開発ツール・学習リソースなどを教員や学生に無料で提供するプログラムだ。 学生認証の方法はいくつかあるが、**大学ドメインのメールアドレス**(ac.jpなど)を使えれば問題ない(学生証などでも認証可能)。 ページ上部の`Microsoft Imagine プロファイルを作成する`ボタンを押して情報登録を始めよう。 Microsoftアカウントへのログインを求められるので、ID(メールアドレス)とパスワードを入力して次に進む。 ### 情報登録 サインインすると、画像のようなページが表示されるはずだ。 ![情報登録画面](_media/imagine_register.png) 氏名やメールアドレスなど、アカウントに登録済みの情報は既に表示されている。 その他に、 - **Imagine の参加国** - **教育機関レベル**(学部生は"College"、院生は"Graduate") - **学校名**(日本語で構わない) を追加で入力する必要がある。 入力が終わったら、`同意する`を押して情報を登録しよう。 ### 学生認証 情報登録が終わるとアカウントの管理画面を閲覧できるが、まだ登録は終了していない。 そのまま、左メニューの「**学生認証を行ってください**」と書かれたリンクをクリックしよう。 大学のメールアドレスを使える場合は、「学校のメール アドレス」を選択してアドレスを入力しよう。 入力したアドレスに**確認メール**が送信されるので、受け取ってリンクにアクセスすれば認証完了だ。 ![大学アドレスの確認メール](_media/imagine_verify_mail.png) 念のため、[アカウント管理画面](https://imagine.microsoft.com/ja-jp/account/Manage)の「アカウントの状態」が「認証済み。有効期限: \*\*/\*\*/\*\*\*\*」のようになっているかチェックしておこう。 ## Windows Embedded 8.1 Industry Proを入手する ### OSのイメージファイルを入手する Imagineにログインした状態で、[ソフトウェアとサービス カタログ](https://imagine.microsoft.com/ja-jp/Catalog)にアクセスする。 「オペレーティング システム」の区分に"Windows Embedded 8.1 Industry Pro Update"があるはずなので、ダウンロードと書かれたリンクをクリックすればよい。 左のメニューに、`ダウンロード`と`キーを入手`の二つのボタンが表示されるので、言語を選んでから`ダウンロード`をクリックして指示に従おう。 ダウンロードファイルは数GBあるので**通信や電源の安定した環境**で行うこと。 Windows Embedded 8.1のISOファイルが手に入ったら、あとはディスクに焼くなりインストール用USBメモリを作るなり好きにすればよい。 ### ライセンス認証 Windows Embedded 8.1を無事起動したら、忘れずにライセンス認証を済ませよう。 認証用の**プロダクトキー**(25文字)は、[ダウンロード画面](https://imagine.microsoft.com/ja-jp/Catalog/Product/82)の`キーを入手`ボタンや、[アカウント管理画面](https://imagine.microsoft.com/ja-jp/account/Manage)下部の「マイ ダウンロード」で確認できる。 「設定」アプリの最上部に「Windowsのライセンス認証」なるメニューがあるので、キーを入力して承認されれば認証完了だ。 ![Windows Embedded 8.1のライセンス認証](_media/imagine_win_licence.png) <file_sep># 部品の買い方 - 書いた人: <NAME>(nichiden_27) - 更新日時: 2017/02/17 - 実行に必要な知識・技能: 秋葉原の土地勘 - 難易度: 2/少しやれば可能 - 情報の必須度: 3/必要な場合がある ## 概要 回路を設計したら、部品を買いましょう。 日電は重要なので予算はある程度優遇されますが、無限ではないのでできれば安く手に入れたいところです。 通販は便利ですが、回数が重なると送料が無視できません。 せっかく東京にいることだし、(2年秋に本郷に通う人は特に)秋葉原に通うことをオススメします。 ## リアル店舗で買う ### 全体の注意 - ほぼ大体10割くらい秋葉です - 自分の経験と勘に絶対の自信がある人以外は、買うものの**型番を**メモすべし + 名称が似ていても仕様が違ったりするので、型番で!!! - 予備を絶対に買うこと + 壊れやすい部品(ICとか)は特に注意 ### 秋葉原電気街へのアクセス - 駒場から + 山手線に乗り、秋葉原駅で降りる + 銀座線に乗り、末広町駅で降りる - 本郷から + 徒歩で * キャンパス内の位置にもよるが、30分足らずで移動できる * 湯島や外神田を散策できるので、余裕のある日は是非 + 電車で * 根津駅から千代田線で新御茶ノ水駅まで移動 * 御茶ノ水からは徒歩 * 電気街は秋葉原駅より西側なので、思いのほか早く着く + バスで * 正門前や赤門前から`茶51`系統で万世橋まで * 本郷二食前から`学07`系統で御茶ノ水駅前まで * 徒歩が少なくて楽 ### [秋月電子通商](http://akizukidenshi.com/) 迷ったらここ。大抵のものは揃う上価格も安い。 ただ店内が狭く、平日昼間とか以外はすごく混雑するので注意。 あと初見だと棚の配置が分からない。店内に地図があるはずなのでまずはゲットしよう。 [ネット通販](http://akizukidenshi.com/)もあるので、店員に質問するときは通販のページを見せながらだとスムーズかと。 とにかく部品の種類が凄いので見つからないと思ったら臆せず聞くべし。 ここの1000円のお楽しみ袋は伝説。初心者は勉強のために一回は買ったほうがいいだろう。 ### [千石電商](http://www.sengoku.co.jp/) 第二選択肢。秋月より広く三号店まであるものの、値段が全体的に高い。 秋月では揃わないコネクタや工具、切り売りの線材などはここで入手しよう。 会計は各フロアで行わないといけないので注意。 ### [西川電子](http://nishikawa.or.tv/) 総武線の高架近くにある店。「ネジ」と「コネクタ」に強いとされる。 特にネジは一通り揃っているのは秋葉でもここくらいで、ハ◯ズなんかよりずっと安価で手に入るので近くを訪れた際はぜひ寄ろう。 また、二階のヒロセや日圧のコネクタもたいへん充実している。 鈴商亡き今、秋葉の部品屋の「人情」みたいなものを感じられる店の一つかも。 秋月や千石からすると閑散としていて心配だからみんな買いに行こうな。 ### [akibaLEDピカリ館](http://www.akiba-led.jp/) 秋月、千石と同じ並びにあるLED専門店(!)。夕方に通ると大変まぶしい。 秋月がパワーLEDの店頭在庫を切らしていた時に助けてもらった。 値段は秋月と同じくらいだったと思う。とにかくLED関連の品揃えが凄いので時間が余ったら寄ると面白いかも。 なお、これを運営している(株)ピースコーポレーションは[LEDパラダイス](http://www.led-paradise.com/)というLED通販サイトも手がけている。 ### [マルツ秋葉原本店/2号店](http://www.marutsu.co.jp/) 言わずと知れた通販大手だが店舗も全国に点在している。 秋葉には本店と2号店があり、後者は秋月のはす向かいのブロックにあるので行きやすい。 近くに秋月千石の二強がある以上、ここで買い物する機会は多くないが、実は夜に真価を発揮する。 秋葉の部品屋は19時くらいまでに軒並み閉まってしまうのに、ここは20:00まで開いている。 今すぐに欲しい部品がある場合は駆けこもう。 また2号店の入り口近くには怪しい電源装置が特価で置いてあったりする。 ### [鈴商](http://suzushoweb.shop-pro.jp/) 今はないお店。千石〜秋月〜マルツの並びにあった老舗だが、[2015年11月に閉店](http://rocketnews24.com/2015/11/27/671666/)。跡地には秋葉原神社という謎の施設が入った。 ### [ラジオデパート](http://www.tokyoradiodepart.co.jp/) 総武線の高架沿い、西川電子と同じ並びにある。 行ったことがないので不明だが、多数の部品屋が入居しており、珍しい部品があるかもしれない。 ## ネットで買う ### 全体の注意 - まともなサイトは仕様をまとめたデータシートをPDFなどで配布している - 必ず確認してから買おう! - データシートなしの部品には手を出さないのが無難 - 送料・納期を確認すべし - 領収書は、納品書+支払いの証拠(振込の明細書など)とするのが基本 - 電子部品は店の選択肢が少ないのでこうするしかないようです ### [秋月電子通商](http://akizukidenshi.com/) 送料一律500円。お店に行く時にもここで予習しておくと便利。 そのうち本店での商品位置情報が分かるアプリがリリースされるらしい。 ### [千石電商](http://www.sengoku.co.jp/) これも予習に使える。送料432円。 ### [マルツ](http://www.marutsu.co.jp/) 大手だけどここで買ったことがないのであまり分からず。 法人/官公庁向けの販売もしているのでサイト構成はちょっと敷居が高い感じ。 [LEDの使い方](http://www.marutsu.co.jp/pc/static/large_order/led)をはじめ、初心者~脱初心者向けの情報を提供していたりする。 回路を組んでいて迷ったら探してみよう。 ケース加工やプリント基板加工もしており、しっかりとしたものを作りたい場合はお世話になるかも? 大学生協との提携も盛んで、学科や研究室で電子回路を扱う時に関わることになるのかもしれない。 ### [スイッチサイエンス](https://www.switch-science.com/) 10000円以上で送料無料。海外向け製品など秋月で扱ってない商品もあるようだ。 電子工作やIoTの[イベント](https://connpass.com/search/?q=%E3%82%B9%E3%82%A4%E3%83%83%E3%83%81%E3%82%B5%E3%82%A4%E3%82%A8%E3%83%B3%E3%82%B9)を運営していたり、ブログに解説記事を載せたりと活動は活発。 ### [オリエンタルモータ](https://www.orientalmotor.co.jp/) モータ専門の企業。日周・緯度変のモータとモータドライバは代々ここで買っている。 買い替える場合は型番を見て同じものを買えばいいだろう。 ドライバはかなり高額だが、部室に予備があるしそもそも既製品なのであんまり壊れない。 ### [maxon](http://www.maxonjapan.co.jp/) 同じくモータ製造大手。データシートが詳細で、モータの勉強ができる。 [マクソンアカデミー](http://academy.maxonjapan.co.jp/)という解説記事群もある。 ### [ミスミ](http://jp.misumi-ec.com/) 金属系の部品なら買えないものはない、神のような存在。 しかも送料無料(ネジ一本でも)。ただし法人格のアカウントがないと買えない。 日電で本格的に機械部品を扱うことは稀なので、無理に使うことはないかもしれない。 <file_sep>備品管理 ======== - 書いた人: <NAME>(nichiden_27) - 更新: <NAME>(nichiden_28) - 更新日時: 2018/08/26 - 実行に必要な知識・技能: 特になし - タスクの重さ: 1/数時間で可能 - タスクの必須度: 2/たまにやるべき 概要 ---- 日電は、日電自体の備品の他に電子部品や工具なども管理することになっています。 各投影機が備品を有効活用できるよう、日頃から備品の状態に気を配りましょう。 日電カゴ -------- .. figure:: _media/basket.jpg :alt: 日電カゴの外観 日電カゴの外観 部室の机がある側の区画に入って左側の棚の一番下に、黒色で持ち手が黄色のカゴと蓋つきの半透明のケースがある。 この二つが日電のカゴとなっている。 また、本番で入りきらなかったものはダンボールに入れてある。 なお、画像は27代のときのものなので2つともカゴだが、28代で片方はケースに買い替えた。 内容は代によって変化するものの、日周緯度変や無線送受信機、主投影機の配線など重要物品が入っている。 このカゴは基本的に他投影機の人は触らないので、\ **壊れたり無くなったりすると困るもの**\ を入れておこう。 延長コード ---------- 部室の機材がある側の棚に延長コードのたくさん入ったケースと少し古そうな延長コードの入ったカゴ(ダンボールになっているかもしれない)がある。 これも日電の備品だ。 ケースに入っている延長コードは基本的に\ **本番ですべて使う**\ ので、本数などを確認したらあまり使わないほうがいいだろう(駒場祭の片付けで使わないものも混ざった可能性があるので要確認)。 他の投影機にも延長コードを使いたいときはカゴの方から持っていくように伝えておこう。 なお、延長コードのたくさん入ったケースは想像以上に重いので持ち運びの際は注意しよう。 部室の部品及び工具 ------------------ 日電のカゴがあるのと同じ区画の棚には、電子部品や工具などが収納されている。 これらは基本的に日電の管轄で、勝手に使わないようになどと引き継ぎに書いてある投影機もある。 ただし、部室にある部品は基本的に過去に購入して余らせているものなので、各投影機で再利用してもらう方がむしろ有益である。 そのため、27代で部品の一斉調査を行い、機長向けに公開した。 また、部品・工具の使用に関しては以下のガイドラインに従えば自由に可能とした。 - 使用にあたって特に許可を得る必要はありません(何かあれば日電へ)。 - 学生会館の外には持ち出さず、使い終わったらすぐに部室に返してください。 - 箱やカゴごと持ち出されると他の投影機が困りますので、工具や部品はなるべく 必要な数だけ持ち出すようにお願いします。 - 部品については当該棚の一段目~三段目は余った在庫なので使用できますが、 それ以外の他投影機の箱やカゴのものは勝手に使わないでください。 - 多くの投影機が電気関係の作業をするため、工具等が足りなくなることがあります。主投・補助投とも必ずないと困る工具は各自持ち込んでください。 28代ではここまで丁寧な告知はしておらず、この棚にあるものは自由に使って良いということだけ伝えた。 これで特にトラブルは起きなかったが、使う頻度の高い投影機の機長には個別に何があるか等も伝えた方が良いかもしれない。 部品の在庫調査は毎年行う必要は全くないが、各ケースの内容を軽く見ておくと突然部品が必要になっても対処できるようになるだろう。 箱の大部分にはラベルが付してあり、種類別にある程度分類されている。 .. figure:: _media/partsbox-example.jpg :alt: 部品ボックスの内容例 部品ボックスの内容例 27日電がパーツケースの中身を調査した際の資料を以下に示す。 ()内以外の部分はケースのラベルと対応している。 1. ヒューズ 2. トランジスタ・IC・マイコン(トライアック) 3. ピンヘッダ・ソケット・コネクタ 4. 力強い抵抗たちなど(大電力抵抗) 5. ミノ虫クリップ(ジャンパ線) 6. DCジャック・プラグ(トライアック) 7. スイッチ(トグル・プッシュ・タクト・マイクロ・ロータリー) 8. コンデンサ(集合抵抗・インダクタ) 9. あわれなレジスタンスたち(袋入り抵抗) 10. LED 11. 線材 12. 線材2 13. 調光器(トライアック万能調光器キット) 14. リレー 15. 放射板(ヒートシンク) 16. 電池ボックス 17. ボリウム(ツマミ) 18. ACソケット・その他コネクタ(大きめのもの中心) 19. ケース・基板・ブレッドボード 20. その他電球・モータなど 21. コネクタ1, 2 22. ネジ1, 2, 3 ただし、28代で整理をしたため内容が少し変わっているはずである。 また、作業が進むにつれて本来あるべき場所と違う場所にある部品もあるはずだ。 何があるかの把握にもなるので軽く整理するといいかもしれない。 工具に関しては十分な量が用意してあるが、特にハンダ付け関連のものは消耗しやすいので注意しておこう。 コテ台が足りなかったり、コテ先やスポンジが劣化したりしていた場合は買い出しの際に補充すると良い。 <file_sep>Visual Studioをはじめよう ========================= - 書いた人: <NAME>(nichiden_27) - 更新日時: 2017/05/29 - 実行に必要な知識・技能: 特になし - 難易度: 1/常識の範囲 - 情報の必須度: 3/必要な場合がある 概要 ---- Visual Studio(以下VS)は、Microsoft製の統合開発環境(IDE)です。 様々な開発案件に対応でき、特にWindows向けのGUI開発を行いたい場合非常に有効です。 日電においては、日周緯度変のPC制御ソフトや旧星座絵制御ソフトがWindowsのデスクトップアプリケーションです。 今後もWindows向けに開発を行うなら、ぜひVSをインストールしておきましょう。 価格 ---- **無料。** 2014年以前にもVisual Studio Expressという無償版が存在したが、有料版より機能が制限されていた。 尤も、学生であればDreamSpark(現: Microsoft Imagine)というプログラムで有料のProfessional版が無償で入手できたという (`【学生は無償】 最新のVisual Studio 2013 を早くも DreamSpark で提供開始! <https://blogs.msdn.microsoft.com/microsoft_japan_academic/2013/10/30/visual-studio-2013-dreamspark/>`__)。 2014年11月、\ **Visual Studio Community**\ が旧Express版を置き換える形で発表された。 個人や小規模開発者という条件付きだが、Professional相当の機能を無償で利用できるようになった。 学生団体での開発ならば、VS Communityがあれば十分であり、VSが実質的に無料で使えると言っていいだろう。 インストール ------------ ※\ **Windows版を想定** `VS Communityのページ <https://www.visualstudio.com/ja/vs/community/>`__\ にアクセスし、インストーラを入手して起動する。 最新のVS Community 2017は、\ **モジュール式インストーラ**\ を採用しており、インストール前に導入する機能を選択するようになっている。 自分に必要な機能だけの構成にすることで、肥大化して時間がかかっていたVSの初回インストールが短時間で可能になったのだ。 .. figure:: _media/vs-install-1.png :alt: インストーラの機能選択画面 インストーラの機能選択画面 「\ **ワークロード**\ 」タブで、開発を行いたい言語や環境を選択する。 例えばWindowsのデスクトップアプリなら、最低限「.NETデスクトップ開発」を選んでおけば事足りるだろう。 「\ **個別のコンポーネント**\ 」タブではさらに細かく、インストールする機能を個別に選べる。 興味を引くものがあればチェックを入れておこう。 インストール後からでも構成を変更できるので、ここで深く悩む必要はない。 右下に表示される「インストール サイズ」を確認し、空き容量と通信回線に問題がなければ\ ``インストール``\ をクリックして実行しよう。 .. figure:: _media/vs-install-2.png :alt: インストール中の画面 インストール中の画面 インストールが終了すると、Microsoftアカウントへのサインインを促される。 サインインしなければ30日後に使えなくなるので、もしアカウントを持っていないなら作ってしまおう。 サインインすると、ようやくVSが起動し、以下のような画面が表示される(筆者はテーマ色を変更しているため、標準の画面色と異なる場合あり)。 .. figure:: _media/vs-install-3.png :alt: VS初期画面 VS初期画面 <file_sep># 配線(かごしい内) - 書いた人: <NAME>(nichiden_27) - 更新: <NAME>(nichiden_28) - 更新日時: 2018/08/26 - 実行に必要な知識・技能: 端子のはんだ付けや圧着 - タスクの重さ: 2/数日かかる - タスクの必須度: 4/毎年やるべき ## 概要 かごしいは、主投影機群を格納し回転させる機構です。 **組み立て・管理**はかごしいチームの仕事である一方、**内部配線**は複雑で手間がかかるので日電も手伝うことになります。 配線に関する引き継ぎはかごしいにもありますが、日電員が全体を把握できるようまとめて解説します。 ## 用語解説 かごしいの扱う器具には様々な愛称が付いている。実物を見るのが早いが、それぞれの役割について簡単に解説する。 ### かご・しいたけ 主投影機を搭載し、回転する台座。 そのうち半球状になっている部分をその形にちなみ**しいたけ**と呼んでいる。 ![かご・しいたけの外観](_media/kago-shiitake.jpg) アルミ合金製だが、無数の板材が組み合わされておりかなり重い。 日電のものを取り付ける際はこの板に括り付けることになるが、**結束バンド**が大変便利である。 ### ごきぶり かごしいたけの土台となる部分。 名称はその黒い塗装から。 塗装は所々剥げており、**しいたけと電気的に接続している**。 そのため、主投影機群の事実上のアースとなっている(アースとして十分でないという指摘がある)。 ### 緯度変 緯度変のモータとギアボックスが一体となったもの。 かごしいがごきぶりに設置してくれる。 日周にも言えるが、モータのケーブルが頼りないので、**ごきぶりのどこかにテープで留めておく**こと。 ### 日周 日周モータとギアボックス。 同時にかごしいたけを支える回転台座でもあり、かなり大きく重い。 ### パンタグラフ 日周が回転していくと、電源ケーブルが巻きついて回転を妨げてしまう。 これを防ぐために、パンタグラフという円盤状の部品を日周とかごしいたけの間に挟む。 構造としてはボールベアリングだが、軸受けとしてではなく回転するボールを通して送電するために使っている。 外輪が地面に対して静止し、内輪が日周に合わせて回転する。 通電中に金属部分に触れると**感電することがある**ので要注意だ。 パンタグラフには接続用のケーブルが外輪・内輪に一本ずつ付いている。 パンタグラフ側は**丸型の圧着端子**をねじで軽く(回転するように)留めている。 圧着端子やねじは外れることがあるので気をつけよう。 圧着端子は部室のパーツケースに相当数のストックがあり、圧着工具も数本保管してあるので、部室が使える状況なら修理は容易だ(**本番では体育館に持ち込んでおく**と安心)。 なお、配線のうちの片方が本番後に断線したので、交換する必要がある。 ### 頸動脈 **ケーブルを南北間で通す**ため、日周に開いている穴。 ここを通る線は少ないほどよい。 過去には本番直前にケーブルを増やした結果、それが絡まって断線したこともある。 ## 地上からパンタグラフへ パンタグラフは、ベアリング全体が通電するため**一つの大きな端子**として使われている。 家庭用の交流100Vをしいたけ内部に送るには、当然端子が二つ必要になる。 南北それぞれのパンタグラフを巨大なコンセントのように使っていると理解してほしい。 ### 二股ソケット 配線を南北に分離するため、**二股に分かれた電源ソケット(オス→メスx2)**がかごしいの備品に用意されている。 ケーブルはそれぞれ片側一本しかないので、正しい向きに刺さなければ通電しないことに注意。 わかりやすいようにテープが貼ってある。 ### 外輪ケーブル 延長コードに二股ソケットを繋げたら、もう一方をパンタグラフの**外輪から伸びるケーブル**と接続する。 ![パンタグラフの外観](_media/pantograph.jpg) 写真にあるように、外輪のケーブルには**黒い角形の端子(メス)**がついており、二股ソケット側に差し込めば繋がる。 AC電源のソケットと違い、切り欠きによって向きが分かるため便利である。 ただ、この端子の名称が分からなくなっており、現状壊れた際の買い替えができない状況にある。 通るケーブルは一本なので、**DCジャック**などに交換しても機能は果たせるだろう。 (AC電源ソケットにしてしまうと、内輪と外輪の区別が付きづらくなるのでオススメしない) ## パンタグラフから頸動脈へ パンタグラフ内輪のケーブルには**AC電源ソケット(メス)**が繋がっている。 地上側とは逆に、南北二本の内輪ケーブルを二股ソケット(オスx2→メス)で一つに束ねよう。 ケーブルを合流させるには、南北どちらかの内輪ケーブルを反対側に持っていく必要がある。 これには、内輪ケーブルを**頸動脈**に通せばよい。 これで、しいたけと一緒に動くAC100Vのコンセントが完成する。 あとは複数口のある延長コードをつなぐだけである。 南北両方で電源が取れるようにするため、一方の**延長コードを頸動脈に通す**。 太い延長コードは頸動脈を通りづらいので、必要に応じ緯度変を回しながら作業すると楽だ。 ## 主投影機電源 投影機の電源は直流なので、勿論コンセントにそのまま刺すわけではない。 また、投影機が一つならばACアダプタがあれば良いが、主投影機は数十個ある物が多い。 そこで、**【電源→各投影機の配電回路→(ケーブル)→各投影機】**という順番で接続することになる(数が少ないぎんとうは例外)。 ### ACアダプタ 直流を得るにはACアダプタを使うのが最も簡単である。 ただし、主投影機の**消費電力をまかなえるだけの個数を用意する**こと。 ACアダプタの定格を超えて使用すると、寿命を縮めてしまうことがあるので気をつけたい。 26主投時点では、しいたけ内に5V4A(2個)/12V5A(2個)の4つのACアダプタを、結束バンドで固定して給電していた。 28代では電源を12V150WのACアダプター1つにした。 これはPISCIUMやまたたき回路内でレギュレータを用いたため可能となった。 これによりしいたけ内の配線が簡単になり、ATX電源に比べてかなり軽くなったのでかごしい本体への負担も減った。 また、ATX電源より安定して電源を供給できるようになった。 ### ATX電源(参考) 27主投では、ケーブルの多くなるACアダプタを廃止してPC用の**ATX電源**を使用した。 しかし、ちょっとした電流サージで停止してしまうというATX電源の仕様により活用は困難だった。 また、当初案ではしいたけに電源装置をねじ止めする予定だったものの、フレームのサイズが合わず断念した。 ATX電源は使い方にかなり難があるので、配電管理にコストを割けないのであればACアダプタを使う方が楽かもしれない。 そのため、28代では12VACアダプタに統一して三端子レギュレータで電圧を下げるという方針をとった。 なんにせよ、 - 配線の作業がしやすいこと - 本番で安定して電力供給できること を第一に考えて検討すべきだ。 ## 投影機回路BOX しいたけ上でACアダプタと各投影機の間を繋ぐ回路が入った箱(実際はタッパー)。 **こうとうBOX・いっとうBOX・無線BOX**(Piscium)が存在する。 各投影機の備品を入れる箱も「\*\*ボックス」と称するが別物である。 正直ややこしいので呼び方を変えるべきかもしれない。 ### こうとうBOX 恒星投影機16個に電力を供給する回路。 27代まではDCジャックが18個繋がっているだけの簡単なものであったが、28代で[突入電流防止用のNTCサーミスタ](http://akizukidenshi.com/catalog/g/gP-12543/)を入力端子のところに直列で2つずつ取り付けた。 こうとうは一個あたり3Wを消費するので、過大な電流が流れないよう回路を半分の9個ずつに分けてある。 このNTCサーミスタは温度が低い(室温程度)の時は抵抗が1Ω程度だが、電流が流れて温度が高くなると抵抗がほぼ0になる。 そのため突入電流が防げるという仕組みだ。 27でこうとうのONOFFをやろうとしたところおそらく突入電流のせいでできなかったとのことだったので取り付けた。 もしかしたらATX電源をACアダプターに変えたことで突入電流に耐えられるようになっていたかもしれないが、サーミスタはつけたままでも問題ないだろう。 ![こうとうBOX外観](_media/koutou-box-appearance.jpg) 壊れる類のものではないので作り変えは例年行われないものの、27代では大電流を流せるよう基板の裏全体に銅箔を貼り付けた。28代ではNTCサーミスタをとりつけた。 取り付ける部分は、しいたけの下の四角い部分である(他の回路BOXも同様)。 養生テープなどでは剥がれるリスクがあるので、**結束バンドでフレームに固定する**とよさそうだ。 ### いっとうBOX 中身は[またたき回路](twinkle.html)。使い方や仕組みはあちらの記事を参照いただきたい。 主投影機配線の要素の一つとして考えるときは、こちらの呼び方を使うことが多い。 ![またたき回路の外観](_media/twinkle-appearance.jpg) ### 星座絵BOX [Piscium](wireless/piscium.html)のこと。 26代までは無線は星座絵だけだったので、この呼び名が残る。 ## 投影機ケーブル **回路BOXと投影機を繋ぐケーブル**は基本的に日電の管理下にある。 例外として、星座絵投影機は慣例的に本体とケーブルが一体なので製作は任せよう。 ただし、28主投において、正座絵のケーブルの部分でショートしてPisciumの一部が壊れるということが起きた(詳細は[Pisciumのページ](wireless/piscium.html))。 ケーブルの制作は正座絵の負担にもなっているので、他の投影機と同様に正座絵も本体にDCジャックをつけるようにして、ケーブルは日電で制作した方が良いかもしれない。 ケーブルを日電で管理すればショートも防げるだろう。 また、現在使われている投影機ケーブルの太さは0.3sqである。 太い線を使うとDCジャック内でショートしやすくなってしまうので注意してほしい。 なお、正座絵のケーブルがショートした原因も太いケーブルを使ったことである可能性が高いので、日電が作るようにしなくても0.3sqの線(正座絵で持っているものではなく部室にある赤黒の線)を使うように指定すればいいかもしれない。 ### 二色ケーブル 毎年使うものであり、必要本数は大抵部室にある。 とはいえ、もし足りなくなれば早めに増産しておこう。 適度な長さの二色ケーブルに、DCプラグを2個つけるだけで良い。 ![投影機ケーブルの一部](_media/syutou-cable.jpg) ### 二分岐ケーブル ぎんとうは片方の半球に二つしかないため、BOXの代わりに**二つに分岐するケーブル**を挟む。 二分岐は自分で作ると耐久性に難があるので、既製品を使っている。 二つのぎんとうは距離をかなり離して設置されるので、分岐の後さらに**延長ケーブル**を挟まなくてはならない。 他のケーブルと違って一方がDCプラグ、他方がDCジャックとなるので混同しないように。 ### 気をつけたいこと - 投影機の区別をつける * しいたけに取り付けると線が絡み合い、元を辿るのは困難を極める * **色付きのテープを巻く**など、どれがどの投影機かわかるようにする - 長さを確保する * こうとうやいっとうのケーブルは長くないと上まで届かない * 短くて届かないと言われたらすぐ**長いものと交換できる**ようにしておく - 導通チェックをする * 実際使う前に**断線・ショート・+-逆転**がないか確認する * 一本のショートでこうとうが半分つかなかったこともあり、甘く見てはいけない * テスターでチェックするのは大変なので、23代では下図のような回路を使っていた + 正常でなければ二つのLEDが同時に点灯しない仕組み + 非常に簡単なので、一つ作っておいてもいいかも(もしくはまだ部室にある??) ![23代の簡易ケーブルチェッカ](_media/cablechecker-23.png) ## しいたけ内部主投影機配線の全容 最後に、しいたけ内配線の様子をツリー上に示す。 記入してはいないが、こうとうBOXやいっとうBOXにももちろんそれぞれの投影機がつながっている。 Pisciumは全主投影機の電源を制御するので、27代から配線の構造がかなり変化した。 ``` [26まで] 電源 ├── ACアダプタ12V-1 │   └── こうとうBOX-1 ├── ACアダプタ12V-2 │   └── こうとうBOX-2 ├── ACアダプタ5V-1 │   ├── いっとうBOX │   └── 二股DCケーブル │      └── (各ぎんとう) └── ACアダプタ5V-2    └── 星座絵BOX [27] 電源 ├── ATX電源装置+Piscium │   ├── (各星座絵) │   ├── 二股DCケーブル │   │   └── (各ぎんとう) │   ├── いっとうBOX │   ├── こうとうBOX1 │   └── こうとうBOX2 └── USB用ACアダプタ    └── Piscium(無線モジュール) [28] 電源 └── ACアダプタ12V+Piscium    ├── (各星座絵)    ├── 二股DCケーブル    │   └── (各ぎんとう)    ├── いっとうBOX    ├── こうとうBOX1    └── こうとうBOX2 ``` <file_sep>部品の買い方 ============ - 書いた人: <NAME>(nichiden_27) - 更新日時: 2017/02/17 - 実行に必要な知識・技能: 秋葉原の土地勘 - 難易度: 2/少しやれば可能 - 情報の必須度: 3/必要な場合がある 概要 ---- 回路を設計したら、部品を買いましょう。 日電は重要なので予算はある程度優遇されますが、無限ではないのでできれば安く手に入れたいところです。 通販は便利ですが、回数が重なると送料が無視できません。 せっかく東京にいることだし、(2年秋に本郷に通う人は特に)秋葉原に通うことをオススメします。 リアル店舗で買う ---------------- 全体の注意 ~~~~~~~~~~ - ほぼ大体10割くらい秋葉です - 自分の経験と勘に絶対の自信がある人以外は、買うものの\ **型番を**\ メモすべし - 名称が似ていても仕様が違ったりするので、型番で!!! - 予備を絶対に買うこと - 壊れやすい部品(ICとか)は特に注意 秋葉原電気街へのアクセス ~~~~~~~~~~~~~~~~~~~~~~~~ - 駒場から - 山手線に乗り、秋葉原駅で降りる - 銀座線に乗り、末広町駅で降りる - 本郷から - 徒歩で - キャンパス内の位置にもよるが、30分足らずで移動できる - 湯島や外神田を散策できるので、余裕のある日は是非 - 電車で - 根津駅から千代田線で新御茶ノ水駅まで移動 - 御茶ノ水からは徒歩 - 電気街は秋葉原駅より西側なので、思いのほか早く着く - バスで - 正門前や赤門前から\ ``茶51``\ 系統で万世橋まで - 本郷二食前から\ ``学07``\ 系統で御茶ノ水駅前まで - 徒歩が少なくて楽 `秋月電子通商 <http://akizukidenshi.com/>`__ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 迷ったらここ。大抵のものは揃う上価格も安い。 ただ店内が狭く、平日昼間とか以外はすごく混雑するので注意。 あと初見だと棚の配置が分からない。店内に地図があるはずなのでまずはゲットしよう。 `ネット通販 <http://akizukidenshi.com/>`__\ もあるので、店員に質問するときは通販のページを見せながらだとスムーズかと。 とにかく部品の種類が凄いので見つからないと思ったら臆せず聞くべし。 ここの1000円のお楽しみ袋は伝説。初心者は勉強のために一回は買ったほうがいいだろう。 `千石電商 <http://www.sengoku.co.jp/>`__ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 第二選択肢。秋月より広く三号店まであるものの、値段が全体的に高い。 秋月では揃わないコネクタや工具、切り売りの線材などはここで入手しよう。 会計は各フロアで行わないといけないので注意。 `西川電子 <http://nishikawa.or.tv/>`__ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 総武線の高架近くにある店。「ネジ」と「コネクタ」に強いとされる。 特にネジは一通り揃っているのは秋葉でもここくらいで、ハ◯ズなんかよりずっと安価で手に入るので近くを訪れた際はぜひ寄ろう。 また、二階のヒロセや日圧のコネクタもたいへん充実している。 鈴商亡き今、秋葉の部品屋の「人情」みたいなものを感じられる店の一つかも。 秋月や千石からすると閑散としていて心配だからみんな買いに行こうな。 `akibaLEDピカリ館 <http://www.akiba-led.jp/>`__ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 秋月、千石と同じ並びにあるLED専門店(!)。夕方に通ると大変まぶしい。 秋月がパワーLEDの店頭在庫を切らしていた時に助けてもらった。 値段は秋月と同じくらいだったと思う。とにかくLED関連の品揃えが凄いので時間が余ったら寄ると面白いかも。 なお、これを運営している(株)ピースコーポレーションは\ `LEDパラダイス <http://www.led-paradise.com/>`__\ というLED通販サイトも手がけている。 `マルツ秋葉原本店/2号店 <http://www.marutsu.co.jp/>`__ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 言わずと知れた通販大手だが店舗も全国に点在している。 秋葉には本店と2号店があり、後者は秋月のはす向かいのブロックにあるので行きやすい。 近くに秋月千石の二強がある以上、ここで買い物する機会は多くないが、実は夜に真価を発揮する。 秋葉の部品屋は19時くらいまでに軒並み閉まってしまうのに、ここは20:00まで開いている。 今すぐに欲しい部品がある場合は駆けこもう。 また2号店の入り口近くには怪しい電源装置が特価で置いてあったりする。 `鈴商 <http://suzushoweb.shop-pro.jp/>`__ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 今はないお店。千石〜秋月〜マルツの並びにあった老舗だが、\ `2015年11月に閉店 <http://rocketnews24.com/2015/11/27/671666/>`__\ 。跡地には秋葉原神社という謎の施設が入った。 `ラジオデパート <http://www.tokyoradiodepart.co.jp/>`__ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 総武線の高架沿い、西川電子と同じ並びにある。 行ったことがないので不明だが、多数の部品屋が入居しており、珍しい部品があるかもしれない。 ネットで買う ------------ .. _全体の注意-1: 全体の注意 ~~~~~~~~~~ - まともなサイトは仕様をまとめたデータシートをPDFなどで配布している - 必ず確認してから買おう! - データシートなしの部品には手を出さないのが無難 - 送料・納期を確認すべし - 領収書は、納品書+支払いの証拠(振込の明細書など)とするのが基本 - 電子部品は店の選択肢が少ないのでこうするしかないようです .. _秋月電子通商-1: `秋月電子通商 <http://akizukidenshi.com/>`__ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 送料一律500円。お店に行く時にもここで予習しておくと便利。 そのうち本店での商品位置情報が分かるアプリがリリースされるらしい。 .. _千石電商-1: `千石電商 <http://www.sengoku.co.jp/>`__ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ これも予習に使える。送料432円。 `マルツ <http://www.marutsu.co.jp/>`__ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 大手だけどここで買ったことがないのであまり分からず。 法人/官公庁向けの販売もしているのでサイト構成はちょっと敷居が高い感じ。 `LEDの使い方 <http://www.marutsu.co.jp/pc/static/large_order/led>`__\ をはじめ、初心者~脱初心者向けの情報を提供していたりする。 回路を組んでいて迷ったら探してみよう。 ケース加工やプリント基板加工もしており、しっかりとしたものを作りたい場合はお世話になるかも? 大学生協との提携も盛んで、学科や研究室で電子回路を扱う時に関わることになるのかもしれない。 `スイッチサイエンス <https://www.switch-science.com/>`__ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 10000円以上で送料無料。海外向け製品など秋月で扱ってない商品もあるようだ。 電子工作やIoTの\ `イベント <https://connpass.com/search/?q=%E3%82%B9%E3%82%A4%E3%83%83%E3%83%81%E3%82%B5%E3%82%A4%E3%82%A8%E3%83%B3%E3%82%B9>`__\ を運営していたり、ブログに解説記事を載せたりと活動は活発。 `オリエンタルモータ <https://www.orientalmotor.co.jp/>`__ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ モータ専門の企業。日周・緯度変のモータとモータドライバは代々ここで買っている。 買い替える場合は型番を見て同じものを買えばいいだろう。 ドライバはかなり高額だが、部室に予備があるしそもそも既製品なのであんまり壊れない。 `maxon <http://www.maxonjapan.co.jp/>`__ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 同じくモータ製造大手。データシートが詳細で、モータの勉強ができる。 `マクソンアカデミー <http://academy.maxonjapan.co.jp/>`__\ という解説記事群もある。 `ミスミ <http://jp.misumi-ec.com/>`__ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 金属系の部品なら買えないものはない、神のような存在。 しかも送料無料(ネジ一本でも)。ただし法人格のアカウントがないと買えない。 日電で本格的に機械部品を扱うことは稀なので、無理に使うことはないかもしれない。 <file_sep>無料でWindowsを手に入れる ========================= - 書いた人: <NAME>(nichiden_27) - 更新日時: 2017/05/30 - 実行に必要な知識・技能: 特になし - 難易度: 1/常識の範囲 - 情報の必須度: 3/必要な場合がある 概要 ---- 夢のあるタイトルですね。 ん? 買うと1万円もするWindowsが無料のはずない? 普通の人ならばそうでしょう。 しかし、これを読んでいる皆さんは(おそらく)学生のはず。 Microsoftの学生向けプログラム「\ **Microsoft Imagine**\ 」を使えば、Windowsを無料で使えてしまうんです。 Mac(Linux)ユーザーだけどWindowsも使いたいという方、新しいPCを組んでOSが欲しい方など、ぜひお試しください。 注意点 ------ Microsoft Imagineで配布されているのは通常のWindowsではなく、“Windows Embedded 8.1 Industry Pro”。 これは、Windows 8.1に\ **組み込み機器向けの機能を追加**\ したものである。 専用機器向けの機能を持ってはいるが、普通のPC用のWindowsとしても十分使用できる。 Windows Embedded 8.1に限らず、提供されたソフトウェアを\ **営利目的で使用することは原則禁止**\ である。 作ったソフトウェアを販売するなどという事はできないので気をつけよう。 また、当然ではあるが発行されるライセンスは\ **一人につき1ライセンス**\ までとなる。 複数のコンピュータで使うことはできない。 Macの場合は、仮想マシンに入れるかBoot Campを使うかよく考えておくべきだろう。 Microsoft Imagineに登録する --------------------------- ※Microsoft Imagineまたは旧DreamSparkに登録済みの場合、この手順は不要 サインイン ~~~~~~~~~~ まずは、Microsoft Imagineの\ `アカウント作成ページ <https://imagine.microsoft.com/ja-jp/account>`__\ にアクセスしよう。 **Microsoft Imagine**\ は、以前はDreamSparkと呼ばれていたもので、開発ツール・学習リソースなどを教員や学生に無料で提供するプログラムだ。 学生認証の方法はいくつかあるが、\ **大学ドメインのメールアドレス**\ (ac.jpなど)を使えれば問題ない(学生証などでも認証可能)。 ページ上部の\ ``Microsoft Imagine プロファイルを作成する``\ ボタンを押して情報登録を始めよう。 Microsoftアカウントへのログインを求められるので、ID(メールアドレス)とパスワードを入力して次に進む。 情報登録 ~~~~~~~~ サインインすると、画像のようなページが表示されるはずだ。 .. figure:: _media/imagine_register.png :alt: 情報登録画面 情報登録画面 氏名やメールアドレスなど、アカウントに登録済みの情報は既に表示されている。 その他に、 - **Imagine の参加国** - **教育機関レベル**\ (学部生は“College”、院生は“Graduate”) - **学校名**\ (日本語で構わない) を追加で入力する必要がある。 入力が終わったら、\ ``同意する``\ を押して情報を登録しよう。 学生認証 ~~~~~~~~ 情報登録が終わるとアカウントの管理画面を閲覧できるが、まだ登録は終了していない。 そのまま、左メニューの「\ **学生認証を行ってください**\ 」と書かれたリンクをクリックしよう。 大学のメールアドレスを使える場合は、「学校のメール アドレス」を選択してアドレスを入力しよう。 入力したアドレスに\ **確認メール**\ が送信されるので、受け取ってリンクにアクセスすれば認証完了だ。 .. figure:: _media/imagine_verify_mail.png :alt: 大学アドレスの確認メール 大学アドレスの確認メール 念のため、\ `アカウント管理画面 <https://imagine.microsoft.com/ja-jp/account/Manage>`__\ の「アカウントの状態」が「認証済み。有効期限: \**/**/****」のようになっているかチェックしておこう。 Windows Embedded 8.1 Industry Proを入手する ------------------------------------------- OSのイメージファイルを入手する ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Imagineにログインした状態で、\ `ソフトウェアとサービス カタログ <https://imagine.microsoft.com/ja-jp/Catalog>`__\ にアクセスする。 「オペレーティング システム」の区分に“Windows Embedded 8.1 Industry Pro Update”があるはずなので、ダウンロードと書かれたリンクをクリックすればよい。 左のメニューに、\ ``ダウンロード``\ と\ ``キーを入手``\ の二つのボタンが表示されるので、言語を選んでから\ ``ダウンロード``\ をクリックして指示に従おう。 ダウンロードファイルは数GBあるので\ **通信や電源の安定した環境**\ で行うこと。 Windows Embedded 8.1のISOファイルが手に入ったら、あとはディスクに焼くなりインストール用USBメモリを作るなり好きにすればよい。 ライセンス認証 ~~~~~~~~~~~~~~ Windows Embedded 8.1を無事起動したら、忘れずにライセンス認証を済ませよう。 認証用の\ **プロダクトキー**\ (25文字)は、`ダウンロード画面 <https://imagine.microsoft.com/ja-jp/Catalog/Product/82>`__\ の\ ``キーを入手``\ ボタンや、\ `アカウント管理画面 <https://imagine.microsoft.com/ja-jp/account/Manage>`__\ 下部の「マイ ダウンロード」で確認できる。 「設定」アプリの最上部に「Windowsのライセンス認証」なるメニューがあるので、キーを入力して承認されれば認証完了だ。 .. figure:: _media/imagine_win_licence.png :alt: Windows Embedded 8.1のライセンス認証 Windows Embedded 8.1のライセンス認証 <file_sep>またたき回路 ============ - 書いた人: <NAME>(nichiden_27) - 更新: <NAME>(nichiden_28) - 更新日時: 2017/10/4 - 実行に必要な知識・技能: 電子回路、AVRマイコン - タスクの重さ: 3/数週間 - タスクの必須度: 2/たまにやるべき - 元資料 - ``一等星投影機付属またたき回路仕様書.docx`` by 西村陽樹(nichiden_23) 概要 ---- いっとうはただ明るいだけでなく、またたいているように見える効果が付いています。 そのための「またたき回路」の開発は日電に委託されており、遅くとも20主投の頃から存在していました。 現行のプログラム、回路は23が作ったもので、プログラムは27で改造、回路は28で改造して作り直したものです。 原理 ---- またたきの再現には様々な方法が考えられるが、ここでは20代から現在まで使われている「\ **1/fゆらぎ**\ 」と「\ **間欠カオス法**\ 」による方法を解説する。 自然のゆらぎ ~~~~~~~~~~~~ またたきのパターンは周期的ではなく、ランダムであるべきだということは直感的にわかるだろう。 ただし、日電が用いたのは完全な乱数ではなく、自然の「ゆらぎ」を擬似的に再現したものである。 恒星のまたたきは、大気の「ゆらぎ」による光の強弱の変化と説明できる。 ゆらぎ(fluctuation)とは、ある量が平均値からずれる現象である。 なかでも、\ **1/fゆらぎ** は自然現象によくみられ、星のまたたきもこれに分類される。 電子回路などにおけるゆらぎはノイズとして表れる。 ノイズは周波数特性(パワースペクトルと周波数の関係)によって分類されているが、1/fゆらぎによるノイズは\ **ピンクノイズ** と呼ばれる。 ピンクノイズはパワーと周波数が反比例しており、高周波成分であるほど弱い。 これを可視光に当てはめると波長の長い色が残り、ピンク色に見えるというわけだ。 間欠カオス法 ~~~~~~~~~~~~ 従って、いっとうの明るさを1/fゆらぎに近いパターンで変化させればまたたきが再現できる。 1/fゆらぎをプログラムで生成する方法はいくつかあるが、またたき回路では処理の軽い「\ **間欠カオス法**\ 」が用いられてきた。 これは、漸化式によって擬似乱数を作り出す方法である。 以下に基本となる式を示す。 .. math:: \begin{aligned} \begin{cases} X(t+1)=X(t)+2X(t)^{2} & (X(t)<0.5)\\ X(t+1)=X(t)-2(1-X(t))^{2} & (X(t)\geqq 0.5 ) \end{cases} \end{aligned} ただし、実はこのままではこの式はあまり実用的でない。 まず、\ ``X(t)=0.5``\ の場合、以降のXの値は0に張り付いてしまう。 また、0と1の近傍では値の変化が小さくなりすぎる問題もある。 そこで、実際のプログラムでは上限と下限の付近で若干値をいじるようになっている。 また10進数の浮動小数点演算はマイコンでは時間がかかりすぎるので、実際には\ ``double``\ 型ではなく\ ``unsigned long``\ 型(32bit長整数)の値としてある。 回路 ---- 北天用と南天用の二つが現存する。 回路は全く同じで、プログラムだけが違う。 **電源電圧は12V**\ である。 いっとうのユニットやマイコンの電源は5Vであるが、他の主投の電源が12Vであるためそれに合わせて12Vになっている。 それを3端子レギュレータで5Vに降圧して利用している。 もともと27までのまたたき回路は電源電圧が5Vで、12Vを刺し間違えても壊れないように過電圧保護回路が入っていた。 しかし、他の主投と電圧を統一するために28で回路を変更した。 ただし、\ **いっとうのユニット自体の電源電圧自体は5V**\ なので、またたき回路を通さずにいっとうを光らせたい場合は12Vをつながないように注意しよう。 .. figure:: _media/twinkle-circuit28.png :alt: またたき回路の回路図 またたき回路の回路図 回路図を掲載する。 **電源部**\ (変圧部)、**またたき制御部**\ (マイコン)、**またたき出力部**\ (トランジスタアレイ、DCジャック)が主だった構成である。 スイッチ類 ~~~~~~~~~~ .. figure:: _media/twinkle-appearance.jpg :alt: またたき回路の外観 またたき回路の外観 トグルスイッチ(\ ``SW2``)が、\ **またたきのON/OFFスイッチ** である。 OFFにすると消灯するわけではなく、またたきの効果のない常時点灯となる。 いっとうユニット自体のテストやデバッグに使用することを想定している。 スイッチの近くに設置されたLEDはまたたきの確認用である。 横のジャンパピンを外すと消灯するので、上映中は外しておくとよい。 タクトスイッチは\ **リセットスイッチ**\ で、押すとマイコンが再起動する。 またたき制御部 ~~~~~~~~~~~~~~ ``ATTiny861A``\ を使用している。 ``SW2``\ がpin9(\ ``INT0/PB6``)に繋がれており、INT0割り込みを使用してまたたきON/OFFを切り替える。 INT割り込みはI/Oポートが出力設定になっていても機能するので、プログラムでは\ ``PB6``\ が出力設定になっていても問題ない。 また、ON/OFFの制御をするだけのスイッチであるためチャタリング除去はなされていない。 ``PB0``\ 、\ ``PA0``\ に確認用LEDが接続されている。 またたき出力部 ~~~~~~~~~~~~~~ ``TD62003``\ トランジスタアレイを使用する。 ``ATTiny861A``\ の\ ``PA0-PA5``/``PB0-PB5``\ の12本が出力ピンとなる。 いっとうとの接続部はφ2.5の基板用DCジャックを使っている。 各出力ピンが\ ``HIGH``\ になると、対応したDCジャックのGNDが導通して電流が流れる仕組みである。 電源部 ~~~~~~ 三端子レギュレータを用いて12Vの電源電圧を5Vに降圧している。 三端子レギュレータの使い方は\ `このサイト <http://radio1ban.com/bb_regu/>`__\ を参考にするとよい。 なお、降圧した7V分は熱として放出される。 放熱効率を上げるために\ `放熱器 <http://akizukidenshi.com/catalog/g/gP-00429/>`__\ を取り付けている。 放熱器と接触する面に\ `放熱用シリコングリス <http://akizukidenshi.com/catalog/g/gT-04721/>`__\ を塗ってとりつけよう。 プログラム ---------- 27でプログラムを改修した際、Arduino IDEを使用してビルドと書き込みを行った。 Arduino IDEではメインのソースファイルは.inoという拡張子のファイルになる。 ただし、ベースはC++なので.cppや.hのファイルに分割して記述しても問題ない。 23日電のまたたき回路のプログラムでは\ **マイコンを実際に動作させる部分**\ と\ **またたきパターンを生成する部分**\ が混在していた。 可読性を高める目的で、前者を\ ``Twinkle.ino``\ に、後者を\ ``Twinkle.cpp``\ 及び\ ``Twinkle.h``\ と分けることにした。 ``Twinkle.h``\ で宣言している\ ``Twinkle``\ クラスがパターン生成のライブラリのように使えることを目指したが、完全なブラックボックスにはできていないので適宜改善が必要。 Twinkle.h ~~~~~~~~~ プログラム中で使う変数・関数の宣言があるファイル。 ``NORTH_HEMISPHERE``\ や\ ``SOUTH_HEMISPHERE``\ がdefineされているが、これは北天・南天で数値を切り替えるために用いる。 書き込み前によく確かめて、不要な方をコメントアウトすること(片方をコメントにしていないと、変数宣言が二重となりエラーが出る)。 使っている変数や配列の注釈を箇条書きしておこう。 - public変数 - int bit_num[6]: パターンの番号とマイコン側のピンの順番の対応を示す - unsigned int on[12]: 27で追加した、またたきをピンごとに無効化するための配列。1か0 - unsigned int on_duration[12]: 一周期のうちLEDが点灯している時間(=またたきパターン)を格納する - private変数 - unsigned long shift_chaos: ピン同士を入れ替える際に使う乱数値 - unsigned long chaos[12]: またたきパターン用の乱数値 - unsigned int min_duration[12]: on_durationの最小値。大きくするとまたたき効果が強くなる - unsigned int refresh_rate/rr_count/shift_rate/sr_count: (後述) Twinkle.cpp ~~~~~~~~~~~ 冒頭でいくつか記号定数が宣言されている。 コメントを読めば概ね理解できるであろう。 結局\ ``Twinkle``\ クラスの内部処理で使うだけなので、ヘッダファイルのクラス宣言の方に書いても問題なかったかも。 .. code-block:: cpp #define CHAOS_DIV 256 // chaos_gen()で生成される乱数は1~32768の幅であるが、このままではタイマ0割込に使用できないので適当な2の乗数で割る #define ON_DURATION_MAX 160 // LEDの点灯時間の最大値を決定するパラメーター(タイマ割込の間隔によって決まっているのでオシロスコープで波形を見ながら調整のこと) #define TWINKLE_RATE 2 // またたき用の乱数値の更新レート、nを設定するとn回のタイマ割込に1回の割合で値が更新する #define TWINKLE_SHIFT 100 // 乱数の周期性問題を解決するために、乱数とそれに対応する信号出力ビットをport_shift()で変更している。nを設定するとn回の乱数更新に1回の割合で出力がビットシフトする 次に、コンストラクタがある。 と言っても変数の初期化をしているだけである。 ここで、\ ``refresh_rate``\ や\ ``shift_rate``\ などを設定する。 .. code-block:: cpp Twinkle::Twinkle():refresh_rate(TWINKLE_RATE), rr_count(TWINKLE_RATE), shift_rate(TWINKLE_SHIFT), sr_count(TWINKLE_SHIFT){}; port_shift() ^^^^^^^^^^^^ 間欠カオス法はあくまで擬似乱数なので、周期性が目立つことがある(らしい)。 定期的にまたたきパターンと各出力ピンの対応を変えることで、これを防ぐ。 **ただし、このメソッドは現在使用していない。** 23では12のピンを強弱2種類にしか分けていなかったが、27で惑星(またたかない)を追加したのでこれが3種類に増えた。 当初それに気づかず実験したところ、またたき強・弱・惑星が数秒で入れ替わってしまう。 修正の時間も限られており、本番ではポートの入れ替えを使わずに投影をすることとなった。 見ていた限りでは特に不自然には感じなかったが、この仕様が必要かどうかは更なる検証を待ちたい。 参考のためにピンを入れ替える仕組みを解説する。 .. code-block:: cpp for(int i=0;i<6;i++) bit_num[i] = (bit_num[i] + (shift_chaos >= 12000 ? 1 : 4)) % 6; // 6要素の数列を左に回転シフト 回転シフトは、配列の中身を押し出して溢れた分を逆側に追加するものだ。 円環状に並んだ数字を回転させるイメージである。 アルゴリズムとしてはある数字(6要素なら1~5)を足し、6以上になった要素からは6を引くというものだ。 6で割った余りを保ったまま6を下回ればいいので、\ **実は割り算して余りをとるだけでもいい。** なお、23の計測によるこの処理の実行時間は100μsだが、割り算の方法で処理を簡略化したので短くなったかもしれない。 refresh() ^^^^^^^^^ またたきパターンの更新を行う。 ``chaos``\ の12個の要素それぞれに、新たな乱数値を格納している。 .. code-block:: cpp void Twinkle::refresh(void){ // 乱数値を更新する。所要時間は12変数で1ms for(int i=0;i<SIZE_OF(on_duration);i++){ chaos[i] = chaos_gen(chaos[i]); on_duration[i] = min((int)(chaos[i] / CHAOS_DIV + min_duration[i]), ON_DURATION_MAX); } } 実際のまたたきパターンで使う\ ``on_duration``\ には、\ ``chaos``\ から二つの変化を加える。 まず、最大32768の出力を\ ``CHAOS_DIV``\ で除した上で、\ ``min_duration``\ という数を加えている。 ``min_duration``\ が大きいほど、\ **LEDが点灯している時間が増え、またたきの効果が薄まる**\ 。 また、\ ``on_duration``\ は160を超えてはいけないので、\ ``ON_DURATION_MAX``\ と比較して小さい方を採用する。 実行時間は1msらしい。 chaos_gen(y) ^^^^^^^^^^^^ 入力yに対して間欠カオス法による擬似乱数を一個出力する。 元の漸化式にアレンジを加え、yの変化が微小になることがないよう調整してある。 .. code-block:: cpp unsigned long Twinkle::chaos_gen(unsigned long y){ // Max == 32768までの整数値を返す疑似乱数(1/fゆらぎ) if(y < 1638) y += 2 * pow(y, 2) / 32768 + 1966; else if(y < 16384) y += 2 * pow(y, 2) / 32768; else if(y > 31129) y -= 2 * pow(32768 - y, 2) / 32768 + 1310; else y -= 2 * pow(32768 - y, 2) / 32768; return y; } generate() ^^^^^^^^^^ またたき生成や出力ピンの入れ替えを制御する。 タイマ割り込みで毎回呼ばれることを想定している。 割り込みが入るたびに\ ``rr_count``\ と\ ``sr_count``\ が1ずつ減少し、0になると\ ``port_shift()``\ や\ ``refresh()``\ を実行する。 ただし、27の仕様変更で\ ``port_shift()``\ は不使用としたので、その部分はコメントになっている。 .. code-block:: cpp void Twinkle::generate(void){ // またたきをつかさどる部分 rr_count--; //乱数更新時期の判定と実行をする if(!rr_count){ sr_count--; //ビットシフト更新時期の判定と実行をする if(!sr_count){ //port_shift(); sr_count = shift_rate; }else _delay_us(100); refresh(); rr_count = refresh_rate; }else _delay_us(1100); //それらの操作をしない場合でも、同じだけの時間waitして調整する } Twinkle.ino ~~~~~~~~~~~ AVRマイコンの制御に直接関連するコードはこちらにまとめた。 ISR(INT0_vect) ^^^^^^^^^^^^^^ INT0割り込みで呼ばれる。 PORTAとPORTBをすべてH、つまり常時点灯・またたきなしの状態にする。 .. code-block:: cpp ISR(INT0_vect){ //またたきOFF(スイッチで切り替え) PORTA = 0xFF; PORTB = 0xFF; } ISR(TIMER0_COMPA_vect) ^^^^^^^^^^^^^^^^^^^^^^ タイマ0割り込みで呼ばれる。 PORTAとPORTBをすべてHにしてから、Twinkleクラスの\ ``generate()``\ 関数を呼んでパターンの更新処理をする。 .. code-block:: cpp PORTA = 0xFF; PORTB = 0xFF; twinkle.generate(); unsigned int c_up = 0; 以降は、実際にピンから出力するコードになる。 ``pattern_count``\ は出力ピンの数(現状12)を表す。 forループ内では、7μsごとに\ ``c_up``\ をインクリメント(コメントに\ ``twinkle.c_up``\ とあるがこれはミス)していく。 ``twinkle.on_duration[i]``\ と一致したら\ ``pattern_count``\ を一つ減らして、\ ``twinkle.on[i]``\ が0でなければLEDを消灯する。 ``i``\ とピン番号の対応は\ ``twinkle.bit_num``\ に書いてある。 .. code-block:: cpp unsigned int pattern_count = SIZE_OF(twinkle.on_duration); while(pattern_count){ //twinkle.on_durationの値とtwinkle.c_up(カウントアップ)の値を比較し、一致するまではON、一致したらLEDをOFFにする。全部OFFになったらループを抜けてmainに戻る。 c_up++; for(int i=0;i<SIZE_OF(twinkle.on_duration);i++){ if(twinkle.on_duration[i] == c_up){ pattern_count--; if(!twinkle.on[i]) continue; if(i < 6) PORTA ^= 1 << twinkle.bit_num[i]; else PORTB ^= 1 << twinkle.bit_num[i-6]; } } _delay_us(7); } 出力ポートの制御であるが、マイコンボードのデジタル出力のようには便利でなく、\ **出力レジスタというものを使う**\ 。 ``PORTA``\ や\ ``PORTB``\ とあるのが出力レジスタで、ピンの状態が二進数で保存されている。 これを書き換えることで出力がなされる仕組みだ。 例えば、\ ``PORTA = 0xFF(11111111)``\ の時に、6番目のピンを\ ``LOW``\ にしたいとする。 ``^=``\ 演算子はXOR代入といい、右の数との排他的論理和を代入する。 XORは二つの数が違えば1、同じなら0を返すので、\ ``PORTA``\ の6桁目と1のXORを取ればそこだけが0になる。 n桁目が1の数は1を(n-1)ビット左にビットシフトすると作れるので、コードはこうなる。 .. code-block:: cpp PORTA ^= 1 << 5 main() ^^^^^^ 初期設定とメインルーチン。 I/Oポートの設定・タイマ0(CTCモード)とプリスケーラの設定・タイマ0割り込みの設定・INT0割り込みの設定を行っているらしい。 ここを変更したければAVRの勉強をしよう。 ``sei()``\ は割り込みを許可する組み込み関数である。 設定終了後にこれを呼んで無限ループに入り、割り込みを待つことになる。 .. code-block:: cpp int main(void){ /*** 初期設定(TIMER0_CTC、TIMER割込、INT0割込) ***/ _delay_ms(100); DDRA = 0xFF; //PORTA0~7を出力に設定 DDRB = 0xFF; /*タイマ0 CTCモード、タイマ0_Compare_A割込*/ TCCR0A = 0x01; //CTC0をHに TCCR0B = 0x00 | 1<<CS02 | 0<<CS01 | 0<<CS00; OCR0A = 180; //CTCのMAX値の設定(180、プリスケーラ256の設定でタイマ割込間隔は7.5msec) TIMSK |= 1<<OCIE0A | 0<<TOIE0; //タイマ0CompA割込有効 GIMSK |= 1<<INT0; //INT0割り込み有効 MCUCR |= 0<<ISC01 | 0<<ISC00; //INTピンのLowで割り込み発生 PORTA = 0x00; PORTB = 0x00; /*************************************************/ sei(); for(;;){} } 書き込むには ~~~~~~~~~~~~ 書き込みの際、Fuseビットの\ ``DIVCLK8``\ を\ ``Disable``\ する必要がある(内部クロックを1MHzではなく8MHzで使用するため)。 27では、書き込みにArduino IDEを使った。 Arduinoの中身はAVRマイコンなので、マイコン(ボード)の定義を読み込む事で書き込み可能になる。 ボードマネージャで\ `設定ファイルのURL <http://drazzy.com/package_drazzy.com_index.json>`__\ を指定すると各種設定が選べるので、\ ``ATTiny861A``\ を選択して書き込もう。 手順の詳細は\ `Arduino IDE に ATtiny45/85/2313 他の開発環境を組み込む <http://make.kosakalab.com/make/electronic-work/arduino-ide/attiny-dev/>`__\ など参照。 改善点 ------ 現在のまたたき回路は起動に時間がかかるため、いっとうも無線制御にしようとしても、どうしてもONにしてから点灯するまでにラグが生じてしまう。 現在の間欠カオス法による1/fゆらぎの再現は現実に近いものなのかもしれないが、再現性を少し犠牲にしてでも、処理が軽く起動の速い新しいまたたき回路を作ることを考えてもいいかもしれない。 もしくは、またたき回路自体を無線制御できるようにするという手も考えられる。 <file_sep># Visual Studioをはじめよう - 書いた人: <NAME>(nichiden_27) - 更新日時: 2017/05/29 - 実行に必要な知識・技能: 特になし - 難易度: 1/常識の範囲 - 情報の必須度: 3/必要な場合がある ## 概要 Visual Studio(以下VS)は、Microsoft製の統合開発環境(IDE)です。 様々な開発案件に対応でき、特にWindows向けのGUI開発を行いたい場合非常に有効です。 日電においては、日周緯度変のPC制御ソフトや旧星座絵制御ソフトがWindowsのデスクトップアプリケーションです。 今後もWindows向けに開発を行うなら、ぜひVSをインストールしておきましょう。 ## 価格 **無料。** 2014年以前にもVisual Studio Expressという無償版が存在したが、有料版より機能が制限されていた。 尤も、学生であればDreamSpark(現: Microsoft Imagine)というプログラムで有料のProfessional版が無償で入手できたという ([【学生は無償】 最新のVisual Studio 2013 を早くも DreamSpark で提供開始!](https://blogs.msdn.microsoft.com/microsoft_japan_academic/2013/10/30/visual-studio-2013-dreamspark/))。 2014年11月、**Visual Studio Community**が旧Express版を置き換える形で発表された。 個人や小規模開発者という条件付きだが、Professional相当の機能を無償で利用できるようになった。 学生団体での開発ならば、VS Communityがあれば十分であり、VSが実質的に無料で使えると言っていいだろう。 ## インストール ※**Windows版を想定** [VS Communityのページ](https://www.visualstudio.com/ja/vs/community/)にアクセスし、インストーラを入手して起動する。 最新のVS Community 2017は、**モジュール式インストーラ**を採用しており、インストール前に導入する機能を選択するようになっている。 自分に必要な機能だけの構成にすることで、肥大化して時間がかかっていたVSの初回インストールが短時間で可能になったのだ。 ![インストーラの機能選択画面](_media/vs-install-1.png) 「**ワークロード**」タブで、開発を行いたい言語や環境を選択する。 例えばWindowsのデスクトップアプリなら、最低限「.NETデスクトップ開発」を選んでおけば事足りるだろう。 「**個別のコンポーネント**」タブではさらに細かく、インストールする機能を個別に選べる。 興味を引くものがあればチェックを入れておこう。 インストール後からでも構成を変更できるので、ここで深く悩む必要はない。 右下に表示される「インストール サイズ」を確認し、空き容量と通信回線に問題がなければ`インストール`をクリックして実行しよう。 ![インストール中の画面](_media/vs-install-2.png) インストールが終了すると、Microsoftアカウントへのサインインを促される。 サインインしなければ30日後に使えなくなるので、もしアカウントを持っていないなら作ってしまおう。 サインインすると、ようやくVSが起動し、以下のような画面が表示される(筆者はテーマ色を変更しているため、標準の画面色と異なる場合あり)。 ![VS初期画面](_media/vs-install-3.png) <file_sep># テキストエディタを使ってみよう - 書いた人: <NAME>(nichiden_27) - 更新日時: 2017/04/26 - 実行に必要な知識・技能: 特になし - 難易度: 1/常識の範囲 - 情報の必須度: 3/必要な場合がある ## 概要 コードや文章をたくさん書くようになると、テキストエディタにこだわりたくなってきます。 最近のエディタの特徴などについて書きます。 最近は複数OSで作業することも珍しくなくなってきたので、Windows/Mac OS X/Linuxのどれでも使えることを重視して紹介します。 ## Atom [atom.io](https://atom.io) [GitHub](https://github.com)が開発しているエディタ。 [PV](https://www.youtube.com/watch?time_continue=2&v=Y7aEiVwBAdk)が面白いのでぜひ観よう。 "A hackable text editor"と銘打っており、プログラマが**自由にカスタマイズして使える**ことを売りにしている。 とはいえ、標準の状態で既に使いやすいので、プログラマでなくともぜひ触れてみて頂きたい。 ![Atomの画面例](_media/atom.png) Markdownの文書を書く場合、`Ctrl(Cmd)+Shift+M`を押すと右に**プレビュー画面**を表示してくれる。 いわゆるWYSIWYG(表示と処理結果が一致)なエディタとして使用できるわけだ。 プレビューは編集内容に合わせてリアルタイムで更新される。 Markdown以外にも、プラグインを追加することで様々な言語のプレビューに対応できる。 使い勝手としてはほぼ不満のないAtomだが、**メモリを消費しすぎる**ことがある。 AtomはChromeのオープンソース版であるChromiumをベースに動いている。 このため本質的にはChromeが起動しているのと変わらず、”Atom Helper”なるプロセスがメモリを占有してしまうのだ。 重く感じたら、不要なファイルは閉じるなど対策しよう。 Markdown文書がある程度長い場合は、リアルタイムのプレビューを非表示にするのも効果がある。 ## Visual Studio Code(VSCode) [code.visualstudio.com](https://code.visualstudio.com) Microsoft(MS)が開発しているエディタ。 MSは最近オープンソース化・クロスプラットフォーム化に舵を切っており、VSCodeも各OS向けに無償提供されている。 Atomより後発で、現在も開発が活発である。 最近のアップデートでAtomと遜色ない機能を備えてきており、Markdownプレビューももちろん可能。 ![Visual Studio Codeの画面例](_media/vscode.png) また、Visual Studio譲りの超強力な補完機能である`IntelliSense`をいくつかの言語で利用できる。 コーディングの機会が多い人にとっても有力な選択肢となりそうだ。 今後も、アップデートの度に新機能の追加が期待でき、さらに使い勝手が向上する可能性もある。 Atomを自力でカスタマイズしていくのが面倒に感じたら、VSCodeの豊富な機能を使いこなすのもいいかもしれない。 ## CUIエディタ ### CUIエディタを使う理由 CUI(コマンドライン)のテキストエディタで有名なのは**VimとEmacs**だ。 この二つは宗教戦争的なネタにされがちだが、両者とも実用に足る機能を十分備えているからこそ「Vim派」や「Emacs派」が生まれるとも言える。 CUIエディタはキー入力のみで操作する必要があるのでとっつきにくいが、Vim/Emacs**いずれかの基本操作**くらいは覚えて損はないだろう。 ちょっとしたファイルの書き換えがしたい時など、ターミナルの画面を離れずに編集ができると効率がいい。 また、ssh接続してのリモート作業などでCUIしか触れなくても、VimやEmacsならほとんどの場合使用できる。 ### 設定ファイル キーボードでの操作に慣れてくると、CUIエディタを好んで使うようになるかもしれない。 こうなるとデフォルトの設定では物足りないし、作業効率が悪い。 **設定ファイルやプラグイン**を使い、自分に合ったエディタにしてみよう。 Vimなら`.vimrc`、Emacsなら`.emacs.el`というファイルをホームディレクトリに作ると読み込んでくれる。 ネットにオススメの設定がたくさん落ちているので、いいと思ったものを集めれば自分用設定の完成だ。 なお、起動中は変更しても反映されないので、コマンドで反映させるかエディタを再起動しよう。 [GitHub](https://github.com)などで自分の設定ファイルを管理しておくと、他の環境で作業する時でも設定を簡単に共有できる。 どこの環境でも自分好みの操作感をそのまま引き継げるのは、CUIテキストエディタの特権かもしれない。<file_sep>無線制御(GRAFFIAS) ================== - 書いた人: <NAME>(nichiden_28) - 更新日時: 2018/08/26 - 実行に必要な知識・技能: Web制作、JavaScript、php - タスクの重さ: 2/数日かかる - タスクの必須度: 4/毎年やるべき 概要 ---- ``GRAFFIAS``\ は28代で開発した指示書作成補助用Webアプリケーションです。現状、\ ``Acrab``\ で使用するJSON形式の指示書を作成しやすくする機能のみを持ちます。 最新のブラウザ(Chrome推奨)があれば、どんな環境でも使うことができます。 ``Acrab``\ の補助として用いることから、さそり座β星\ ``Acrab``\ の別名である\ ``Graffias``\ から名前を取っていますがあまり深い意味はありません。\ ``Graffias``\ はラテン語で「爪」を意味するそうですが本アプリに爪要素は一切ありません。 ※無線制御と直接関係はしませんが、性質上\ ``Acrab``\ から切り離せないアプリなので無線制御の項に分類しました。 使い方 ------ 下準備と起動 ~~~~~~~~~~~~ 使いはじめる前に、その年に使用する星座絵を\ ``GRAFFIAS.php``\ に入力する必要がある。\ ``GRAFFIAS.php``\ 内のHTML部分に、 .. code-block:: html <select id="projector_a[0]" name="projector_a[0]"> <option value="XXX">--使用星座絵を選択--</option> などと書かれた部分がある。(\ ``projector``\ は5個まで用意しているので計5か所、1か所書いてコピペすればよい) この後に、使用する星座絵及び星座グループを、(※ただし、2017年現在Acrab側の不具合により現状星座グループ指定は行えないので注意) .. code-block:: html <option value="Lep">うさぎ</option> のように、\ ``<option value="(三文字コード)">(星座名か星座グループ名)</option>``\ の形で書いていく。 ``ACRAB``\ ディレクトリ内に、\ ``88星座+略符一覧.txt``\ という三文字コードと星座名の対応を書いたテキストファイルを置いておいたので参考程度にどうぞ。 書き換えが終わったら、\ ``GRAFFIAS``\ を使う環境の整備を行う。 ``GRAFFIAS``\ はphpで書かれているので、\ ``Acrab``\ と同様にローカルにWebサーバを立てないと使えない。 ローカルにWebサーバを立てる方法としては\ `Acrabの使い方#下準備 <acrab.html>`__\ を参照のこと。\ ``Acrab``\ 本体とはルート環境を別にしておこう。 なお、\ ``GRAFFIAS``\ のみを別のPCで使うときは、\ ``Acrab``\ ディレクトリ内の\ ``GRAFFIAS``\ ディレクトリのみを移せば使える仕様になっている。 これにより、プログラミング担当者以外の人や日電メンバー以外にも指示書作成を手伝ってもらえる…といいなあ。 localhostにアクセスすると、以下のような画面が表示される。 .. figure:: _media/graffias-main.png :alt: GRAFFIASメイン画面 GRAFFIASメイン画面 操作 ~~~~ JSONファイルの作成 ^^^^^^^^^^^^^^^^^^ ``GRAFFIAS``\ で作成しようとするJSONの構造は以下のとおり。 :: ├── "info" [番組情報] │   ├── "day" [(ライブ解説の場合)何日目か] │   ├── "title" [番組名] │   └── "name" [担当者名] └── "scenario" [配列: 指示が入る部分]    ├── 0    │   ├── "word" [セリフ: 0番目は空欄にする]    │   ├── "timing" [タイミング: 0番目は空欄にする]    │   └── "projector" [投影機]    │      ├── "(三文字コード)" [点灯なら1/消灯なら0]    │      └── (以下同様)    ├── 1    │   ├── "word" [セリフ]    │   ├── "timing" [タイミング]    │   └── "projector" [投影機]    │      ├── "(三文字コード)" [点灯なら1/消灯なら0]    │      └── (以下同様)    └── (以下同様) ``GRAFFIAS``\ の画面上の各フォームは、このJSONの構造に対応している。 .. figure:: _media/graffias-opscreen.png :alt: GRAFFIAS操作画面 GRAFFIAS操作画面 - ファイル名…JSONファイルのファイル名。自由に決めていいが、タイトルと一致させた方が分かりやすいと思われる。 - 公演日…\ ``day``\ と対応。セレクトボックスから一日目~三日目、ソフトのいずれかを選ぶ。 - タイトル…\ ``title``\ と対応。番組名を入力する。 - 担当者…\ ``name``\ と対応。担当者の名前を入力する。ソフト製作の番組の場合、空白にしておくといいだろう。 - シナリオ以下…\ ``scenario``\ 以下に対応する。下のプラスボタンを押せばフォームが増え、マイナスボタンを押せば直前のフォームが消える。0番目は「JSONを作成」ボタンを押した時に自動生成されるので、入力不要である。 - タイミング…\ ``timing``\ と対応。セリフの前か後かを選択できるようにしたが、その他の「セリフの3秒ほど後」のような指示は\ ``GRAFFIAS``\ 上では対応できないので、出来上がったJSONに手入力することになる。 - 操作…\ ``projector``\ と対応。星座絵と、その星座絵のon/offを選択する。入力ミスが一番多いところなので注意。 星座のグループも選択できるが、Acrabがこれに対応できていないので現状無効である。詳しくは\ `Acrabの実装解説#acrab_main.js <acrab-code.html>`__\ 参照のこと。 - セリフ…星座絵点灯/消灯の合図となるセリフ。エクセルからコピペ可。 情報を入力していると、指示書の曖昧な点や不明点、矛盾点が見えてくることもある。これらは入力中にソフトの人やライブ解説担当者に問い合わせて、できるだけ潰しておくといいだろう。 全ての情報を入力し終わったら右下の「JSONを作成」ボタンをクリックする。 すると、JSONファイルが\ ``GRAFFIAS/scenario``\ ディレクトリ内に作成される。 | 実は、このままでは\ **AcrabからJSONファイルを参照できない**\ ため、JSONファイルが揃ったら、 **ACRAB/scenarioディレクトリ内にJSONファイルをコピーして使う**\ のが必須となる。 | なぜこんな面倒な仕様なのかというと、\ ``GRAFFIAS``\ は、\ ``GRAFFIAS``\ のみをコピーしてプログラム担当ではない人に渡して使ってもらうことを想定しているためである。 年にもよるが、基本的に指示書の数は多いうえに大体本番ギリギリにならないと揃わない。このため、とにかく作業人数が多いほど本番直前の負担が減る。よって、\ ``GRAFFIAS``\ ディレクトリのみをコピーして複数人に渡し、各自の\ ``GRAFFIAS/scinario``\ 内に出力されたJSONを、USBなりLINEなりメールなりでJSONを取りまとめる人に送信する…ということを考えた。 全員がGitを使いこなせれば無問題な気もするが、そういう専門知識のない人にも容易に使えるような仕様を目指したのでこうなった。 JSONリストの作成 ^^^^^^^^^^^^^^^^ 全ての番組のJSONファイルを作成し終わったら、\ ``GRAFFIAS/scenario``\ ディレクトリに全ての番組のJSONファイルがあることを確認する。 **GRAFFIASディレクトリがACRABディレクトリの直下にあることも確認する。** | ここまで確認できたら、\ ``GRAFFIAS``\ の画面で「\ **↑↑↓↓←→←→BA**\ 」と入力すると、画面一番下の右側(赤っぽいエリアの外)に赤い「JSONリストの作成」ボタンが表示される。 これをクリックすると、\ ``ACRAB``\ ディレクトリ内に\ ``scenario_list.json``\ が作成される。 | 既に\ ``scenario_list.json``\ がある状態で押すと、これが上書きされる仕様。 このため直前のタイトル変更にもササッと対応できる。 | ``scenario_list.json``\ は、\ ``Acrab``\ がサーバにある指示書ファイルの数を知るために使われる。詳しくは\ `Acrabの実装解説#acrab_main.js <acrab-code.html>`__\ 参照のこと。 プログラム ---------- | ``GRAFFIAS``\ はWebの技術を使って内部処理や画面表示を行っている。 画面の情報はHTML、デザインはCSS、画面の書き換えはJavaScript(以下JS)、内部処理やファイルの生成はphpという構成だ。 | phpの仕様上、HTMLは\ ``GRAFFIAS.php``\ の中に書いてある。基本的にはphpをプログラム前半に、HTML部分をプログラムの後半に書いてあるので、編集時はそれぞれを参照してほしい。 プログラムの細かい仕様については説明を省くが、要所については説明を加えておく。 GRAFFIAS.phpの実装解説(HTML部) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``GRAFFIAS``\ では、入力された情報を受け取るのに、HTMLの\ ``<FORM>``\ タグを使用している。\ ``<FORM>``\ タグ内にラジオボタン、セレクトボックス、テキストボックス等を配置し、入力された情報を .. code-block:: html <form id="frm" name="frm" action="GRAFFIAS.php" method="post" > で\ ``GRAFFIAS.php``\ に送信する。送信したデータをphp部分で処理するという流れだ。php部分の説明は後述。 .. code-block:: html <select id="projector_a[0]" name="projector_a[0]"> | 等のセレクトボックスについては、セレクトボックスの中身をいじれば、その年に使用する星座にも対応できる。 セレクトボックスの中身を操作するようなGUIは、時間の都合上作ることができなかったので、もし余裕があったら考えてみるのもいいかもしれない。(GUIを丸ごと作り直した方が速いかもしれないが…) | 他のHTML部については、後述する\ ``script.js``\ に関連する部分以外は、基本的にググればすぐ分かる程度の内容しか書いていないため、割愛する。 script.jsの実装解説 ~~~~~~~~~~~~~~~~~~~ 一旦\ ``GRAFFIAS.php``\ からは外れるが、\ ``GRAFFIAS.php``\ のフォームの追加・削除機能に関する部分である、\ ``script.js``\ の解説に入る。 ``GRAFFIAS.php``\ には、フォーム追加用の+ボタンと、フォーム削除用の-ボタンがあるが、これは\ ``GRAFFIAS.php``\ のみではただのボタンであり、何の機能もない。 これにフォームを追加/削除し、現在のフォームの数を変数を用いカウントして\ ``GRAFFIAS.php``\ に渡すのが\ ``script.js``\ の主な役割である。 また、\ ``script.js``\ には\ ``jQuery``\ が使われている。これは\ ``Acrab``\ 関連のjavascriptを触った人ならお馴染みであろう。ネット上に参考文献が大量にあるので分からない場合は参照してほしい。 今回は\ `こちらのページ <https://qiita.com/SiskAra/items/5f4bc7ee4e598b863add>`__\ を参考にした…というかほとんど丸パクしたのでまずリンク先を参照してほしい。 - ``$(obj).attr('id').replace(/\[\d{1,3}\]+$/, '[' + frm_cnt + ']')``\ などの\ ``/\[\d{1,3}\]+$/``\ の部分は「正規表現」と呼ばれる表記である。 ここだけではなく、日電が作成した他のプログラムにも含まれている…し、プログラミングに関わったことがあるなら見たことがあるかもしれない。 表記がややこしいので、\ `参考文献へのリンク <https://www.sejuku.net/blog/20973#i-3>`__\ を貼っておく。 .. code-block:: js $('#send_button').click(this,function(){ document.forms['frm'].elements['count'].value = frm_cnt + 1; document.frm.submit(); }); 上記の部分は、「JSONを作成」ボタンを押した時に、現在のフォームの数を、\ ``script.js``\ 内でフォームの数を数える変数である、\ ``frm_cnt``\ の数に1を足した数として\ ``GRAFFIAS.php``\ 内のHTML部に組み込むためのコードである。これは、javascriptで変更したフォームの数を、どうしてもphp側で参照できるようにしたかったからである。 色々と調べてはみたが、作成者の技術では、javascript→HTML→phpという流れで受け渡す方法しか思いつかなかったのでこの仕様である。もっとスマートな方法もあるのかもしれない。 .. code-block:: js var inputKey = []; var konamiCommand = [38,38,40,40,37,39,37,39,66,65]; $(window).keyup(function(e) { inputKey.push(e.keyCode); if (inputKey.toString().indexOf(konamiCommand) >= 0) { $('#listmake').css("display","inline"); inputKey = []; } }); | …上記の部分は、完全にお遊びで入れてしまった部分である。指示書用のJSONを全て作成し終わった後、\ ``Acrab``\ から参照できるように、JSONの一覧をまとめたJSONファイルを作らないといけないのだが、このJSONリストを作る機会は少ない。というか基本1回しかない。 | このため、隠しコマンドでJSONリスト作成用のボタンが出せたらいいな…隠しコマンドと言えばコナミコマンドかな?という発想から付け足しただけである。(と思ったが同世代に伝わらなかった)世の中同じことを考える人は多いようで、「コナミコマンド javascript」でググるといろいろ文献が出てくる。このコードもネット上から引っ張ってきた。 GRAFFIAS.phpの実装解説(php部) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | さて、ここからが本題のphp部分になる。php初学者が何とか動くように1週間で無理矢理書き上げたものなので、非常にエラーが多いことに留意していただきたい。 | 冒頭の、\ ``ini_set('display_errors', "Off");``\ をコメントアウトすると、phpの実行時にエラーが表示されるようになる。デバッグ時の参考にしてほしい。 FORMから送信されたデータの変数への格納 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. code-block:: php if(isset($_POST['filename'])){ $filename = $_POST['filename']; //echo $filename; | 上記の形式で記述した部分は、入力された内容をphp部で扱う変数に格納する役割だ。 | コメントアウトしている\ ``echo``\ 部は出力が正しいかのテスト時に使える。 | セリフ、タイミングにあたる\ ``word``\ 、\ ``timing``\ や星座絵にあたる\ ``projector``\ 、各フォームのON/OFFボタンにあたる\ ``on_off``\ については、配列として格納している。 これは、1つの指示書内にこれらが複数あるからである。 | また、現在のフォーム数もこの形式で受け取って、\ ``$count``\ という変数に格納している。 | ここで注意してほしいのが、\ ``projector``\ については、1個目のフォームの、1番上の星座絵用セレクトボックスがprojector_a[0]、1個目のフォームの、上から2番目のものは\ **projector_a[1]ではなく、projector_b[0]**\ になるということである。\ ``on_off``\ のラジオボタンも同じ仕様になっている。 | あらかた作った後で、この分かりにくさに気が付いてしまったが時間的に修正できなかったのでこのままである。非常に分かりにくい仕様になってしまって申し訳ない。 JSONファイルとして出力するための雛形の作成 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. code-block:: php $DATA_ARRAY = array( "info" => array( "day" => $day, "title" => $title, "name" => $staffname, ), "scenario" => array( array( "timing" => "", "word" => "", "projector" => array( "Fst" => 1, "Gxy" => 1, ), ), ), ); 上記の部分は、JSONファイルを作成する際のいわば初期設定にあたる部分を作るためのものである。指示書用のJSONファイルをいくつか見てもらえればすぐ分かると思うが、 各JSONファイルの冒頭部は\ ``day``\ 、\ ``title``\ 、\ ``name``\ 以外は全て一致している。この部分を配列として作成するのが上記コードである。この雛形に、他の星座絵やそのON/OFFについての 情報を加えていき、最終的にJSONとして出力する形である。この部分の記法については\ `こちらのページ <https://syncer.jp/how-to-use-json>`__\ が大いに参考になった。 .. code-block:: php $word = str_replace(array("\r", "\n"), '', $word); このコードはセリフ部分に書き込まれた内容から、改行コードを削除するためのものである。載せる場所に困ったので、ここに記載する。 セリフ部分に改行が入っていると指示書中に変な文字化けが発生することが指示書作成中に発覚したため、急遽追加した箇所である。 これにより、改行コードによる文字化けは防げるようになったが、同時に、そもそもセリフが改行されなくなるというデメリットも発生するようになった。(当然だが) 具体的には、長いセリフの場合にAcrab上で読みにくくなる、Acrab上で「次へ」/「前へ」ボタンが大きく横に伸びてしまうことがあるなどの点が欠点である。 このコードを置き換える、削除する、AcrabのCSSをいじってデザイン面からなんとかする…等の対応をしてほしいところである。 星座絵用セレクトボックスで、星座が未選択の場合の配列からの削除 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. code-block:: php for($n = 0;$n < $count; $n++){ if($projector_a[$n] == "XXX"){ unset($projector_a[$n]); unset($on_off_a[$n]); } if($projector_b[$n] == "XXX"){ unset($projector_b[$n]); unset($on_off_b[$n]); } if($projector_c[$n] == "XXX"){ unset($projector_c[$n]); unset($on_off_c[$n]); } if($projector_d[$n] == "XXX"){ unset($projector_d[$n]); unset($on_off_d[$n]); } if($projector_e[$n] == "XXX"){ unset($projector_e[$n]); unset($on_off_e[$n]); } } 星座絵がセレクトボックスで選択されている場合、各星座に対応した3文字のアルファベットがphp側に送信されるが、未選択の場合は\ ``XXX``\ を送るように割り当てている。 そこで、配列である\ ``$projector``\ と\ ``$on_off``\ の中から、\ ``XXX``\ に対応する部分を削除するためのコードが上記のコードである。 これで一応はちゃんと動くのだが、冒頭で触れた\ **大量のエラーの一番の原因**\ となっている部分でもある。もっと良い方法がある気がしてならないが、作成者の知識ではこれが限界だった。 on/off関連の配列作成 ^^^^^^^^^^^^^^^^^^^^ on/offラジオボタンの情報(0か1)は配列として格納しているが、実はこの情報は数値としての\ ``int型``\ ではなく、\ ``string型``\ として格納されている。これを、 .. code-block:: php $on_off_int_a = clone_int($on_off_a); ... function clone_int($array){ if(is_array($array)){ return array_map("clone_int",$array); }else{ return intval($array); } } と、上記の記述でint型の配列に作成しなおしている。 scinarioの中に入れる配列の作成とJSONの出力 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ここまでで\ ``scenario``\ に入れるデータの用意が全て終わったため、\ ``scenario``\ 以下の配列を作る。 .. code-block:: php $DATA_ARRAY["scenario"][$i]["projector"] = array_filter($DATA_ARRAY["scenario"][$i]["projector"],"strlen"); 上記の記述は\ ``projector``\ 内の空の要素を一括で削除するものである。 配列が出来上がったら、あとはJSONを出力するのみ。 .. code-block:: php $make = json_encode($DATA_ARRAY,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT); 上記の記述だけで、ここまで作ってきた配列($DATA_ARRAY)をJSONに変換して出力できる。後半は出力形式の指定なので、正直おまじないに近い。何か追加したい人は別途調べてみてほしい。 出来上がったJSONファイルは、 .. code-block:: php if($filename){ file_put_contents("scenario/".$filename.".json",$make); $result = file_get_contents("scenario/".$filename.".json"); } の記述により、\ **GRAFFASディレクトリ内の**\ ``GRAFFIAS/scenario``\ ディレクトリに、\ ``(ファイル名).json``\ の形式でJSONが出力される。最初の方にも書いたが、このままでは\ ``Acrab``\ から参照できないので注意。 実際に使う場合は、\ **ACRAB/scenarioディレクトリ内に、GRAFFIAS/scenarioディレクトリの中身をコピーして使う**\ こと。 .. _jsonリストの作成-1: JSONリストの作成 ^^^^^^^^^^^^^^^^ 全てのJSON作成が終わったら、\ ``Acrab``\ が参照できるJSONリストを、JSON形式で出力する。 .. code-block:: php if(isset($_POST['listmake'])){ foreach(glob("scenario/*.json") as $ListMake){ $FileList[] = $ListMake; } for($j=0;$j<count($FileList);$j++){ $FileListResult["scenariolist"][$j] = $FileList[$j]; } $FileListMake = json_encode($FileListResult,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT); file_put_contents("../scenario_list.json",$FileListMake); } 上記の記述により、「JSONリストの作成」を押すとJSONファイルの一覧をJSON形式で出力したものが\ **GRAFFIASディレクトリの1つ上のディレクトリ**\ 内に出力される。 今後の課題点 ------------ 知識0からのスタート&1週間弱で作ったプログラムなので、非常に課題点が多い。ここで挙げた点以外にも、何か気づくところあればどんどん修正なり、機能追加なりしてほしい。 よりよいものが作れそうであれば、もう原型残さず改造でいいレベルでもある。 - 使い始める前の、HTML部の書き換えが面倒。これをさくっと選択形式で直せるような仕様にすると後々楽かも…? - 現状指示書を作る機能しかないので、 Acrabの方でファイルを書き換える作業には非対応。ただ、GRAFFIASは色んな人にGRAFFIAS単体で渡して使ってもらうのを想定しているので、そこまで作成するなら別でAcrab用設定画面UIを作った方が便利な可能性は高い - 改行コードを一括削除する仕様にしたが、長いセリフが来ると読みにくい&ACRABのボタンレイアウトが崩れる。これはAcrabで時々指示書の表示チェックをしながら、AcrabのCSSも弄るのを考えておくといいかもしれない。 - **肝心の星座グループ指定が機能していない。**\ これはGRAFFIAS自体の問題ではないが、かなりの痛手である。原因はAcrabにあるのが分かっているので、是非本番までに直していただきたい。 - エラーがとにかく多い。これでどのような問題が発生しているかはよく分かっていないが、動作の遅さがどうしても気になるなら改善すべき…なのかもしれない。 <file_sep># 日周緯度変(外部制御アプリの歴史) - 書いた人: <NAME>(nichiden_27) - 更新日時: 2017/03/04 - 実行に必要な知識・技能: 特になし - 難易度: 2/少しやれば可能 - 情報の必須度: 2/知ってると楽 - 元資料 + `引き継ぎと技術的補足:日周緯度変外部制御ユーザインタフェース.docx` by 紺野雄介(nichiden_23) + `ふじさわreadme.docx` by 池下 氏(nichiden_24) + `25の日周・緯度変について.docx` by 伊藤太陽(nichiden_25) ## 概要 [日周緯度変(外部制御アプリ)](pc-software.html)から歴代外部制御アプリケーションの紹介を分離した記事です。 現在は実装されていない機能があったりと、それぞれに特徴があるので、把握しておくと今後の改善に繋がるかもしれません。 ## Tokyo Terminal(2012) ![Tokyo Terminalの画面](_media/tokyoterminal.png) 23代荒田氏が制作した。外部制御は23代で初使用されたが、`Tokyo Terminal`はそのテスト用に書かれたものである。 氏の環境がMac OSだったため、Macでしか動作しない。23代の作業データの`日周緯度変外部制御/Saitama6Brain/`以下にソースファイルやアプリ本体があるが、最新のMac OSでは対応していない旨が表示され起動しなかった。 これ以降の外部制御アプリは全てWindows向けに開発されたものだ。Mac向けに開発する必要に迫られることがもしあれば、`Tokyo Terminal`のコードが参考になるかもしれない(Mac開発の経験があれば一から書いた方が早い可能性も大いにあるが...)。 ## NisshuidohenController2(2012) ![NisshuidohenController2の画面](_media/nisshuidohencontroller2.png) 23代紺野氏の作。`Tokyo Terminal`がMac専用だったため、Windows版として開発された。開発言語はC#で、Windows Formアプリケーション(`System.Windows.Forms`名前空間を使用)である。 `Tokyo Terminal`と共通の機能が多いが、大きな違いは**操作の記録・再生ができる**ことである。「速度指定」か「角度指定」かを選択して「記録」ボタンを押すと右のスペースに送るコマンドが表示され、同時に`Instruction.txt`というファイルにも保存される。 あらかじめ必要なコマンドを記録しておいて面倒な操作なしに再実行できる画期的な機能である...と言いたいところだが、**表示されるのはコマンドだけ**(数値は16進数)なので、肝心の再生部分が手軽に利用できるとは言い難い。 「高速」「低速」のボタンで出る角速度は以下の数値に固定されている。なお、上半分で入力する角速度はモーターのもの、以下の角速度はギアによる減速後のかごしいのものなので注意。 - 日周高速ボタン: 4 deg/s - 日周低速ボタン: 1 deg/s - 緯度高速ボタン: 1 deg/s - 緯度低速ボタン: 0.5 deg/s この数値は後発の`Fujisawa`、`Chichibu`でも同じものが使われている。 当時の日周緯度変は相応のスキルのある日電員が操作しており、自分たちで使うための最小限の機能を盛り込んだという印象だ。実際、本番中に使用したのは「高速」などのボタンだけだったという。 将来これを使うことはなさそうだが、速度・角度・方向に対応するコマンドを表示してくれるので、デバッグ用の計算機にはなるかもしれない。 ## Fujisawa(2013) ![Fujisawaの画面](_media/fujisawa.png) 24池下氏によるもの。引き続きC#によるWindowsアプリだが、UIのフレームワークに`Windows Presentation Foundation(WPF)`を使用している。 WPFの詳細についてはググって欲しいが、デザインとコードを分けて書くことができるというのが大きな利点である。つまり、内部の動作を崩さずに見た目だけをいじり倒せるのだ。その甲斐あってか、23のUIに比べデザイン面が大きく改善した。コマンド文字列を生成するコードは`fujisawa/NisshuidohenController.cs`でクラスにまとめて定義されている。 日周緯度変にPCを使うとき、一番問題になるのは画面が光ることだ。PCは画面も大きいし、そのために星がかき消されてしまいかねない。`Fujisawa`は、**黒基調の画面**にすることでPCの光害を抑制している。 使い方は見れば分かると思うが、「びゅーん」が高速回転、「のろのろ」が低速回転だ。また、本番で画面を暗くしているとマウス操作が大変なので、日周はキーボードでも操作できる。`C`: 高速逆転、`V`: 低速逆転、`B`: 停止、`N`: 低速順回転、`M`: 高速順回転 である。 総じて24日電の雰囲気がよく出ており大変分かりやすいものの、回転方向が少し把握しにくい。なお、アプリ名称は往時の天文部の「備品などに駅名をつける」習慣に則ったもので、「ふじさわ」は制作者の地元であるらしい。 ## Chichibu(2014) ![Chichibuの画面](_media/chichibu.png) 25伊藤氏が開発したアプリ。他にない特色として、25ソフト専用のモードが用意され、ボタンを押すだけでシナリオで要求された動きを実現できることがある。 また、23の`NisshuidohenController2`と24の`Fujisawa`の画面もそのまま移植され、それぞれの機能が利用できる。本番でも、ライブ解説時には`Fujisawa`を使っていたようだ。 ![Chichibuに移植されたNisshuidohenController2](_media/chichibu_2.png) フルスクリーン状態で起動することで、以前より更に画面の光漏れを抑えている。ただし、ソフト内に終了ボタンがないうえタイトルバーも見えないので、プログラムを終了させる際は`Alt`+`F4`を押すなどショートカットキーを使うしかない。 ## Ogose(2016) ![Ogoseの画面(画像は28日電使用時)](_media/ogose.png) 27日電の伊東が開発した。これまでのUIの問題点を洗い出した上で、改善すべく様々な変更を加えている。デザイン部分(`MainWindow.xaml`)は一から作り直したが、コマンド文字列生成は`NisshuidohenController.cs`を継続使用した。 指定できる速度が各軸4段階に増えたことで、多彩な演出が可能となった。また、速度指定のボタンを回転スタート/ストップボタンとは別に用意したため、回転を止めずとも速度を変更できる。 ウィンドウモードとフルスクリーンモードをボタンで切り替えられる機能も実装した。また、フルスクリーンボタンの横にある「公演モード」ボタンは、使用できる機能を「日周進める」に限定し誤操作を防止する機能である。キーボード操作などにより意図しない状態になるバグが存在するので注意。 思いがけないことに、ボタンを十字に配置したことで、ゲームコントローラーのボタンと同様の配置となった。本番ではゲームコントローラーを実際に使用し、慣れていない人でも操作ができるという恩恵があった。 実装についてなど、詳細は[外部制御アプリの記事](pc-software.html)に示すこととする。 <file_sep># 日周緯度変(Ikebukuro) - 書いた人: <NAME>(nichiden_27) - 更新: <NAME>(nichiden_28) - 更新日時: 2018/08/26 - 実行に必要な知識・技能: 電子回路 - タスクの重さ: 2/数日かかる - タスクの必須度: 3/年による - 元資料 + `日周・緯度変資料.pdf` by 岩滝宗一郎(nichiden_22) + `saitama.pdf` by 荒田 実樹(nichiden_23) ## 概要 ![池袋](_media/ikebukuro.jpg) さいたま6號には、外部機器(PCなど)を接続して制御することが可能です。これをさいたまの「**外部制御**」と呼んでいます。 埼玉6號の外部制御端子は`RS-485/Mini-DIN6`という規格・形状ですが、残念ながらこのままではPCに直接挿して外部制御することはできません。そこで、`RS-485/Mini-DIN6`と`USB`の変換を行うために製作されたのが、**変換モジュール`Ikebukuro`**(埼玉と繋がっているかららしい...)です。 実際に日周緯度変を動かす際に関わりの多い部分なので、使い方や構造などを解説します。 ## 沿革 外部制御は、埼玉6號を製作した22代の時点で既に仕様に盛り込まれていた。ただし使用はされておらず、テストもされていない状態だった。続く23代で`Ikebukuro`が導入され、**PCを使用しての日周緯度変制御を初めて行った**。 その後の24〜27代では日周緯度変を操作するアプリの開発を行なっており、通信には`Ikebukuro`が使われ続けている。 ## 使い方 さいたま6號側面に通信用の端子(`Mini-DIN6`)があるので、ケーブルで`Ikebukuro`の同じ端子に接続する。次に、`Ikebukuro`のUSB端子(miniB)とPCのUSB端子をUSBケーブルで接続すれば準備完了である。 さいたま6號の外部制御スイッチをONにすれば、PCからの信号を待ち受ける状態になる。あとは日周緯度変用のアプリなどを起動してシリアルポートに接続すれば良い。 ## 電装 ### 通信方式 埼玉6號の外部制御端子は、電気的には`RS-485`という規格に従っている。 `RS-485`では、3本の線(A,B,GND)で半二重通信(双方向の通信ができるが、同時に両方向の通信は不可)ができる。ノイズに強く、長距離にも耐えられるらしい。 埼玉6號の側部にあるMini-DIN6コネクタのピンとの対応は、図のようになっている。 ![外部制御端子の配線](_media/ikebukuro-rs485.png) のはずなのだが、28代で中身を見たところ、この配線は実際のものと違うことが確認された。 作り直す際などはよく調べてほしい。 ### 内部基板 `Ikebukuro`の中身は単なる変換モジュールであり、`RS-485`と`UART`の変換を行うIC(`LTC485`)と、USBとUARTの変換を行うモジュール(`AE-UM232R`)が載っているだけである。 `AE-UM232R`に搭載されているUSB-UART変換チップ(FTDI社の`FT232R`という、定番チップ)の関係で、利用するにはPC側にドライバが必要な場合がある。[FTDI社のWebページ](http://www.ftdichip.com/Drivers/VCP.htm)から入手できるので、必要なら使用するPCにインストールしておこう。 自動インストールされることが多いようだが、手動でインストールする必要がある場合もある。 Ogoseでポートを選択できない場合はドライバがインストールできていないことが原因である可能性がある。 また、このチップは初期状態から設定が書き換えられており、`InvertRTS=1`となっている。この設計はFTDI社謹製の`FT_PROG`(Windows用)というツールで設定できる。 `RS-485`は半二重なので、通信方向の切り替えが必要である。これは、シリアルポートのRTSピンを使用して行っている。 `Ikebukuro`の基板の配線を図に載せる。なお、図には反映していないが、RTSの状態確認用にLEDを実装している。 ![Ikebukuro基板の配線](_media/ikebukuro-circuit.png) `AE-UM232R`はICソケットに差さっているので、容易に`Ikebukuro`から取り外すことができる。他の回路のテストでUSBシリアル変換モジュールを使いたい時は、`Ikebukuro`から`AE-UM232R`を取り外して使うと良いだろう(実際、23代で惑星投影機の基板のテストに利用した。最終的にはXBeeで通信するのだが、デバッグ時は「信頼と安定の」FT232Rを利用しようというわけだ)。 ただし、容易に取り外せるのは良いのだが、USBケーブルに変な力がかかると抜けてしまう可能性がある。 28代では1日目の最終公演後日周緯度変がPCから動かせなくなった。 原因はこのモジュールがソケットから外れかけていることであった。 PCと接続しているUSBケーブルに変な力がかかると抜ける可能性があるということを覚えておこう。 ## プロトコルとコマンド 外部制御モードではPCからさいたま6號に指令(コマンド)を送る。ここでは、コマンドを表す文字列のフォーマットを述べる。 このフォーマットを変更したいと思ったら、さいたま側のプログラムの`main.c`とPC側のプログラムをいじればよい。 ### 各コマンドに共通するフォーマット | 位置 | 0 | 1 | 2 | 3 | 4 | ... | |------ |----- |----- |-------- |------- |------- |----- | | 内容 | `$` | `W` | *addr* | *len* | *cmd* | ... | --- - *addr*: 機器のアドレス (16進1桁; ‘`0`’〜‘`9`’, ‘`A`’〜‘`F`’) - メイン基板上のディップスイッチで設定した値と一致させる - 現在は`0`が使われている - 複数の機器を繋いだ時用のアドレスだが、使うことはないだろう - *len*: 以降のバイト数 (16進1桁; ‘`0`’〜‘`9`’, ‘`A`’〜‘`F`’) - *cmd*: コマンドの種類 ### 速度指定コマンド | 位置 | ... | 3 | 4 | 5 | 6 | 7..10 | ... | |------ |----- |----- |----- |--------- |------- |--------- |----- | | 内容 | ... | `7` | `V` | *motor* | *dir* | *speed* | ... | --- - *len*: 以降のバイト数 = '`7`' (7 byte) - *cmd*: コマンドの種類 = '`V`' - *motor*: モーター (日周:‘`D`’, 緯度:‘`L`’) - *dir*: 回転方向 (時計回り:‘`+`’, 反時計回り‘`-`’) - *speed*: 回転速度[deg/s] (16進4桁; ‘`0`’〜‘`9`’, ‘`A`’〜‘`F`’) ### 角度指定コマンド | 位置 | ... | 3 | 4 | 5 | 6 | 7...12 | 13...16 | |------ |----- |----- |----- |--------- |------- |--------- |--------- | | 内容 | ... | `D` | `P` | *motor* | *dir* | *angle* | *speed* | --- - *len*: 以降のバイト数 = '`D`' (13 byte) - *cmd*: コマンドの種類 = '`P`' - *motor* モーター (日周:‘`D`’, 緯度:‘`L`’) - *dir* 回転方向 (時計回り:‘`+`’, 反時計回り‘`-`’) - *angle* 回転角度[`$10^{-2}$`deg] (16進6桁; ‘`0`’〜‘`9`’, ‘`A`〜‘`F`’) - *speed* 回転速度[deg/s] (16進4桁; ‘`0`’〜‘`9`’, ‘`A`’〜‘`F`’) ### コマンド実例集 以上がさいたま外部制御コマンドの仕様だが、これだけでは少々分かりにくいはずなのでいくつか実例を挙げておく。 - 緯度モーターを3000deg/sで時計回りに回す -> `$W07VL+0BB8` - 日周モーターを1800deg/sで時計回りに90000deg回す -> `$W0DPD+8954400708` ### PC側のプログラム PC側からは、Ikebukuroが仮想COMポートに見えるので、そのCOMポートに対して上に述べたコマンドを書き込めば良い。この辺りの具体的な話は[外部制御アプリの資料](pc-software.html)に譲る。 <file_sep>日周緯度変(外部制御アプリ) ========================== - 書いた人: <NAME>(nichiden_27) - 更新: <NAME>(nichiden_28) - 更新日時: 2018/10/08 - 実行に必要な知識・技能: シリアル通信、C# - タスクの重さ: 3/数週間 - タスクの必須度: 4/毎年やるべき 概要 ---- 日周緯度変の\ `外部制御 <ikebukuro.html>`__\ には、大きな可能性があります。PCを使える以上かなり複雑な操作も自動化できるためです。 ただし、本番で日周緯度変を動かすのは人間である部員たち。 それも、プログラムの挙動を知っている日電員だけが操作するとは限りません(26-28と、かごしいにも日周緯度変操作を手伝って貰っています)。 誰にでも使いやすい日周緯度変外部制御アプリを作るために注意すべきことを書きます。 沿革 ---- **過去に開発されたアプリケーションが多数にのぼるため、**\ `外部制御アプリの歴史 <pc-software-history.html>`__\ **に分離する。** Ogoseの特徴と使い方 ------------------- ``Ogose``\ は、27代日電で作成した、2017/03/01現在最新の外部制御アプリである。 特徴は\ `沿革 <pc-software-history.html>`__\ の方に文章で書いたので、ここでは簡単に箇条書きするにとどめる。 .. figure:: _media/ogose.png :alt: Ogoseの画面 Ogoseの画面 - 各軸4段階で速度を指定 - 回転中の速度変更が可能 - 回転の開始/停止はトグルボタン(押すたびにON/OFFが切り替わる) - フルスクリーン切り替えボタン - 誤操作防止用の「公演モード」 - メモ帳を表示・編集可能 - フリーソフトを使ってゲームコントローラに操作を割り当て可能 基本操作 ~~~~~~~~ 起動したら、まずは最上部からシリアルポートを選んで\ **接続ボタン**\ を押す。 さいたまを\ ``Ikebukuro``\ を介して繋いだだけの状態ならポートは一つしか出ないことがほとんどだが、複数出たとしても一つずつ試してモーターが動くかどうかで判断すればよい。 未接続のままコマンドを送る操作をした場合は、エラーメッセージとともに送信するコマンドが表示される。 接続していないことに気づけるようにする一方、わざと未接続にすることでコマンド送信のデバッグも可能だ。 実際に日周緯度変を動かすときは、左側と上側にある\ **速度切り替えボタン**\ から速度を選び、動かしたい方向のボタンをクリックする。 起動後に一度も速度を選んでいないときは、各軸とも「速い」速度が選択される。 回転開始ボタンは押すと「停止」に表示が切り替わり、再度押すと回転が停止する。 反対方向のボタンは「停止」するまでグレーアウトしてクリックに反応しない。これは、ボタンの表示がおかしくなるのを防ぐためである。 **フルスクリーンボタン**\ にチェックするとフルスクリーンになる。 画面全体が黒背景になるので、本番中はフルスクリーンが望ましい。 **公演モード**\ ボタンは、ONにすると警告が表示され日周を進めることしかできなくなる。 | 画面の右側には.txtファイルを表示する欄がある。あまり機会はないかもしれないが、Ogoseの画面上で編集して保存することも可能。新規作成はできない。 | 表示する.txtファイルは\ ``Ogose/Ogose/WorkInstructions``\ ディレクトリ内のものなので、.txtファイルの追加・削除・変更等はここから行えばよい。 | この.txtファイルはOgose操作時の指示書として使うことがほとんどだと思うので、本番前に忘れずに準備しておこう。 ``Ogose``\ のコードの解説は、たいへん長いので別記事とする。 -> `Ogoseの実装解説 <pc-software-code.html>`__ 通信プログラム -------------- シリアル通信の基本 ~~~~~~~~~~~~~~~~~~ `Ikebukuroの記事 <ikebukuro.html>`__\ にある通り、パソコン側からは\ ``Ikebukuro``\ はシリアルポートとして見える。 よって、シリアルポートにアクセスするプログラムを書けばよい。 ポート名は、Windowsであれば\ ``COM1``\ や\ ``COM4``\ のように、「‘``COM``’+数字」の形式である。 Mac OS XやLinuxのようなUNIX環境であれば、\ ``/dev/tty.usbserial-A5017ABT``\ である。 シリアルポートの設定は、さいたま6號側のプログラム中に記述してある設定と一致させなければならない。 現時点での設定は、 - baud rate: 2400 - parity: none - char bits: 8 - stopbit: 1 である。baud rateはこの値である必然性はないので、変えても良い(さいたま6號のプログラムも一緒に変更すること!)。 通信経路の途中で\ ``RS485``\ を使っている関係上、シリアルポートには読み取りと書き込みのいずれか一方しかできない。 ``RS485``\ の通信方向の切り替えには、シリアルポートのRTS端子を使う。 RTSが\ ``HIGH``\ になるとパソコン側から日周緯度変側への通信ができ、\ ``LOW``\ になると逆方向の通信ができる。 コマンドを送信する直前にRTSを\ ``HIGH``\ にし、終了したら\ ``LOW``\ に戻すといいだろう。 .Netでのシリアル通信 ~~~~~~~~~~~~~~~~~~~~ ``.Net Framework``\ を使う場合は、\ ``System.IO.Ports``\ 名前空間以下にある\ ``SerialPort``\ クラスを利用すると便利である。 Mac OS XやLinuxでは\ ``.Net``\ のオープンソース実装である\ ``Mono``\ を利用できるが、\ ``Mono``\ においても同様である。 以下ではC#のコード例を示す。 まず、ソースコードの冒頭に以下の文を書いておくと便利であろう: .. code-block:: c# using System.IO.Ports; 通信を開始する前に、まずポートを開く: .. code-block:: c# SerialPort port = new SerialPort( portName:portName, baudRate:2400, parity:Parity.None, dataBits:8, stopBits:StopBits.One ); port.Open(); この後、\ ``port.IsOpen``\ により、ポートを開くのに成功したか確認しておこう。 実際に通信するには\ ``SerialPort.Write``\ メソッドを使う。プログラムを終了する際には、\ ``port.Close()``\ によりポートを閉じておく。 他の言語でのシリアル通信 ~~~~~~~~~~~~~~~~~~~~~~~~ 日電では23からC#で外部制御アプリを開発してきたが、他の各種の言語でもシリアル通信を扱えるので記しておく。 - C, Lua: `librs232 <https://github.com/ynezz/librs232/>`__ - Lua: LuaSys - Python: `pySerial <http://pyserial.sourceforge.net/>`__ - Ruby: `ruby-serialport <http://ruby-serialport.rubyforge.org/>`__ - Java: Java Communications API / RXTX(Windows) - JavaScript(Node.js): `serialport <https://www.npmjs.com/package/serialport>`__ それぞれの使い方やインストール方法についてはググって欲しい。 仮想シリアルポート ~~~~~~~~~~~~~~~~~~ 開発中、きちんとコマンド文字列が送れているか確認したくなることがあるだろう。 **仮想シリアルポート**\ は、シリアルポートとして振る舞い、自分自身にデータを送信するループバックテストを可能にするソフトウェアだ。 Windows用だが、\ `com0com <https://sourceforge.net/projects/com0com/>`__\ を紹介する。 .. figure:: _media/com0com.png :alt: com0comの設定画面 com0comの設定画面 セットアップすると、互いに繋がった二つのCOMポートを用意してくれる。 番号は、他と被らないよう大きめにしておけば大丈夫だろう。 あとは、一方に作ったアプリから接続し、他方に\ ``Tera Term``\ などのターミナルソフトで接続すれば、送っている内容が見えるようになる。 今後の展望 ---------- GUIフレームワーク ~~~~~~~~~~~~~~~~~ 日周緯度変をある程度誰でも動かせるようにするには、GUIは欠かせない。 歴代日電では、GUI開発にWindows FormアプリケーションやWPFを用いてきた。 もちろん他にもGUIのフレームワークは山ほどあるが、時間も限られている以上、定番で枯れた技術を使っておくのが無難ではなかろうか。 一つの可能性としては、最近イケイケのWebアプリがある。 ChromeとJavaScriptをベースにデスクトップアプリを実現する\ ``Electron``\ など、ここ最近急速にシェアを伸ばしている技術もある。 もしあなたがそういった技術を得意としているなら、乗り換える価値はあるかもしれない。 入力機器 ~~~~~~~~ 本番でアプリの操作性にはまだまだ改善の余地がある。 暗い画面ですばやく操作をするには、マウスよりもキーボードがいいし、タッチパネルやゲームコントローラーといった馴染みのある操作系も役に立つだろう。 ゲームコントローラーは、27プラネではフリーソフトでキー操作と無理やり関連付けしたが、\ ``DirectInput``\ を使えば単体でも利用できる。 入力機器として完成されているし、操作に慣れている人も多いので、案外自前のボタン配置に凝るよりコスパがいいかもしれない。 .. figure:: _media/honban-nichiden.jpg :alt: 27本番の日周緯度変スタッフ席の様子 27本番の日周緯度変スタッフ席の様子 …28プラネでは、マウス操作一本に絞った。メモ帳をつけたために、キーやコントローラーの割り当てが難しくなったためである。 また、メモ帳を作ったことでボタン⇔メモ帳欄でのフォーカス変更が難しくなったのもある。キーボード、ゲームコントローラーを使いたい場合、このあたりの問題をクリアする必要が出てくるだろう。 マウスを使う場合、PCを操作する人の間で、本番ではマウスを誰が持ち込むかの割り当てを決めておいた方がいいだろう。 機能追加 ~~~~~~~~ 機能の追加案としては、\ **操作の記録・再生**\ が考えられる。 23や25で行ってきたことを発展させ、ボタン一つで一本のソフトをまるまる上映できるようになれば楽だろう。 ただし、当然ソフトの指示は毎年変わるので、開発の負担は増加する。 ライブ解説ではタイミングを人力で判断せねばならず、想定外の事態も起こりうる以上、全自動化への道は平坦ではない。 コストに見合うメリットが得られるような仕組みを、ぜひ考案してほしい。 メモ帳欄の改良 ~~~~~~~~~~~~~~ | 28でメモ帳の表示機能をつけてみたはいいものの、メモ帳を開くコンボボックスの表示がゴチャゴチャしてしまう点をどうしても解決できなかった。 また、メモ帳のレイアウトも、現状は取り敢えず右に置いてみただけとなっているので、さらに使いやすいレイアウト案があったら改良していってほしい。 また、28でOgoseを実際に使った人からは、メモ欄に原稿の抜粋ではなく、原稿を全部表示して、操作があるところだけ強調or改行を挟んではどうかという意見があった。 | 表示に使っているのがtxtファイルである以上、強調のためにハイライトを入れるのは難しいが、改行を挟むことや強調のための記号等を入れることくらいならささっとできるので検討してみてもいいかと思う。 <file_sep># 無線制御(Acrab) - 書いた人: <NAME>(nichiden_27) - 更新: Hanaka Satoh(nichiden_28) - 更新日時: 2017/05/06 - 実行に必要な知識・技能: Web制作、JavaScript - タスクの重さ: 3/数週間 - タスクの必須度: 4/毎年やるべき ## 概要 `Acrab`は、27代で開発した投影機無線操作用Webアプリケーションです。 最新のブラウザ(Chrome推奨)があれば、どんな環境でも使うことができます。 名称は、ブラウザで星座絵などを操れることからApplication for Constellation Remote controlling Assistance on Browserの頭文字をとりました。 さそり座β星の固有名でもあります。 ## 使い方 ### 下準備 まず、[Acrabの各種ファイル](https://github.com/Triangulum-M33/nichiden28/tree/master/ACRAB)を同じフォルダに配置する。 ファイルの読み込みにAjaxを使っているので、index.htmlをそのまま開いただけ(file:///)では機能が使えない。 回避方法は「Ajax ローカル」などとググれば複数出てくるが、ローカルにWebサーバを立てる方法を解説する。 Windowsでローカルホストを立てるには、[XAMPP](https://www.apachefriends.org/jp/index.html)を使うのが簡単だ。 GUIなので、操作も分かりやすいだろう。XAMPPの設定については[xamppでローカル作業環境構築をしよう](http://creator.aainc.co.jp/archives/6388)や[XAMPPで任意のディレクトリをバーチャルホストにする方法](https://qiita.com/nbkn/items/e72b283c54403a30b2e1)等が参考になるだろう。 MacならApacheが標準で入っているはずなので、`sudo apachectl start`を打てば`httpd`が動き出す。 設定については、ググれば役に立つ情報が得られる。 ### 起動と接続 localhostにアクセスすれば以下のような画面が表示されるはずだ。 もしボタンに日本語が表示されない場合、設定ファイルの読み込みに失敗しているので再読み込みすること。 ![Acrabのメイン画面(※画像は27代のもの)](_media/acrab-main.png) 次に、`Piscium`との接続を確認する。 `Piscium`の電源が入っていて、Wi-Fiネットワークに接続していれば、画面上の「受信状況」が緑色に変わるはずだ。 もし「接続なし」のままなら、PCと`Piscium`が同じLANに接続しているか(PCが別のルーターに接続してしまうミスは結構ある)、受信モジュールのIPアドレスが正しいかなどを確認しよう。 「受信状況」欄右の更新ボタンを押すと、`Piscium`へのリクエストが再送される。 無事接続できたら下に並ぶボタンを押して投影機をオンオフさせてみよう。 投影機を繋いでいなくても、コマンド自体は送ることができる。 `Piscium`から応答が来なかった場合はボタンの色が変わらないので、不具合に気づける。 ### 公演用画面 ソフトの指示を次へ・前へのボタンで実行できるモード。 画面上に「**公演用**」ボタンがあり、押すと画面が切り替わる。 ![Acrabの公演用画面](_media/acrab-scenario.png) 左上のメニューから番組名を選べるので、選んでから「**開始**」ボタンを押すと一番初めのコマンドが送信される。 下にタイミングが表示されるので、緑色の「**次へ**」ボタンを押して番組を進行する。 「**前へ**」ボタンでは、直前と逆の指示を送信できる。 「**Skip**」ボタンでは、番組は進行するが、指示は送信されない。番組進行者が「次へ」ボタンをうっかり押し忘れた時等に使う。 「開始」した後は左のボタンが「**停止**」「**再開**」に変化するが、これは右上のタイマーが止まるだけで深い意味はない。 「**リセット**」ボタンを押すと、タイマーと番組の進行状況が最初に戻る。 誤操作防止のため、「リセット」は「停止」状態でないとできない。 また、番組選択メニューは「リセット」しなければ操作できない。 ## プログラム `Acrab`はWebの技術を使って通信や画面表示を行っている。 画面の情報はHTML、デザインはCSS、内部処理や画面の書き換えはJavaScript(以下JS)という構成だ。 ### ファイル構成 以下のようなディレクトリ構成になっている。 ファイルを動かす際はリンク切れに注意すること。 ``` ACRAB ├── acrab_conf.json ├── img │   ├── acrab-banner.svg │   ├── main_01.png │   ├── main_02.png │   └── (省略) ├── index.html ├── js │   ├── acrab_main.js │   ├── acrab_scenario.js │   └── jquery-3.1.0.js ├── scenario │   ├── 0.json │   ├── 1.json │   ├── (省略) │   └── csv │   └── (省略) ├── style.css └── testscript.json ``` `index.html`がAcrabのメインページである。 デザイン関連の記述は`style.css`に分離した。 `acrab_conf.json`には、各種設定が格納されている。 `img/`以下にはページで使用した画像、`js/`以下にはJavaScriptのコードが入っている。 `scenario/`内は、番組の指示書を指定形式で入力したデータ。 ### 技術要素 #### HTMLとCSS 最近のWebアプリは、サーバ側でHTMLファイルを動的に生成して送ってくることが多い。 しかし、`Acrab`は**静的なHTMLファイルを準備し、クライアント(ブラウザ)側で書き換える**方式を採っている。 単に開発が楽であること、サーバ側で作業する必要がないこと、多数のユーザに後悔するような規模でないことがその理由である。 `Acrab`の**ページ構成**を変えたければ`index.html`を、**色やサイズ**なら`style.css`を編集すれば良い。 どちらもググれば分かる程度の機能しか使っていないつもりなので、Webの経験がなくても対応できるだろう。 それぞれの内容についてはここでは触れないが、JS部分と連動する箇所は都度解説する。 #### jQuery プログラムにはJSを用いていると書いたが、素のJSだけで書くと記述が長くなってしまう。 そこで、jQueryというライブラリを採用している。 動的なページの書き換えやAjaxによるファイル取得などを簡単に書けるようになり、コードを読みやすくできる。 近頃のWebアプリはサーバ側が急速に発展し、jQueryは不要な存在となりつつあるが、`Acrab`はクライアントサイドだけで動作する仕様のためあえて採用した。 数年前の流行りとはいえネット上に解説記事が充実しており、学習が容易であることも採用の理由だ。 jQueryは単一のjsファイルにまとめて配布されるので、最新版をダウンロードして`js/`内に入れておけば使えるようになる。 わざわざダウンロードしておくのは、ネットに接続できない本番ドーム内などでもjQueryを取得できるようにするため。 jQueryの機能は解説しないのでググって補完されたい。 `acrab_main.js`や`acrab_scenario.js`内に頻繁に登場する`$`という文字は、jQueryを呼び出すためのものである。 `$.(メソッド名)`といった形式で各種メソッドを使用できる。 #### JSON `Acrab`では、各種設定を個別ファイルに分離している。 投影する星座の名称を変えたい、指示書を編集したいと言った要求はいつ来てもおかしくない。 こうした変更に迅速に対応できるよう**JSON**形式の設定ファイルを読み込む方式とした。 JSON(JavaScript Object Notation)は、JavaScriptのオブジェクトの形式でデータを記述するものである。 「JavaScriptのオブジェクト」というのは配列や連想配列を入れ子にした構造を指す。 ```js { "hoge": [ 1, null ], "fuga": { "one": [ true, "tenmon" ], "two": "nichiden" } } ``` 上の例のように、項目にラベルを付ける、入れ子にするといったことが比較的シンプルな記述で可能になる。 また、オブジェクトなので`.`でラベル名を繋ぐだけでデータを取り出せる(例: `fuga.one[1]`は`"tenmon"`)。 文法がJavaScriptからの流用なので親和性がよく、読み込みが簡単なのも嬉しい。 ただ、文法がたいへん厳しくかつ目で眺めてもミスに気づきにくいので、パースエラーが出ないことを確かめてから使うよう心がけたい。 [JSONLint](http://jsonlint.com/)など、JSONの文法ミスを検出してくれるサービスが存在する。 また、`Acrab`では、JSON形式の指示書の一覧を`scenario_list.json`というJSONファイルにして、`ACRAB`ディレクトリ内に配置している。 これは、`Acrab_scenario.js`が指示書の個数やタイトルを読み込むのに必要なファイルであり、`GRAFFIAS`によって簡単に生成することができる。 ### 指示書の検討 PCで投影機を操作する場合、指示書の内容が表示されていると便利なのは言うまでもない。 しかし、コードに直接書き込むような方式では、翌年にはもう使えなくなってしまう。 そこで、`Acrab`が**外部の指示書ファイルを読み込む**方式を検討した。 #### 指示書をどう表現するか ソフトの指示書には様々な情報が書かれているが、主投影機に限れば必要な情報は - 順番 - セリフ - タイミング - 指示 + どの投影機を + 点灯する/消灯する となる。 一公演に対して普通は多数のセリフが存在し、また一つのセリフに複数の投影機への指示がつくこともある。 つまり、「番組」→「セリフ(タイミング)」→「指示」と**階層的に表現**できればとても嬉しい。 ソフトは指示書をExcel(xlsxファイル)で作成している。 xlsxファイルはかなり複雑で、プログラムから読むのは大変なので、テキスト形式のデータに変換したい。 エクセルならCSVが扱えるが、CSVは表形式のデータとなり階層構造が表現できない。 階層状にできるXMLかJSONのうち、XMLは扱いづらそうだったため**JSON**を採用した。 JSONならばJavaScriptの`Acrab`との親和性もある。 具体的にどのような構造のJSONかについては、ソースコード解説の記事にゆずる(概ね上の箇条書きの通りと思ってよい)。 #### エクセルからJSONデータへ 指示書のデータはソフトが持っているので貰ってくるとして、一発でJSONに変換できる訳ではない。 日本語の指示を**プログラム用の形式にする**作業が待っている。 とはいえ、JSONを手で書くのは非常に面倒で、しかもミスがあるとパースができない。 そこで28では`GRAFFIAS`という、JSON作成を補助するGUIを作成・使用した。 `GRAFFIAS`の使用法・解説については長くなるので、[GRAFFIASの記事](graffias.html)に分離する。 ### ソースコード解説 たいへん長くなるので、[Acrabの実装解説](acrab-code.html)に分離する。 ## 今後の展望 ### 既知の問題 #### 同時多数点灯対策でごちゃごちゃしている 27の本番近くになり、星座絵の突入電流で電源が不安定化するのを避けるため`each_slice()`や`sleep_ms()`を急遽追加した。 これでも動作はするが、こういった処理はマイコン側でする方が簡単である(sleep関数も用意されている)。 直前に追加したことでコードが読みにくくなっているので、**無線受信機側で小分けにして点灯**するような対策に切り替えるのが良いだろう。 #### 星座のグループが正しく点灯・消灯しない 28の公演中、公演用画面で夏の大三角・冬のダイヤモンドと言った星座グループについて点灯・消灯を指定してもこれが反映されない問題が発生した。 後にこれは`acrab_scenario.js`でのコードのミスだと判明したが、修正する時間が足りなかったのでJSONを書き換えて星座グループを使用しないことで無理矢理対応した。 詳しくは[Acrabの実装解説](acrab-code.html)で説明しているので、修正をお願いしたい。 #### 画面レイアウトの改善 28では、27に比べ表示する星座絵の数が増えたため、ボタンの幅を狭めるなどしてこれに対処したが、これを別PCの画面で見ると表示ずれが起きることがあった。 これはおそらくPCの画面サイズの違いが原因だと思われるので、余裕があれば他のPCでも表示テストをしてみるといいかもしれない。 また、「前へ」・「次へ」ボタンは中のテキストによって横幅が変わる仕様(`Flexbox`による)だが、これにより「次へ」ボタンの一部が画面からはみ出すことがある。 cssを調整する、`GRAFFIAS.php`を弄って改行コードを有効にする等して対応してほしい。(MacとWindowsでも表示異なる可能性あり…?要検証) Skipボタンについても、とりあえず「次へ」ボタンの右側に配置してみたが、本番で一度押し間違いがあったようなので配置を変更した方がいいかもしれない。(そもそも担当者が本番中に寝落ちしなければ不要説も…) 求むデザインセンス。 #### フルスクリーン機能について 28の公演中に`Acrab`画面外のアドレスバーの光が漏れていたことがあったので、プログラム的に弄るべきところはないがここに記載しておく。 `Acrab`は`Google Chrome`上で動かすことを前提としたアプリであるため、`Google Chrome`の**フルスクリーン**機能が使える。 Windowsでは`F11`、Macでは`shift+command+F`でフルスクリーンにできる。当日、公演用のPCを持ってきてくれた人に伝えておくといいだろう。 あと、`Acrab`はマウスを使うと操作しやすいので、誰がマウスを持ってくるかをちゃんと割り当てておこう。 ### 追加機能案 #### 設定画面の改善・機能追加 `Acrab`は、メンテナンス性・拡張性を高めるために各種設定をプログラムとは別のファイルに保存している。 しかし、設定ファイル自体の読み書きがプログラマにしかできないようでは、その変更は結局日電メンバの仕事となる。 そこで28日電では指示書のJSONファイル作成補助として`GRAFFIAS`を製作した。 ローカルにWebサーバを立てると、大体の場合**PHPも動く**ようになる。 PHPならサーバのファイルに書き込めるので、設定用のJSONファイルを読み込んで画面に表示し、修正して書き込むということが可能だ。 JSONの入出力については[PHPでJSONのデータを処理する方法](https://syncer.jp/how-to-use-json)など詳しい記事を参照のこと。 現状では指示書用JSONの作成補助と、作成したJSONファイルの一覧を作る機能しかない簡素なものだが、今後は、`acrab_conf.json`の書き換えにも対応した設定画面を作る、受信機や投影機の数の増減にも対応できるよう、行の追加・削除ができる表のような仕掛けを用意するなどしてもいい。 色々と工夫の余地がありそうなところだ。 #### デスクトップアプリ化 最近Web界で流行っている`Electron`という技術を使うと、Webの作法を使ってクロスプラットフォーム(Win/Mac/Linux)のアプリが組める。 `Acrab`は基本的にサーバサイドで処理をしないので、移植しようと思えばできるだろう。 Web技術が大好きor勉強してみたいのであれば、やってみてはいかがだろうか。 参考: [WebアプリをElectronに乗せる](https://www.slideshare.net/hiroyukianai/webelectron)<file_sep>テキストエディタを使ってみよう ============================== - 書いた人: <NAME>(nichiden_27) - 更新日時: 2017/04/26 - 実行に必要な知識・技能: 特になし - 難易度: 1/常識の範囲 - 情報の必須度: 3/必要な場合がある 概要 ---- コードや文章をたくさん書くようになると、テキストエディタにこだわりたくなってきます。 最近のエディタの特徴などについて書きます。 最近は複数OSで作業することも珍しくなくなってきたので、Windows/Mac OS X/Linuxのどれでも使えることを重視して紹介します。 Atom ---- `atom.io <https://atom.io>`__ `GitHub <https://github.com>`__\ が開発しているエディタ。 `PV <https://www.youtube.com/watch?time_continue=2&v=Y7aEiVwBAdk>`__\ が面白いのでぜひ観よう。 “A hackable text editor”と銘打っており、プログラマが\ **自由にカスタマイズして使える**\ ことを売りにしている。 とはいえ、標準の状態で既に使いやすいので、プログラマでなくともぜひ触れてみて頂きたい。 .. figure:: _media/atom.png :alt: Atomの画面例 Atomの画面例 Markdownの文書を書く場合、\ ``Ctrl(Cmd)+Shift+M``\ を押すと右に\ **プレビュー画面**\ を表示してくれる。 いわゆるWYSIWYG(表示と処理結果が一致)なエディタとして使用できるわけだ。 プレビューは編集内容に合わせてリアルタイムで更新される。 Markdown以外にも、プラグインを追加することで様々な言語のプレビューに対応できる。 使い勝手としてはほぼ不満のないAtomだが、\ **メモリを消費しすぎる**\ ことがある。 AtomはChromeのオープンソース版であるChromiumをベースに動いている。 このため本質的にはChromeが起動しているのと変わらず、”Atom Helper”なるプロセスがメモリを占有してしまうのだ。 重く感じたら、不要なファイルは閉じるなど対策しよう。 Markdown文書がある程度長い場合は、リアルタイムのプレビューを非表示にするのも効果がある。 Visual Studio Code(VSCode) -------------------------- `code.visualstudio.com <https://code.visualstudio.com>`__ Microsoft(MS)が開発しているエディタ。 MSは最近オープンソース化・クロスプラットフォーム化に舵を切っており、VSCodeも各OS向けに無償提供されている。 Atomより後発で、現在も開発が活発である。 最近のアップデートでAtomと遜色ない機能を備えてきており、Markdownプレビューももちろん可能。 .. figure:: _media/vscode.png :alt: Visual Studio Codeの画面例 Visual Studio Codeの画面例 また、Visual Studio譲りの超強力な補完機能である\ ``IntelliSense``\ をいくつかの言語で利用できる。 コーディングの機会が多い人にとっても有力な選択肢となりそうだ。 今後も、アップデートの度に新機能の追加が期待でき、さらに使い勝手が向上する可能性もある。 Atomを自力でカスタマイズしていくのが面倒に感じたら、VSCodeの豊富な機能を使いこなすのもいいかもしれない。 CUIエディタ ----------- CUIエディタを使う理由 ~~~~~~~~~~~~~~~~~~~~~ CUI(コマンドライン)のテキストエディタで有名なのは\ **VimとEmacs**\ だ。 この二つは宗教戦争的なネタにされがちだが、両者とも実用に足る機能を十分備えているからこそ「Vim派」や「Emacs派」が生まれるとも言える。 CUIエディタはキー入力のみで操作する必要があるのでとっつきにくいが、Vim/Emacs\ **いずれかの基本操作**\ くらいは覚えて損はないだろう。 ちょっとしたファイルの書き換えがしたい時など、ターミナルの画面を離れずに編集ができると効率がいい。 また、ssh接続してのリモート作業などでCUIしか触れなくても、VimやEmacsならほとんどの場合使用できる。 設定ファイル ~~~~~~~~~~~~ キーボードでの操作に慣れてくると、CUIエディタを好んで使うようになるかもしれない。 こうなるとデフォルトの設定では物足りないし、作業効率が悪い。 **設定ファイルやプラグイン**\ を使い、自分に合ったエディタにしてみよう。 Vimなら\ ``.vimrc``\ 、Emacsなら\ ``.emacs.el``\ というファイルをホームディレクトリに作ると読み込んでくれる。 ネットにオススメの設定がたくさん落ちているので、いいと思ったものを集めれば自分用設定の完成だ。 なお、起動中は変更しても反映されないので、コマンドで反映させるかエディタを再起動しよう。 `GitHub <https://github.com>`__\ などで自分の設定ファイルを管理しておくと、他の環境で作業する時でも設定を簡単に共有できる。 どこの環境でも自分好みの操作感をそのまま引き継げるのは、CUIテキストエディタの特権かもしれない。 <file_sep># 東京大学地文研究会天文部 日電引き継ぎ - 更新: 2017/03/04 <NAME>(nichiden_27) 日電の引き継ぎ文書です。ソースは全て公開しますので、ご自由に修正・追記してください。 ![Creative Commons Attribution-ShareAlike 3.0 Unported License](_media/88x31.png) ## 冒頭部の情報について 各資料の冒頭部分には、「書いた人」「更新日時」「実行に必要な知識・技能」「タスクの重さ or 難易度」「タスクの必須度 or 情報の必須度」といった項目が示されています。 ## 実行に必要な知識・技能 資料で解説しているタスクや知識を実践するのに必要な知識などです。 自分が理解できそうな資料を探したり、作業をするために何を身につけるべきか判断したりする際に参考にしてください。 ## タスクの重さ タスク関連の記事に付いています。 - 1: 数時間で可能 - 2: 数日かかる - 3: 数週間 - 4: 一月はかかる - 5: 準備だけで数ヶ月 の5段階です。作業計画を立てる際などにご覧ください。 ただし、各代の方針によって、個々のタスクの重さは変動することに注意しましょう。 ## 難易度 技術情報などをまとめた記事に付いています。 - 1: 常識の範囲 - 2: 少しやれば可能 - 3: 練習・勉強が必要 - 4: 分野に慣れてればできる - 5: 得意分野ならどうぞ 学んでおきたい分野の大枠を掴むのに利用してください。 ## タスクの必須度 タスク関連の記事に付いています。 - 1: よほど暇なら - 2: たまにやるべき - 3: 年による - 4: 毎年やるべき - 5: しないとプラネ終了 今年の日電で何をやるか決める手助けになるかもしれません。 ## 情報の必須度 技術情報などをまとめた記事に付いています。 - 1: 趣味レベル - 2: 知ってると楽 - 3: 必要な場合がある - 4: 担当者には必須 - 5: 全員必須 <file_sep>日周緯度変(Ogoseの実装解説) =========================== - 書いた人: <NAME>(nichiden_27) - 更新: <NAME>(nichiden_28) - 更新日時: 2018/10/08 - 実行に必要な知識・技能: Windows GUI開発、C#、WPF、Visual Studioの操作 - 難易度: 3/練習・勉強が必要 - 情報の必須度: 3/必要な場合がある 概要 ---- `日周緯度変(外部制御アプリ) <pc-software.html>`__\ から\ ``Ogose``\ の実装解説を分離した記事です。 ``Ogose``\ のソースコードを読む、あるいは書き換える際に参考にしてください。 ファイル構成 ------------ ``Ogose``\ のソースファイル等は、\ ``Ogose``\ フォルダ内に入っている。以下にファイル・ディレクトリ構成の抜粋を示す。 :: Ogose ├── Ogose │ ├── App.config │ ├── App.xaml │ ├── App.xaml.cs │ ├── MainWindow.xaml │ ├── MainWindow.xaml.cs │ ├── NisshuidohenController.cs │ ├── Ogose.csproj │ ├── Properties │ | └── (省略) │ ├── bin │ │ ├── Debug │ │ │ ├── Ogose.exe │ | │ └── (省略) │ │ └── Release │ │ ├── Ogose.exe │ | └── (省略) │ ├── main_projector_27_w.png │ └── obj │ └── (省略) └── Ogose.sln 一見複雑で身構えてしまうかもしれない。 ただ、\ ``Visual Studio(以下VS)``\ でプロジェクトを作成すると自動で生成されるファイルがほとんどで、実際に開発者が触るべきファイルは多くない。 ``Ogose``\ 直下には\ ``Ogose.sln``\ がある。これは「ソリューション(開発プロジェクトをまとめたもの)」の状態を管理している。 slnファイルをダブルクリックするか、VS内の読み込みメニューで選択してあげれば\ ``Ogose``\ の各ファイルを閲覧できる。 ``Ogose``\ の下に更に\ ``Ogose``\ ディレクトリがあり、この中にソースコードなどが収められている。 このうち、開発で実際に触ったのは\ ``App.xaml`` ``MainWindow.xaml`` ``MainWindow.xaml.cs`` ``NisshuidohenController.cs``\ の四つのみである。 ``Ogose/Ogose/bin/``\ 以下には、ビルドで生成された\ ``.exe``\ ファイルが格納される。 ``Debug``\ と\ ``Release``\ は適当に使い分ければいい。exeの他にも様々なファイルが吐き出されるが、基本的には\ ``Ogose.exe``\ 単体で動作する。 以下、ソースコードを簡単に解説する。WPF開発の基本的な知識全てに触れるとは限らないので、よく理解できない部分はググるなどして補完してもらいたい。 App.xaml -------- ``App.xaml``\ や\ ``App.xaml.cs``\ の内容は、GUIのみならずアプリケーション全体に適用される。 何も書かなくても問題ないが、\ ``Ogose``\ ではコントロールの外見に関する記述をこちらに分離した。\ `MainWindow.xaml <#mainwindow-xaml>`__\ が長くなりすぎないようにするのが目的である。 XAML(ざむる)は、XMLをベースとしたGUIの記述言語である。XMLのタグを用いて階層状に指示を書けるようになっている。 なお、\ ``<>``\ で囲まれた単位は「タグ」とも「要素」とも言うが、GUIの要素と混同する危険があるので、ここでは「タグ」に統一する。 ``<Application>``\ タグには色々とおまじないが書いてあるが、気にする必要はない。その下の\ ``<Application.Resources>``\ 内からがコードの本番だ。 ブラシ ~~~~~~ .. code-block:: xml <!-- App.xaml --> <SolidColorBrush x:Key="WindowBackground" Color="#FF111111"/> <SolidColorBrush x:Key="ButtonNormalBackground" Color="#AA444444"/> <SolidColorBrush x:Key="ButtonHoverBackground" Color="#FF334433"/> <SolidColorBrush x:Key="ButtonNormalForeground" Color="White"/> <SolidColorBrush x:Key="ButtonDisableBackground" Color="#AA222222"/> <SolidColorBrush x:Key="ButtonDisableForeground" Color="SlateGray"/> <SolidColorBrush x:Key="ButtonNormalBorder" Color="#FF707070"/> <LinearGradientBrush x:Key="TextBoxBorder" EndPoint="0,20" MappingMode="Absolute" StartPoint="0,0"> <GradientStop Color="#ABADB3" Offset="0.05"/> <GradientStop Color="#E2E3EA" Offset="0.07"/> <GradientStop Color="#E3E9EF" Offset="1"/> </LinearGradientBrush> **ブラシ**\ は、色などのデザインに名前(\ ``x:Key``)をつけて使い回せるようにしたものである。各色の役割が明確になるし、後からの変更も楽なので積極的に利用した。 ``SolidColorBrush``\ は単色のブラシ、\ ``LinearGradientBrush``\ はグラデーションのブラシである。 配色が気に入らなければ、ここの色指定を変えれば良い。 色は名称で指定しても良いし(\ `色一覧 <http://www.atmarkit.co.jp/fdotnet/dotnettips/1071colorname/colorname.html#colorsample>`__)、Webなどでお馴染みの16進数で更に細かく決めることもできる。 ここでは\ ``ARGB``\ というRGBに加えアルファ値(透過度)も指定する方式で書いているので注意。例えば\ ``#FF111111``\ なら、不透明で{R,G,B} = {17,17,17}の色を指す。 コントロールテンプレート ~~~~~~~~~~~~~~~~~~~~~~~~ **コントロールテンプレート**\ は、コントロール(ボタンやテキストエリアなど)のテンプレートである。 この中にボタンなどの見た目を書いておくと使い回しが効く。今あるコントロールテンプレートとその用途は以下の通り。 - “NormalToggleButton” … 日周緯度変回転用のトグルボタン - “ComboBoxToggleButton” … 接続するシリアルポートを選択するコンボボックス また、\ ``<ControlTemplate.Triggers>``\ タグ内で「トリガー」を指定できる。 トリガーは、特定のイベントが起きたら動的にコントロールの見た目を変更する機能だ。 マウスでポイントした時やクリックした時に色が変わると、操作の結果がユーザーに視覚的に伝わる。 .. code-block:: xml <!-- App.xaml --> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="true"> <Setter TargetName="InnerBackground" Property="Fill" Value="#FF222288" /> </Trigger> <Trigger Property="IsChecked" Value="true"> <Setter Property="Content" Value="停止" /> <Setter TargetName="InnerBackground" Property="Fill" Value="#FF111144"/> </Trigger> <Trigger Property="IsEnabled" Value="false"> <Setter TargetName="Content" Property="TextBlock.Foreground" Value="{StaticResource ButtonDisableForeground}" /> <Setter TargetName="InnerBackground" Property="Fill" Value="{StaticResource ButtonDisableBackground}" /> </Trigger> </ControlTemplate.Triggers> 例として、\ ``"NormalToggleButton"``\ のトリガー定義を紹介する。 マウスポインタが乗った時、Checked(ON)状態になった時でそれぞれ“InnerBackground”の色を変更するようになっている。 ``Property="IsEnabled"``\ は、ボタンが有効(=操作できる)かを示しており、これが\ ``false``\ の時は、文字・背景の色をグレー調にしてクリックできないことをアピールする。 スタイル ~~~~~~~~ **スタイル**\ には、要素の外観を定義できる。 前項のコントロールテンプレートに比べ機能が制限され、より個別の要素に対して用いる。 スタイルの適用の仕方はいくつかある。\ ``TargetType``\ **に要素の種類を入れると、同じ種類の要素全てに適用される**\ 。 以下は\ ``Window``\ の見た目を指定している例。 .. code-block:: xml <!-- App.xaml --> <Style TargetType="Window"> <Setter Property="Background" Value="{StaticResource WindowBackground}" /> <Setter Property="Height" Value="600" /> <Setter Property="MinHeight" Value="600" /> <Setter Property="Width" Value="700" /> <Setter Property="MinWidth" Value="700" /> </Style> ``<Setter>``\ タグはプロパティを操作するために使う。\ ``Property``\ にプロパティの名前、\ ``Value``\ に値を入れるだけである。 ``Value``\ は実際の値でもいいし、ブラシなど他で定義したリソースを与えてもよい。 ``<Setter>``\ の中には更に様々な機能を持ったタグを入れられる。\ ``<ControlTemplate>``\ が入っていることもあるし、\ ``<Style.Triggers>``\ タグでトリガーを設定することもできる。 複雑な使い方は筆者もよく把握していないので、頑張ってググって貰いたい。 もう一つのスタイル適用方法は、\ ``x:Key``\ **プロパティ**\ を用いることだ。\ ``<Style>``\ タグに\ ``x:Key="hogefuga"``\ のように分かりやすい名前をつけておく。 .. code-block:: xml <!-- App.xaml --> <Style x:Key="DiurnalPlusButton" TargetType="ToggleButton" BasedOn="{StaticResource ToggleButton}"> <Setter Property="Content" Value="日周戻す" /> <Setter Property="FontSize" Value="18" /> </Style> <Style x:Key="DiurnalMinusButton" TargetType="ToggleButton" BasedOn="{StaticResource DiurnalPlusButton}"> <Setter Property="Content" Value="日周進める" /> </Style> そして、適用したいボタンなどに\ ``Style="{StaticResource hogefuga}"``\ などと指定すれば該当する\ ``x:Key``\ を持つスタイルが適用される。 .. code-block:: xml <!-- MainWindow.xaml --> <ToggleButton x:Name="diurnalPlusButton" Style="{StaticResource DiurnalPlusButton}" Grid.Row="2" Grid.Column="0" Command="{x:Static local:MainWindow.diurnalPlusButtonCommand}" /> 上の\ ``App.xaml``\ のコードでは、\ **スタイルの継承**\ という機能も活用している。 ``BasedOn``\ プロパティに基にしたいスタイルの\ ``x:Key``\ を指定すると、そのスタイルの中身を引き継いだり、部分的に書き換えたりできる。 例えば、\ ``"DiurnalMinusButton"``\ スタイルは\ ``"DiurnalPlusButton"``\ スタイルを継承したので、\ ``FontSize``\ について再度記述する必要がない。 一方で、ボタンに表示する文字は変更したいので、\ ``Content``\ を書き換えている。 MainWindow.xaml --------------- メインのウィンドウの構造を記述する。 といっても\ ``Ogose``\ には一つしかウィンドウがないので、配置を変えたい場合はこれを編集すればいい。 UIのデザインについてもこの中に書けるが、たいへん長いので\ `App.xaml <#app-xaml>`__\ に移した。 編集方法について ~~~~~~~~~~~~~~~~ ウィンドウの見た目はXAMLのコードだけで自在に操れるが、VSではより便利に、実際の画面をプレビューしながらドラッグ&ドロップで編集することもできる。 .. figure:: _media/mainwindow-xaml.png :alt: Visual Studioの画面プレビュー編集 Visual Studioの画面プレビュー編集 GUIでの編集は手軽で初心者にも扱いやすいが、コードが自動生成されるので手で書くよりも読みにくくなりがちだ。 また、数値を細かく決めたい場合はコードを直接編集した方が早い。 図のように画面プレビューとコードは並べて表示できるので、双方の利点を使い分けるとよかろう。 グリッド ~~~~~~~~ WPFのレイアウト要素はいくつかあるが、\ ``Ogose``\ では\ ``<Grid>``\ タグを使ってレイアウトしている。 **グリッド**\ は、画面を格子状に分割してその中に要素を配置していくことができる。 いちいち行や列を定義せねばならず面倒だが、サイズを相対的に決められるので、ウィンドウを大きくしたときボタンも拡大されるというメリットがある。 .. code-block:: xml <!-- MainWindow.xaml --> <Grid x:Name="MainGrid"> <Grid.RowDefinitions> <RowDefinition Height="1*"/> <RowDefinition Height="30"/> <RowDefinition Height="40*"/> <RowDefinition Height="2*"/> <RowDefinition Height="1*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="1*"/> <ColumnDefinition Width="60*"/> <ColumnDefinition Width="20*"/> <ColumnDefinition Width="20*"/> <ColumnDefinition Width="1*"/> </Grid.ColumnDefinitions> <Grid x:Name="HeaderGrid" Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="3"> <Grid.ColumnDefinitions> <ColumnDefinition Width="9*"/> <ColumnDefinition Width="1*"/> <ColumnDefinition Width="13*"/> <ColumnDefinition Width="7*"/> </Grid.ColumnDefinitions> 上のコード片は、グリッドを定義している例である。 一意の\ ``x:Name``\ を付けて\ ``<Grid>``\ を宣言したら、\ ``<Grid.RowDefinitions>``\ で行を、\ ``<Grid.ColumnDefinitions>``\ で列を定義する。 グリッドの使い方 ^^^^^^^^^^^^^^^^ それぞれの中に行・列を欲しいだけ並べれば良いのだが、\ **高さや幅の指定**\ にポイントがある。 数値のみを書くとピクセル数を表すが、\ ``数値*``\ とすると相対サイズを表せるのだ。 例えば、\ ``Height="1*"``\ の行と\ ``Height="2*"``\ の行だけがある場合、グリッドは1:2の比率で分割される。 また、コード例では使っていないが\ ``Auto``\ を指定すると、中に配置した子要素のサイズに合わせてくれる。 ピクセル指定、相対指定、Auto指定は混ぜて書いても問題ない。 画面プレビューで行や列を分割した場合、サイズが単純な数値にならないので適宜コード側で修正するといいだろう。 **グリッドの中に要素を置く**\ 時は、画面プレビュー上で設置したい場所に動かすだけで良い。 ただし、グリッドは入れ子にすることもでき(コード例では\ ``MainGrid``\ の下に\ ``HeaderGrid``\ を入れてある)、意図した階層に置けないことも多々ある。 その場合は、望みの階層に要素の定義をコピペした上で、\ ``Grid.Row``\ と\ ``Grid.Column``\ プロパティに何行何列目かを指定する。 両プロパティは\ **0始まり**\ なので要注意。\ ``Grid.Row="1" Grid.Column="1"``\ なら2行2列目だ。 要素が横に長く、\ **複数の列に渡って配置**\ したいーそんな時は、\ ``Grid.RowSpan``\ や\ ``Grid.ColumnSpan``\ を使おう。 それぞれに指定した数だけ要素が占める場所が下方向・右方向に伸びる。 これは、画面プレビューで操作している時に勝手に追加されていることもあるので、やはりコード側で直してあげよう。 UI要素 ~~~~~~ 個別のUI要素については実際にコードを見ていただく方が早い。 ``Ogose``\ では\ ``ComboBox``\ 、\ ``ToggleButton``\ 、\ ``RadioButton``\ 、\ ``CheckBox``\ などを使い分けている。 それぞれの動作を規定するコードについては、\ `MainWindow.xaml.cs <#mainwindow-xaml-cs>`__\ の項で扱う。 少し説明が必要なのは、\ ``RadioButton``\ についてだ。 **ラジオボタン**\ というと、 :: ◎ 選択肢1 ◎ 選択肢2 のようなデザインが普通だ。 しかし、\ ``Ogose``\ では縦に並べたり横に並べたりするので、横の二重丸がなく/普通のボタンと同じ見た目で/全体がクリック可能 である方が都合がよい。 実は、これには複雑なコーディングは必要なく、トグルボタン用のスタイルを適用してやるだけで済む。 .. code-block:: xml <!-- App.xaml --> <Style TargetType="RadioButton" BasedOn="{StaticResource ToggleButton}"> これは、\ ``RadioButton``\ クラスが\ ``ToggleButton``\ クラスを継承しているため、共通のスタイル指定が使えることによる (参考にした記事: `RadioButtonなToggleButtonを実現する <http://neareal.net/index.php?Programming%2F.NetFramework%2FWPF%2FRadioToggleButton>`__)。 MainWindow.xaml.cs ------------------ ``MainWindow.xaml``\ のコードビハインドである。C#で書かれている。 日電のWindowsアプリケーションは代々C#なので、宗教上やむを得ない事情がなければC#を読み書きできるようになろう。 とはいえ、VSのコード補完(\ ``IntelliSense``)が凄く優秀なので、コードを書いていて苦労することはあまりなさそうだ。 筆者もC#経験はないが、言語使用についてはfor文を少しググったくらいで不便を感じることは少なかった。 コード中にやたら\ ``<summary></summary>``\ で囲まれたコメントを目にすると思うが、これはVSのドキュメント自動生成機能の推奨XMLタグらしい。 ドキュメントを作るかは別として、面倒でなければこの形式のコメントにして損はなさそうだ。 400行近いコードの全てを解説することはしないので、コードだけでは分かりにくいと思われる項目のみを以下に掲載する。 コマンド ~~~~~~~~ **コマンド**\ とは、ユーザの操作を抽象化したものである。 例えば、Wordで編集していてペースト操作をしたいとき、どうするか考えてみよう。 ショートカットキーを知っていれば\ ``Ctrl(Command)``\ +\ ``V``\ を叩くだろうし、右クリックしてペーストを選ぶ人もいるだろう。 メニューバーからペーストメニューを選択してもペーストできる。 操作はいろいろだが、結果として呼ばれる処理は同一なのだ。 この仕組みがコマンドで、WPFでは\ ``ICommand``\ というインターフェースで実現される。 無理にコマンドを使わずともアプリは作れるのだが、\ ``Ogose``\ のキーボード操作を実装する際、必要に迫られて導入した。 これまでと違い\ ``Ogose``\ の回転/停止ボタンはトグル式で、色やラベルが状態により変化する。 25までClickイベントを用いる方式では上手く行かなくなったのである(キー操作だと、外観を変えるべきボタンの名称を関数内で取得できないため…だった気がする)。 そこで、\ ``ICommand``\ を使うようにプログラムを書き直した。 時間がない中でやったので、かなり汚いコードになってしまった。 今後書き換える際はぜひ何とかして欲しい。 コマンドの使い方 ^^^^^^^^^^^^^^^^ コマンドは高機能の代わりに難解なので、使い始めるときは\ `この記事 <http://techoh.net/wpf-make-command-in-5steps/>`__\ あたりを参考にした。 まず、\ ``RoutedCommand``\ クラスを宣言する。絶賛コピペなので意味はよく知らない。 ``diurnalPlus``\ は日周を進めるという意味だ。 .. code-block:: c# /// <summary> RoutedCommand </summary> public readonly static RoutedCommand diurnalPlusButtonCommand = new RoutedCommand("diurnalPlusButtonCommand", typeof(MainWindow)); この状態ではまだコマンドとボタン・処理が結びついていない。 CommandBindingという操作でこれらを紐付けする。これもコピペ。 .. code-block:: c# /// <summary> /// MainWindowに必要なコマンドを追加する。コンストラクタで呼び出して下さい /// </summary> private void initCommandBindings() { diurnalPlusButton.CommandBindings.Add(new CommandBinding(diurnalPlusButtonCommand, diurnalPlusButtonCommand_Executed, toggleButton_CanExecuted)); /// (省略) } これをボタンの数だけ書き連ねる。 ``new CommandBinding()``\ に与えている引数は順に、コマンド・実行する関数・実行可能かを与える関数である。 三番目のコマンド実行可否は、コマンドを実行されては困る時のための仕組みだ。 .. code-block:: c# /// <summary> 各ボタンが操作できるかどうかを記憶 </summary> private Dictionary<string, bool> isEnabled = new Dictionary<string, bool>() { {"diurnalPlusButton", true}, {"diurnalMinusButton", true}, {"latitudePlusButton", true}, {"latitudeMinusButton", true} }; .. code-block:: c# private void toggleButton_CanExecuted(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = isEnabled[((ToggleButton)sender).Name]; } 上手い方法が全然思いつかなかったので、\ ``isEnabled``\ という連想配列を作っておいて、呼び出し元ボタンの名前をもとに参照するようにした。 呼び出し元は、引数\ ``sender``\ に与えられて、\ ``ToggleButton``\ など元々のクラスに型変換するとプロパティを見たりできる。 さて、\ ``private void initCommandBindings()``\ をプログラム開始時に実行しなければバインディングが適用されない。 ``MainWindow``\ のコンストラクタ内で呼び出しておく。 .. code-block:: c# public MainWindow() { InitializeComponent(); initCommandBindings(); } 考えてみれば大したことはしてないので、コンストラクタの中に直接書いてしまっても良かったかもしれない。 あとはXAML側でコマンドを呼び出せるようにするだけである。 ``<Window>``\ タグ内にローカルの名前空間(\ ``xmlns:local="clr-namespace:Ogose"``)がなければ追加しておこう。 各コントロールの\ ``Command``\ プロパティにコマンドをコピペする。 .. code-block:: xml <!-- MainWindow.xaml --> <ToggleButton x:Name="diurnalPlusButton" Style="{StaticResource DiurnalPlusButton}" Grid.Row="2" Grid.Column="0" Command="{x:Static local:MainWindow.diurnalPlusButtonCommand}" /> これでクリック操作でコマンドが使えるようになる。 キー操作でコマンドを実行する(※28日電では誤操作防止のため使用せず) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ここまできたら、キー操作でもコマンドが実行されるようにしたい。 XAMLで\ ``<KeyBinding>``\ タグを使えば実現できるのだが、なんとこれではボタンが\ ``sender``\ にならない。 色々調べても対処法が見つからないので、結局キー操作イベントから無理やりコマンドを実行させるしかなかった。 .. code-block:: c# private void Window_KeyDown(object sender, KeyEventArgs e) { var target = new ToggleButton(); switch (e.Key) { case Key.W: latitudePlusButtonCommand.Execute("KeyDown", latitudePlusButton); break; case Key.A: diurnalPlusButtonCommand.Execute("KeyDown", diurnalPlusButton); break; case Key.S: latitudeMinusButtonCommand.Execute("KeyDown", latitudeMinusButton); break; case Key.D: diurnalMinusButtonCommand.Execute("KeyDown", diurnalMinusButton); break; } ``(コマンド名).Execute()``\ メソッドの第一引数は\ ``ExecutedRoutedEventArgs e``\ の\ ``Parameter``\ 、第二引数は\ ``object sender``\ として渡される。 結局、\ ``sender``\ は第二引数に人力で指定した。 ``e.Parameter``\ というのは、仕様では「コマンドに固有の情報を渡す」とされていて、要は自由に使っていいようだ。 キーボード操作によるものかどうか、コマンドの処理で判定するために“KeyDown”という文字列(勝手に決めた)を渡している。 ※28代でメモ欄を設置したことにより、キー操作による誤操作の可能性が高まったことと、皆結局マウスで操作していることからいったん\ ``MainWindow.xaml``\ の\ ``Keydown``\ イベントを削除し、キー操作でのコマンド実行を無効にした。 コマンドで呼ばれる処理 ^^^^^^^^^^^^^^^^^^^^^^ 最後に、CommandBindingでコマンドと紐付けた関数について書く。 日周を進めるボタンのものは以下のようになっている。 .. code-block:: c# private void diurnalPlusButtonCommand_Executed(object sender, ExecutedRoutedEventArgs e) { if (e.Parameter != null && e.Parameter.ToString() == "KeyDown") { ((ToggleButton)sender).IsChecked = !((ToggleButton)sender).IsChecked; } if (sender as ToggleButton != null && ((ToggleButton)sender).IsChecked == false) { emitCommand(nisshuidohenController.RotateDiurnalBySpeed(0)); } else { emitCommand(nisshuidohenController.RotateDiurnalBySpeed(diurnal_speed)); } if (sender as ToggleButton != null) toggleOppositeButton((ToggleButton)sender); } どうしてこのような汚いコードになったのか弁解しておこう。 この関数は、三箇所から呼び出される可能性がある。 まず、対応するボタンがクリックされた場合。 クリックした時点でボタンの\ ``IsChecked``\ プロパティが反転するので、falseならモータを停止させ、trueなら動かせば良い。 ところが、キー操作イベントから呼ばれた場合、ボタンの状態は変わらない。 最初のif文で、\ ``e.Parameter.ToString() == "KeyDown"``\ であるときだけ、ボタンの\ ``IsChecked``\ を反転させることで対応した。 もう一つの可能性は、速度を切り替えたときだ。 日周の速度を管理している\ ``diurnalRadioButton``\ がクリックされたとき実行されるコードを見てみよう。 .. code-block:: c# private void diurnalRadioButton_Checked(object sender, RoutedEventArgs e) { var radioButton = (RadioButton)sender; if (radioButton.Name == "diurnalRadioButton1") diurnal_speed = SPEED_DIURNAL["very_high"]; else if (radioButton.Name == "diurnalRadioButton2") diurnal_speed = SPEED_DIURNAL["high"]; else if (radioButton.Name == "diurnalRadioButton3") diurnal_speed = SPEED_DIURNAL["low"]; else if (radioButton.Name == "diurnalRadioButton4") diurnal_speed = SPEED_DIURNAL["very_low"]; if (diurnalPlusButton.IsChecked == true) diurnalPlusButtonCommand.Execute(null, diurnalPlusButton); if (diurnalMinusButton.IsChecked == true) diurnalMinusButtonCommand.Execute(null, diurnalMinusButton); } 前半は、\ ``sender``\ がどの項目かによって速度を変更しているだけなので問題ないだろう。 後半で、「日周進める」か「日周戻す」がCheckedになっていれば、新しい設定をさいたまに送るためコマンドを実行している。 このときボタンの\ ``IsChecked``\ プロパティはすでにtrueなので、二重に変更されないよう\ ``e.Parameter``\ をnullとしている。 だが、考えてみればさいたまと通信さえすればいいので、\ **ボタンなど経由せず直接**\ ``emitCommand()``\ **(さいたまにコマンドを送る関数)を呼べばいいだけである。** 総じて、コマンドを使うことにこだわりすぎて酷いコードになってしまった。 バグの原因になっている可能性もあるので、後任の方は綺麗に書き直してやって頂きたい。 シリアル通信 ~~~~~~~~~~~~ ``MainWindow.xaml.cs``\ のうちシリアル通信に関する記述の大部分は、24の\ ``Fujisawa``\ から受け継いでいる。 この項では、通信を行うためのコードを読み、必要に応じて解説を加える。 ポート一覧の取得 ^^^^^^^^^^^^^^^^ .. code-block:: c# /// <summary> /// シリアルポート名を取得し前回接続したものがあればそれを使用 ボーレートの設定 /// </summary> /// <param name="ports[]">取得したシリアルポート名の配列</param> /// <param name="port">ports[]の要素</param> private void Window_Loaded(object sender, RoutedEventArgs e) { var ports = SerialPort.GetPortNames(); foreach (var port in ports) { portComboBox.Items.Add(new SerialPortItem { Name = port }); } if (portComboBox.Items.Count > 0) { if (ports.Contains(Settings.Default.LastConnectedPort)) portComboBox.SelectedIndex = Array.IndexOf(ports, Settings.Default.LastConnectedPort); else portComboBox.SelectedIndex = 0; } serialPort = new SerialPort { BaudRate = 2400 }; } | ``Window_Loaded``\ は、ウィンドウが描画されるタイミングで実行される。 | 処理としては、シリアルポート一覧を取得して\ ``portComboBox``\ に候補として追加し、さらに前回の接続先と照合するというものだ。 また、\ ``SerialPort``\ クラスのオブジェクト\ ``serialPort``\ を宣言し、ボーレートを2400に設定している。 foreach文の中で使用している\ ``SerialPortItem``\ は自作クラスで、\ ``ToString()``\ をオーバーライドしている。 何の為のものかは理解していないので、興味があればソースコードを確認してほしい。 ポートへの接続 ^^^^^^^^^^^^^^ 接続ボタンがクリックされると、\ ``ConnectButton_IsCheckedChanged()``\ が呼ばれる。 その中身はこうだ。 .. code-block:: c# /// <summary> /// PortComboBoxが空でなくConnectButtonがチェックされている時にシリアルポートの開閉を行う シリアルポートの開閉時に誤動作が発生しないよう回避している /// </summary> private void ConnectButton_IsCheckedChanged(object sender, RoutedEventArgs e) { var item = portComboBox.SelectedItem as SerialPortItem; if (item != null && ConnectButton.IsChecked.HasValue) { bool connecting = ConnectButton.IsChecked.Value; ConnectButton.Checked -= ConnectButton_IsCheckedChanged; ConnectButton.Unchecked -= ConnectButton_IsCheckedChanged; ConnectButton.IsChecked = null; if (serialPort.IsOpen) serialPort.Close(); if (connecting) { serialPort.PortName = item.Name; try { serialPort.WriteTimeout = 500; serialPort.Open(); } catch (IOException ex) { ConnectButton.IsChecked = false; MessageBox.Show(ex.ToString(), ex.GetType().Name); return; } catch (UnauthorizedAccessException ex) { ConnectButton.IsChecked = false; MessageBox.Show(ex.ToString(), ex.GetType().Name); return; } Settings.Default.LastConnectedPort = item.Name; Settings.Default.Save(); } ConnectButton.IsChecked = connecting; ConnectButton.Checked += ConnectButton_IsCheckedChanged; ConnectButton.Unchecked += ConnectButton_IsCheckedChanged; portComboBox.IsEnabled = !connecting; } else { ConnectButton.IsChecked = false; } } かなり長いが、順番に見ていこう。 最初のif文はポートが選択されているかチェックしているだけだ。 ``bool connecting``\ はポートを開くのか閉じるのかの分岐に使われている。 後はtry-catch文でポートを開き、エラーが出れば警告を出すのだが、このブロックの上下に変な記述がある。 .. code-block:: c# ConnectButton.Checked -= ConnectButton_IsCheckedChanged; ConnectButton.Unchecked -= ConnectButton_IsCheckedChanged; ConnectButton.IsChecked = null; /// (省略) ConnectButton.IsChecked = connecting; ConnectButton.Checked += ConnectButton_IsCheckedChanged; ConnectButton.Unchecked += ConnectButton_IsCheckedChanged; これはおそらくコメントの言う「シリアルポートの開閉時に誤動作が発生しないよう回避している」部分であろう。 ``MainWindow.xaml``\ の、\ ``ConnectButton``\ に関する部分を見てみよう。 .. code-block:: xml <!-- MainWindow.xaml --> <ToggleButton x:Name="ConnectButton" Checked="ConnectButton_IsCheckedChanged" Unchecked="ConnectButton_IsCheckedChanged" Margin="0"> ``Checked``\ と\ ``Unchecked``\ は、いずれもボタンがクリックされた時に発生するイベントだ。 ``ConnectButton.Checked -= ConnectButton_IsCheckedChanged;``\ などとしておくことで、ポートへの接続を試行している間ボタンのクリックを無効化しているようだ。 このコードを削除した状態でボタンを連打しても特に問題はなかったので効果のほどは分からないが、あっても害にはならないだろう。 ポート一覧の更新 ^^^^^^^^^^^^^^^^ ポート一覧のコンボボックスは、開くたびにシリアルポートを取得し直している。 ``portComboBox_DropDownOpened()``\ に処理が書かれているが、\ ``Window_Loaded()``\ と同じようなことをしているだけなので省略する。 コマンド送信 ^^^^^^^^^^^^ ``emitCommand()``\ は、コマンド文字列を与えて実行すると接続しているポートに送信してくれる。 ``serialPort.IsOpen``\ がfalseの時は、警告とともにコマンド文字列をMessageBoxに表示する。 .. code-block:: c# /// <summary> /// シリアルポートが開いている時にコマンドcmdをシリアルポートに書き込み閉じている時はMassageBoxを表示する /// </summary> /// <param name="cmd"></param> private void emitCommand(string cmd) { if (serialPort.IsOpen) { var bytes = Encoding.ASCII.GetBytes(cmd); serialPort.RtsEnable = true; serialPort.Write(bytes, 0, bytes.Length); Thread.Sleep(100); serialPort.RtsEnable = false; } else { MessageBox.Show("Error: コントローラと接続して下さい\ncommand: "+ cmd, "Error", MessageBoxButton.OK, MessageBoxImage.Warning); } } 公演モード(誤操作防止モード) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``checkBox2``\ は公演モードのON/OFFを管理している。 公演モードは、日周を進める以外の機能を制限して誤操作を防ぐ為のものだ。 一応28で目立ったバグは修正したつもりだが、何らかの不具合が確認された場合は適宜修正してもらいたい。 .. code-block:: c# private void checkBox2_Checked(object sender, RoutedEventArgs e) { var result = new MessageBoxResult(); result = MessageBox.Show("公演モードに切り替えます。\n日周を進める以外の動作はロックされます。よろしいですか?", "Changing Mode", MessageBoxButton.YesNo); if(result == MessageBoxResult.No) { checkBox2.IsChecked = false; return; } isPerfMode = true; List<string> keyList = new List<string>(isEnabled.Keys); // isEnabled.Keysを直接見に行くとループで書き換えてるので実行時エラーになる foreach (string key in keyList) { if(key != "diurnalMinusButton") isEnabled[key] = !isPerfMode; } latitudeRadioButton1.IsEnabled = latitudeRadioButton2.IsEnabled = latitudeRadioButton3.IsEnabled = latitudeRadioButton4.IsEnabled = !isPerfMode; notepadCombobox.IsEnabled = Savebutton1.IsEnabled = !isPerfMode; textBox1.Focusable = !isPerfMode; } private void checkBox2_Unchecked(object sender, RoutedEventArgs e) { var result = new MessageBoxResult(); result = MessageBox.Show("公演モードを終了します。", "Finish PerfMode", MessageBoxButton.OK); isPerfMode = false; List<string> keyList = new List<string>(isEnabled.Keys); // isEnabled.Keysを直接見に行くとループで書き換えてるので実行時エラーになる foreach (string key in keyList) { if (key != "diurnalMinusButton") isEnabled[key] = !isPerfMode; } latitudeRadioButton1.IsEnabled = latitudeRadioButton2.IsEnabled = latitudeRadioButton3.IsEnabled = latitudeRadioButton4.IsEnabled = !isPerfMode; notepadCombobox.IsEnabled = Savebutton1.IsEnabled = !isPerfMode; textBox1.Focusable = !isPerfMode; } 他の関数等で公演モードかどうかいちいち判定する必要が出てきたので、\ ``isPerfMode``\ というbool値に記録するようにした。 たいへん紛らわしいが、\ ``diurnalMinusButton``\ が「日周進める」ボタンである。 実機で運用した際に、かごしいの実際の動きを合わせてラベルだけ交換したため逆になっている。 28でもかごしいに合わせ何度かラベル交換したので、29のかごしいの動きではそれぞれのボタンを押したときにどのような動きをするのかしっかりと確認し、変更してほしい。 メモ帳機能 ~~~~~~~~~~ | ``notepadCombobox_DropDownOpened``\ は、メモ帳を読み込むときに使われる。コンボボックスを開いた時も閉じたときもこの処理が行われるようになっているが、 | この仕様のせいで妙に重い等の不具合がもしあれば修正したほうがいいのかもしれない。 | メモ帳に加えた変更の保存は、\ ``Savebutton1_Click``\ の方で行っている。 .. code-block:: c# private void notepadCombobox_DropDownOpened(object sender, EventArgs e) { var item = notepadCombobox.SelectedItem; notepadCombobox.SelectedIndex = -1; notepadCombobox.Items.Clear(); string[] files = Directory.GetFiles( @"..\..\WorkInstructions", "*.txt", SearchOption.AllDirectories); Array.Sort(files); foreach (var file in files) notepadCombobox.Items.Add(file); if (item != null) { textblock1.Text = Path.GetFileName(item.ToString()); notepadCombobox.SelectedIndex = Array.IndexOf(files, item.ToString()); using (FileStream fs = new FileStream(item.ToString(), FileMode.Open, FileAccess.ReadWrite)) { using (StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("shift_jis"), true)) { try { textBox1.Text = sr.ReadToEnd(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } } } | 構文は\ `こちらのリンク <https://divakk.co.jp/aoyagi/csharp_tips_using.html>`__\ を見て書いた部分が大きい。 読み込むファイルについては、\ ``Directory.GetFiles``\ を使って\ ``WorkInstructions``\ ディレクトリ内の.txtファイルを読み込むようにしている…のだが、 | そのファイルのパスがそのままコンボボックスに表示されてしまうため見栄えが悪い。28日電の知識ではどうにもならなかったが、修正できる人がいれば修正してほしいところだ。 NisshuidohenController.cs ------------------------- さいたまに送るコマンド文字列を生成するための\ ``NisshuidohenController``\ クラスが実装されている。 27では、24が書いたものをほぼそのまま利用した。 一点のみ、日周・緯度のギヤ比の換算もこちらでやってしまうように変更した。 これで、クラスの外側からはかごしいを回したい角速度(1 deg/sなど)を指定すればいいようになった。 使うだけなら\ ``RotateDiurnalBySpeed()``\ や\ ``RotateLatitudeBySpeed()``\ をブラックボックスとして利用するだけでいいだろう。 ただし、23や25が使っていた角度指定メソッドは残してあるだけで一切触っていないので、使いたい場合はしっかりデバッグしてほしい。
8fd1450d019294084a49f8d5d3772ae07e1c5858
[ "Markdown", "HTML", "reStructuredText", "Shell" ]
54
Markdown
kadostar/29nichiden-handover
8734a9ba423655e0064ad0bb637019138175dbd6
0578c544f2585cab820c453b4dbe507fd5f9c1e9
refs/heads/master
<file_sep><?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class Chitietphieunhap extends Authenticatable { use Notifiable; protected $primaryKey = 'MaSP'; protected $table = 'ctphieunhap'; public $timestamps = false; } <file_sep><?php include("connect.php"); ?> <!DOCTYPE html> <html lang="en"> <head> <!-- start: Meta --> <meta charset="utf-8"> <title>Đơn hàng</title> <meta name="description" content="Bootstrap Metro Dashboard"> <meta name="author" content="<NAME>"> <meta name="keyword" content="Metro, Metro UI, Dashboard, Bootstrap, Admin, Template, Theme, Responsive, Fluid, Retina"> <!-- end: Meta --> <!-- start: Mobile Specific --> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- end: Mobile Specific --> <!-- start: CSS --> <link id="bootstrap-style" href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/bootstrap-responsive.min.css" rel="stylesheet"> <link id="base-style" href="css/style.css" rel="stylesheet"> <link id="base-style-responsive" href="css/style-responsive.css" rel="stylesheet"> <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800&subset=latin,cyrillic-ext,latin-ext' rel='stylesheet' type='text/css'> <!-- end: CSS --> <!-- The HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <link id="ie-style" href="css/ie.css" rel="stylesheet"> <![endif]--> <!--[if IE 9]> <link id="ie9style" href="css/ie9.css" rel="stylesheet"> <![endif]--> <!-- start: Favicon --> <link rel="shortcut icon" href="img/favicon.ico"> <!-- end: Favicon --> </head> <body> <div class="row-fluid sortable"> <div class="box span12"> <table class="table table-bordered"> <thead> <tr> <th>STT</th> <th>Họ Và Tên</th> <th>Ngày Đăng Ký</th> <th>Vai Trò</th> <th>Ghi Chú</th> </tr> </thead> <tbody> <?php $qr="SELECT * FROM nguoidung"; $rs=mysqli_query($con,$qr); $tinhtrang=""; $i=0; while($row=mysqli_fetch_array($rs)){ $i=$i+1; switch ($row['Quyen']) { case '1': $tinhtrang="Khách Hàng"; break; case '2': $tinhtrang="Nhân Viên"; break; case '3': $tinhtrang="Quản Lý"; break; default: $tinhtrang="Khách Hàng"; break; } echo" <tr> <td class='center'>{$i}</td> <td>{$row['HoTen']}</td> <td class='center'>{$row['ngDK']}</td> <td class='center'>{$tinhtrang}</td> <td class='center'></td> </tr>"; } ?> </tbody> </table> </div> </div><!--/span--> </body> </html><file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Project; use App\SanPham; use App\Nhacungcap; use App\Loaihang; use App\Donhang; use App\Chitietdonhang; use DB,Cart; use Auth; use App\Taikhoan; class WelcomeController extends Controller { public function index(){ $product=DB::table('sanpham')->select('MaSP','TenSP','DonGia','Sluongcon','ManhaCC','MaLoai','Ram','img','vga','hedieuhanh','giakm','cpu','baohanh','mota','chuthich')->orderBy('MaSP','DESC')->paginate(9); $moinhat=DB::table('sanpham')->select('MaSP','TenSP','DonGia','Sluongcon','ManhaCC','MaLoai','Ram','img','vga','hedieuhanh','giakm','cpu','baohanh','mota','chuthich')->orderBy('MaSP','DESC')->take(3)->get(); // $banchay = // DB::table('sanpham') // ->whereExists(function($query) // { // $query->select(DB::raw('sum(Soluong) as Soluong' ) // ->from('chitietdh') // ->whereRaw('sanpham.MaSP = chitietdh.MaSP' // ) // ->groupBy('Soluong') // }) // ->get(); $banchay = DB::table('sanpham')->select('MaSP','TenSP','DonGia','Sluongcon','ManhaCC','MaLoai','Ram','img','vga','hedieuhanh','giakm','cpu','baohanh','mota','chuthich','Sluongban')->orderBy('Sluongban','DESC')->take(3)->get(); return view('user.index',compact('product','moinhat','banchay')); } public function loaisanpham($id){ $product=DB::table('sanpham')->select('MaSP','TenSP','DonGia','Sluongcon','ManhaCC','MaLoai','Ram','img','vga','hedieuhanh','giakm','cpu','baohanh','mota','chuthich')->orderBy('MaSP','DESC')->skip(0)->take(4)->get(); $loaisanpham=DB::table('sanpham')->select('MaSP','TenSP','DonGia','Sluongcon','ManhaCC','MaLoai','Ram','img','vga','hedieuhanh','giakm','cpu','baohanh','mota','chuthich')->where('MaLoai',$id)->get(); return view('user.loaisanpham',compact('product','loaisanpham')); } public function chitietsanpham($id){ $product=DB::table('sanpham')->select('MaSP','TenSP','DonGia','Sluongcon','ManhaCC','MaLoai','Ram','img','vga','hedieuhanh','giakm','cpu','baohanh','mota','chuthich')->orderBy('MaSP','DESC')->skip(0)->take(4)->get(); $loaisanpham=DB::table('sanpham')->select('MaSP','TenSP','DonGia','Sluongcon','ManhaCC','MaLoai','Ram','img','vga','hedieuhanh','giakm','cpu','baohanh','mota','chuthich')->where('MaLoai',$id)->get(); $chitiet=DB::table('sanpham')->select('MaSP','TenSP','DonGia','Sluongcon','ManhaCC','MaLoai','Ram','img','vga','hedieuhanh','giakm','cpu','baohanh','mota','chuthich')->where('MaSP',$id)->first(); return view('user.chitietsanpham', compact('product','chitiet','loaisanpham')); } public function muahang($id){ $muahang=DB::table('sanpham')->where('MaSP',$id)->first(); Cart::add(array('id'=>$id,'name'=>$muahang->TenSP,'qty'=>1,'price'=>$muahang->DonGia, 'options' => ['img' => $muahang->img])); // $content=Cart::content(); // print_r($content); $a= return redirect()->route('CHshop'); } public function giohang(){ $content=Cart::content(); $tongtien=Cart::total(); return view('user.giohang',compact('content','tongtien')); } public function xoasanpham($id){ Cart::remove($id); return redirect()->route('giohang'); } public function tinhtien( Request $request){ if(Cart::count()==0){ echo "<script> alert('Giỏ hàng của bạn đang trống, hãy chắc là bạn đã mua hàng'); window.location='". route('CHshop') ."' </script>"; } else{ if(Auth::check()){ $donhang = new Donhang; $tongtien=Cart::total(); $content=Cart::content(); $mand=Auth::user(); date_default_timezone_set("Asia/Ho_Chi_Minh"); $now = getdate(); $currentDate = $now["mday"] . "/" . $now["mon"] . "/" . $now["year"]; $donhang->MaND=$mand->MaND; $donhang->NgDat=$currentDate; $donhang->TenKH=$request->ten; $donhang->DiaChiGH=$request->diachi; $donhang->sdt=$request->sdt; $donhang->email=$request->email; $donhang->TinhTrang=1; $donhang->Tongtien=$tongtien; $donhang->save(); $zz=Cart::content(); $cc= DB::table('donhang')->orderBy('MaDH','DESC')->first(); $aa= $cc->MaDH; foreach ($zz as $t) { $chitiet=new Chitietdonhang; $chitiet->MaDH=$aa; $chitiet->MaSP=$t->id; $chitiet->GiaSP=$t->price; $chitiet->Soluong=$t->qty; $chitiet->save(); $cc2=SanPham::find($t->id); $cc2->Sluongban=$cc2->Sluongban+ $t->qty; $cc2->save(); } Cart::destroy(); echo "<script> alert('Cảm ơn bạn đã tin tưởng mua hàng của cửa hàng chúng tôi, đơn hàng của bạn sẽ đưọc gửi đi trong thời gian sớm nhất, trong khi đó sẽ có nhân viên gọi đến bạn để xác thực việc bạn có mua hàng hay không, Cảm ơn bạn'); window.location='". route('CHshop') ."' </script>"; } else{ echo "<script> alert('Bạn cần đăng nhập để có thể mua hàng'); window.location='". route('dangnhap1') ."' </script>"; } } } public function getDangnhap(){ return view('user.dangnhap'); } public function postDangnhap( Request $request){ $login=array( 'TaiKhoan'=>$request->TaiKhoan, 'password'=>$request->password, ); if(Auth::attempt($login)){ return redirect('CHshop')->with('users',Auth::user()); }else{ return redirect()->back(); } } Public function logout() { Auth::logout(); return redirect('CHshop'); } public function getdangki(){ return view('user.dangki'); } public function postdangki( Request $request){ if(!empty($request->tk) || !empty($request->mk)){ $tao= new Taikhoan(); $tao->HoTen=$request->ten; $tao->Gioitinh=$request->gt; $tao->DiaChi=$request->dc; $tao->SDT=$request->sdt; $tao->level=2; $tao->TaiKhoan=$request->tk; $tao->password=$request->mk; $tao->save(); return redirect('CHshop'); }else{ return redirect('dangki'); } } public function getthongtin(){ $thongtin = Auth::user(); return view('user.capnhattaikhoan' ,compact('thongtin')); } public function postthongtin( Request $request){ $thongtin = Auth::user(); $matk = $thongtin->MaND; $sua = Taikhoan::find($matk); $sua->HoTen=$request->HoTen; $sua->Gioitinh=$request->GioiTinh; $sua->DiaChi=$request->DiaChi; $sua->TaiKhoan=$request->TaiKhoan; $sua->password=$request->password; $sua->save(); return redirect('CHshop'); } public function getdonhangcu(){ $thongtin = Auth::user(); $matk = $thongtin->MaND; $data=DB::table('donhang')->where('MaND',$matk)->get(); return view('user.danhsachdonhangnv', compact('data')); } public function postdonhangcu($id){ $user=Donhang::find($id); $cc=$user->TinhTrang; if($cc==4){ echo "<script> alert('Xin lỗi, bạn không thể xóa được đơn hàng đã thanh toán'); window.location='". route('donhangcu') ."' </script>"; } else{ $capnhat=DB::table('chitietdh')->select('MaSP','MaDH','Soluong')->where('MaDH',$id)->get(); foreach($capnhat as $cc){ $bb= $cc->MaSP; $hh=$cc->Soluong; $aa=SanPham::find($bb); $aa->Sluongcon=$aa->Sluongcon+$hh; $aa->save(); $cc2=SanPham::find($bb); $cc2->Sluongban=$cc2->Sluongban - $hh; $cc2->save(); } $user->delete(); return redirect('donhangcu'); } } public function capnhat(){ if(request()->ajax()){ $id=Request()->get('id'); $qty = Request()->get('qty'); $maosp=Request()->get('maosp'); $data=DB::table('sanpham')->where('MaSP',$maosp)->first(); $aa=$data->Sluongcon; if($qty>$aa){ } else{ Cart::update($id,$qty); echo "oke";} } } public function timkiem( Request $request){ $tk = $request->input('timkiem'); $aa = DB::table('sanpham')->where('TenSP','LIKE','%'.$tk.'%')->get(); // $aa=SanPham::where('TenSP','LIKE','%$tk%')->first(); $moinhat=DB::table('sanpham')->select('MaSP','TenSP','DonGia','Sluongcon','ManhaCC','MaLoai','Ram','img','vga','hedieuhanh','giakm','cpu','baohanh','mota','chuthich')->orderBy('MaSP','DESC')->take(3)->get(); return view('user.timkiem',compact('aa','moinhat')); } public function motrieu(){ $product=DB::table('sanpham')->select('MaSP','TenSP','DonGia','Sluongcon','ManhaCC','MaLoai','Ram','img','vga','hedieuhanh','giakm','cpu','baohanh','mota','chuthich')->where('DonGia','>=','1000000')->where('DonGia','<=','2000000')->orderBy('MaSP','DESC')->paginate(9); $moinhat=DB::table('sanpham')->select('MaSP','TenSP','DonGia','Sluongcon','ManhaCC','MaLoai','Ram','img','vga','hedieuhanh','giakm','cpu','baohanh','mota','chuthich')->orderBy('MaSP','DESC')->take(3)->get(); $banchay = DB::table('sanpham')->select('MaSP','TenSP','DonGia','Sluongcon','ManhaCC','MaLoai','Ram','img','vga','hedieuhanh','giakm','cpu','baohanh','mota','chuthich','Sluongban')->orderBy('Sluongban','DESC')->take(3)->get(); return view('user.motrieu',compact('product','moinhat','banchay')); } public function haitrieu(){ $product=DB::table('sanpham')->select('MaSP','TenSP','DonGia','Sluongcon','ManhaCC','MaLoai','Ram','img','vga','hedieuhanh','giakm','cpu','baohanh','mota','chuthich')->where('DonGia','>=','2000000')->where('DonGia','<=','3000000')->orderBy('MaSP','DESC')->paginate(9); $moinhat=DB::table('sanpham')->select('MaSP','TenSP','DonGia','Sluongcon','ManhaCC','MaLoai','Ram','img','vga','hedieuhanh','giakm','cpu','baohanh','mota','chuthich')->orderBy('MaSP','DESC')->take(3)->get(); $banchay = DB::table('sanpham')->select('MaSP','TenSP','DonGia','Sluongcon','ManhaCC','MaLoai','Ram','img','vga','hedieuhanh','giakm','cpu','baohanh','mota','chuthich','Sluongban')->orderBy('Sluongban','DESC')->take(3)->get(); return view('user.motrieu',compact('product','moinhat','banchay')); } public function batrieu(){ $product=DB::table('sanpham')->select('MaSP','TenSP','DonGia','Sluongcon','ManhaCC','MaLoai','Ram','img','vga','hedieuhanh','giakm','cpu','baohanh','mota','chuthich')->where('DonGia','>','3000000')->orderBy('MaSP','DESC')->paginate(9); $moinhat=DB::table('sanpham')->select('MaSP','TenSP','DonGia','Sluongcon','ManhaCC','MaLoai','Ram','img','vga','hedieuhanh','giakm','cpu','baohanh','mota','chuthich')->orderBy('MaSP','DESC')->take(3)->get(); $banchay = DB::table('sanpham')->select('MaSP','TenSP','DonGia','Sluongcon','ManhaCC','MaLoai','Ram','img','vga','hedieuhanh','giakm','cpu','baohanh','mota','chuthich','Sluongban')->orderBy('Sluongban','DESC')->take(3)->get(); return view('user.motrieu',compact('product','moinhat','banchay')); } public function chitietdonhangcu($id){ $ten = Auth::user(); $sua = Donhang::find($id); return view ('user.chitietdonhangcu',compact('sua','ten')); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use App\Http\Requests\CateRequest; use App\Http\Controllers\Controller; use App\Project; use App\SanPham; use App\Nhacungcap; use App\Loaihang; use App\Taikhoan; use Auth; class LoaihangController extends Controller { public function getList(){ $data= Loaihang::paginate(5); return view('admin.loaihang',compact('data')); } public function getDelete($id){ $cate=Loaihang::find($id); $sanpham=DB::table('sanpham')->select('MaLoai')->where('MaLoai',$id)->first(); if($sanpham==null){ $cate->delete(); return redirect('admin/loaihang/list'); } else{ echo "<script> alert('Xin lỗi, bạn không thể xóa do danh mục này vì danh mục đã có bên bản sản phẩm, để xóa đưọc bạn cần xóa sản phẩm bên kia rồi mới xóa đưọc'); window.location='". route('admin.loaihang.getList') ."' </script>"; } } public function getAdd(){ return view('admin.adloaihang'); } public function postAdd(CateRequest $request){ $sanpham= new Loaihang; $sanpham->TenLoai=$request->TenLoai; $sanpham->mota=$request->MoTa; $sanpham->save(); return redirect('admin/loaihang/list'); } public function getEdit($id){ $sua=TaiKhoan::Loaihang($id); return view ('admin.suataikhoan',compact('sua')); } public function postEdit( $id,CateRequest $request){ $sanpham= Taikhoan::find($id); $sanpham->HoTen=$request->HoTen; $sanpham->Gioitinh=$request->Gioitinh; $sanpham->SDT=$request->SDT; $sanpham->email=$request->email; $sanpham->password=<PASSWORD>($request->password); $sanpham->TaiKhoan=$request->TaiKhoan; $sanpham->level=$request->level; $sanpham->DiaChi=$request->DiaChi; $sanpham->save(); return redirect('admin/nguoidung/list'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Auth; class authController extends Controller { Public function getLogin() { if(!Auth::check()){ return view('form'); }else{ return redirect('user'); } } Public function getadmin() { if(!Auth::check()){ return view('form'); }else{ return view('admin',['user'=>Auth::user()]); } } Public function postadmin(Request $request) { $user = [ 'name' => $request->input('name'), 'password' => $request->input('password'), ]; if(Auth::attempt($user)){ return view('admin',['user'=>Auth::user()]); }else{ return redirect('form')->with('error','Login False'); } } Public function logout() { Auth::logout(); return redirect('form'); } } <file_sep><?php $server=$_SERVER['SERVER_NAME']; $user='root'; $pass=''; $db='dacn'; $con=mysqli_connect($server,$user,$pass,$db) or die("connect fail"); mysqli_query($con,"SET NAMES 'utf8'"); ?><file_sep><?php namespace Tests\Unit\Http\Controllers; use Tests\TestCase; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; use App\User; use App\Http\Requests; use Auth; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Foundation\Auth\AuthenticatesUsers; use DB,Cart; use App\Taikhoan; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\WithoutMiddleware; class WelcomeControllerTest extends TestCase { /** * A basic test example. * * @return void */ public function testgiaodientrangchu() { $response = $this->get('/CHshop'); $response->assertStatus(200); $response->assertViewIs("user.index"); } public function test_data_giaodientrangchu() { $response = $this->get('/CHshop'); // lấy all dữ liệu $content = $response->getOriginalContent(); $content = $content->getData(); // kiem tra xem có dữ liệu bán chạy $count_banchay = (count($content['banchay']->all())); if($count_banchay > 0){ $count_banchay = 1; } $this->assertEquals(1, $count_banchay ); // kiem tra xem có dữ liệu product $count_product = (count($content['product']->all())); if($count_product > 0){ $count_product = 1; } $this->assertEquals(1, $count_product ); // kiem tra xem có dữ liệu moinhat $count_moinhat = (count($content['moinhat']->all())); if($count_moinhat > 0){ $count_moinhat = 1; } $this->assertEquals(1, $count_moinhat ); $response->assertStatus(200); } public function testdangkithongtin() { $response = $this->post('/dangki', [ 'ten' => 'myku123', 'gt' => 'myku123', 'dc' => '3123123', 'sdt' => '222', 'tk' => 'mydaica', 'mk' => '12344', 'Gioitinh' => '' ]); //this works $response->assertRedirect('CHshop'); //this fails $response->assertStatus(302); } public function testpostdangki_sai() { $response = $this->post('/dangki', [ 'ten' => 'myku123', 'gt' => 'myku123', 'dc' => '3123123', 'sdt' => '222', 'tk' => '', 'mk' => '', 'Gioitinh' => '' ]); //this works $response->assertRedirect('dangki'); //this fails $response->assertStatus(302); } public function testviewdangki() { $response = $this->get('dangki'); $response->assertStatus(200); $response->assertViewIs("user.dangki")->assertSee('Đăng ký tài khoản!'); } public function testpostthongtin() { $user = Taikhoan::find(49); $result = $user->update([ 'email' => '<EMAIL>', ]); $this->assertEquals(true, $result); } public function testDetele() { $user = Taikhoan::create([ 'TaiKhoan' => '2222', 'password' => '<PASSWORD>', ]); $result = $user->delete(); $this->assertEquals(true, $result); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Taikhoan extends Model { protected $primaryKey = 'MaND'; protected $table = 'nguoidung'; protected $fillable = [ 'HoTen', 'level', ]; // protected function create($request){ // $tao= new Taikhoan(); // $tao->HoTen= $request->HoTen; // $tao->Gioitinh=$request->Gioitinh; // $tao->DiaChi=$request->DiaChi; // $tao->SDT=$request->SDT; // $tao->level=2; // $tao->TaiKhoan=$request->TaiKhoan; // $tao->password=$<PASSWORD>; // $tao->save(); // } } <file_sep><?php include("connect.php"); session_start(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>SB Admin - Bootstrap Admin Template</title> <!-- Bootstrap Core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="css/sb-admin.css" rel="stylesheet"> <!-- Morris Charts CSS --> <link href="css/plugins/morris.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div id="page-wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-lg-4 col-md-4"> <div class="panel panel-primary"> <div class="panel-heading"> <div class="row"> <div class="col-xs-3"> <i class="fa fa-user fa-5x"></i> </div> <div class="col-xs-9 text-right"> <div class="huge"><?php $qr="SELECT COUNT(MaND) as SoTV FROM nguoidung"; $rs=mysqli_query($con,$qr); $row=mysqli_fetch_array($rs); echo"{$row['SoTV']}"; ?> </div> <div>Số Thành Viên</div> </div> </div> </div> <a href="../members.php"> <div class="panel-footer"> <span class="pull-left">Xem chi tiết</span> <span class="pull-right"><i class="fa fa-arrow-circle-right"></i></span> <div class="clearfix"></div> </div> </a> </div> </div> <div class="col-lg-4 col-md-4"> <div class="panel panel-yellow"> <div class="panel-heading"> <div class="row"> <div class="col-xs-3"> <i class="fa fa-shopping-cart fa-5x"></i> </div> <div class="col-xs-9 text-right"> <div class="huge"><?php $qr="SELECT COUNT(MaDH) as SoDH FROM donhang"; $rs=mysqli_query($con,$qr); $row=mysqli_fetch_array($rs); echo"{$row['SoDH']}"; ?> </div> <div>Số Đơn Hàng</div> </div> </div> </div> <a href="../orders.php"> <div class="panel-footer"> <span class="pull-left">Xem chi tiết</span> <span class="pull-right"><i class="fa fa-arrow-circle-right"></i></span> <div class="clearfix"></div> </div> </a> </div> </div> <div class="col-lg-4 col-md-4"> <div class="panel panel-red"> <div class="panel-heading"> <div class="row"> <div class="col-xs-3"> <i class="fa fa-barcode fa-5x"></i> </div> <div class="col-xs-9 text-right"> <div class="huge"> <?php $qr="SELECT COUNT(MaSP) as SoSP FROM sanpham"; $rs=mysqli_query($con,$qr); $row=mysqli_fetch_array($rs); echo"{$row['SoSP']}"; ?> </div> <div>Số Sản Phẩm</div> </div> </div> </div> <a href="../orders.php"> <div class="panel-footer"> <span class="pull-left">Xem Chi Tiết</span> <span class="pull-right"><i class="fa fa-arrow-circle-right"></i></span> <div class="clearfix"></div> </div> </a> </div> </div> </div> <!-- /.row --> <!-- Morris Charts --> <div class="row" style="display: none;"> <div class="col-lg-12"> <div class="panel panel-green"> <div class="panel-heading"> <h3 class="panel-title"><i class="fa fa-bar-chart-o"></i> Area Line Graph Example with Tooltips</h3> </div> <div class="panel-body"> <div id="morris-area-chart"></div> </div> </div> </div> </div> <!-- /.row --> <div class="row"> <div class="col-lg-4" style="display: none;"> <div class="panel panel-yellow"> <div class="panel-heading"> <h3 class="panel-title"><i class="fa fa-long-arrow-right"></i> Donut Chart Example</h3> </div> <div class="panel-body"> <div id="morris-donut-chart"></div> <div class="text-right"> <a href="#">Xem chi tiết <i class="fa fa-arrow-circle-right"></i></a> </div> </div> </div> </div> <div class="col-lg-12"> <div class="panel panel-red"> <div class="panel-heading"> <h3 class="panel-title"><i class="fa fa-long-arrow-right"></i> Doanh thu trong tháng</h3> </div> <div class="panel-body"> <div id="morris-line-chart"></div> <div class="text-right"> <a href="#">Xem Chi Tiết <i class="fa fa-arrow-circle-right"></i></a> </div> </div> </div> </div> <div class="col-lg-4" style="display: none;"> <div class="panel panel-primary"> <div class="panel-heading"> <h3 class="panel-title"><i class="fa fa-long-arrow-right"></i> Bar Graph Example</h3> </div> <div class="panel-body"> <div id="morris-bar-chart"></div> <div class="text-right"> <a href="#">View Details <i class="fa fa-arrow-circle-right"></i></a> </div> </div> </div> </div> </div> <!-- /.row --> <!-- Bảng --> <div class="row"> <div class="col-lg-6"> <h2> Danh sách khách mua nhiều</h2> <div class="table-responsive"> <table class="table table-bordered table-hover table-striped"> <thead> <tr> <th>STT</th> <th>Họ tên</th> <th>SĐT</th> <th>Tổng tiền</th> </tr> </thead> <tbody> <?php $qr=" SELECT HoTen, donhang.MaND, sum(Tongtien) as TT,donhang.sdt,TinhTrang From nguoidung, donhang WHERE nguoidung.MaND = donhang.MaND and TinhTrang>=3 GROUP BY donhang.MaND ORDER BY TT DESC LIMIT 0, 10"; $rs=mysqli_query($con,$qr); $str=""; $i=0; while($row=mysqli_fetch_array($rs)){ $i=$i+1; $str.=" <tr> <td>{$i}</td> <td>{$row['HoTen']}</td> <td>{$row['sdt']}</td> <td>{$row['TT']} VNĐ</td> </tr>"; } echo $str; ?> </tbody> </table> </div> </div> <div class="col-lg-6"> <h2>Danh sách sản phẩm bán chạy</h2> <div class="table-responsive"> <table class="table table-bordered table-hover table-striped"> <thead> <tr> <th>STT</th> <th>Mã sản phẩm</th> <th>Hình ảnh</th> <th>Số lượng</th> <th>Giá Sản phẩm</th> </tr> </thead> <tbody> <?php $qr=" SELECT chitietdh.MaSP, sum(Soluong) as Soluong,chitietdh.MaSP,DonGia,img From sanpham, chitietdh WHERE sanpham.MaSP= chitietdh.MaSP GROUP BY chitietdh.MaSP ORDER BY Soluong DESC LIMIT 0, 10"; $rs=mysqli_query($con,$qr); $i=0; $str=""; while($row=mysqli_fetch_array($rs)){ $i=$i+1; $str.="<tr> <td>{$i}</td> <td>{$row['MaSP']}</td> <td ><img src='../{$row['img']}' alt='' width='45px' height='60px'></td> <td>{$row['Soluong']}</td> <td>{$row['DonGia']}</td> </tr>"; } echo $str; ?> </tbody> </table> </div> </div> </div> <!-- /.row --> </div> <!-- /.container-fluid --> </div> <!-- /#page-wrapper --> <!-- jQuery --> <script src="js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> <!-- Morris Charts JavaScript --> <script src="js/plugins/morris/raphael.min.js"></script> <script src="js/plugins/morris/morris.min.js"></script> <script> // Morris.js Charts sample data for SB Admin template $(function() { // Area Chart Morris.Area({ element: 'morris-area-chart', data: [{ period: '2010 Q1', iphone: 2666, ipad: null, itouch: 2647 }, { period: '2010 Q2', iphone: 2778, ipad: 2294, itouch: 2441 }, { period: '2010 Q3', iphone: 4912, ipad: 1969, itouch: 2501 }, { period: '2010 Q4', iphone: 3767, ipad: 3597, itouch: 5689 }, { period: '2011 Q1', iphone: 6810, ipad: 1914, itouch: 2293 }, { period: '2011 Q2', iphone: 5670, ipad: 4293, itouch: 1881 }, { period: '2011 Q3', iphone: 4820, ipad: 3795, itouch: 1588 }, { period: '2011 Q4', iphone: 15073, ipad: 5967, itouch: 5175 }, { period: '2012 Q1', iphone: 10687, ipad: 4460, itouch: 2028 }, { period: '2012 Q2', iphone: 8432, ipad: 5713, itouch: 1791 }], xkey: 'period', ykeys: ['iphone', 'ipad', 'itouch'], labels: ['iPhone', 'iPad', 'iPod Touch'], pointSize: 2, hideHover: 'auto', resize: true }); // Donut Chart Morris.Donut({ element: 'morris-donut-chart', data: [{ label: "Download Sales", value: 12 }, { label: "In-Store Sales", value: 30 }, { label: "Mail-Order Sales", value: 20 }], resize: true }); // Line Chart Morris.Line({ // ID of the element in which to draw the chart. element: 'morris-line-chart', // Chart data records -- each entry in this array corresponds to a point on // the chart. <?php echo"data: ["; $qr=" SELECT SUM(Tongtien)as DoanhThu, NgTT as Ngay FROM donhang where TinhTrang>=3 GROUP BY NgTT ORDER BY NgTT DESC LIMIT 0, 30"; $rs=mysqli_query($con,$qr); //$row=mysqli_fetch_array($rs) while($row=mysqli_fetch_array($rs)){ echo"{ d: '{$row['Ngay']}', visits: {$row['DoanhThu']} }, "; } echo" ],"; ?> // The name of the data record attribute that contains x-visitss. xkey: 'd', // A list of names of data record attributes that contain y-visitss. ykeys: ['visits'], // Labels for the ykeys -- will be displayed when you hover over the // chart. labels: ['Tổng thu'], // Disables line smoothing smooth: false, resize: true }); // Bar Chart Morris.Bar({ element: 'morris-bar-chart', data: [{ device: 'iPhone', geekbench: 136 }, { device: 'iPhone 3G', geekbench: 137 }, { device: 'iPhone 3GS', geekbench: 275 }, { device: 'iPhone 4', geekbench: 380 }, { device: 'iPhone 4S', geekbench: 655 }, { device: 'iPhone 5', geekbench: 1571 }], xkey: 'device', ykeys: ['geekbench'], labels: ['Geekbench'], barRatio: 0.4, xLabelAngle: 35, hideHover: 'auto', resize: true }); }); </script> <!-- Flot Charts JavaScript --> <!--[if lte IE 8]><script src="js/excanvas.min.js"></script><![endif]--> <script src="js/plugins/flot/jquery.flot.js"></script> <script src="js/plugins/flot/jquery.flot.tooltip.min.js"></script> <script src="js/plugins/flot/jquery.flot.resize.js"></script> <script src="js/plugins/flot/jquery.flot.pie.js"></script> <script src="js/plugins/flot/flot-data.js"></script> </body> </html> <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Project; use App\SanPham; use App\Nhacungcap; use App\Loaihang; use App\Lienhe; use Mail,DB; class LienheController extends Controller { public function getAdd(){ $loaihang=Loaihang::all(); $nhacungcap=Nhacungcap::all(); return view('user.lienhe',compact('loaihang','nhacungcap')); } public function postAdd( Request $request){ $cungcap=new Lienhe; $cungcap->hoten=$request->hoten; $cungcap->cty=$request->cty; $cungcap->email=$request->email; $cungcap->dienthoai=$request->dienthoai; $cungcap->fax=$request->fax; $cungcap->diachi=$request->diachi; $cungcap->noidung=$request->noidung; $cungcap->ngaylienhe=$request->ngaylienhe; $cungcap->save(); $data=['hoten'=>$request->hoten,'tinnhan'=>$request->noidung,'email'=>$request->email]; Mail::send('user.blan',$data, function($message){ $message->from('<EMAIL>','Pho Pho'); $message->to('<EMAIL>','Pho Pho')->subject('ý kiến khách hàng'); }); echo "<script> alert('Cảm ơn bạn đã liên hệ với chúng tôi, mọi đóng góp của bạn sẽ tạo động lực cho trang web ngày càng phát triển'); window.location='". route('CHshop') ."' </script>"; //return redirect()->route('CHshop'); } public function index(){ $data= Lienhe::paginate(3); return view('admin.lienhe',compact('data')); } public function getDelete($id){ $cate=Lienhe::find($id); $cate->delete(); return redirect('admin/lienhe/list'); } public function getEdit($id){ $data=Lienhe::find($id); return view('admin.editlienhe',compact('data')); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use App\Http\Requests\CateRequest; use App\Http\Controllers\Controller; use App\Project; use App\SanPham; use App\Nhacungcap; use App\Loaihang; use App\Taikhoan; use App\Donhang; use App\Chitietdonhang; use Auth; class DonhangController extends Controller { public function getList(){ $data= Donhang::paginate(5); return view('admin.danhsachdonhang',compact('data')); } public function getDelete($id){ $user=Donhang::find($id); $cc=$user->TinhTrang; if($cc==4){ echo "<script> alert('Xin lỗi, bạn không thể xóa được đơn hàng đã thanh toán'); window.location='". route('admin.donhang.getList') ."' </script>"; } else{ $capnhat=DB::table('chitietdh')->select('MaSP','MaDH','Soluong')->where('MaDH',$id)->get(); foreach($capnhat as $cc){ $bb= $cc->MaSP; $hh=$cc->Soluong; $aa=SanPham::find($bb); $aa->Sluongcon=$aa->Sluongcon+$hh; $aa->save(); $cc2=SanPham::find($bb); $cc2->Sluongban=$cc2->Sluongban - $hh; $cc2->save(); } $user->delete(); return redirect('admin/donhang/list'); } } public function getAdd(){ return view('admin.adtaikhoan'); } public function postAdd(Request $request){ $sanpham= new Taikhoan; $sanpham->HoTen=$request->HoTen; $sanpham->Gioitinh=$request->Gioitinh; $sanpham->SDT=$request->SDT; $sanpham->email=$request->email; $sanpham->password=<PASSWORD>($request->password); $sanpham->TaiKhoan=$request->TaiKhoan; $sanpham->level=$request->level; $sanpham->DiaChi=$request->DiaChi; $sanpham->save(); return redirect('admin/donhang/list'); } public function getEdit($id){ $cc=Donhang::find($id); $up=$cc->TinhTrang; if($up==1){ $cc->TinhTrang=2; $cc->save(); } $ten=Auth::user(); $sua=Donhang::find($id); return view ('admin.chitietdonhang',compact('sua','ten')); } public function postEdit( $id,Request $request){ $sanpham= Donhang::find($id); $sanpham->TinhTrang=$request->TinhTrang; $sanpham->NhanVienGH=$request->NhanVienGH; $sanpham->NhanVienTT=$request->NhanVienTT; $sanpham->NgGH=$request->nggh; $sanpham->NgTT=$request->ngtt; $sanpham->save(); return redirect('admin/donhang/list'); } public function capdo(){ $sanpham=Taikhoan::all(); return view('admin.capdotaikhoan',compact('sanpham')); } public function getEditnv($id){ $ten=Auth::user(); $sua=Donhang::find($id); return view ('admin.chitietdonhangnv',compact('sua','ten')); } public function postEditnv( $id,Request $request){ $sanpham= Donhang::find($id); $sanpham->TinhTrang=$request->TinhTrang; $sanpham->NhanVienGH=$request->NhanVienGH; $sanpham->NhanVienTT=$request->NhanVienTT; $sanpham->save(); return redirect('admin/donhang/list'); } public function getListnv(){ $data= DB::table('donhang')->select('MaDH','MaND','TenKH','NhanVienGH','NhanVienTT','DiaChiGH','Tongtien','TinhTrang','NgGH','NgTT','NgDat','sdt','email')->where('TinhTrang',3)->get(); //echo $data; return view('admin.danhsachdonhangnv',compact('data')); } public function indonhang($id){ $in=Donhang::find($id); return view ('admin.inhoadon',compact('in')); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Project; use App\SanPham; use App\Nhacungcap; use App\Loaihang; use App\Taikhoan; class ThongkeController extends Controller { public function index(){ return view('admin.thongke'); } public function getEdit(){ $data=Taikhoan::all(); return view('admin.editthanhvien',compact('data')); } } <file_sep><?php namespace App\Http\Middleware; use Closure; use Auth; class CheckAge { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if(!Auth::check()){ return redirect('admin/login1'); } else{ $a=Auth::user(); $b=$a->level; if($b==1){ return $next($request);} else{ Auth::logout(); return redirect('admin/login1'); } } } } <file_sep><?php use Illuminate\Database\Seeder; class UserTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('nguoidung')->insert([ 'TaiKhoan'=>'nguoidung', 'HoTen'=>'Thien', 'SDT'=>'22131231231', 'ngDk'=>'2016-12-11', 'trangthai'=>'1', 'password' => bcrypt('<PASSWORD>'), 'level'=>'2', ]); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use App\Http\Requests\CateRequest; use App\Http\Controllers\Controller; use App\Project; use App\SanPham; use App\Nhacungcap; use App\Loaihang; use App\Taikhoan; use Auth; class TaikhoanController extends Controller { public function getList(){ $data= Taikhoan::paginate(3); return view('admin.taikhoan',compact('data')); } public function getDelete($id){ $user=Auth::user()->MaND; $cate=Taikhoan::find($id); if(($id==12) || ($user!=12) && ($user['level'] ==1) ){ return redirect('admin/nguoidung/list')->with('loi','Không đủ level để xóa'); } else{ $cate->delete(); return redirect('admin/nguoidung/list'); } } public function getAdd(){ return view('admin.adtaikhoan'); } public function postAdd(Request $request){ $sanpham= new Taikhoan; $sanpham->HoTen=$request->HoTen; $sanpham->Gioitinh=$request->Gioitinh; $sanpham->SDT=$request->SDT; $sanpham->email=$request->email; $sanpham->password=<PASSWORD>($request->password); $sanpham->TaiKhoan=$request->TaiKhoan; $sanpham->level=$request->level; $sanpham->DiaChi=$request->DiaChi; $sanpham->save(); return redirect('admin/nguoidung/list'); } public function getEdit($id){ $sua=TaiKhoan::find($id); return view ('admin.suataikhoan',compact('sua')); } public function postEdit( $id,Request $request){ $sanpham= Taikhoan::find($id); $sanpham->HoTen=$request->HoTen; $sanpham->Gioitinh=$request->Gioitinh; $sanpham->SDT=$request->SDT; $sanpham->email=$request->email; $sanpham->password=<PASSWORD>($request->password); $sanpham->TaiKhoan=$request->TaiKhoan; $sanpham->level=$request->level; $sanpham->DiaChi=$request->DiaChi; $sanpham->save(); return redirect('admin/nguoidung/list'); } public function capdo(){ $sanpham=Taikhoan::all(); return view('admin.capdotaikhoan',compact('sanpham')); } } <file_sep><?php include("connect.php"); ?> <!DOCTYPE html> <html lang="en"> <head> <!-- start: Meta --> <meta charset="utf-8"> <title></title> <meta name="description" content="Bootstrap Metro Dashboard"> <meta name="author" content="<NAME>"> <meta name="keyword" content="Metro, Metro UI, Dashboard, Bootstrap, Admin, Template, Theme, Responsive, Fluid, Retina"> <!-- end: Meta --> <!-- start: Mobile Specific --> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- end: Mobile Specific --> <!-- start: CSS --> <link id="bootstrap-style" href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/bootstrap-responsive.min.css" rel="stylesheet"> <link id="base-style" href="css/style.css" rel="stylesheet"> <link id="base-style-responsive" href="css/style-responsive.css" rel="stylesheet"> <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800&subset=latin,cyrillic-ext,latin-ext' rel='stylesheet' type='text/css'> <!-- end: CSS --> <!-- The HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <link id="ie-style" href="css/ie.css" rel="stylesheet"> <![endif]--> <!--[if IE 9]> <link id="ie9style" href="css/ie9.css" rel="stylesheet"> <![endif]--> <!-- start: Favicon --> <link rel="shortcut icon" href="img/favicon.ico"> <!-- end: Favicon --> </head> <body> <div class="row-fluid sortable"> <div class="box span12"> <table class="table table-bordered" width="1000px"> <thead> <tr> <th align="center">Mã <NAME></th> <th>Mã Thành Viên</th> <th>Họ Và Tên</th> <th>Địa Chỉ</th> <th>Ngày Đặt</th> <th>Ngày Thanh Toán</th> <th>Nhân Viên Thanh Toán</th> <th>Tổng Tiền</th> <th>Ghi Chú</th> </tr> </thead> <tbody> <?php $qr="SELECT * FROM donhang"; $rs=mysqli_query($con,$qr); // $tinhtrang=""; $i=0; while($row=mysqli_fetch_array($rs)){ $i=$i+1; if($row['MaND']==null){ $MaND="không có"; }else{ $MaND=$row['MaND']; } echo" <tr> <td >{$row['MaDH']}</td> <td >{$MaND}</td> <td >{$row['TenKH']}</td> <td >{$row['DiaChiGH']}</td> <td >{$row['NgDat']}</td> <td >{$row['NgTT']}</td> <td >{$row['NhanVienTT']}</td> <td >{$row['Tongtien']}</td> <td ></td> </tr>"; } ?> </tbody> </table> </div> </div><!--/span--> </body> </html><file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; use App\Http\Requests\CateRequest; use Auth; use App\Http\Controllers\Controller; use App\Project; use App\SanPham; use App\Nhacungcap; use App\Loaihang; class CateController extends Controller { public function getAdd(){ $loaihang=Loaihang::all(); $nhacungcap=Nhacungcap::all(); return view('admin.themsanpham',compact('loaihang','nhacungcap')); } public function postAdd(Request $request){ $sanpham= new SanPham; $sanpham->TenSP=$request->TenSP; $sanpham->CPU=$request->cpu; $sanpham->baohanh=$request->baohanh; $sanpham->DonGia=$request->DonGia; $sanpham->Ram=$request->Ram; $sanpham->Sluongcon=$request->Sluongcon; $sanpham->giakm=$request->giakm; $sanpham->vga=$request->vga; $sanpham->hedieuhanh=$request->hedieuhanh; $sanpham->mota=$request->mota; $sanpham->MaLoai=$request->MaLoai; $sanpham->ManhaCC=$request->manhacc; $sanpham->img = $request->hinh; $sanpham->save(); return redirect('admin/cate/list'); } public function getList(){ $data= SanPham::paginate(5); return view('admin.list',compact('data')); } public function getDelete($id){ $cate=SanPham::find($id); $cate->delete(); return redirect('admin/cate/list'); } public function getEdit($id){ $loaihang=Loaihang::all(); $nhacungcap=Nhacungcap::all(); $sua=SanPham::find($id); return view('admin.edit',compact('loaihang','nhacungcap','sua')); } public function postEdit( $id,Request $request){ $sanpham= SanPham::find($id); $sanpham->TenSP=$request->TenSP; $sanpham->CPU=$request->cpu; $sanpham->baohanh=$request->baohanh; $sanpham->DonGia=$request->DonGia; $sanpham->Ram=$request->Ram; $sanpham->Sluongcon=$request->Sluongcon; $sanpham->giakm=$request->giakm; $sanpham->vga=$request->vga; $sanpham->hedieuhanh=$request->hedieuhanh; $sanpham->mota=$request->mota; $sanpham->MaLoai=$request->MaLoai; $sanpham->ManhaCC=$request->ManhaCC; $sanpham->img = $request->hinh; $sanpham->save(); return redirect('admin/cate/list'); } } <file_sep>$(document).ready(function(){ $(".updatecart").click(function(){ var rowid= $(this).attr('id'); var qty=$(this).parent().parent().find(".qty").val(); var token = $("input[name='_token']").val(); var maosp = $("input[name='maosp']").val(); $.ajax({ url:'capnhat/'+ rowid+'/'+qty, type:'GET', cache:false, data:{"_token":token,"id":rowid,"qty":qty,"maosp":maosp}, success:function(data){ if(data=="oke"){ window.location("giohang"); } else{ alert('Xin lỗi,hiện tại số lưọng hàng trong kho không đáp ứng đưọc nhu cầu của quý khách, rất xin lỗi quí khách'); } } }); }); }); <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Project; use App\SanPham; use App\Nhacungcap; use App\Loaihang; use App\Phieunhap; use App\Chitietphieunhap; use App\Http\Requests\CateRequest; class PhieunhapController extends Controller { public function getList(){ $data= Phieunhap::paginate(3); $nhacungcap=Nhacungcap::all(); return view('admin.listphieunhap',compact('data','nhacungcap')); } public function getDelete($id){ $cate=Phieunhap::find($id); $cate->delete(); return redirect('admin/phieunhap/list'); } public function getAdd(){ $nhacungcap=Nhacungcap::all(); return view('admin.addphieunhap',compact('nhacungcap')); } public function postAdd(Request $request){ $sanpham= new Phieunhap; $sanpham->ManhaCC=$request->nhacungcap; $sanpham->NgNhap=$request->ngnhap; $sanpham->save(); return redirect('admin/phieunhap/list'); } public function getEdit($id){ $sua=Phieunhap::find($id); $sanpham=SanPham::all(); return view ('admin.suaphieunhap',compact('sua','sanpham')); } public function postEdit( $id,Request $request){ $them= new Chitietphieunhap; $upsanpham=SanPham::find($request->MaSP); $Sluongcon= $upsanpham->Sluongcon; $Soluongthem=$request->Soluong; $upsanpham->Sluongcon=$Sluongcon+$Soluongthem; $them->MaSP=$request->MaSP; $them->Soluong=$request->Soluong; $them->dongia=$request->dongia; $sl=$request->Soluong; $dg=$request->dongia; $them->ThanhTien=$sl*$dg; $cc = Phieunhap::find($id); $them->IdPN=$cc->IdPN; $them->save(); $upsanpham->save(); return redirect('admin/phieunhap/list'); } } <file_sep><?php namespace Tests\Unit\Http\Model; use Tests\TestCase; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; class UserTest extends TestCase { /** * A basic test example. * * @return void */ public function testExample() { // kiểm tra tồn tại email <EMAIL> trong bản ghi $this->assertDatabaseHas('nguoidung', [ 'email' => '<EMAIL>' ]); } } <file_sep><?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); Route::get('dangnhap','admincontroller@getlogin'); Route::get('user','admincontroller@getadmin'); Route::post('user','admincontroller@postadmin'); Route::get('logout','admincontroller@logout'); Auth::routes(); Route::get('/home', 'HomeController@index'); Route::get('message', function() { return view('janux.messages'); }); Route::resource('sanpham','sanphamcontroller'); Route::resource('nhacungcap','nhacungcapController'); //////////////////////////////////////////////////////////////////////////////////// Route::group(['prefix' => 'admin','middleware'=>'check'], function() { Route::group(['prefix' => 'cate'], function() { Route::get('list',['as'=>'admin.cate.getList','uses'=>'CateController@getList']); Route::get('add',['as'=>'admin.cate.getAdd','uses'=>'CateController@getAdd']); Route::post('add',['as'=>'admin.cate.getAdd','uses'=>'CateController@postAdd']); Route::get('delete/{id}',['as'=>'admin.cate.getDelete','uses'=>'CateController@getDelete']); Route::get('edit/{id}',['as'=>'admin.cate.getEdit','uses'=>'CateController@getEdit']); Route::post('edit/{id}',['as'=>'admin.cate.postEdit','uses'=>'CateController@postEdit']); }); }); ////////////////// Route::group(['prefix' => 'admin','middleware'=>'check'], function() { Route::group(['prefix' => 'cungcap'], function() { // Route::get('addcungcap',['as'=>'admin.cungcap.getAdd','uses'=>'CungcapController@getAdd']); Route::post('addcungcap',['as'=>'admin.cungcap.getAdd','uses'=>'CungcapController@postAdd']); }); }); ///////////////////////////// Route::group(['prefix' => 'admin','middleware'=>'check'], function() { Route::group(['prefix' => 'loaihang'], function() { Route::get('list',['as'=>'admin.loaihang.getList','uses'=>'LoaihangController@getList']); Route::get('add',['as'=>'admin.loaihang.getAdd','uses'=>'LoaihangController@getAdd']); Route::post('add',['as'=>'admin.loaihang.getAdd','uses'=>'LoaihangController@postAdd']); Route::get('delete/{id}',['as'=>'admin.loaihang.getDelete','uses'=>'LoaihangController@getDelete']); Route::get('edit/{id}',['as'=>'admin.loaihang.getEdit','uses'=>'LoaihangController@getEdit']); Route::post('edit/{id}',['as'=>'admin.loaihang.postEdit','uses'=>'LoaihangController@postEdit']); }); }); //////////////////////////// Route::group(['prefix' => 'admin','middleware'=>'check'], function() { Route::group(['prefix' => 'lienhe'], function() { // Route::get('list',['as'=>'admin.lienhe.list','uses'=>'LienheController@index']); Route::get('delete/{id}',['as'=>'admin.lienhe.getDeletes','uses'=>'LienheController@getDelete']); Route::get('edit/{id}',['as'=>'admin.lienhe.getEdit','uses'=>'LienheController@getEdit']); }); }); ///////////////////////// Route::group(['prefix' => 'admin','middleware'=>'check'], function() { Route::group(['prefix' => 'thongke'], function() { // Route::get('list',['as'=>'admin.thongke.list','uses'=>'ThongkeController@index']); Route::get('edit',['as'=>'admin.thongke.getEdit','uses'=>'ThongkeController@getEdit']); }); }); /////////////////////////////////////////////////////// Route::group(['prefix' => 'admin','middleware'=>'check'], function() { Route::group(['prefix' => 'nguoidung'], function() { Route::get('list',['as'=>'admin.nguoidung.getList','uses'=>'TaikhoanController@getList']); Route::get('delete/{id}',['as'=>'admin.nguoidung.getDelete','uses'=>'TaikhoanController@getDelete']); Route::get('add',['as'=>'admin.nguoidung.getAdd','uses'=>'TaikhoanController@getAdd']); Route::post('add',['as'=>'admin.nguoidung.getAdd','uses'=>'TaikhoanController@postAdd']); Route::get('edit/{id}',['as'=>'admin.nguoidung.getEdit','uses'=>'TaikhoanController@getEdit']); Route::post('edit/{id}',['as'=>'admin.nguoidung.postEdit','uses'=>'TaikhoanController@postEdit']); Route::get('capdo',['as'=>'admin.nguoidung.capdo','uses'=>'TaikhoanController@capdo']); }); }); Route::group(['prefix' => 'admin','middleware'=>'check'], function() { Route::group(['prefix' => 'phieunhap'], function() { Route::get('list',['as'=>'admin.phieunhap.getList','uses'=>'PhieunhapController@getList']); Route::get('addphieunhap',['as'=>'admin.phieunhap.getAdd','uses'=>'PhieunhapController@getAdd']); Route::post('addphieunhap',['as'=>'admin.phieunhap.getAdd','uses'=>'PhieunhapController@postAdd']); Route::get('delete/{id}',['as'=>'admin.phieunhap.getDelete','uses'=>'PhieunhapController@getDelete']); Route::get('edit/{id}',['as'=>'admin.phieunhap.getEdit','uses'=>'PhieunhapController@getEdit']); Route::post('edit/{id}',['as'=>'admin.phieunhap.postEdit','uses'=>'PhieunhapController@postEdit']); }); }); ///////////////////////////////////// Route::group(['prefix' => 'admin','middleware'=>'check'], function() { Route::group(['prefix' => 'donhang'], function() { Route::get('list',['as'=>'admin.donhang.getList','uses'=>'DonhangController@getList']); Route::get('delete/{id}',['as'=>'admin.donhang.getDelete','uses'=>'DonhangController@getDelete']); Route::get('add',['as'=>'admin.donhang.getAdd','uses'=>'DonhangController@getAdd']); Route::post('add',['as'=>'admin.donhang.getAdd','uses'=>'DonhangController@postAdd']); Route::get('edit/{id}',['as'=>'admin.donhang.getEdit','uses'=>'DonhangController@getEdit']); Route::post('edit/{id}',['as'=>'admin.donhang.postEdit','uses'=>'DonhangController@postEdit']); Route::get('indonhang/{id}',['as'=>'admin.donhang.indonhang','uses'=>'DonhangController@indonhang']); Route::get('listnv',['as'=>'admin.donhang.getListnv','uses'=>'DonhangController@getListnv']); Route::get('editnv/{id}',['as'=>'admin.donhang.getEditnv','uses'=>'DonhangController@getEditnv']); Route::post('editnv/{id}',['as'=>'admin.donhang.getEditnv','uses'=>'DonhangController@postEditnv']); Route::get('capdo',['as'=>'admin.donhang.capdo','uses'=>'DonhangController@capdo']); }); }); //////////////// Route::get('admin/login1',['as'=>'admin.login','uses'=>'Auth\LoginController@getLogin']); Route::post('admin/login1',['as'=>'admin.login','uses'=>'Auth\LoginController@postLogin']); Route::get('logout',['uses'=>'Auth\LoginController@logout']); /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Route::get('CHshop',['as'=>'CHshop','uses'=>'WelcomeController@index']); Route::get('loaisanpham/{id}',['as'=>'loaisanpham','uses'=>'WelcomeController@loaisanpham']); Route::get('chitietsanpham/{id}',['as'=>'chitietsanpham','uses'=>'WelcomeController@chitietsanpham']); Route::get('muahang/{id}',['as'=>'muahang','uses'=>'WelcomeController@muahang']); Route::get('giohang',['as'=>'giohang','uses'=>'WelcomeController@giohang']); Route::get('xoasanpham/{id}',['as'=>'xoasanpham','uses'=>'WelcomeController@xoasanpham']); Route::post('tinhtien',['as'=>'tinhtien','uses'=>'WelcomeController@tinhtien']); ////// Route::get('lienhe',['as'=>'lienhe','uses'=>'LienheController@getAdd']); Route::post('lienhe',['as'=>'lienhe','uses'=>'LienheController@postAdd']); Route::get('dangnhap1',['as'=>'dangnhap1','uses'=>'WelcomeController@getDangnhap']); Route::post('dangnhap1',['as'=>'dangnhap1','uses'=>'WelcomeController@postDangnhap']); Route::get('thoat','WelcomeController@logout'); Route::get('dangki',['as'=>'dangki','uses'=>'WelcomeController@getdangki']); Route::post('dangki',['as'=>'dangki','uses'=>'WelcomeController@postdangki']); Route::get('thongtin',['as'=>'thongtin','uses'=>'WelcomeController@getthongtin']); Route::post('thongtin',['as'=>'thongtin','uses'=>'WelcomeController@postthongtin']); Route::get('donhangcu',['as'=>'donhangcu','uses'=>'WelcomeController@getdonhangcu']); Route::get('donhangcu/{id}',['as'=>'postdonhangcu','uses'=>'WelcomeController@postdonhangcu']); Route::get('capnhat/{id}/{qty}',['as'=>'capnhat','uses'=>'WelcomeController@capnhat']); Route::post('timkiem',['as'=>'timkiem','uses'=>'WelcomeController@timkiem']); Route::get('chitietdonhangcu/{id}',['as'=>'chitietdonhangcu','uses'=>'WelcomeController@chitietdonhangcu']); Route::get('motrieu',['as'=>'motrieu','uses'=>'WelcomeController@motrieu']); Route::get('haitrieu',['as'=>'haitrieu','uses'=>'WelcomeController@haitrieu']); Route::get('batrieu',['as'=>'batrieu','uses'=>'WelcomeController@batrieu']); <file_sep><?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class Project extends Authenticatable { use Notifiable; protected $table = 'nhacungcap'; protected $fillable = [ 'MaNhaCC', 'TennhaCC', 'SDT','Diachi' ]; public $timestamps = false; } <file_sep><?php namespace App\Http\Controllers; use App\Http\Requests; use Auth; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class admincontroller extends Controller { Public function getLogin() { return view('janux.login'); } Public function getadmin() { if(!Auth::check()){ return view('janux.login'); }else{ return view('janux.sanpham',['user'=>Auth::user()]); } } Public function postadmin(Request $request) { $user = [ 'TaiKhoan' => $request->name, 'password' => $request->password, ]; if(Auth::attempt($user)){ return redirect('sanpham')->with('user',Auth::user()); } else{ return redirect('dangnhap')->with('error','Đăng nhập thất bại'); } } Public function logout() { Auth::logout(); return redirect('dangnhap'); } Public function them( Request $request){ $sida=Auth::user(); return view('them')->with('sida',$sida); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Project; use App\SanPham; use App\Nhacungcap; use App\Loaihang; class CungcapController extends Controller { public function getAdd(){ $loaihang=Loaihang::all(); $nhacungcap=Nhacungcap::all(); return view('admin.nhacungcap',compact('loaihang','nhacungcap')); } public function postAdd( Request $request){ $cungcap=new Nhacungcap; $cungcap->TennhaCC=$request->TennhaCC; $cungcap->SDT=$request->SDT; $cungcap->Diachi=$request->Diachi; $cungcap->save(); return redirect()->route('admin.cungcap.getAdd'); } } <file_sep><?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class SanPham extends Authenticatable { use Notifiable; protected $primaryKey = 'MaSP'; protected $table = 'sanpham'; protected $fillable = [ 'MaSP', 'TenSP', 'DonGia','SLuongcon','img','Sluongban' ]; public $timestamps = false; } <file_sep><?php namespace Tests\Unit\Http\Controllers; use Tests\TestCase; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; use App\User; use App\Http\Requests; use Auth; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Foundation\Auth\AuthenticatesUsers; class LoginControllerTest extends TestCase { /** * A basic test example. * * @return void */ public function testLogin(){ $response = $this->post('dangnhap1', [ 'TaiKhoan' => 'admin', 'password' => '<PASSWORD>' ]); //this works $response->assertRedirect('/CHshop'); //this fails $this->assertTrue(Auth::check()); } public function testLogin_faild(){ $response = $this->post('dangnhap1', [ 'TaiKhoan' => 'admin13123', 'password' => '<PASSWORD>' ]); //this works $response->assertRedirect('/'); $response->assertStatus(302); //this fails } public function testlogout(){ $response = $this->get('thoat'); $response->assertRedirect('/CHshop'); $response->assertStatus(302); $this->assertFalse(Auth::check()); } }
fea952c1ee4cf141590842350172e103059f8503
[ "JavaScript", "PHP" ]
26
PHP
Eatkaka/CHshop
ddc7ccc8aab964d6ccfa825f086224312b50492c
451c8370d3eea25d551a7543cba6bfba5e13cfd5
refs/heads/master
<repo_name>ArsenalHolmes/wumaqi0718<file_sep>/Assets/Scripts/UI/BasePanel.cs using UnityEngine; using System.Collections; using DG.Tweening; public class BasePanel : MonoBehaviour { private CanvasGroup canvasGroup; void Start() { if (canvasGroup == null) canvasGroup = GetComponent<CanvasGroup>(); } /// <summary> /// 入栈 /// </summary> public virtual void OnEnter() { if (canvasGroup == null) canvasGroup = GetComponent<CanvasGroup>(); canvasGroup.alpha = 1; canvasGroup.blocksRaycasts = true; Vector3 temp = transform.localPosition; temp.x = 1500; transform.localPosition = temp; transform.DOLocalMoveX(0, 0.5f); //设置UI层级 transform.SetSiblingIndex(transform.parent.childCount - 2); } /// <summary> /// 出栈 /// </summary> public virtual void OnExit() { canvasGroup.blocksRaycasts = false; transform.DOLocalMoveX(1500, 0.5f).OnComplete(() => canvasGroup.alpha = 0); } /// <summary> /// 设置不能点击 /// </summary> public virtual void OnPause() { canvasGroup.blocksRaycasts = false; } /// <summary> /// 设置点击 /// </summary> public virtual void OnResume() { canvasGroup.blocksRaycasts = true; } } <file_sep>/Assets/Scripts/UI/UIManger.cs using UnityEngine; using System.Collections; using System.Collections.Generic; using System; public enum UIName { EndPanel, IntroducePanel, StartPanel, PlayPanel, } public class UIManger { /// /// 单例模式的核心 /// 1,定义一个静态的对象 在外界访问 在内部构造 /// 2,构造方法私有化 private static UIManger _instance; public static UIManger Instance { get { if (_instance == null) { _instance = new UIManger(); } return _instance; } } private Transform canvasTransform; private Transform CanvasTransform { get { if (canvasTransform == null) { canvasTransform = GameObject.Find("Canvas").transform; } return canvasTransform; } } private Dictionary<UIName, string> panelPathDict;//存储所有面板Prefab的路径 private Dictionary<UIName, BasePanel> panelDict;//保存所有实例化面板的游戏物体身上的BasePanel组件 private Stack<BasePanel> panelStack; private UIManger() { ParseUIPanelTypeJson(); } /// <summary> /// 把某个页面入栈, 把某个页面显示在界面上 /// </summary> public void PushPanel(UIName panelType) { if (panelStack == null) panelStack = new Stack<BasePanel>(); //判断一下栈里面是否有页面 if (panelStack.Count > 0) { BasePanel topPanel = panelStack.Peek(); topPanel.OnPause(); } BasePanel panel = GetPanel(panelType); panel.OnEnter(); panelStack.Push(panel); } /// <summary> /// 出栈 ,把页面从界面上移除 /// </summary> public void PopPanel() { if (panelStack == null) panelStack = new Stack<BasePanel>(); if (panelStack.Count <= 0) return; //关闭栈顶页面的显示 BasePanel topPanel = panelStack.Pop(); topPanel.OnExit(); if (panelStack.Count <= 0) return; BasePanel topPanel2 = panelStack.Peek(); topPanel2.OnResume(); } /// <summary> /// 根据面板类型 得到实例化的面板 /// </summary> /// <returns></returns> private BasePanel GetPanel(UIName panelType) { if (panelDict == null) { panelDict = new Dictionary<UIName, BasePanel>(); } BasePanel panel = panelDict.TryGet(panelType); if (panel == null) { //如果找不到,那么就找这个面板的prefab的路径,然后去根据prefab去实例化面板 string path = panelPathDict.TryGet(panelType); GameObject instPanel = GameObject.Instantiate(Resources.Load(path)) as GameObject; instPanel.transform.SetParent(CanvasTransform, false); panelDict.Add(panelType, instPanel.GetComponent<BasePanel>()); return instPanel.GetComponent<BasePanel>(); } else { return panel; } } void ParseUIPanelTypeJson() { panelPathDict = new Dictionary<UIName, string>(); TextAsset ta = Resources.Load<TextAsset>("UIPath"); string[] strArr = ta.ToString().Trim().Split('\n'); foreach (var item in strArr) { string[] Arr = item.Split('\t'); UIName un = (UIName)Enum.Parse(typeof(UIName), Arr[0].Trim()); panelPathDict.Add(un, Arr[1].Trim()); } } } <file_sep>/Assets/Scripts/UI/IntroducePanel.cs using UnityEngine; using System.Collections; using UnityEngine.UI; public class IntroducePanel: BasePanel { public static IntroducePanel Instance; Button tiao; Button ka; Button da; Button zhong; Button back; private void Awake() { Instance = this; UIInit(); } void UIInit() { tiao = transform.Find("tiao").GetComponent<Button>(); ka = transform.Find("ka").GetComponent<Button>(); da = transform.Find("da").GetComponent<Button>(); zhong = transform.Find("zhong").GetComponent<Button>(); back = transform.Find("Back").GetComponent<Button>(); back.onClick.AddListener(back_Btn_Event); } void tiao_Btn_Event() { } void ka_Btn_Event() { } void da_Btn_Event() { } void zhong_Btn_Event() { } void back_Btn_Event() { UIManger.Instance.PushPanel(UIName.StartPanel); } } <file_sep>/Assets/Scripts/UI/StartDoor.cs using UnityEngine; using System.Collections; public class StartDoor : MonoBehaviour { // Use this for initialization void Start () { //UI入口 UIManger.Instance.PushPanel(UIName.StartPanel); } } <file_sep>/Assets/Scripts/CompterAi.cs using UnityEngine; using System.Collections.Generic; using UnityEngine.EventSystems; using System.Collections; public class CompterAi : MonoBehaviour { public static CompterAi Instance; Base AIBase; private void Awake() { Instance = this; } public void AIPlayChess() { List<MoveBase> MBL = GetBaseCanMoveList(); MBL = Sort(MBL);//根据NUM排序 NUM是走的那里可以吃的格子的数量 MoveBase mbTemp; if (BaseManger.Instance.RedList.Count==1) { mbTemp = GetMovePath(BaseManger.Instance.RedList[0], MBL); } else { MBL = GetMaxNumList(MBL);//得到最大值得列表 if (MBL.Count == 0) { Debug.Log("出大问题了AI没路可以走了"); return; } int index = Random.Range(0, MBL.Count); mbTemp = MBL[index]; } BaseManger.Instance.StartBase = mbTemp.Start; BaseManger.Instance.EndBase = mbTemp.End; AIBase = mbTemp.Start.TakeUpChess();//拿起 mbTemp.End.PutDownChess(AIBase,false,false,true);//放下 BaseManger.Instance.ChangsPlayer();//换人走 } /// <summary> /// 得到黑色格子所有可以走的路径 /// </summary> /// <returns></returns> List<MoveBase> GetBaseCanMoveList() { List<MoveBase> MBL = new List<MoveBase>(); foreach (var b in BaseManger.Instance.BlackList) { foreach (var item in b.aroundBaseList) { if (item.isDropedChess) { int count = BaseManger.Instance.GetNum(item); //MoveBase mb = new MoveBase(b, item, BaseManger.Instance.AroundRedBase(item).Count); MoveBase mb = new MoveBase(b, item, count); if (mb.Canmove) { MBL.Add(mb); } } } } return MBL; } /// <summary> /// 列表根据NUM排序 /// </summary> /// <param name="lmb"></param> /// <returns></returns> List<MoveBase> Sort(List<MoveBase> lmb) { //外层循环控制的是趟数 for (int i = 0; i < lmb.Count - 1; i++) { for (int j = 0; j < lmb.Count - 1 - i; j++) { if (lmb[j].Num < lmb[j + 1].Num) { MoveBase temp = lmb[j]; lmb[j] = lmb[j + 1]; lmb[j + 1] = temp; } } } return lmb; } /// <summary> /// 获得列表中。前两个可以走的格子 /// </summary> /// <param name="lmb"></param> /// <returns></returns> List<MoveBase> GetMaxNumList(List<MoveBase> lmb) { List<MoveBase> lb = new List<MoveBase>(); for (int i = 0; i < lmb.Count; i++) { if (lmb[i].Canmove) { lb.Add(lmb[i]); } if (lb.Count>=3) { break; } } return lb; } /// <summary> /// 得到移动路径 /// </summary> /// <param name="b"></param> /// <param name="lmb"></param> /// <returns></returns> MoveBase GetMovePath(Base b , List<MoveBase> lmb) { foreach (var item in lmb) { if (b.aroundBaseList.Contains(item.End)) { return item; } } Debug.Log("没找到"); return null; } } public class MoveBase { Base start; Base end; int num; public MoveBase(Base start, Base end, int num) { this.start = start; this.end = end; this.num = num; } public Base Start { get { return start; } set { start = value; } } public Base End { get { return end; } set { end = value; } } public int Num { get { return num; } set { num = value; } } public bool Canmove { get { return BaseManger.Instance.ChessMove(start, end); } } public override string ToString() { return (start + " " + end + " " + num); } } <file_sep>/Assets/Scripts/Base.cs using UnityEngine; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine.EventSystems; using DG.Tweening; using System; public enum PlayerState { Red, Black, None, } public class Base : MonoBehaviour ,IDropHandler, IInitializePotentialDragHandler,IDragHandler { Color c = new Color(1, 1, 1, 0);//初始颜色 Image _image;//图片 public bool canChess=true;//能不能下棋//默认可以 public bool isDropedChess;//能下棋。true 可以走 public int x; public int y; public PlayerState Ps; public List<Base> aroundBaseList;//周围可走路径 private void Awake() { _image = transform.Find("Image").GetComponent<Image>(); _image.color = c; } /// <summary> /// 初始化可走格子 /// </summary> public void InitList() { //待优化 初始化可走格子 bool b1 = ((x == 0||x==2||x==4) && (y == 1 || y == 3||y==5)); bool b2 = ((x == 1||x==3) && (y == 0 || y == 2|| y == 4)); if (b1||b2) { aroundBaseList = BaseManger.Instance.aroundLineBase(this); } else { aroundBaseList = BaseManger.Instance.aroundBase(this); } if ((x==0&&y==2)|| (x == 1 && y == 3) || (x == 4 && y == 2) || (x == 3 && y == 3) ) { return; } //if (x==2&&y==5) //{ // aroundBaseList.Remove(BaseManger.Instance.baseArr[0, 5]); // aroundBaseList.Remove(BaseManger.Instance.baseArr[4, 5]); //} if ((x==3||x==1||x==0||x==4)&&y==4) { aroundBaseList.Remove(BaseManger.Instance.baseArr[1, 5]); aroundBaseList.Remove(BaseManger.Instance.baseArr[3, 5]); //aroundBaseList.Remove(BaseManger.Instance.baseArr[2, 6]); } if (((x==1||x==3)&&y==5)||(x==2&&y==6)) { aroundBaseList = BaseManger.Instance.GetAppointBase(x, y); } } /// <summary> /// //放下棋子 /// </summary> /// <param name="b">实现的目标</param> /// <param name="back">是否是退回 用来区别是否是退回-退回true正常下false</param> /// <param name="current">是否是选中的棋子</param> /// <param name="ai">是否是AI放置的棋子</param> public void PutDownChess(Base b,bool back=false,bool current=false,bool ai=false) { if (ai) { _image.DOFade(1, 1);//TODO 修改AI棋子显示的时间 _image.sprite = b._image.sprite; } else { _image.color = Color.white; _image.sprite = b._image.sprite; } isDropedChess = false; Ps = b.Ps; b.Ps = PlayerState.None; if (current) { return; } BaseManger.Instance.GetPlayerBaseList(Ps).Add(this); if (back) { return; } BaseManger.Instance.EatChess(this); } /// <summary> /// 初始化图片 /// </summary> /// <param name="s"></param> /// <param name="p"></param> public void PutDownChess(Sprite s,PlayerState p) { _image.color = Color.white; _image.sprite = s; isDropedChess = false; Ps = p; } /// <summary> /// 拿起棋子 /// </summary> /// <returns></returns> public Base TakeUpChess() { isDropedChess = true; _image.color = c; BaseManger.Instance.GetPlayerBaseList(Ps).Remove(this); return this; } /// <summary> /// 被吃之后初始化 /// </summary> public void BeEat() { _image.DOFade(0, 0.5f);//TODO 修改被吃掉棋子消失的时间 BaseManger.Instance.GetPlayerBaseList(Ps).Remove(this); isDropedChess = true; Ps = PlayerState.None; } #region 旧的棋子移动模式 点击模式 要改回去需要改BaseManger.CurrentMove public void OnPointerClick(PointerEventData eventData) { if (Ps != BaseManger.Instance.tempPs && !BaseManger.Instance.isCurrent) { //该走颜色的棋子。跟你选择的棋子不一致 return; } if (eventData == null || PointerEventData.InputButton.Left == eventData.button) { if (BaseManger.Instance.isCurrent)//选中东西了 { if (isDropedChess) { //先判断能否走这个格子 BaseManger.Instance.EndBase = this; if (!BaseManger.Instance.ChessMove()) { //不能走 BaseManger.Instance.DontMove(); return; } //这块没东西把东西放下 PutDownChess(BaseManger.Instance.CloseCurrent(true)); } } else { if (!isDropedChess) { //拿起东西 BaseManger.Instance.CurrentBase.Ps = Ps; BaseManger.Instance.ShowCurrent(TakeUpChess()); BaseManger.Instance.StartBase = this; } } } } #endregion public void OnDrop(PointerEventData eventData) { //放下时候执行 if (Ps != BaseManger.Instance.tempPs && !BaseManger.Instance.isCurrent) { //该走颜色的棋子。跟你选择的棋子不一致 return; } if (eventData == null || PointerEventData.InputButton.Left == eventData.button) { if (BaseManger.Instance.isCurrent)//选中东西了 { if (isDropedChess) { //先判断能否走这个格子 BaseManger.Instance.EndBase = this; if (!BaseManger.Instance.ChessMove()) { //不能走 BaseManger.Instance.DontMove(); return; } //这块没东西把东西放下 PutDownChess(BaseManger.Instance.CloseCurrent(true)); } } } } public void OnInitializePotentialDrag(PointerEventData eventData) { if (Ps != BaseManger.Instance.tempPs && !BaseManger.Instance.isCurrent) { //该走颜色的棋子。跟你选择的棋子不一致 return; } if (eventData == null || PointerEventData.InputButton.Left == eventData.button) { if (!isDropedChess) { //拿起东西 BaseManger.Instance.CurrentBase.Ps = Ps; BaseManger.Instance.ShowCurrent(TakeUpChess()); BaseManger.Instance.StartBase = this; } } } public void OnDrag(PointerEventData eventData) { } } <file_sep>/Assets/Scripts/BaseManger.cs using UnityEngine; using System.Collections.Generic; using UnityEngine.UI; using System; using System.Collections; public class BaseManger : MonoBehaviour { #region 一些属性 public Base CurrentBase;//选中的棋子 GameObject BasePre; public static BaseManger Instance; public bool isCurrent; public Base[,] baseArr; Action InitBack; public Base StartBase; public Base EndBase; public List<Base> RedList; public List<Base> BlackList; public PlayerState tempPs; public Action AIPlay; #endregion //TODO 注意点 //不管胜几个棋子。只要没路走就算输。测试 //一次走一个格子 //平局咋算 //缺少介绍的4个按钮动画和结束输赢的动画 private void Awake() { Instance = this; BasePre = Resources.Load<GameObject>("Base"); CurrentBase = GameObject.Find("Canvas/Current").GetComponent<Base>(); } void Start() { } void Test() { List<int> list01 = new List<int>() {1,3,5,7,9}; List<int> list02 = new List<int>() {2,4,6,8,10}; List<int> list03 = new List<int>(); int alen = list01.Count; int blen = list02.Count; int a=0, b=0; while (a<alen&&b<blen) { if (list01[a]<list02[b]) { list03.Add(list01[a]); a++; } else { list03.Add(list02[b]); b++; } } while (a<alen) { list03.Add(list01[a]); a++; } while (b<blen) { list03.Add(list02[b]); b++; } foreach (var item in list03) { Debug.Log(item); } } void Update() { //CurrentMove(); //if (isCurrent && !Input.GetMouseButton(0)) if (isCurrent && Input.GetMouseButtonUp(0)) { DontMove(); } } private void FixedUpdate() { //CurrentMove(); if (isCurrent && Input.GetMouseButton(0)) { CurrentBase.transform.position = Input.mousePosition; } } #region 选中棋子的跟随。显示。隐藏 /// <summary> /// 点中棋子跟随鼠标 /// </summary> void CurrentMove() { if (isCurrent&&Input.GetMouseButton(0)) { CurrentBase.transform.position = Input.mousePosition; } else if (isCurrent&&!Input.GetMouseButton(0)) { DontMove(); } } /// <summary> /// 显示点中棋子 /// </summary> /// <param name="s"></param> public void ShowCurrent(Base b) { CurrentBase.transform.position = Input.mousePosition; isCurrent = true; CurrentBase.PutDownChess(b,true,true); CurrentBase.gameObject.SetActive(true); } /// <summary> /// 隐藏点中棋子 /// </summary> /// <returns></returns> public Base CloseCurrent(bool back=false) { isCurrent = false; CurrentBase.gameObject.SetActive(false); if (back) { ChangsPlayer(); StartCoroutine(Aplay()); } return CurrentBase; } /// <summary> /// 实现AI的移动 /// </summary> /// <returns></returns> IEnumerator Aplay() { yield return new WaitForSeconds(0.35f); if (AIPlay != null && StartBase != EndBase && StartBase.aroundBaseList.Contains(EndBase) && CurrentBase.Ps != PlayerState.Black) { AIPlay(); } } #endregion #region 一些初始化 /// <summary> /// 开始游戏初始化 /// </summary> public void StartGame() { baseArr = new Base[5, 7]; RedList = new List<Base>(); BlackList = new List<Base>(); tempPs = PlayerState.Red; NotificationManger.Instance.DispatchEvent(EventName.PlayerChang, new Notification(1)); InitBase(); InitPlayerChess(); } /// <summary> /// 结束游戏初始化 /// </summary> public void EndGame() { if (isCurrent) { DontMove(); } for (int i = 0; i < 5; i++) { for (int j = 0; j < 7; j++) { InitBack -= baseArr[i, j].InitList; Destroy(baseArr[i, j].gameObject); } } if (AIPlay != null) { AIPlay-=CompterAi.Instance.AIPlayChess; } PlayPanel.Instance.isPlay = false; } /// <summary> /// 初始化Base /// </summary> void InitBase() { for (int i = 0; i <= 4; i++) { for (int j = 0; j <= 6; j++) { GameObject g = Instantiate(BasePre); g.transform.SetParent(transform); g.transform.localScale = Vector3.one; Base b = g.GetComponent<Base>(); if (j==5&&(i==0||i==4)) { b.canChess = false; } else if (j==6&&i!=2) { b.canChess = false; } baseArr[i, j] = b; b.x = i; b.y = j; b.Ps = PlayerState.None; InitBack += b.InitList; g.name = i + "-" + j; } } InitBack(); } /// <summary> /// 初始化玩家格子 /// </summary> void InitPlayerChess() { Sprite Black = Resources.Load<Sprite>("Image/黑棋子"); Sprite Red = Resources.Load<Sprite>("Image/红棋子"); for (int i = 0; i < 5; i++) { baseArr[0, i].PutDownChess(Black, PlayerState.Black); BlackList.Add(baseArr[0, i]); baseArr[4, i].PutDownChess(Red, PlayerState.Red); RedList.Add(baseArr[4, i]); } baseArr[1, 0].PutDownChess(Black, PlayerState.Black); BlackList.Add(baseArr[1, 0]); baseArr[1, 4].PutDownChess(Black, PlayerState.Black); BlackList.Add(baseArr[1, 4]); baseArr[3, 0].PutDownChess(Red, PlayerState.Red); RedList.Add(baseArr[3, 0]); baseArr[3, 4].PutDownChess(Red, PlayerState.Red); RedList.Add(baseArr[3, 4]); } #endregion #region 判断两点中是否有障碍物和棋子是否符合移动的条件 /// <summary> /// 判断结束格子是否在可走格子内 /// </summary> /// <returns></returns> public bool endBaseInStartBaseList(Base a ,Base b) { if (a.aroundBaseList.Contains(b)) { //在内。可以走 return true; } return false; } /// <summary> /// 判断能否棋子移动 /// </summary> /// <returns></returns> public bool ChessMove(Base start = null,Base end = null) { if (start==null&&end==null) { start = StartBase; end = EndBase; } bool InList = endBaseInStartBaseList(start,end); if (InList) { return true; } else { return false; } } #endregion #region 一些其他的方法 /// <summary> /// 移动失败恢复走前状态 /// </summary> public void DontMove() { StartBase.PutDownChess(CloseCurrent(), true); } /// <summary> /// 倒计时到。随机走一步 /// </summary> public void TimeOut() { List<Base> tempList = GetPlayerBaseList(tempPs); Base temp; Base temp02; while (true) { temp = tempList[UnityEngine.Random.Range(0, tempList.Count)]; temp02 = temp.aroundBaseList[UnityEngine.Random.Range(0, temp.aroundBaseList.Count)]; if (temp02.Ps == PlayerState.None && temp02.isDropedChess) { break; } } Instance.StartBase = temp; Instance.EndBase = temp02; Base AIBase = temp.TakeUpChess();//拿起 temp02.PutDownChess(AIBase, false, false, true);//放下 ChangsPlayer();//换人走 } #endregion #region 吃棋子的判断和实现 /// <summary> /// 吃棋子 传入落子的base /// </summary> /// <param name="b"></param> public void EatChess(Base b) { ToEatBase(OnePickTwo(b));//一挑二 ToEatBase(TwoClipOne(b));//二夹一 ToEatBase(dachi(b));//打吃 if (WinOrLose()) { WinOrLose02(); } } /// <summary> /// 二夹一 /// </summary> /// <param name="b"></param> List<Base> TwoClipOne(Base b) { //周围距离1格的棋子 List<Base> AroundChess = aroundZeroBaseList(b,2); List<Base> lb = new List<Base>(); //如果有棋子而且类型一样。找找俩中间是否有棋子 for (int i = 0; i < AroundChess.Count; i++) { Base item = AroundChess[i]; if (b.Ps == item.Ps && !item.isDropedChess) { Base temp = GetBaseAroundByAtoB(b, item); if (temp==null) { continue; } if (temp.Ps != b.Ps && !temp.isDropedChess) { //说明吃掉了 lb.Add(temp); } } } return lb; } /// <summary> /// 一挑二 /// </summary> /// <param name="b"></param> List<Base> OnePickTwo(Base b) { List<Base> aroundList = aroundZeroBaseList(b); List<Base> samePathList = GetSamePathList(b, aroundList); List<Base> lb = new List<Base>(); while (samePathList.Count > 0) { Base temp01 = samePathList[0]; if (temp01.Ps==b.Ps) { samePathList.Remove(temp01); continue; } Base temp02 = GetSymmetricBase(b, temp01); if (temp02 == null)//如果temp02为空说明那边没格子 { samePathList.Remove(temp01); continue; } else if (temp01.isDropedChess || temp02.isDropedChess || temp01.Ps != temp02.Ps) { //如果2个格子中有一个格子没棋子或者两个格子的颜色不一致则执行 //要求两个格子都必须都东西。并且两个格子的颜色一致 samePathList.Remove(temp01); samePathList.Remove(temp02); continue; } else if (temp01.Ps == temp02.Ps && !temp01.isDropedChess && !temp02.isDropedChess) { samePathList.Remove(temp01); samePathList.Remove(temp02); lb.Add(temp01); lb.Add(temp02); continue; } Debug.Log("不会到这"); samePathList.Remove(temp01); samePathList.Remove(temp02); } return lb; } /// <summary> /// 打吃 同一条线上两颗相邻的相同颜色的棋子。可以吃在他俩同一条线上的其他棋子; /// </summary> List<Base> dachi(Base b) { List<Base> AroundSameBase = new List<Base>(); //遍历周围紧贴的格子。并且是相同路径的 foreach (var item in GetSamePathList(b, aroundZeroBaseList(b))) { //如果这个格子跟方子的格子ps一样。加入LIST if (item.Ps==EndBase.Ps) { AroundSameBase.Add(item); } } List<Base> lbs = new List<Base>(); foreach (var item in AroundSameBase) { List<Base> lb = GetLineBase(b, item); foreach (var tempBase in lb) { lbs.Add(tempBase); } } return lbs; } /// <summary> /// 实现列表中的格子被吃掉 /// </summary> /// <param name="lb"></param> void ToEatBase(List<Base> lb) { foreach (var item in lb) { item.BeEat(); } } #endregion #region 输赢显示和判断 /// <summary> /// 展示输赢 /// </summary> /// <param name="ps"></param> void ShowWin(PlayerState ps) { Notification no = new Notification(); //TODO 人人对战的结局 if (ps == PlayerState.Red) { no.Str = "RedWin"; } else if (ps==PlayerState.Black) { no.Str = "BlackWin"; } EndGame(); UIManger.Instance.PushPanel(UIName.EndPanel); NotificationManger.Instance.DispatchEvent(EventName.WinImage, no); } /// <summary> /// 输赢判断 不管剩几个字。如果一方的周围都不能走了。就算该方输 /// </summary> /// <param name="b"></param> bool WinOrLose() { List<Base> TempList = new List<Base>(); //遍历黑色方 if (EndBase.Ps == PlayerState.Red) { foreach (var item in BlackList) { TempList = GetSamePathList(item, aroundZeroBaseList(item)); foreach (var item02 in TempList) { if (item02.isDropedChess) { return true; } } } //说明黑色的无路可走了 Debug.Log("qq"); ShowWin(PlayerState.Red); return false; } else if (EndBase.Ps == PlayerState.Black) { foreach (var item in RedList) { TempList = GetSamePathList(item, aroundZeroBaseList(item)); foreach (var item02 in TempList) { if (item02.isDropedChess) { return true; } } } //说明红色的无路可走了 Debug.Log("ww"); ShowWin(PlayerState.Black); return false; } Debug.Log("出大问题了"); return false; } /// <summary> /// 第二种输赢判断 看双方剩余棋子的数量 /// </summary> /// <returns></returns> bool WinOrLose02() { if (RedList.Count==0) { ShowWin(PlayerState.Black); return false; } else if (BlackList.Count==0) { Debug.Log("ee"); ShowWin(PlayerState.Red); return false; } else if (BlackList.Count==1&&RedList.Count==1) { Debug.Log("rr"); //TODO 平局算黑手赢 ShowWin(PlayerState.Black); return false; } return true; } #endregion #region 获得特定格子的方法 /// <summary> /// 周围竖向和横向的格子--一格 /// </summary> /// <param name="b"></param> /// <returns></returns> public List<Base> aroundLineBase(Base b) { List<Base> Lb = new List<Base>(); for (int i = -1; i <= 1; i++) { int x = b.x + i; if ((x >= 5 || x < 0)) { continue; } for (int j = -1; j <= 1; j++) { int y = b.y + j; if (y >= 7 || y < 0 || Mathf.Abs(i) == Mathf.Abs(j)) { continue; } if ((i != 0 && j != 0)) { continue; } if (baseArr[x, y].canChess) { Lb.Add(baseArr[x, y]); } } } return Lb; } /// <summary> /// 获得周围周围格子--格 /// </summary> /// <param name="b"></param> /// <returns></returns> public List<Base> aroundBase(Base b) { List<Base> Lb = new List<Base>(); for (int i = -1; i <= 1; i++) { int x = b.x + i; if ((x >= 5 || x < 0)) { continue; } for (int j = -1; j <= 1; j++) { if ((Mathf.Abs(i) == Mathf.Abs(j) || i == 0 || j == 0) && !(i == 0 && j == 0)) { int y = b.y + j; if (y >= 7 || y < 0) { continue; } if (baseArr[x, y].canChess) { Lb.Add(baseArr[x, y]); } } } } return Lb; } /// <summary> /// 得到特定点的可移动的base /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public List<Base> GetAppointBase(int x, int y) { List<Base> Lb = new List<Base>(); if ((x == 1 && y == 5) || (x == 3 && y == 5)) { Lb.Add(baseArr[2, 4]); Lb.Add(baseArr[2, 5]); Lb.Add(baseArr[2, 6]); } else if (x == 2 && y == 6) { Lb.Add(baseArr[2, 5]); Lb.Add(baseArr[1, 5]); Lb.Add(baseArr[3, 5]); } return Lb; } /// <summary> /// 获得周围紧贴着的格子 /// </summary> /// <param name="b"></param> /// <returns></returns> List<Base> aroundZeroBaseList(Base b,int num =1) { List<Base> Lb = new List<Base>(); for (int i = -1*num; i <= 1 * num; i=i+1 * num) { int x = b.x + i; if (x > 4 || x < 0) { continue; } for (int j = -1 * num; j <= 1 * num; j=j+1 * num) { int y = b.y + j; if (y > 6 || y < 0) { continue; } if (baseArr[x, y].canChess) { Lb.Add(baseArr[x, y]); } } } return Lb; } /// <summary> /// 返回两个格子中间的格子 /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> Base GetBaseAroundByAtoB(Base a, Base b) { int x = (a.x + b.x) / 2; int y = (a.y + b.y) / 2; //这个格子可以走并且这个格子在两个格子的可走路径中 if (baseArr[x, y].canChess && a.aroundBaseList.Contains(baseArr[x, y]) && b.aroundBaseList.Contains(baseArr[x, y])) { return (baseArr[x, y]); } return null; } /// <summary> /// 得到存储玩家Base的List /// </summary> /// <param name="ps"></param> /// <returns></returns> public List<Base> GetPlayerBaseList(PlayerState ps) { if (ps == PlayerState.Red) { return RedList; } else if (ps==PlayerState.Black) { return BlackList; } else { return null; } } /// <summary> /// 根据b可走路径的list和周围格子的list 得到b周围可走的格子 /// </summary> /// <param name="b"></param> /// <param name="Lb"></param> /// <returns></returns> List<Base> GetSamePathList(Base b, List<Base> Lb) { List<Base> lb = new List<Base>(); foreach (var item in Lb) { if (b.aroundBaseList.Contains(item)) { if (item.canChess) { lb.Add(item); } } } return lb; } /// <summary> /// 得到以center为中心。point为点的。对称对应的base /// </summary> /// <param name="center"></param> /// <param name="Point"></param> /// <returns></returns> Base GetSymmetricBase(Base center, Base Point) { int tempx = center.x - Point.x; int tempy = center.y - Point.y; int x = center.x + tempx; int y = center.y + tempy; if (x > 4 || x < 0 || y > 6 || y < 0|| !baseArr[x, y].canChess) { return null; } //另外一个格子的可走路径必须有中心点 if (!baseArr[x, y].aroundBaseList.Contains(center)) { return null; } return baseArr[x, y]; } /// <summary> /// 该另外一个人走了 /// </summary> public void ChangsPlayer() { if (StartBase==EndBase||!StartBase.aroundBaseList.Contains(EndBase)) { return; } if (tempPs == PlayerState.Black) { tempPs = PlayerState.Red; Notification no = new Notification(); no.Flo = 1f; NotificationManger.Instance.DispatchEvent(EventName.PlayerChang, no); return; } else if (tempPs==PlayerState.Red) { tempPs = PlayerState.Black; Notification no = new Notification(); no.Flo = 2f; NotificationManger.Instance.DispatchEvent(EventName.PlayerChang, no); return; } Debug.Log(tempPs); Debug.Log("出问题了"); } /// <summary> /// 返回根据在两点确定的同一条线上的另外两个格子 /// </summary> /// <param name="start"></param> /// <param name="end"></param> /// <returns></returns> List<Base> GetLineBase(Base start,Base end) { int tempx = start.x - end.x; int tempy = start.y - end.y; int x1 = start.x + tempx; int y1 = start.y + tempy; int x2 = end.x - tempx; int y2 = end.y - tempy; List<Base> lb = new List<Base>(); if (x1 >= 0 && x1 < 5 && y1 >= 0 && y1 < 7) { if (baseArr[x1, y1].Ps != start.Ps&& baseArr[x1, y1].Ps !=PlayerState.None) { lb.Add(baseArr[x1, y1]); } } if (x2 >= 0 && x2 < 5 && y2 >= 0 && y2 < 7) { if (baseArr[x2, y2].Ps != start.Ps && baseArr[x2, y2].Ps != PlayerState.None) { lb.Add(baseArr[x2, y2]); } } return lb; } /// <summary> /// 得到指定格子可以吃其他格子的数量 /// </summary> /// <param name="b"></param> /// <returns></returns> public int GetNum(Base b) { int num = OnePickTwo(b).Count + TwoClipOne(b).Count + dachi(b).Count; return num; } #endregion } <file_sep>/Assets/Scripts/UI/StartPanel.cs using UnityEngine; using System.Collections; using UnityEngine.UI; public class StartPanel: BasePanel { public static StartPanel Instance; Button Introduce; Button PeoplePlay; Button CompterPlay; GameObject g; private void Awake() { Instance = this; InitUI(); } #region 初始化BTN。绑定对应事件 void InitUI() { Introduce = transform.Find("Introduce").GetComponent<Button>(); Introduce.onClick.AddListener(Introduce_Event); PeoplePlay = transform.Find("PeoplePlay").GetComponent<Button>(); PeoplePlay.onClick.AddListener(PeoplePlay_Event); CompterPlay = transform.Find("CompterPlay").GetComponent<Button>(); CompterPlay.onClick.AddListener(CompterPlay_Event); } public void Introduce_Event() { UIManger.Instance.PushPanel(UIName.IntroducePanel); } void PeoplePlay_Event() { UIManger.Instance.PushPanel(UIName.PlayPanel); PlayPanel.Instance.Open(0); } void CompterPlay_Event() { UIManger.Instance.PushPanel(UIName.PlayPanel); PlayPanel.Instance.Open(1); } #endregion } <file_sep>/Assets/Scripts/UI/PlayPanel.cs using UnityEngine; using System.Collections; using UnityEngine.UI; using DG.Tweening; public class PlayPanel : BasePanel { public static PlayPanel Instance; Text TimeText; Image PromptImage; Button back; Image player1; Image player2; public float AppointTime=30f; float Times; Color _color01 = new Color(90 / 255f, 90 / 255f, 90 / 255f, 1); Color _color02 = Color.white; public bool isPlay; private void Start() { Times = AppointTime; } private void Awake() { Instance = this; UIInit(); EventInit(); } private void Update() { if (isPlay) { if (Times < 0.5f) { BaseManger.Instance.TimeOut(); } Times -= Time.deltaTime; ChangsTime(Times); ChangsImage(); } } #region 初始化UI及Btn赋值 void UIInit() { back = transform.Find("Back").GetComponent<Button>(); back.onClick.AddListener(back_Btn_Event); TimeText = transform.Find("Time/Time_Text").GetComponent<Text>(); PromptImage = transform.Find("Prompt/PromptImage").GetComponent<Image>(); player1 = transform.Find("qipan/Player1").GetComponent<Image>(); player2 = transform.Find("qipan/Player2").GetComponent<Image>(); } void EventInit() { NotificationManger.Instance.AddEventListener(EventName.PlayerChang, ChangPlayer); //NotificationManger.Instance.AddEventListener(EventName.PromptChangs, ChangsPromptText); } void back_Btn_Event() { BaseManger.Instance.EndGame(); isPlay = false; UIManger.Instance.PushPanel(UIName.StartPanel); } #endregion public void Open(float Time = 0) { PlayerPrefs.SetFloat("state", Time); Times = AppointTime; timeKeep = 0; if (Time==1) { player1.sprite = Resources.Load<Sprite>("Image/玩家"); player2.sprite = Resources.Load<Sprite>("Image/电脑"); BaseManger.Instance.AIPlay += CompterAi.Instance.AIPlayChess; } else { player1.sprite = Resources.Load<Sprite>("Image/玩家"); player2.sprite = player1.sprite; } isPlay = true; BaseManger.Instance.StartGame(); } /// <summary> /// 修改提示文字 /// </summary> /// <param name="str"></param> /// public void ChangPlayer(Notification obj) { //PromptText.text = obj.Str; if (obj.Flo==1) { player1.color = _color02; player2.color = _color01; } else if (obj.Flo==2) { player1.color = _color01; player2.color = _color02; } else { Debug.Log("出问题了"); } Times = AppointTime; } float timeKeep = 0; int index = 0; void ChangsImage() { timeKeep += Time.deltaTime; if (timeKeep >= 3) { PromptImage.sprite = Resources.Load<Sprite>("Image/TS0" + index % 3); //AniChangs(); timeKeep = 0; index++; } } void AniChangs() { PromptImage.DOFade(0, 0.5f*2).OnComplete(() => { PromptImage.sprite = Resources.Load<Sprite>("Image/TS0" + index % 3); PromptImage.DOFade(1, 0.5f*2); }); } void ChangsTime(float Times) { TimeText.text = Times.ToString("0"); } } <file_sep>/Assets/Test/Test.cs using UnityEngine; using System.Collections; using UnityEngine.EventSystems; using System; public class Test : MonoBehaviour,IPointerClickHandler { public void OnPointerClick(PointerEventData eventData) { Debug.Log("qqq"); } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } } <file_sep>/Assets/Scripts/Notification/NotificationManger.cs using UnityEngine; using System.Collections; using System.Collections.Generic; public enum EventName { TimeChangs,//时间 PromptChangs,//提醒 WinImage,//总时间 PlayerChang,//修改玩家 } public class NotificationManger { public delegate void OnNotification(Notification obj); private static NotificationManger instance = null; public static NotificationManger Instance { get { if (instance == null) { instance = new NotificationManger(); return instance; } return instance; } } /// <summary> /// 存储事件的字典 /// </summary> private Dictionary<EventName, OnNotification> eventListeners = new Dictionary<EventName, OnNotification>(); /// <summary> /// 注册事件 /// </summary> ///<param name="eventKey">事件Key ///<param name="eventListener">事件监听器 public void AddEventListener(EventName eventKey, OnNotification eventListener) { if (!eventListeners.ContainsKey(eventKey)) { eventListeners.Add(eventKey, eventListener); } } /// <summary> /// 移除事件 /// </summary> ///<param name="eventKey">事件Key public void RemoveEventListener(EventName eventKey) { if (!eventListeners.ContainsKey(eventKey)) return; eventListeners[eventKey] = null; eventListeners.Remove(eventKey); } /// <summary> /// 分发事件 /// </summary> ///<param name="eventKey">事件Key ///<param name="param">通知内容 public void DispatchEvent(EventName eventKey, Notification obj) { if (!eventListeners.ContainsKey(eventKey)) return; eventListeners[eventKey](obj); } /// <summary> /// 是否存在指定事件的监听器 /// </summary> public bool HasEventListener(EventName eventKey) { return eventListeners.ContainsKey(eventKey); } } public class Notification { string str; float flo; object obj; public string Str { get { return str; } set { str = value; } } public float Flo { get { return flo; } set { flo = value; } } public object Obj { get { return obj; } set { obj = value; } } public Notification() { } public Notification(string str) { this.Str = str; } public Notification(float flo) { this.Flo = flo; } public Notification(object obj) { this.Obj = obj; } } <file_sep>/Assets/Scripts/UI/EndPanel.cs using UnityEngine; using System.Collections; using UnityEngine.UI; public class EndPanel : BasePanel { Image WinImage; Button back; Button ReturnPlay; private void Awake() { UIInit(); EventInit(); } #region 初始化UI及Btn赋值 void UIInit() { back = transform.Find("Back").GetComponent<Button>(); back.onClick.AddListener(back_Btn_Event); ReturnPlay = transform.Find("RetrunPlay").GetComponent<Button>(); ReturnPlay.onClick.AddListener(ReturnPlay_Btn_Event); WinImage = transform.Find("WinImage").GetComponent<Image>(); } void EventInit() { NotificationManger.Instance.AddEventListener(EventName.WinImage, WinImageChang); } void WinImageChang(Notification no) { WinImage.sprite = Resources.Load<Sprite>("Image/" + no.Str); } void back_Btn_Event() { //回主菜单 UIManger.Instance.PushPanel(UIName.StartPanel); } void ReturnPlay_Btn_Event() { UIManger.Instance.PushPanel(UIName.PlayPanel); PlayPanel.Instance.Open(PlayerPrefs.GetFloat("state")); } #endregion }
ff66117e350235f87144f9b58e801482f57ea99f
[ "C#" ]
12
C#
ArsenalHolmes/wumaqi0718
5410360bad9ce960da2c7b6722986e6ca54d99eb
e9cd5f0128f1d951955ffa40dc73a05fd16fe9fb
refs/heads/main
<repo_name>nguyenvandai61/BKDN_AI_CONTEST<file_sep>/ai_contest_website/api/routes/UserRoutes.py from django.urls import path from api.api_views import UserLoginView, UserRegisterView, UserList, UserInfo urlpatterns = [ path('', UserList.as_view(), name='index'), path('<str:pk>/', UserInfo.as_view(), name='user_detail'), ]<file_sep>/tool_run_model/result/bai1/code_test.py import pickle import sys from sklearn.metrics import confusion_matrix, classification_report, accuracy_score model = pickle.load(open("model.pkl", "rb")) import numpy as np import pandas as pd inp = sys.stdin.read() inp = np.array([inp.split(",")]) inp = pd.DataFrame(inp, columns = ['SepalLengthCm','SepalWidthCm','PetalLengthCm','PetalWidthCm']) # print(type(inp)) # test_X = iris[['SepalLengthCm','SepalWidthCm','PetalLengthCm','PetalWidthCm']] # taking test data feature prediction = model.predict(inp) # print(list(prediction)) [print(x) for x in list(prediction)]<file_sep>/ai_contest_website/api/serializers/__init__.py from .ContestSerializer import ContestSerializer from .LanguageSerializer import LanguageSerializer from .ProblemSerializer import ProblemSerializer from .ResultSerializer import ResultSerializer from .UserSerializer import UserSerializer, RegisterUserSerializer from .HtmlDocumentSerializer import HtmlDocumentSerializer<file_sep>/ai_contest_website/api/api_views/contest_api.py from bson import json_util from rest_framework import permissions, viewsets, status, views from django.shortcuts import render from django.http import JsonResponse from rest_framework.decorators import api_view from rest_framework.response import Response from django.core import serializers from api.models import Contest from api.serializers.UserSerializer import UserSerializer from rest_framework.renderers import JSONRenderer from api.serializers.ContestSerializer import ContestSerializer from rest_framework import generics, permissions from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework import status from rest_framework.views import APIView from rest_framework_simplejwt.serializers import TokenObtainPairSerializer class ContestList(generics.ListCreateAPIView): queryset = Contest.objects.all() serializer_class = ContestSerializer def list(self, request): queryset = self.get_queryset() serializer = ContestSerializer(queryset, many=True) return Response(serializer.data) class ContestInfo(generics.GenericAPIView): queryset = Contest.objects serializer_class = ContestSerializer def get(self, request, *args, **kwargs): try: obj = self.get_object() except Exception as exc: return Response(status=status.HTTP_404_NOT_FOUND) serializer = self.get_serializer(obj) return Response(serializer.data) def delete(self, request, *args, **kwargs): try: obj = self.get_object() except Exception as exc: return Response(status=status.HTTP_404_NOT_FOUND) operator = obj.delete() data = {} if operator: data["success"] = "Delete contest successful" else: data["failure"] = "Delete contest failed" return Response(data=data) def put(self, request, *args, **kwargs): try: obj = self.get_object() except Exception as exc: return Response(status=status.HTTP_404_NOT_FOUND) serializer = ContestSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({ 'message': 'Contest is updated successful' }, status=status.HTTP_200_OK) return Response({ 'message': 'Contest is updated failed' }, status=status.HTTP_400_BAD_REQUEST) class AttendedContest(generics.GenericAPIView): queryset = Contest.objects.all() serializer_class = ContestSerializer def get(self, request, *args, **kwargs): id = self.kwargs['id'] print("id: ", id) queryset = self.get_queryset() # queryset = queryset.filter(title='BKDN AI') # testList = ["BKDN AI","bkdnContest 1"] queryset = queryset.filter(contestants=id) # queryset = queryset.filter(username__in = contestList) # queryset = queryset.filter(contestants=username) serializer = ContestSerializer(queryset, many=True) return Response(serializer.data)<file_sep>/tool_run_model/controller.py from data_access import * from variable import * import shutil, os, subprocess from datetime import datetime def excute_code(file_path, language, code_test_name_file, code_train_name_file, input_file, output_file): # try: os.chdir(file_path) # Load result data_output = open(os.path.join(file_path, output_file), 'r').readlines() data_output = [x.replace("\n","").strip() for x in data_output if x != "" or x != None] # Load input data_input = open(os.path.join(file_path, input_file), 'r').readlines() data_input = [x.replace("\n","").strip() for x in data_input if x != "" or x != None] # excute if language == "python2": count = 0 list_test = [] for inp, out in tuple(zip(data_input, data_output)): test_info = {} ttime = datetime.now().timestamp() output_test = subprocess.run(["python", code_test_name_file], capture_output=True, text=True, input=inp) ttime = datetime.now().timestamp() - ttime test_info["time_excute"] = str(ttime) print(str(output_test.stdout).replace("\n","").strip()) if str(out) == str(output_test.stdout).replace("\n","").strip(): test_info["status"] = True count += 1 else: test_info["status"] = False test_info["error"] = str(output_test.stderr) list_test.append(test_info) print(list_test) accuracy = round(float(count/len(data_output)), 5) return (accuracy, list_test) elif language == "python3": count = 0 list_test = [] for inp, out in tuple(zip(data_input, data_output)): test_info = {} ttime = datetime.now().timestamp() output_test = subprocess.run([PYTHON3_VENV, code_test_name_file], capture_output=True, text=True, input=inp) ttime = datetime.now().timestamp() - ttime test_info["time_excute"] = str(ttime) print(str(output_test.stdout).replace("\n","").strip()) if str(out) == str(output_test.stdout).replace("\n","").strip(): test_info["status"] = True count += 1 else: test_info["status"] = False test_info["error"] = str(output_test.stderr) list_test.append(test_info) print(list_test) accuracy = round(float(count/len(data_output)), 5) return (accuracy, list_test) elif language == "c++": count = 0 list_test = [] for inp, out in tuple(zip(data_input, data_output)): test_info = {} ttime = datetime.now().timestamp() output_test = subprocess.run(["g++", code_test_name_file], capture_output=True, text=True, input=inp) ttime = datetime.now().timestamp() - ttime test_info["time_excute"] = str(ttime) print(str(output_test.stdout).replace("\n","").strip()) if str(out) == str(output_test.stdout).replace("\n","").strip(): test_info["status"] = True count += 1 else: test_info["status"] = False test_info["error"] = str(output_test.stderr) list_test.append(test_info) print(list_test) accuracy = round(float(count/len(data_output)), 5) return (accuracy, list_test) elif language == "javascript": count = 0 list_test = [] for inp, out in tuple(zip(data_input, data_output)): test_info = {} ttime = datetime.now().timestamp() output_test = subprocess.run([PYTHON3_VENV, code_test_name_file], capture_output=True, text=True, input=inp) ttime = datetime.now().timestamp() - ttime test_info["time_excute"] = str(ttime) print(str(output_test.stdout).replace("\n","").strip()) if str(out) == str(output_test.stdout).replace("\n","").strip(): test_info["status"] = True count += 1 else: test_info["status"] = False test_info["error"] = str(output_test.stderr) list_test.append(test_info) print(list_test) accuracy = round(float(count/len(data_output)), 5) return (accuracy, list_test) # except Exception as exc: # print("Error in excute code: %s" % str(exc)) return (None, None) def process_result(): try: db = DataBase() result = db.get_result() if result != None: result["status"] = "I" db.update_result(result) language = db.get_language(str(result["language_id"])) problem = db.get_problem(result["problem_id"]) input_test_file = problem["train_data"] # input.csv result_file = problem["test_data"] # output.csv start_time = datetime.now().timestamp() result["accuracy"], result["result_info"] = excute_code(result["path_code"], language, result["code_test"], result["code_train"], input_test_file, result_file) result["time_excute"] = round(datetime.now().timestamp() - start_time, 5) result["status"] = "S" db.update_result(result) except Exception as exc: print("Error in process result: %s" % str(exc)) <file_sep>/ai_contest_website/api/serializers/ContestSerializer.py from rest_meets_djongo.serializers import DjongoModelSerializer from api.models import Contest from django.http import JsonResponse from rest_framework.renderers import JSONRenderer from api.serializers.UserSerializer import UserIdSerializer from api.serializers.LanguageSerializer import LanguageSerializer class ContestSerializer(DjongoModelSerializer): # created_user = UserIdSerializer() # language = LanguageSerializer(many=True) contestants = UserIdSerializer(many=True) class Meta: model = Contest fields = ('_id', 'title', 'created', 'contestants', 'time_start', 'time_end') def create(self, validated_data): contest = Contest.objects.create(**validated_data) return contest def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) # instance.created_user = validated_data.get('created_user', instance.created_user) instance.created = validated_data.get('created', instance.created) instance.contestants = validated_data.get('contestants', instance.contestants) # instance.language = validated_data.get('language', instance.language) instance.time_start = validated_data.get('time_start', instance.time_start) instance.time_end = validated_data.get('time_end', instance.time_end) instance.save() return instance def validate(self, data): validated_data = data return data class ContestIdSerializer(DjongoModelSerializer): class Meta: model = Contest fields = ['_id'] def create(self, validated_data): contest = Contest.objects.create(**validated_data) return contest def validate(self, data): validated_data = data return data # contest = Contest(title='bkdnContest 1') # contest.save() # serializer_class = ContestSerializer(contest) # print(JSONRenderer().render(serializer_class.data))
8cc8e5ed09d482a89dd86272df0588b0302e3176
[ "Python" ]
6
Python
nguyenvandai61/BKDN_AI_CONTEST
928f459b033251242024b997e77d54446d2ffd97
6dcbec8cf1b4d75fd9fe8995c010dc0ff8818d06
refs/heads/main
<file_sep>// $('#navigation ul li').css('display', 'inline-block'); Refer this to change style using jquery function leftnew() { $(".accupaymain").addClass("triggerChange"); // $(".signupleft").addClass("signupleftnew"); // $(".signupright").addClass("signuprightnew"); // // $(".signupleft").addClass("loginmsgright"); // $(".loginright").addClass("loginrightnewone"); // // $(".signupright").addClass("signuprightnew"); // $(".loginleft").addClass("loginleftnewone"); } function rightnew() { $(".accupaymain").removeClass("triggerChange"); // $(".loginright").addClass("loginrightnew"); // $(".loginleft").addClass("loginleftnew"); // $(".signupright").addClass("signupleftnewone"); // $(".signupleft").addClass("signuprightnewone"); } function init(){ $(".navin").click(leftnew); $(".navup").click(rightnew); } $(document).ready(init);
cc008761a2121dfcdae458e1477cc8eedc05c2e9
[ "JavaScript" ]
1
JavaScript
developerbro12/developerbro.github.io
ce8bd24a74276c47ae0ce7d08200703822fb22aa
6a013a1a2c6fd4c8d6bf9d4c73c77c375c567dd4
refs/heads/main
<file_sep>// // LoginVC.swift // SnipDesignSustainably // // Created by <NAME> on 12/28/20. // import UIKit class LoginVC: UIViewController, UITextFieldDelegate { @IBOutlet var emailTextField: UITextField! @IBOutlet var passwordTextField: UITextField! @IBOutlet var LoginBtn: UIButton! @IBOutlet weak var FBBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() //Style buttons title = "Login" FBBtn.layer.cornerRadius = FBBtn.frame.height/2 FBBtn.clipsToBounds = true LoginBtn.layer.cornerRadius = LoginBtn.frame.size.height / 2 LoginBtn.clipsToBounds = true LoginBtn.backgroundColor = .clear LoginBtn.layer.borderWidth = 3 LoginBtn.layer.borderColor = CGColor.init(red: 0.84, green: 0.84, blue: 0.84, alpha:1) //Textfiied emailTextField.delegate = self passwordTextField.delegate = self } func textFieldDidBeginEditing(_ textField: UITextField) { } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { return true } @IBAction func LoginClick(_ sender: Any) { if emailTextField.text == "admin" && passwordTextField.text == "<PASSWORD>" && emailTextField.text?.count ?? 0 >= 5 && passwordTextField.text?.count ?? 0 >= 5 { let storyboard = UIStoryboard(name: "Main", bundle: nil) let dashBoard = storyboard.instantiateViewController(identifier: "onboarding1") self.navigationController?.dismiss(animated: false, completion: nil) self.show(dashBoard, sender: self) } else { let alert = UIAlertController(title: "Password and username too short", message: "Please input the a username and password greater than 5.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) self.present(alert, animated: true) } } @IBAction func backBtnPressed(_ sender: Any) { self.navigationController?.popViewController(animated: true) } } <file_sep>// // HomeViewController.swift // SnipDesignSustainably // // Created by <NAME> on 1/27/21. // import UIKit import Kingfisher struct Car: Decodable { let models : [String] } class HomeViewController: UIViewController { @IBOutlet var tableView: UITableView! let vm = HomeViewModel() override func viewDidLoad() { super.viewDidLoad() vm.getDataFromDataProvider() self.navigationController?.dismiss(animated: true, completion: nil) self.navigationItem.setHidesBackButton(true, animated: false) //Load Local JSON //Set the logo in the navigation bar let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20)) imageView.contentMode = .scaleAspectFit let image = UIImage(named: "logo") imageView.image = image navigationItem.titleView = imageView } } extension HomeViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return vm.size() } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print(" You have selected ---> \(indexPath.row)") // let storyboard = UIStoryboard(name: "Main", bundle: nil) // let infoCollection = storyboard.instantiateViewController(identifier: "DetailsViewController") // self.show(infoCollection, sender: self) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell1 = HomeCell(title: vm.getUserTitel(pos: indexPath.row), location: vm.getLocation(pos: indexPath.row), time: vm.getTime(pos: indexPath.row), tags: vm.getTags(pos: indexPath.row), description: vm.getDescription(pos: indexPath.row), GP:vm.getGP(pos: indexPath.row)) let cell = tableView.dequeueReusableCell(withIdentifier: "restaurantCell") as! HomeTableViewCell cell.image1.kf.setImage(with: vm.randomImage()) cell.setCell(homeCell: cell1) return cell } } //------------------------------------------------------- <file_sep>// // ShareViewController.swift // SnipDesignSustainably // // Created by <NAME> on 2/5/21. // import UIKit import Kingfisher let reuseIdentifier1 = "CellIdentifer1"; class ShareViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { @IBOutlet var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() // let url1 = "https://picsum.photos/id/" // let url2 = "/300/300" // let aRandomInt = Int.random(in: 0...1000) // let randNum = String(aRandomInt) // let url = url1 + randNum + url2 // _ = URL(string: url) // // } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //UICollectionViewDatasource methods func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 50 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as UICollectionViewCell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier1, for: indexPath) as! CollectionViewCell1 let url1 = "https://picsum.photos/id/" let url2 = "/300/300" let aRandomInt = Int.random(in: 0...1000) let randNum = String(aRandomInt) let url = url1 + randNum + url2 let URL1 = URL(string: url) cell.image.kf.setImage(with: URL1) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let noOfCellsInRow = 3 let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout let totalSpace = flowLayout.sectionInset.left + flowLayout.sectionInset.right + (flowLayout.minimumInteritemSpacing * CGFloat(noOfCellsInRow - 1)) let size = Int((collectionView.bounds.width - totalSpace) / CGFloat(noOfCellsInRow)) return CGSize(width: size, height: size) } } <file_sep>// // SavedDetailsViewController.swift // SnipDesignSustainably // // Created by <NAME> on 2/4/21. // import UIKit class SavedDetailsViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } } <file_sep>// // DIYTypeViewController.swift // SnipDesignSustainably // // Created by <NAME> on 1/27/21. // import UIKit import CoreData class DIYTypeViewController: UIViewController { @IBOutlet var DYIInputView: UITextField! @IBOutlet var FavoriteCategoriesEditText: UITextField! var u: User? let appDelegate = UIApplication.shared.delegate as! AppDelegate var selectedDiy: String? var selectedCategories: String? let FavoriteDIY = ["Furniture", "Crafts", "Clothes", "Costumes", "Electronics"] let Categories = ["Weekend build", "Best Daily", "Easy", "Medium", "Hard"] override func viewDidLoad() { super.viewDidLoad() //Data for picker views let ALPicker = UIPickerView() ALPicker.delegate = self ALPicker.dataSource = self ALPicker.tag = 1 //ALPicker.delegate = DIYPickerDelegate DYIInputView.inputView = ALPicker //DYIInputView.text = FavoriteDIY[ALPicker.selectedRow(inComponent: 0)] let ALPicker2 = UIPickerView() ALPicker.tintColor = UIColor.black ALPicker2.delegate = self ALPicker2.dataSource = self ALPicker2.tag = 2 //ALPicker2.delegate = CategoriesPickerDelegate FavoriteCategoriesEditText.inputView = ALPicker2 } @IBAction func nextPressed(_ sender: Any) { if u != nil { print("here 1") u?.diyFav = DYIInputView.text u?.catFav = FavoriteCategoriesEditText.text appDelegate.saveContext() let storyboard = UIStoryboard(name: "Main", bundle: nil) let dashBoard = storyboard.instantiateViewController(identifier: "onboarding3") self.navigationController?.dismiss(animated: false, completion: nil) self.show(dashBoard, sender: self) } u = User.init(context: appDelegate.getMOCOrViewContext()) u?.diyFav = DYIInputView.text u?.catFav = FavoriteCategoriesEditText.text appDelegate.saveContext() } @IBAction func backBtnPressed(_ sender: Any) { self.navigationController?.popViewController(animated: true) } @IBAction func skipPressed(_ sender: Any) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let dashBoard = storyboard.instantiateViewController(identifier: "onboarding3") self.navigationController?.dismiss(animated: false, completion: nil) self.show(dashBoard, sender: self) } } extension DIYTypeViewController: UIPickerViewDelegate, UIPickerViewDataSource{ func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if pickerView.tag == 1 { return FavoriteDIY.count } else { return Categories.count } } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if pickerView.tag == 1 { return FavoriteDIY[row] } else { return Categories[row] } } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if pickerView.tag == 1 { selectedDiy = FavoriteDIY[row] DYIInputView.text = selectedDiy } else { selectedCategories = Categories[row] FavoriteCategoriesEditText.text = selectedCategories } } func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { var label: UILabel if let view = view as? UILabel{ label = view } else { label = UILabel() } if pickerView.tag == 1 { label.textColor = .white label.textAlignment = .center label.text = FavoriteDIY[row] return label } else { label.textColor = .white label.textAlignment = .center label.text = Categories[row] return label } } private func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { if pickerView.tag == 1 { return FavoriteDIY[row] } else { return Categories[row] } }} <file_sep>// // DataProvider.swift // MVVMEx1 // // Created by <NAME> on 09/02/21. // import UIKit import CoreData class DataProvider { func getData() ->[UserModel] { let appDelegate = UIApplication.shared.delegate as! AppDelegate var dataSourceArray: [User]? var data = [UserModel]() let command = NSFetchRequest<User>.init(entityName: "User") do{ dataSourceArray = try appDelegate.getMOCOrViewContext().fetch(command) } catch { } var count = 0 for _ in dataSourceArray ?? [] { let firstName = dataSourceArray?[count].firstName let lastName = dataSourceArray?[count].lastName let age = dataSourceArray?[count].age let favCategory = dataSourceArray?[count].catFav let favDIY = dataSourceArray?[count].diyFav let gender = dataSourceArray?[count].gender let email = dataSourceArray?[count].email let u = UserModel.init(firstName: firstName ?? "No First Name", lastName: lastName ?? "No Last Name", age: age ?? 0, favCategory: favCategory ?? "No Category", favDIY: favDIY ?? "No DIY", gender: gender ?? "No Gender", email: email ?? "No Email") data.append(u) count = count + 1 } return data } } <file_sep>// // ViewController.swift // SnipDesignSustainably // // Created by <NAME> on 2/1/21. // import UIKit import Kingfisher class ProfileViewController: UIViewController { var cars: [Car] = [] @IBOutlet var tableView: UITableView! @IBOutlet var profilePicture: UIImageView! override func viewDidLoad() { super.viewDidLoad() jsonTwo() profilePicture.layer.cornerRadius = profilePicture.frame.height/2 let url1 = "https://picsum.photos/id/" let url2 = "/300/300" var aRandomInt = Int.random(in: 0...1000) let randNum = String(aRandomInt) var url = url1 + randNum + url2 let URL1 = URL(string: url) profilePicture.kf.setImage(with: URL1) // Do any additional setup after loading the view. } func jsonTwo() { let url = Bundle.main.url(forResource: "user", withExtension: "json")! let data = try! Data(contentsOf: url) cars = try! JSONDecoder().decode([Car].self, from: data) for car in cars { let models = car.models print(models) } } } extension ProfileViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cars.count } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print(" You have selected ---> \(indexPath.row)") } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let user = cars[indexPath.row] let data = user.models let cell1 = HomeCell(title: data[0], location: data[1], time: data[2], tags: data[3], description: data[4], GP: data[5]) let cell = tableView.dequeueReusableCell(withIdentifier: "restaurantCell") as! HomeTableViewCell let url = URL(string: data[6]) cell.image1.kf.setImage(with: url) cell.setCell(homeCell: cell1) return cell } } <file_sep>// // SavedViewController.swift // SnipDesignSustainably // // Created by <NAME> on 2/4/21. // import UIKit class SavedViewController: UIViewController { @IBOutlet var image1: UIImageView! @IBOutlet var image2: UIImageView! override func viewDidLoad() { super.viewDidLoad() let tapGesture = UITapGestureRecognizer(target: self, action: #selector(SavedViewController.imageTapped(gesture:))) image1.addGestureRecognizer(tapGesture) image1.isUserInteractionEnabled = true image2.addGestureRecognizer(tapGesture) image2.isUserInteractionEnabled = true } @objc func imageTapped(gesture: UIGestureRecognizer) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let dashBoard = storyboard.instantiateViewController(identifier: "savedDetails") self.navigationController?.dismiss(animated: false, completion: nil) self.show(dashBoard, sender: self) } } <file_sep>// // HomeCEll.swift // SnipDesignSustainably // // Created by <NAME> on 1/27/21. // import UIKit //MAKE CLASS, DECLARE VARIBALES. VARIABLE ARE THE VIEWS IN THE CELL class HomeCell { var title: String var location: String var time: String var tags: String var description: String var GP: String //INITIALIZE THE CLASS BY ASIGNING INIT PARAMATERS TO VARIABLES DECLARED ABOVE init(title: String, location: String, time: String, tags: String, description: String, GP: String) { self.title = title self.location = location self.time = time self.tags = tags self.description = description self.GP = GP } } <file_sep>// // AgeViewController.swift // SnipDesignSustainably // // Created by <NAME> on 1/27/21. // import UIKit class AgeViewController: UIViewController { let appDelegate = UIApplication.shared.delegate as! AppDelegate var u: User? let Gender = ["Male", "Female", "Other"] @IBOutlet var ageBtn: UIButton! @IBOutlet var genderBtn: UIButton! @IBOutlet var skipBtn: UIButton! @IBOutlet var ageTF: UITextField! @IBOutlet var genderTF: UITextField! override func viewDidLoad() { super.viewDidLoad() ageTF.keyboardType = UIKeyboardType.numberPad let ALPicker = UIPickerView() ALPicker.delegate = self ALPicker.dataSource = self ALPicker.tag = 1 //ALPicker.delegate = DIYPickerDelegate genderTF.inputView = ALPicker //DYIInputView.text = FavoriteDIY[ALPicker.selectedRow(inComponent: 0)] //Round blue button ageBtn.layer.cornerRadius = ageBtn.frame.size.height / 2 ageBtn.clipsToBounds = true genderBtn.layer.cornerRadius = ageBtn.frame.size.height / 2 genderBtn.clipsToBounds = true } @IBAction func NextPressed(_ sender: Any) { if u != nil { let number: Int64? = Int64(ageTF.text!) u?.gender = genderTF.text u?.age = number ?? 0 appDelegate.saveContext() let storyboard = UIStoryboard(name: "Main", bundle: nil) let dashBoard = storyboard.instantiateViewController(identifier: "onboarding3") self.navigationController?.dismiss(animated: false, completion: nil) self.show(dashBoard, sender: self) } let u = User.init(context: appDelegate.getMOCOrViewContext()) let number: Int64? = Int64(ageTF.text!) u.gender = genderTF.text u.age = number ?? 0 appDelegate.saveContext() } @IBAction func agePressed(_ sender: Any) { ageTF.becomeFirstResponder() } @IBAction func GenderPressed(_ sender: Any) { genderTF.becomeFirstResponder() } @IBAction func backPressed(_ sender: Any) { self.navigationController?.popViewController(animated: true) } @IBAction func skipPressed(_ sender: Any) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let dashBoard = storyboard.instantiateViewController(identifier: "onboarding2") self.navigationController?.dismiss(animated: false, completion: nil) self.show(dashBoard, sender: self) } } extension AgeViewController: UIPickerViewDelegate, UIPickerViewDataSource{ func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return Gender.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return Gender[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let selectedDiy = Gender[row] genderTF.text = selectedDiy } func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { var label: UILabel if let view = view as? UILabel{ label = view } else { label = UILabel() } label.textColor = .white label.textAlignment = .center label.text = Gender[row] return label } private func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { return Gender[row] }} <file_sep>// // ExperienceViewController.swift // SnipDesignSustainably // // Created by <NAME> on 1/27/21. // import UIKit class ExperienceViewController: UIViewController { let appDelegate = UIApplication.shared.delegate as! AppDelegate var u: User? @IBOutlet var beginnerBtn: UIButton! @IBOutlet var intermediateBtn: UIButton! @IBOutlet var expertBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() beginnerBtn.layer.cornerRadius = beginnerBtn.frame.size.height / 2 beginnerBtn.clipsToBounds = true intermediateBtn.layer.cornerRadius = intermediateBtn.frame.size.height / 2 intermediateBtn.clipsToBounds = true expertBtn.layer.cornerRadius = expertBtn.frame.size.height / 2 expertBtn.clipsToBounds = true } @IBAction func beginnerPressed(_ sender: Any) { if u != nil { print("here 1") u?.experience = "Beginner" appDelegate.saveContext() let storyboard = UIStoryboard(name: "Main", bundle: nil) let dashBoard = storyboard.instantiateViewController(identifier: "onboarding3") self.navigationController?.dismiss(animated: false, completion: nil) self.show(dashBoard, sender: self) } u = User.init(context: appDelegate.getMOCOrViewContext()) u?.experience = "Beginner" appDelegate.saveContext() let storyboard = UIStoryboard(name: "Main", bundle: nil) let dashBoard = storyboard.instantiateViewController(identifier: "onboarding4") self.navigationController?.dismiss(animated: false, completion: nil) self.show(dashBoard, sender: self) } @IBAction func intermediatePressed(_ sender: Any) { if u != nil { print("here 1") u?.experience = "Intermediate" appDelegate.saveContext() let storyboard = UIStoryboard(name: "Main", bundle: nil) let dashBoard = storyboard.instantiateViewController(identifier: "onboarding3") self.navigationController?.dismiss(animated: false, completion: nil) self.show(dashBoard, sender: self) } u = User.init(context: appDelegate.getMOCOrViewContext()) u?.experience = "Intermediate" appDelegate.saveContext() let storyboard = UIStoryboard(name: "Main", bundle: nil) let dashBoard = storyboard.instantiateViewController(identifier: "onboarding4") self.navigationController?.dismiss(animated: false, completion: nil) self.show(dashBoard, sender: self) } @IBAction func expertPressed(_ sender: Any) { if u != nil { print("here 1") u?.experience = "Expert" appDelegate.saveContext() let storyboard = UIStoryboard(name: "Main", bundle: nil) let dashBoard = storyboard.instantiateViewController(identifier: "onboarding3") self.navigationController?.dismiss(animated: false, completion: nil) self.show(dashBoard, sender: self) } u = User.init(context: appDelegate.getMOCOrViewContext()) u?.experience = "Expert" appDelegate.saveContext() let storyboard = UIStoryboard(name: "Main", bundle: nil) let dashBoard = storyboard.instantiateViewController(identifier: "onboarding4") self.navigationController?.dismiss(animated: false, completion: nil) self.show(dashBoard, sender: self) } @IBAction func backBtnPressed(_ sender: Any) { self.navigationController?.popViewController(animated: true) } @IBAction func skipBtnPressed(_ sender: Any) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let dashBoard = storyboard.instantiateViewController(identifier: "onboarding4") self.navigationController?.dismiss(animated: false, completion: nil) self.show(dashBoard, sender: self) } } <file_sep>// // CustomNavBar.swift // design_to_code18 // // Created by <NAME> on 09/09/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class CustomNavBar: UIView { var controller:ProfileViewController1? let cardView:UIView = { let v = UIView() v.translatesAutoresizingMaskIntoConstraints = false v.backgroundColor = .clear v.layer.masksToBounds = true return v }() let gameThumbImage:UIImageView = { let img = UIImageView() img.translatesAutoresizingMaskIntoConstraints = false img.image = UIImage(named: "profile") img.layer.cornerRadius = 10 img.clipsToBounds = true return img }() let getButton:UIButton = { let btn = UIButton() btn.translatesAutoresizingMaskIntoConstraints = false btn.layer.cornerRadius = 17.5 btn.backgroundColor = UIColor.systemBlue btn.setTitle("GET", for: .normal) btn.setTitleColor(.white, for: .normal) btn.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .bold) return btn }() override init(frame: CGRect) { super.init(frame: frame) addSubview(cardView) cardView.addSubview(gameThumbImage) cardView.addSubview(getButton) setUpConstraints() gameThumbImage.transform = CGAffineTransform(translationX: 0, y: +50) getButton.transform = CGAffineTransform(translationX: 0, y: +50) } func setUpConstraints(){ NSLayoutConstraint.activate([ cardView.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor), cardView.leadingAnchor.constraint(equalTo: leadingAnchor), cardView.trailingAnchor.constraint(equalTo: trailingAnchor), cardView.bottomAnchor.constraint(equalTo: bottomAnchor), gameThumbImage.widthAnchor.constraint(equalToConstant: 35), gameThumbImage.heightAnchor.constraint(equalToConstant: 35), gameThumbImage.centerYAnchor.constraint(equalTo: cardView.centerYAnchor), gameThumbImage.centerXAnchor.constraint(equalTo: cardView.centerXAnchor), getButton.trailingAnchor.constraint(equalTo: cardView.trailingAnchor, constant: -15), getButton.centerYAnchor.constraint(equalTo: cardView.centerYAnchor), getButton.widthAnchor.constraint(equalToConstant: 80), getButton.heightAnchor.constraint(equalToConstant: 35), ]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } <file_sep>// // Constants.swift // TableView // // Created by <NAME> on 1/26/21. // struct Save { //Volume Tracker vars static let restName = "restname" static let description = "description" static let waitTime = "waittime" static let rating = "rating" } <file_sep>// // CollectionViewCell1.swift // SnipDesignSustainably // // Created by <NAME> on 2/5/21. // import UIKit class CollectionViewCell1: UICollectionViewCell { @IBOutlet var image: UIImageView! } <file_sep>// // SignUpVC.swift // SnipDesignSustainably // // Created by <NAME> on 12/28/20. // import UIKit class SignUpVC: UIViewController { let appDelegate = UIApplication.shared.delegate as! AppDelegate var u: User? @IBOutlet weak var SignUpBtn: UIButton! @IBOutlet weak var FBBtn: UIButton! @IBOutlet var nameTF: UITextField! @IBOutlet var lastNameTF: UITextField! @IBOutlet var emailTF: UITextField! @IBOutlet var passwordTF: UITextField! override func viewDidLoad() { super.viewDidLoad() title = "Sign Up" //round Blue button FBBtn.layer.cornerRadius = FBBtn.frame.size.height / 2 FBBtn.clipsToBounds = true //Gray transparent button SignUpBtn.layer.cornerRadius = SignUpBtn.frame.size.height / 2 SignUpBtn.clipsToBounds = true SignUpBtn.backgroundColor = .clear SignUpBtn.layer.borderWidth = 3 SignUpBtn.layer.borderColor = CGColor.init(red: 0.84, green: 0.84, blue: 0.84, alpha:1) } @IBAction func backBtnClicked(_ sender: Any) { let storyboard = UIStoryboard(name: "Main", bundle: nil) self.navigationController?.popViewController(animated: true) } @IBAction func SignUpClicked(_ sender: Any) { if nameTF.text?.count ?? 0 >= 2 && lastNameTF.text?.count ?? 0 >= 2 && emailTF.text?.count ?? 0 >= 5 && passwordTF.text?.count ?? 0 >= 5 { if u != nil { u?.firstName = nameTF.text u?.lastName = lastNameTF.text u?.password = <PASSWORD> u?.email = emailTF.text appDelegate.saveContext() let storyboard = UIStoryboard(name: "Main", bundle: nil) let dashBoard = storyboard.instantiateViewController(identifier: "onboarding3") self.navigationController?.dismiss(animated: false, completion: nil) self.show(dashBoard, sender: self) } u = User.init(context: appDelegate.getMOCOrViewContext()) u?.firstName = nameTF.text u?.lastName = lastNameTF.text u?.password = <PASSWORD> u?.email = emailTF.text appDelegate.saveContext() let storyboard = UIStoryboard(name: "Main", bundle: nil) let dashBoard = storyboard.instantiateViewController(identifier: "onboarding1") self.navigationController?.dismiss(animated: false, completion: nil) self.show(dashBoard, sender: self) } else { let alert = UIAlertController(title: "Password and username too short", message: "Please input the a username and password greater than 5.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) self.present(alert, animated: true) } } } <file_sep>// // restCell.swift // TableView // // Created by <NAME> on 1/25/21. // import Foundation import UIKit class restCell: UITableViewCell { // OUTLET TO OBJECTS IN THE CELL @IBOutlet weak var category: UILabel! @IBOutlet weak var burger: UIImageView! @IBOutlet weak var title: UILabel! @IBOutlet weak var time: UILabel! @IBOutlet weak var rating: UILabel! //@IBOutlet weak var description: UILabel! var restaurant: Restaurant! func setCell(restaurant1: Restaurant) { restaurant = restaurant1 // category.text = restaurant.title //buger.text = restaurant.repsText title.text = restaurant.title time.text = restaurant.waitTime rating.text = restaurant.rating //Styling for rounded labels with light grey background time.layer.borderWidth = 1 time.layer.borderColor = CGColor.init(red: 0, green: 0, blue: 0, alpha: 0.01) time.layer.cornerRadius = 8 time.layer.masksToBounds = true rating.layer.borderWidth = 1 rating.layer.borderColor = CGColor.init(red: 0, green: 0, blue: 0, alpha: 0.01) rating.layer.cornerRadius = 8 rating.layer.masksToBounds = true } } <file_sep>// // ExploreViewController.swift // SnipDesignSustainably // // Created by <NAME> on 1/29/21. // import UIKit import Kingfisher let reuseIdentifier = "CellIdentifer"; var array = ["First Cell", "Second Cell", "Third Cell", "Fourth Cell", "Fifth Cell"] class ExploreViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { @IBOutlet var story1: UIImageView! @IBOutlet var story2: UIImageView! @IBOutlet var story3: UIImageView! @IBOutlet var story4: UIImageView! @IBOutlet var story5: UIImageView! @IBOutlet var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() let url1 = "https://picsum.photos/id/" let url2 = "/300/300" var aRandomInt = Int.random(in: 0...1000) var randNum = String(aRandomInt) var url = url1 + randNum + url2 var URL1 = URL(string: url) story1.kf.setImage(with: URL1) story1.layer.cornerRadius = story1.frame.size.height / 2 aRandomInt = Int.random(in: 0...1000) randNum = String(aRandomInt) url = url1 + randNum + url2 URL1 = URL(string: url) story2.kf.setImage(with: URL1) story2.layer.cornerRadius = story1.frame.size.height / 2 aRandomInt = Int.random(in: 0...1000) randNum = String(aRandomInt) url = url1 + randNum + url2 URL1 = URL(string: url) story3.kf.setImage(with: URL1) story3.layer.cornerRadius = story1.frame.size.height / 2 aRandomInt = Int.random(in: 0...1000) randNum = String(aRandomInt) url = url1 + randNum + url2 URL1 = URL(string: url) story4.kf.setImage(with: URL1) story4.layer.cornerRadius = story1.frame.size.height / 2 aRandomInt = Int.random(in: 0...1000) randNum = String(aRandomInt) url = url1 + randNum + url2 URL1 = URL(string: url) story5.kf.setImage(with: URL1) story5.layer.cornerRadius = story1.frame.size.height / 2 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //UICollectionViewDatasource methods func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 50 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as UICollectionViewCell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionViewCell let url1 = "https://picsum.photos/id/" let url2 = "/300/300" let aRandomInt = Int.random(in: 0...1000) let randNum = String(aRandomInt) let url = url1 + randNum + url2 let URL1 = URL(string: url) cell.image.kf.setImage(with: URL1) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let noOfCellsInRow = 3 let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout let totalSpace = flowLayout.sectionInset.left + flowLayout.sectionInset.right + (flowLayout.minimumInteritemSpacing * CGFloat(noOfCellsInRow - 1)) let size = Int((collectionView.bounds.width - totalSpace) / CGFloat(noOfCellsInRow)) return CGSize(width: size, height: size) } } <file_sep>// // NavViewController.swift // SnipDesignSustainably // // Created by <NAME> on 1/27/21. // import UIKit class NavViewController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20)) imageView.contentMode = .scaleAspectFit let image = UIImage(named: "logo") imageView.image = image navigationItem.titleView = imageView } } <file_sep>// // HomeTableViewCell.swift // SnipDesignSustainably // // Created by <NAME> on 1/27/21. // import UIKit //import SDWebImage //CREATE DELGATE FOR CUSTOM ACTION ON EACH CELL "ADD SET BUTTON" class HomeTableViewCell: UITableViewCell { // OUTLET TO OBJECTS IN THE CELL // @IBOutlet weak var iconImageView: UIImageView! @IBOutlet var nameLabel: UILabel! @IBOutlet var tagsLabel: UILabel! @IBOutlet var timeLabel: UILabel! @IBOutlet var descriptionLabel: UILabel! @IBOutlet var image1: UIImageView! @IBOutlet var GP: UILabel! var homeCellItem: HomeCell! func setCell(homeCell: HomeCell) { homeCellItem = homeCell // iconImageView.image = history.image nameLabel.text = homeCellItem.title tagsLabel.text = homeCellItem.tags timeLabel.text = homeCellItem.time descriptionLabel.text = homeCellItem.description GP.text = homeCellItem.GP } } <file_sep>// // GameRatingsTableViewCell.swift // design_to_code18 // // Created by <NAME> on 09/09/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class GameRatingsTableViewCell: UITableViewCell { let ratings:UILabel = { let l = UILabel() l.text = "Favorite Category" l.font = UIFont.systemFont(ofSize: 18, weight: .semibold) //l.textColor = CustomColors.lightGray l.translatesAutoresizingMaskIntoConstraints = false return l }() let ratingCount:UILabel = { let vm = ProfileViewModel() vm.getDataFromDataProvider() let user = vm.arrUser[0] let category = user.favCategory let l = UILabel() l.text = category l.font = UIFont.systemFont(ofSize: 14, weight: .light) //l.textColor = CustomColors.lightGray l.translatesAutoresizingMaskIntoConstraints = false return l }() let rankLabel:UILabel = { let l = UILabel() l.translatesAutoresizingMaskIntoConstraints = false l.text = "Favorite DIY" l.font = UIFont.systemFont(ofSize: 18, weight: .semibold) //l.textColor = CustomColors.lightGray return l }() let categoryLabel:UILabel = { let vm = ProfileViewModel() vm.getDataFromDataProvider() let user = vm.arrUser[0] let diy = user.favDIY let l = UILabel() l.text = diy l.font = UIFont.systemFont(ofSize: 14, weight: .light) //l.textColor = CustomColors.lightGray l.translatesAutoresizingMaskIntoConstraints = false return l }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) addSubview(ratings) addSubview(ratingCount) addSubview(rankLabel) addSubview(categoryLabel) setUpConstraints() } func setUpConstraints(){ NSLayoutConstraint.activate([ ratings.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20), ratings.topAnchor.constraint(equalTo: topAnchor, constant: 0), ratingCount.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20), ratingCount.topAnchor.constraint(equalTo: ratings.bottomAnchor, constant: 2), rankLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -20), rankLabel.topAnchor.constraint(equalTo: topAnchor, constant: 0), categoryLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -20), categoryLabel.topAnchor.constraint(equalTo: rankLabel.bottomAnchor, constant: 2) ]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } <file_sep>// // SearchViewController.swift // TableView // // Created by <NAME> on 1/25/21. // import UIKit class SearchViewController: UIViewController { var restArray = ["Five Guys", "Red Robbin","Shake Shack","In-N-Out","Burger King","McDonalds","Phatburger","Smashburger","Burger Palace" ,"Burger Dynasty","Wendy's","Sonic"] @IBOutlet var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() print("insidesaerch vC") } } extension SearchViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return restArray.count } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print(" You have selected ---> \(indexPath.row)") //For memory Storage let defaults = UserDefaults.standard let description = "$$*American*Fast Food*Sandwiches" let waittime = " 20-30min " let rating = " 5 " defaults.set(restArray[indexPath.row], forKey: Save.restName) defaults.set(description, forKey: Save.description) defaults.set(waittime, forKey: Save.waitTime) defaults.set(rating, forKey: Save.rating) let storyboard = UIStoryboard(name: "Main", bundle: nil) let infoCollection = storyboard.instantiateViewController(identifier: "DetailsViewController") self.show(infoCollection, sender: self) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let description = "$$*American*Fast Food*Sandwiches" let waittime = " 20-30min " let rating = " 5 " let cell1 = Restaurant(category: "Burger", title: restArray[indexPath.row], description: description, waitTime: waittime, rating: rating) let cell = tableView.dequeueReusableCell(withIdentifier: "restaurantCell") as! restCell cell.setCell(restaurant1: cell1) return cell } } //------------------------------------------------------- <file_sep>// // Book.swift // autolayoutlearning // // Created by <NAME> on 05/02/21. // import Foundation struct HomeModel{ let firstName: String let lastName: String let age: Int64 let favCategory: String let favDIY: String let gender: String let email: String } <file_sep>// // LoadingViewController.swift // SnipDesignSustainably // // Created by <NAME> on 1/27/21. // import UIKit class LoadingViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() //Remove from navigation to prevent going back to the onbarding sequence self.navigationItem.setHidesBackButton(true, animated: false) //Delay to navigate to home tabs DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let dashBoard = storyboard.instantiateViewController(identifier: "home") self.navigationController?.dismiss(animated: false, completion: nil) self.show(dashBoard, sender: self) } } } <file_sep>// // ViewController.swift // SnipDesignSustainably // // Created by <NAME> on 2/1/21. // import UIKit import Kingfisher import CoreData class ProfileViewController1: UIViewController { lazy var tableView:UITableView = { let tv = UITableView() tv.translatesAutoresizingMaskIntoConstraints = false tv.delegate = self tv.dataSource = self tv.register(GameOverviewTableViewCell.self, forCellReuseIdentifier: "GameOverviewTableViewCell") tv.register(GameRatingsTableViewCell.self, forCellReuseIdentifier: "GameRatingsTableViewCell") tv.register(UpdatesTableViewCell.self, forCellReuseIdentifier: "UpdatesTableViewCell") tv.showsVerticalScrollIndicator = false return tv }() override var prefersStatusBarHidden: Bool { return true } @IBOutlet var name: UILabel! let vm = ProfileViewModel() override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) tableView.pin(to: view) let headerView = StrechyHeaderView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 250)) headerView.imageView.image = UIImage(named: "profile") self.tableView.tableHeaderView = headerView print("++++++++++++++++++++++++++++++++++++++") vm.getDataFromDataProvider() let user = vm.arrUser[0] print(user.lastName + user.firstName + user.favCategory + user.favDIY) print(vm.arrUser.count) name.text = user.firstName // profilePicture.layer.cornerRadius = profilePicture.frame.height/2 // let url1 = "https://picsum.photos/id/" // let url2 = "/300/300" // var aRandomInt = Int.random(in: 0...1000) // let randNum = String(aRandomInt) // var url = url1 + randNum + url2 // let URL1 = URL(string: url) // profilePicture.kf.setImage(with: URL1) } } extension ProfileViewController1:UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: "GameOverviewTableViewCell", for: indexPath) as! GameOverviewTableViewCell cell.backgroundColor = .white cell.selectionStyle = .none cell.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: tableView.frame.width) return cell } if indexPath.row == 1 { let cell = tableView.dequeueReusableCell(withIdentifier: "GameRatingsTableViewCell", for: indexPath) as! GameRatingsTableViewCell cell.backgroundColor = .white cell.selectionStyle = .none cell.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) return cell } if indexPath.row == 2 { let cell = tableView.dequeueReusableCell(withIdentifier: "UpdatesTableViewCell", for: indexPath) as! UpdatesTableViewCell cell.backgroundColor = .white cell.selectionStyle = .none cell.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) return cell } return UITableViewCell() } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row == 0 { return 80 } if indexPath.row == 1 { return 55 } if indexPath.row == 2 { return 680 } return CGFloat() } func scrollViewDidScroll(_ scrollView: UIScrollView) { let headerView = self.tableView.tableHeaderView as! StrechyHeaderView headerView.scrollViewDidScroll(scrollView: scrollView) let y = scrollView.contentOffset.y let v = y/210 let value = Double(round(100*v)/100) print(value) // It return 1 when header end reaches the height of navbar which is 160. if value >= 1.0 { UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.7, options: .curveEaseInOut, animations: { }, completion: nil) UIView.animate(withDuration: 0.4) { } } else { UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.7, options: .curveEaseInOut, animations: { }, completion: nil) UIView.animate(withDuration: 0.4) { } } } } <file_sep>//// //// ProgramaticProfileViewController.swift //// SnipDesignSustainably //// //// Created by <NAME> on 2/8/21. //// // //import SwiftUI // // //class ProgramaticProfileViewController: UIViewController{ // // // lazy var tableView:UITableView = { // let tv = UITableView() // tv.translatesAutoresizingMaskIntoConstraints = false // tv.delegate = self as UITableViewDelegate // tv.dataSource = self // tv.register(GameOverviewTableViewCell.self, forCellReuseIdentifier: "GameOverviewTableViewCell") // tv.register(GameRatingsTableViewCell.self, forCellReuseIdentifier: "GameRatingsTableViewCell") // tv.register(UpdatesTableViewCell.self, forCellReuseIdentifier: "UpdatesTableViewCell") // tv.showsVerticalScrollIndicator = false // return tv // }() // // lazy var navBar:CustomNavBar = { // let v = CustomNavBar() // v.controller = self // v.translatesAutoresizingMaskIntoConstraints = false // v.backgroundColor = .white // v.layer.shadowRadius = 10 // v.layer.shadowColor = UIColor(white: 0, alpha: 0.1).cgColor // v.layer.shadowOpacity = 1 // v.layer.shadowOffset = CGSize(width: 0, height: 10) // return v // }() // // override var prefersStatusBarHidden: Bool { // return true // } // // override func viewDidLoad() { // super.viewDidLoad() // view.addSubview(tableView) // view.addSubview(navBar) // tableView.pin(to: view) // setUpConstraints() // // let headerView = StrechyHeaderView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 250)) // headerView.imageView.image = UIImage(named: "cover") // self.tableView.tableHeaderView = headerView // navBar.alpha = 0 // // } // // func setUpConstraints(){ // NSLayoutConstraint.activate([ // navBar.topAnchor.constraint(equalTo: view.topAnchor), // navBar.leadingAnchor.constraint(equalTo: view.leadingAnchor), // navBar.trailingAnchor.constraint(equalTo: view.trailingAnchor), // navBar.heightAnchor.constraint(equalToConstant: 100) // ]) // } // //} // //extension ProgramaticProfileViewController:UITableViewDelegate, UITableViewDataSource { // // func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // return 3 // } // // func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // if indexPath.row == 0 { // let cell = tableView.dequeueReusableCell(withIdentifier: "GameOverviewTableViewCell", for: indexPath) as! GameOverviewTableViewCell // cell.backgroundColor = .white // cell.selectionStyle = .none // cell.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: tableView.frame.width) // return cell // } // if indexPath.row == 1 { // let cell = tableView.dequeueReusableCell(withIdentifier: "GameRatingsTableViewCell", for: indexPath) as! GameRatingsTableViewCell // cell.backgroundColor = .white // cell.selectionStyle = .none // cell.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) // return cell // } // if indexPath.row == 2 { // let cell = tableView.dequeueReusableCell(withIdentifier: "UpdatesTableViewCell", for: indexPath) as! UpdatesTableViewCell // cell.backgroundColor = .white // cell.selectionStyle = .none // cell.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) // return cell // } // return UITableViewCell() // } // // func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { // if indexPath.row == 0 { // return 160 // } // if indexPath.row == 1 { // return 75 // } // if indexPath.row == 2 { // return 680 // } // return CGFloat() // } // // func scrollViewDidScroll(_ scrollView: UIScrollView) { // let headerView = self.tableView.tableHeaderView as! StrechyHeaderView // headerView.scrollViewDidScroll(scrollView: scrollView) // // let y = scrollView.contentOffset.y // let v = y/210 // let value = Double(round(100*v)/100) // print(value) // // It return 1 when header end reaches the height of navbar which is 160. // // if value >= 1.0 { // UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.7, options: .curveEaseInOut, animations: { // self.navBar.alpha = 1 // }, completion: nil) // // UIView.animate(withDuration: 0.4) { // self.navBar.gameThumbImage.transform = CGAffineTransform(translationX: 0, y: 0) // self.navBar.getButton.transform = CGAffineTransform(translationX: 0, y: 0) // } // // } else { // UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.7, options: .curveEaseInOut, animations: { // self.navBar.alpha = 0 // }, completion: nil) // // UIView.animate(withDuration: 0.4) { // self.navBar.gameThumbImage.transform = CGAffineTransform(translationX: 0, y: +50) // self.navBar.getButton.transform = CGAffineTransform(translationX: 0, y: +50) // } // } // } // //} // <file_sep>// // BookViewModel.swift // MVVMEx1 // // Created by <NAME> on 09/02/21. // import Foundation class ProfileViewModel { var arrUser = [UserModel]() //iteraction with data provider func getDataFromDataProvider() { let dataP = DataProvider.init() arrUser = try dataP.getData() } func randomImage() -> URL{ let url1 = "https://picsum.photos/id/" let url2 = "/300/300" let aRandomInt = Int.random(in: 0...1000) let randNum = String(aRandomInt) let url = url1 + randNum + url2 let URL1 = URL(string: url) return URL1! } func size() -> Int { arrUser.count } func getFirstName(user: User)->String { return user.firstName ?? "Name not found" } func getLastName(user: User)->String { return user.lastName ?? "Last Name not Found" } func getAGe(user: User)->Int64 { return user.age } func getCategory(user: User)->String { return user.catFav ?? "Category not Found" } func getDIY(user: User)->String { return user.diyFav ?? "DIY not found" } func getGender(user: User)->String { return user.gender ?? "Gender not Found" } func getEmail(user: User)->String { return user.email ?? "Email not Found" } } <file_sep># Uncomment the next line to define a global platform for your project # platform :ios, '9.0' target 'SnipDesignSustainably' do # Comment the next line if you don't want to use dynamic frameworks use_frameworks! pod 'RxSwift', '6.1.0' pod 'RxCocoa', '6.1.0' pod 'IQKeyboardManagerSwift' # Pods for SnipDesignSustainably target 'SnipDesignSustainablyTests' do inherit! :search_paths # Pods for testing end target 'SnipDesignSustainablyUITests' do # Pods for testing end end <file_sep>// // SplashVC.swift // SnipDesignSustainably // // Created by <NAME> on 12/28/20. // import UIKit class SplashVC: UIViewController { @IBOutlet weak var SignUpBtn: UIButton! @IBOutlet weak var LoginBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() let vm = ProfileViewModel() vm.getDataFromDataProvider() if (vm.size() > 0) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let dashBoard = storyboard.instantiateViewController(identifier: "home") self.navigationController?.dismiss(animated: false, completion: nil) self.show(dashBoard, sender: self) } let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20)) imageView.contentMode = .scaleAspectFit let image = UIImage(named: "logo") imageView.image = image navigationItem.titleView = imageView SignUpBtn.layer.cornerRadius = SignUpBtn.frame.size.height / 2 SignUpBtn.clipsToBounds = true LoginBtn.layer.cornerRadius = LoginBtn.frame.size.height / 2 LoginBtn.clipsToBounds = true LoginBtn.backgroundColor = .clear LoginBtn.layer.borderWidth = 2 LoginBtn.layer.borderColor = CGColor.init(red: 0.84, green: 0.84, blue: 0.84, alpha:1) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } <file_sep>// // CollectionViewCell.swift // SnipDesignSustainably // // Created by <NAME> on 1/29/21. // import UIKit class CollectionViewCell: UICollectionViewCell { @IBOutlet var image: UIImageView! } <file_sep>// // FirstUSeViewController.swift // SnipDesignSustainably // // Created by <NAME> on 2/28/21. // import UIKit class FirstUSeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let vm = ProfileViewModel() vm.getDataFromDataProvider() let user = vm.arrUser[0] let name = user.firstName print(name) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } <file_sep>// // userSingleton.swift // SnipDesignSustainably // // Created by <NAME> on 2/25/21. // import Foundation import UIKit class UserSingleton { let appDelegate = UIApplication.shared.delegate as! AppDelegate var person: User private init (){ person = User.init(context: appDelegate.getMOCOrViewContext()) appDelegate.saveContext() } func getPerson() -> User { return person } } <file_sep>// // BookViewModel.swift // MVVMEx1 // // Created by <NAME> on 09/02/21. // import Foundation class HomeViewModel { var cells = [Car]() //iteraction with data provider func getDataFromDataProvider() { let dataP = HomeDataProvider.init() cells = try dataP.getData() } func size() -> Int { return cells.count } func randomImage() -> URL{ let url1 = "https://picsum.photos/id/" let url2 = "/300/300" let aRandomInt = Int.random(in: 0...1000) let randNum = String(aRandomInt) let url = url1 + randNum + url2 let URL1 = URL(string: url) return URL1! } func getUserTitel(pos: Int)->String { return cells[pos].models[0] } func getLocation(pos: Int)->String { return cells[pos].models[1] } func getTime(pos: Int)->String { return cells[pos].models[2] } func getTags(pos: Int)->String { return cells[pos].models[3] } func getDescription(pos: Int)->String { return cells[pos].models[4] } func getGP(pos: Int)->String { return cells[pos].models[5] } } <file_sep>// // GameOverviewTableViewCell.swift // design_to_code18 // // Created by <NAME> on 08/09/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class GameOverviewTableViewCell: UITableViewCell { let gameImageView:UIImageView = { let img = UIImageView() img.translatesAutoresizingMaskIntoConstraints = false img.contentMode = .scaleAspectFill img.layer.cornerRadius = 25 img.image = UIImage(named: "logo") img.layer.masksToBounds = true return img }() let gameTitle:UILabel = { let vm = ProfileViewModel() vm.getDataFromDataProvider() let user = vm.arrUser[0] let name = user.firstName + " " + user.lastName let l = UILabel() l.translatesAutoresizingMaskIntoConstraints = false l.numberOfLines = 0 let attributedText = NSMutableAttributedString(string: name, attributes:[NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 22)]) attributedText.append(NSAttributedString(string: "\n" + user.email , attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15 , weight:.regular), NSAttributedString.Key.foregroundColor: UIColor.lightGray])) l.attributedText = attributedText return l }() let followersText:UILabel = { let vm = ProfileViewModel() vm.getDataFromDataProvider() let user = vm.arrUser[0] let name = user.firstName + " " + user.lastName let l = UILabel() l.translatesAutoresizingMaskIntoConstraints = false l.numberOfLines = 0 let attributedText = NSMutableAttributedString(string: "", attributes:[NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 22)]) attributedText.append(NSAttributedString(string: "0 following\n0 followers" , attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15 , weight:.regular), NSAttributedString.Key.foregroundColor: UIColor.lightGray])) l.attributedText = attributedText return l }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) // addSubview(gameImageView) addSubview(gameTitle) addSubview(followersText) setUpConstraints() } func setUpConstraints(){ NSLayoutConstraint.activate([ // gameImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20), // gameImageView.topAnchor.constraint(equalTo: topAnchor, constant: 20), // gameImageView.widthAnchor.constraint(equalToConstant: 120), // gameImageView.heightAnchor.constraint(equalToConstant: 120), gameTitle.topAnchor.constraint(equalTo: topAnchor, constant: 20), gameTitle.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20), gameTitle.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -20), followersText.topAnchor.constraint(equalTo: topAnchor, constant: 20), // followersText.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20), followersText.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -20), // getButton.leadingAnchor.constraint(equalTo: gameImageView.trailingAnchor, constant: 20), // getButton.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -20), // getButton.widthAnchor.constraint(equalToConstant: 80), // getButton.heightAnchor.constraint(equalToConstant: 35), // moreBtn.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -20), // moreBtn.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -20), // moreBtn.widthAnchor.constraint(equalToConstant: 35), // moreBtn.heightAnchor.constraint(equalToConstant: 35) ]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } <file_sep>// // DataProvider.swift // MVVMEx1 // // Created by <NAME> on 09/02/21. // import UIKit import CoreData class HomeDataProvider { var cars: [Car] = [] func getData() ->[Car] { let url = Bundle.main.url(forResource: "user", withExtension: "json")! let data = try! Data(contentsOf: url) cars = try! JSONDecoder().decode([Car].self, from: data) for car in cars { let models = car.models } return cars } } <file_sep>// // Exercises.swift // BeginnerTableView // // Created by <NAME> on 7/6/20 // // OBJECT FOR EXERCISE LIST CELLS import UIKit //MAKE CLASS, DECLARE VARIBALES. VARIABLE ARE THE VIEWS IN THE CELL import UIKit //MAKE CLASS, DECLARE VARIBALES. VARIABLE ARE THE VIEWS IN THE CELL class Restaurant { var category: String var title: String var description: String var waitTime: String var rating: String //INITIALIZE THE CLASS BY ASIGNING INIT PARAMATERS TO VARIABLES DECLARED ABOVE init(category: String, title: String, description: String, waitTime: String, rating: String) { self.category = category self.title = title self.description = description self.waitTime = waitTime self.rating = rating } } <file_sep>// // UpdatesTableViewCell.swift // design_to_code18 // // Created by <NAME> on 09/09/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit import Kingfisher class UpdatesTableViewCell: UITableViewCell { let vm = ProfileViewModel() let gameImageView:UIImageView = { let img = UIImageView() let url1 = "https://picsum.photos/id/" let url2 = "/300/300" var aRandomInt = Int.random(in: 0...1000) var randNum = String(aRandomInt) var url = url1 + randNum + url2 var URL1 = URL(string: url) img.translatesAutoresizingMaskIntoConstraints = false img.contentMode = .scaleAspectFill // img.layer.cornerRadius = 25 img.kf.setImage(with: URL1) img.layer.masksToBounds = true return img }() let gameImageView2:UIImageView = { let img = UIImageView() let url1 = "https://picsum.photos/id/" let url2 = "/300/300" var aRandomInt = Int.random(in: 0...1000) var randNum = String(aRandomInt) var url = url1 + randNum + url2 var URL1 = URL(string: url) img.translatesAutoresizingMaskIntoConstraints = false img.contentMode = .scaleAspectFill // img.layer.cornerRadius = 25 img.kf.setImage(with: URL1) img.layer.masksToBounds = true return img }() let gameImageView3:UIImageView = { let img = UIImageView() let url1 = "https://picsum.photos/id/" let url2 = "/300/300" var aRandomInt = Int.random(in: 0...1000) var randNum = String(aRandomInt) var url = url1 + randNum + url2 var URL1 = URL(string: url) img.translatesAutoresizingMaskIntoConstraints = false img.contentMode = .scaleAspectFill // img.layer.cornerRadius = 25 img.kf.setImage(with: URL1) img.layer.masksToBounds = true return img }() let gameImageView4:UIImageView = { let img = UIImageView() let url1 = "https://picsum.photos/id/" let url2 = "/300/300" var aRandomInt = Int.random(in: 0...1000) var randNum = String(aRandomInt) var url = url1 + randNum + url2 var URL1 = URL(string: url) img.translatesAutoresizingMaskIntoConstraints = false img.contentMode = .scaleAspectFill // img.layer.cornerRadius = 25 img.kf.setImage(with: URL1) img.layer.masksToBounds = true return img }() let gameImageView5:UIImageView = { let img = UIImageView() let url1 = "https://picsum.photos/id/" let url2 = "/300/300" var aRandomInt = Int.random(in: 0...1000) var randNum = String(aRandomInt) var url = url1 + randNum + url2 var URL1 = URL(string: url) img.translatesAutoresizingMaskIntoConstraints = false img.contentMode = .scaleAspectFill // img.layer.cornerRadius = 25 img.kf.setImage(with: URL1) img.layer.masksToBounds = true return img }() let gameImageView6:UIImageView = { let img = UIImageView() let url1 = "https://picsum.photos/id/" let url2 = "/300/300" var aRandomInt = Int.random(in: 0...1000) var randNum = String(aRandomInt) var url = url1 + randNum + url2 var URL1 = URL(string: url) img.translatesAutoresizingMaskIntoConstraints = false img.contentMode = .scaleAspectFill // img.layer.cornerRadius = 25 img.kf.setImage(with: URL1) img.layer.masksToBounds = true return img }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) addSubview(gameImageView) addSubview(gameImageView2) addSubview(gameImageView3) addSubview(gameImageView4) addSubview(gameImageView5) addSubview(gameImageView6) setUpConstrainst() } func setUpConstrainst(){ NSLayoutConstraint.activate([ gameImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20), gameImageView.topAnchor.constraint(equalTo: topAnchor, constant: 20), gameImageView.widthAnchor.constraint(equalToConstant: 150), gameImageView.heightAnchor.constraint(equalToConstant: 150), gameImageView2.leadingAnchor.constraint(equalTo: gameImageView.trailingAnchor, constant: 20), gameImageView2.topAnchor.constraint(equalTo: topAnchor, constant: 20), gameImageView2.widthAnchor.constraint(equalToConstant: 150), gameImageView2.heightAnchor.constraint(equalToConstant: 150), gameImageView3.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20), gameImageView3.topAnchor.constraint(equalTo: gameImageView.bottomAnchor, constant: 20), gameImageView3.widthAnchor.constraint(equalToConstant: 150), gameImageView3.heightAnchor.constraint(equalToConstant: 150), gameImageView4.leadingAnchor.constraint(equalTo: gameImageView3.trailingAnchor, constant: 20), gameImageView4.topAnchor.constraint(equalTo: gameImageView.bottomAnchor, constant: 20), gameImageView4.widthAnchor.constraint(equalToConstant: 150), gameImageView4.heightAnchor.constraint(equalToConstant: 150), gameImageView5.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20), gameImageView5.topAnchor.constraint(equalTo: gameImageView3.bottomAnchor, constant: 20), gameImageView5.widthAnchor.constraint(equalToConstant: 150), gameImageView5.heightAnchor.constraint(equalToConstant: 150), gameImageView6.leadingAnchor.constraint(equalTo: gameImageView5.trailingAnchor, constant: 20), gameImageView6.topAnchor.constraint(equalTo: gameImageView4.bottomAnchor, constant: 20), gameImageView6.widthAnchor.constraint(equalToConstant: 150), gameImageView6.heightAnchor.constraint(equalToConstant: 150), ]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
af594cc064641e151697b80eb94717df0597b92d
[ "Swift", "Ruby" ]
36
Swift
elestevy18/SnipAndDesignApp
35f2ab54c845007e35284aac6f131a8716b72676
7a905efcc2cba49a32131229692ead96a15a80a8
refs/heads/master
<file_sep><h1 align="center">Bootcamp - JavaScript Game Developer</h1> <h3 align="center">DIO - Digital Innovation One</h3> ## Descrição Bootcamp de desenvolvimento Front-End de nível intermediário com 108 horas de aulas teóricas, projetos práticos e muitos desafios em JavaScript. ## Projetos * [Introdução ao HTML5 e ao CSS3](https://github.com/flaviomarcilio/Bootcamp-JavaScriptGameDeveloper/tree/master/01_Introducao-HTML5-CSS3) * [Introdução ao JavaScript](https://github.com/flaviomarcilio/Bootcamp-JavaScriptGameDeveloper/tree/master/03_Introducao-JavaScript) * [Projeto 1 - Recriando a página inicial do Instagram](https://github.com/flaviomarcilio/Bootcamp-JavaScriptGameDeveloper/tree/master/02_P1-Instagram) * [Projeto 2 - Recriando a página inicial do NetFlix](https://github.com/flaviomarcilio/Bootcamp-JavaScriptGameDeveloper/tree/master/04_P2-Netflix) * [Projeto 3 - Jogo de Naves](https://github.com/flaviomarcilio/Bootcamp-JavaScriptGameDeveloper/tree/master/05_P3-Jogo-de-Naves) * [Projeto 4 - Jogo de Memória estilo Genius](https://github.com/flaviomarcilio/Bootcamp-JavaScriptGameDeveloper/tree/master/06_P4-Jogo-Memoria-estilo-Genius) * [Projeto 5 - Jogo de Dinossauro](https://github.com/flaviomarcilio/Bootcamp-JavaScriptGameDeveloper/tree/master/07_P5-Jogo-do-Dinossauro) * [Projeto 6 - Jogo da Memória](https://github.com/flaviomarcilio/Bootcamp-JavaScriptGameDeveloper/tree/master/08_P6-Jogo-da-Memoria) * [Projeto 7 - Jogo da Velha](https://github.com/flaviomarcilio/Bootcamp-JavaScriptGameDeveloper/tree/master/09_P7-Jogo-da-Velha) * [Projeto 8 - Jogo Space Shooter](https://github.com/flaviomarcilio/Bootcamp-JavaScriptGameDeveloper/tree/master/10_P8-Jogo-Space-Shooter) <file_sep>/* Variáveis var nome = "<NAME>"; var num = 23 var num2 = 10 var frase = "Japão é o melhor time do mundo!" //alert(`Bem vindo ${nome}`); //alert(num + num2); console.log(num + num2); console.log(nome); console.log(frase.replace("Japão", "Brasil"));*/ /* Listas var lista = ["maçã", "pêra", "laranja"]; console.log(lista); lista.push("uva") console.log(lista) lista.pop() console.log(lista) console.log(lista.length) console.log(lista.reverse()) console.log(lista.toString()) console.log(lista.join("-"))*/ /* Dicionários var fruta = {nome:"maçã", cor:"vermelha"} console.log(fruta) console.log(fruta.nome) var frutas = [{nome:"maçã", cor:"Vermelha"}, {nome:"uva", cor:"roxa"}] console.log(frutas) alert(frutas[1].nome)*/ /* Condicionais, laços de repetição e datas var idade = prompt("Qual a sua idade?") if(idade >= 18){ alert("Maior de idade!") }else{ alert("Menor de idade!") } var count = 0 while(count < 5){ console.log(count) count++ } var count for (count = 0; count <= 5; count++){ alert(count) } var d = new Date() alert(d.getDate()) */ /* Funções function soma(n1, n2){ return n1 + n2 } alert(soma(2,5))*/ function clicou(){ document.getElementById("agradecimento").innerHTML = "<b>Obrigado por clicar!</b>" //alert("Obrigado por clicar!") } function redirecionar(){ window.open("https://www.google.com.br/") } function trocar(elemento){ //document.getElementById("mousemove").innerHTML = "Obrigado por passar o mouse" elemento.innerHTML = "Obrigado por passar o mouse" } function voltar(elemento){ elemento.innerHTML = "Passe o mouse aqui!" } function load(){ alert("Página carregada!") } function funcaoChange(elemento){ console.log(elemento.value) }
796735b6b7371db5d766c73a96dfa1866eb98082
[ "Markdown", "JavaScript" ]
2
Markdown
flaviomarcilio/Bootcamp-JavaScriptGameDeveloper
7806f555a900e401abb9c913571c7b31641497ca
affdc777f2942e5c311f66eedd06e5eca8bf1a71
refs/heads/master
<repo_name>GordanSajevic/LearnSqlHardWay<file_sep>/sqlQuery.sql INSERT INTO person VALUES(0, "Zed", "Shaw", 37); INSERT INTO pet VALUES(0, "Fluffy", "Unicorn", 1000, 0); INSERT INTO pet VALUES(1, "Gigantor", "Robot", 1, 1); INSERT INTO person_pet VALUES (person_id, pet_id) VALUES (0,0); INSERT INTO person_pet VALUES (0, 1); INSERT INTO pet VALUES (1, "Gigantor", "Robot", 1, 0); INSERT INTO person VALUES(0, 'Frank', 'Smith', 100); INSERT OR REPlACE INTO person VALUES(0, 'Frank', 'Smith', 100); REPlACE INTO person VALUES(0, "Zed", "Shaw", 37);<file_sep>/sqlUpdate.sql UPDATE person SET first_name = "<NAME>" WHERE first_name = "Zed"; UPDATE pet SET name = "Fancy pants" WHERE id = 0; UPDATE pet SET name = "<NAME>" WHERE id IN ( SELECT pet.id FROM pet, person_pet, person WHERE person.id = person_pet.person_id AND pet.id = person_pet.pet_id AND person.first_name = "Zed" );<file_sep>/sqlPrint.sql SELECT * FROM person; SELECT name, age FROM pet; SELECT name, age FROM pet WHERE dead = 0; SELECT * FROM person WHERE first_name != "Zed"; SELECT pet.id, pet.name, pet.age, pet.dead FROM pet, person_pet, person WHERE pet.id = person_pet.pet_id AND person_pet.person_id = person_id AND person.first_name = "Zed"; SELECT name, age FROM pet WHERE dead = 1; SELECT * FROM pet; SELECT * FROM person_pet; <file_sep>/sqlChange.sql ALTER TABLE person RENAME TO peoples; ALTER TABLE peoples ADD COLUMN hatred INTEGER; ALTER TABLE peoples RENAME TO person;
657c3a767c90682545fe1ce073ed9433a338f66f
[ "SQL" ]
4
SQL
GordanSajevic/LearnSqlHardWay
1957b05a60d90e010aeef8b3735227de9b9db61e
c64459ed3dd8fb702d37b542b956e2ee8c58b35e
refs/heads/master
<file_sep>(function() { var Platform = { Android: function() { return navigator.userAgent.match(/Android/i); }, iOS: function() { return navigator.userAgent.match(/iPhone|iPad|iPod/i); }, Huawei: function() { return navigator.userAgent.match(/Huawei/i); } }; var platformClassName = null; if (Platform.iOS()) { platformClassName = 'ios'; } if (Platform.Android()) { platformClassName = 'android'; } if (Platform.Huawei()) { platformClassName = 'huawei'; } if (platformClassName) { var html = document.getElementsByTagName('body')[0]; html.classList.add(platformClassName); } })();
2c488a507fe67b668fc0b28e867158e4a384706e
[ "JavaScript" ]
1
JavaScript
sagacious123/bolt
35d5bdbff14a25d5cdcedb4b95fffcce17e89b59
734d8ce8577507fd0544f56ec46fa976cf58172d
refs/heads/master
<repo_name>DebRez/SpaceRock<file_sep>/README.md # SpaceRock #Compilation The preferred method is to use a tool called Gradle (https://gradle.org/). You can run it however you would like, but gradle is easy and makes packaging jars simple. The hard part (creating build.gradle) is already done. ###To create Intellij project files using Gradle: Run: gradle idea This will create project Intellij Idea project files already configured. Then select "Open Project" in Intellij and select the directory. Intellij may ask to import the gradle project: don't bother. ###Setting up Intellij manually or if you have issues with Gradle In Intellij, browse to src/main. Right click java->Mark Directory As->Sources Root Right click resources->Mark Directory As->Resources Root If we use junit for unit testing, you will need to do similiar with test resources. #Directory Layout The directories follow the Apache standard. See: https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html ###Naming conventions: General Java rules: http://www.oracle.com/technetwork/java/codeconventions-135099.html Note that Packages are named with lowercase to prevent naming conflicts with Classes. #Execution The current Main class set in build.gradle is sensor.demo.Demo. This will undoubtedly change. You can set your own in intellij by clicking Run->Edit Configurations ###To run the application type: gradle run ###To create a runnable jar type: gradle build The jar is found in build/libs/ <file_sep>/src/main/java/debrisProcessingSubsystem/Camera.java package debrisProcessingSubsystem; /** * Team 01 will implement the Operator * This will be the interface implemented by the Camera object shown * in the SADD. * This is a preliminary placeholder and very subject to change. * Created by dsr on 3/4/17. */ public interface Camera { } <file_sep>/src/main/java/debrisProcessingSubsystem/debrisCollection/DRList.java package debrisProcessingSubsystem.debrisCollection; import java.util.ArrayList; /** * A list of debris records. Implements DebrisList. * Created by jdt on 3/7/17. */ public class DRList implements DebrisList { private ArrayList<DebrisRecord> debrisList; private boolean sentHome; public DRList(){ debrisList = new ArrayList<>(); sentHome = false; } /** * Get a debris element from the list. * @return The next DebrisRecord as determined by the internal iterator. * TODO make this. */ public DebrisRecord getDebrisElement(){ return null; } /** * Get size of the DebrisList * @return int: debrisList's size. */ public int size(){ return debrisList.size(); } public void addDebris(DebrisRecord newDebrisRecord) throws NullPointerException{ debrisList.add(newDebrisRecord); } public void flagAsSent(){ sentHome = true; } public void flagAsNotSent(){ sentHome = false; } public boolean hasBeenSentHome(){ return sentHome; } /** * Is this list empty? * @return true if empty. */ public boolean isEmpty(){ return debrisList == null || debrisList.isEmpty(); } }
14aa102e4c6004b04f08f0cf0ee3d95ca731d64c
[ "Markdown", "Java" ]
3
Markdown
DebRez/SpaceRock
f47aaac067a8f4ed6397d14e4b5b54d0ec351e37
6d2029de8708478232b8bc6333d92bde070be451
refs/heads/master
<repo_name>vanhung/ExpectedMove<file_sep>/ExpectedMove/Scenes/ExpectedMove/ExpectedMoveViewController.swift // // ExpectedMoveViewController.swift // ExpectedMove // // Created by <NAME> on 6/8/16. // Copyright (c) 2016 <NAME>. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so you can apply // clean architecture to your iOS and Mac projects, see http://clean-swift.com // import UIKit protocol ExpectedMoveViewControllerInput { func displayProfitLossDaysAhead(viewModel: ExpectedMove.FetchTicker.ViewModel) func setNetworkActivityIndicatorVisible(visible: Bool) } protocol ExpectedMoveViewControllerOutput { func fetchTicker(request: ExpectedMove.FetchTicker.Request) } class ExpectedMoveViewController: UITableViewController, ExpectedMoveViewControllerInput { var output: ExpectedMoveViewControllerOutput! var router: ExpectedMoveRouter! // MARK: Outlets @IBOutlet weak var tickerTextField: UITextField! @IBOutlet weak var numberOfSharesTextField: UITextField! @IBOutlet weak var impliedVolatilityTextField: UITextField! @IBOutlet weak var displayedPriceLabel: UILabel! @IBOutlet var profitLosslabels: [UILabel]! @IBOutlet weak var calculateButton: UIButton! // MARK: Object lifecycle override func awakeFromNib() { super.awakeFromNib() ExpectedMoveConfigurator.sharedInstance.configure(self) } // MARK: View lifecycle override func viewDidLoad() { super.viewDidLoad() doSomethingOnLoad() } // MARK: Actions @IBAction func calculateButtonTapped() { let request = ExpectedMove.FetchTicker.Request( ticker: tickerTextField.text!, numberOfShares: numberOfSharesTextField.text!, impliedVolatility: impliedVolatilityTextField.text!) output.fetchTicker(request) } // MARK: Event handling func doSomethingOnLoad() { enableOrDisableCalculateButton() // NOTE: Ask the Interactor to do some work } // MARK: Display logic func displayProfitLossDaysAhead(viewModel: ExpectedMove.FetchTicker.ViewModel) { // NOTE: Display the result from the Presenter self.displayedPriceLabel.text = viewModel.price var tag = 0 for profitLoss in viewModel.expectedProfitLossDaysAhead { self.profitLosslabels[tag].text = profitLoss.loss tag += 1 self.profitLosslabels[tag].text = profitLoss.profit tag += 1 } } private var numberOfTimesNetworkActivityIndicatorSetToVisible = 0 func setNetworkActivityIndicatorVisible(visible: Bool) { if visible { numberOfTimesNetworkActivityIndicatorSetToVisible += 1 } else { numberOfTimesNetworkActivityIndicatorSetToVisible -= 1 } assert(numberOfTimesNetworkActivityIndicatorSetToVisible >= 0 , "Network activity indicator was asked to hide more often than shown") UIApplication.sharedApplication().networkActivityIndicatorVisible = visible } func enableOrDisableCalculateButton() { if let ticker = tickerTextField.text, let numberOfShares = numberOfSharesTextField.text, let impliedVolatility = impliedVolatilityTextField.text where ticker != "" && numberOfShares != "" && impliedVolatility != "" { calculateButton.enabled = true } else { calculateButton.enabled = false } } } extension ExpectedMoveViewController: UITextFieldDelegate { func textFieldDidEndEditing(textField: UITextField) { enableOrDisableCalculateButton() } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { enableOrDisableCalculateButton() return true } }
4b277f49db51896c2c9e41692be0f7c68d698635
[ "Swift" ]
1
Swift
vanhung/ExpectedMove
4192b526a0c05b4d6979c564e6f1f7616cfebf00
b2a5525aa422c96e45850544ffb027dab039cab9
refs/heads/master
<repo_name>ChrisZcu/CheetahTraj<file_sep>/src/main/java/vqgs/util/Config.java package vqgs.util; import de.tototec.cmdoption.CmdOption; import de.tototec.cmdoption.CmdlineParser; public class Config { @CmdOption(names = {"--help", "-h"}, description = "Show this help", isHelp = true) public boolean help; @CmdOption(names = {"--color", "-c"}, description = "Choose the render type: color or not, not color by default") public boolean color; @CmdOption(names = {"--dataset", "-s"}, args = {"DATASET"}, description = "The dataset path") public String dataset = null; @CmdOption(names = {"--vqgs", "-g"}, args = {"VQGS"}, description = "VQGS/VQGS+ calculation result directory path") public String vfgs = null; @CmdOption(names = {"--delta", "-d"}, args = {"DELTA"}, description = "The delta in VQGS+, 64 by default") public int delta = 64; @CmdOption(names = {"--rate", "-r"}, args = {"RATE"}, description = "The sampling rate in VQGS/VQGS+, 0.005 by default") public String rate = "0.005"; @CmdOption(names = {"--datatype", "-t"}, args = {"DATATYPE"}, description = "The data type, including Shenzhen data(0) and Portugal dataset(1)") public int type = 0; public static void main(String[] args) { Config config = new Config(); CmdlineParser cp = new CmdlineParser(config); cp.setProgramName("Config"); cp.setAggregateShortOptionsWithPrefix("-"); cp.parse(new String[]{"-h"}); if (config.help) { cp.usage(); System.exit(0); } } }<file_sep>/README.md ## CheetahTraj #### Overview The source code of CheetahTraj. #### Prerequisites * JDK 1.8 * Maven * Dependent jars are in *lib* directory. #### Files Calculate VQGS: * src.main.java.vqgs.vfgs.PreProcess.java: Pre-process for the original dataset. * src.main.java.vqgs.vfgs.VFGS.java: The VQGS algorithm mentioned in the paper. Store all the result into static files. * src.main.java.vqgs.app.VFGSColor.java: The VQGS+ algorithm with color attribute mentioned in the paper. * src.main.java.vqgs.app.ScreenShot.java: get the screenshot of the result, the figures are all in the *data/figure_result*. * src.main.java.vqgs.util.PSC: All the config information need, including the default file path. Others: * src.main.java.app.TimeProfile.java: run and speed up the render with GPU. * src.main.java.index.SearchRegionPart.java: Build up the index and store the result into a file. #### Datasets We use three datasets in our work: * GPS data for taxis in Portugal. * GPS data for taxis in Shenzhen, China. * GPS data for taxis in Chengdu, China. The paths of the data(part) are *data/porto_5k* and *data/shenzhen_5k*, if you need the full dataset, please contect with us. #### Run the program Parameter usage: > --color, -c :Choose the render type: color or not, not color by default<br> > --dataset, -s DATASET :The dataset path<br> > --datatype, -t DATATYPE :The data type, including Shenzhen data(0) and Portugal dataset(1)<br> --delta, -d DELTA :The delta in VQGS+, 64 by default<br> --help, -h :Show the help<br> --rate, -r RATE :The sampling rate in VQGS/VQGS+, 0.005 by default<br> --vqgs, -g VQGS :VQGS/VQGS+ calculation result directory path<br> > * Calculate the VQGS, VQGS+ and VQGS+ with color data: File: src.main.java.vqgs.StaticCal.java >javac StaticCal.java <br> >java StaticCal -s &lt;dataset file path&gt; -d &lt;delta> -r &lt;rate&gt; * Run the demo: File: src.main.java.vqgs.app.VFGSMapApp.java >javac VFGSMapApp.java <br> >java VFGSMapApp The demo is coming with the data of Porto for total 5k trajectories, keyboard interrupt: >| key | function | >| ---- | ---- | >| p | save the current screenshot | >| o | print current location | > |1 | show the full dataset| > | 2 | show the result of VQGS without color| > |3 | show the result of VQGS with color| > |4| show the random result| > |d| increase the delta value| > |a| decrease the delta value| > |s| increase the rate value| > |w| decrease the rate value| >|esc| quit| * Get all the screenshot: File: src.main.java.vqgs.app.ScreenShot.java >javac ScreenShot.java <br> >java ScreenShot -s &lt;dataset file path&gt; -g &lt;VQGS/VQGS+ file directory path&gt; <file_sep>/src/main/java/index/IndexStructManager.java package index; import app.TimeProfileSharedObject; import de.fhpotsdam.unfolding.geo.Location; import model.QuadRegion; import model.RectRegion; import model.TrajToQuality; import model.TrajectoryMeta; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static index.QuadTree.getWayPointPos; public class IndexStructManager { private double minLat; private double maxLat; private double minLon; private double maxLon; private TrajectoryMeta[] trajFull; private int H; public IndexStructManager(double minLat, double maxLat, double minLon, double maxLon, TrajectoryMeta[] trajFull, int h) { this.minLat = minLat; this.maxLat = maxLat; this.minLon = minLon; this.maxLon = maxLon; this.trajFull = trajFull; H = h; } public QuadRegion startIndexStructure() { // init root RectRegion rectRegion = new RectRegion(); rectRegion.initLoc(new Location(minLat, minLon), new Location(maxLat, maxLon)); TimeProfileSharedObject.getInstance().addQuadRectRegion(rectRegion); QuadRegion quadRegion = new QuadRegion(minLat, maxLat, minLon, maxLon); TrajToQuality[] trajToQualities = VfgsForIndex.getVfgs(trajFull); quadRegion.setTrajQuality(trajToQualities); if (H > 1) { //start children ExecutorService indexPool = new ThreadPoolExecutor(4, 4, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); double latOff = (maxLat - minLat) / 2; double lonOff = (maxLon - minLon) / 2; for (int i = 0; i < 4; i++) { int laxId = i / 2; int lonId = i % 2; double tmpLatMin = minLat + latOff * laxId; double tmpLonMin = minLon + lonOff * lonId; TrajectoryMeta[] wayPoint = getWayPointPos(trajFull, tmpLatMin, tmpLatMin + latOff, tmpLonMin, tmpLonMin + lonOff); IndexStructWorker indexStructWorker = new IndexStructWorker(tmpLatMin, tmpLatMin + latOff, tmpLonMin, tmpLonMin + lonOff, wayPoint, H - 1, this, i); indexPool.submit(indexStructWorker); } indexPool.shutdown(); try { indexPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { System.err.println(e); } quadRegion.setQuadRegionChildren(childrenQuad); System.out.println("index done"); } return quadRegion; } private QuadRegion[] childrenQuad = new QuadRegion[4]; public void setQuadRegion(QuadRegion quadRegion, int id) { childrenQuad[id] = quadRegion; } } <file_sep>/src/main/java/vqgs/StaticCal.java import de.fhpotsdam.unfolding.UnfoldingMap; import de.tototec.cmdoption.CmdlineParser; import processing.core.PApplet; import vqgs.util.*; import vqgs.vfgs.PreProcess; import vqgs.vfgs.Quality; import vqgs.vfgs.VFGS; import vqgs.vfgs.VFGSColor; /** * Run all processes conveniently. * <br> <b>Warning: May lead to out of memory exception.</b> * Only use it when memory is sufficient. * <br> JVM options: -Xmn48g -Xms48g -Xmx48g */ public class StaticCal extends PApplet { @Override public void setup() { UnfoldingMap map = new UnfoldingMap(this); DM.printAndLog(PSC.LOG_PATH, PSC.str()); for (WF process : PSC.PROCESS_LIST) { switch (process) { case PRE_PROCESS: PreProcess.main(map); break; case VFGS_CAL: VFGS.main(map); break; case VFGS_COLOR_CAL: VFGSColor.main(map); break; case QUALITY_CAL: Quality.main(map); break; } if (WF.error) { EmailSender.sendEmail(); exit(); return; } } WF.status = WF.END; EmailSender.sendEmail(); exit(); } public static void main(String[] args) { Config config = new Config(); CmdlineParser cp = new CmdlineParser(config); cp.setAggregateShortOptionsWithPrefix("-"); cp.setProgramName("Static Calculation"); cp.parse(args); if (config.help) { cp.usage(); } else if (config.dataset == null) { System.err.println("Dataset file path is necessary!!!"); System.err.println("Run with --help/-h for parameter information"); System.exit(0); } else { PSC.RATE_LIST = new double[]{Double.parseDouble(config.rate)}; PSC.DELTA_LIST = new int[]{config.delta}; PApplet.main(StaticCal.class.getName()); } } } <file_sep>/src/main/java/vqgs/origin/util/colorCal.java package vqgs.origin.util; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.geo.Location; import de.fhpotsdam.unfolding.providers.MapBox; import de.fhpotsdam.unfolding.utils.MapUtils; import processing.core.PApplet; import vqgs.origin.model.Position; import vqgs.origin.model.Trajectory; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; /** * input: * portScore.txt, (score, traj) paris, from {@link scoreFileCal} * ResRecord_DELTA.txt, selected traj (R) in specific DELTA, from {@link deltaRecordCal} * * output: * color_delta?_rate?.txt * * change !!! x 3 */ public class colorCal extends PApplet { private static final int[] DELTALIST = {0, 4, 8, 16}; private static final double[] RATELIST = {0.05, 0.01/*, 0.005, 0.001, 0.0005, 0.0001, 0.00005, 0.00001*/}; private static List<HashSet<Integer>[]> deltaCellList = new ArrayList<HashSet<Integer>[]>(); private static List<Trajectory> TrajTotal; //所有traj 等同于arr private static void preProcess() throws IOException { // !!! String dataPath = "data/porto_test/__score_set.txt"; //"data/portScore.txt"; TrajTotal = new ArrayList<>(); UTIL.totalListInit(TrajTotal, dataPath); for (Integer e : DELTALIST) { HashSet[] cellList = new HashSet[RATELIST.length]; for (int i = 0; i < RATELIST.length; i++) { cellList[i] = new HashSet<Integer>(); } readFile(e, cellList); deltaCellList.add(cellList); } System.out.println("processing done "); } private static int[] szDaySizeList = {21425, 4285, 2142, 428, 214, 42, 21, 4}; private static int[] portoPartList = {50, 10}; private static void readFile(int delta, HashSet<Integer>[] cellList) throws IOException { int[] sizeList = portoPartList; for (int j = 0; j < sizeList.length; j++) { // !!! String filePath = String.format("data" + "/porto_test/vfgs_%d.txt", delta); BufferedReader reader = new BufferedReader(new FileReader(filePath)); for (int i = 0; i < sizeList[j]; i++) { String line = reader.readLine(); String[] item = line.split(","); cellList[j].add(Integer.parseInt(item[0])); } reader.close(); } } @Override public void settings() { size(1200, 800, P2D); } @Override public void setup() { map = new UnfoldingMap(this); String mapStyle = whiteMapPath; map = new UnfoldingMap(this, "VIS_Demo", new MapBox.CustomMapBoxProvider(mapStyle)); map.zoomAndPanTo(20, new Location(41.101, -8.58)); influCal(); map.setZoomRange(1, 20); MapUtils.createDefaultEventDispatcher(this, map); System.out.println("SET UP DONE"); exit(); } private void influCal() { for (int i = 0; i < DELTALIST.length; i++) { HashSet<Integer>[] cellList = deltaCellList.get(i); HashSet<Integer> influList = cellList[0];// 最大的集合,做初始化用,以此减小,进行判断减少计算 HashMap<Integer, HashSet<Position>> id2poi = new HashMap<>(); for (Integer e : influList) {//处理选中的轨迹的position集合 Trajectory traj = TrajTotal.get(e); HashSet<Position> trajSet = new HashSet<>(); for (Location p : traj.getPoints()) { double px = map.getScreenPosition(p).x; double py = map.getScreenPosition(p).y; trajSet.add(new Position(px, py)); } id2poi.put(e, trajSet); } HashMap<Integer, Integer> maxSetIR = initMaxSetIR(id2poi, influList); HashMap<Integer, Integer> influId2Score = new HashMap<>(); for (Integer e : maxSetIR.keySet()) { int influId = maxSetIR.get(e); // id -> influId int score = influId2Score.getOrDefault(influId, 0); influId2Score.put(influId, score + 1); } write2file(influId2Score, DELTALIST[i], RATELIST[0]); for (int j = 1; j < cellList.length; j++) {//计算其他集合下 influList = cellList[j]; HashMap<Integer, HashSet<Position>> id2poiSub = new HashMap<>(); for (Integer e : influList) { id2poiSub.put(e, id2poi.get(e)); } influId2Score.clear(); HashMap<Integer, Integer> setIR = new HashMap<>(); for (int k = 0; k < TrajTotal.size(); k++) { if (influList.contains(k)) { continue; } if (maxSetIR.containsKey(k) && influList.contains(maxSetIR.get(k))) { setIR.put(k, maxSetIR.get(k)); continue; } Trajectory traj = TrajTotal.get(k); int influId = getMaxInfluId(traj, id2poiSub); setIR.put(k, influId); } for (Integer e : setIR.keySet()) { int influId = setIR.get(e); int score = influId2Score.getOrDefault(influId, 0); influId2Score.put(influId, score + 1); } write2file(influId2Score, DELTALIST[i], RATELIST[j]); } } } /** * Calculate the map from traj id (not include traj in R) * to another traj id that has most common pixels with it. * @param id2poi the map from traj to its position set * @param influList R, i.e. the list of traj that need to compute color score */ private HashMap<Integer, Integer> initMaxSetIR(HashMap<Integer, HashSet<Position>> id2poi, HashSet<Integer> influList) { HashMap<Integer, Integer> id2influId = new HashMap<>(); for (int i = 0; i < TrajTotal.size(); i++) { if (influList.contains(i)) { continue; } Trajectory traj = TrajTotal.get(i); int influId = getMaxInfluId(traj, id2poi); id2influId.put(i, influId); } return id2influId; } private int getMaxInfluId(Trajectory traj, HashMap<Integer, HashSet<Position>> id2poi) { HashSet<Position> trajSet = new HashSet<>(); for (Location p : traj.getPoints()) { // 计算未选中轨迹对应的position double px = map.getScreenPosition(p).x; double py = map.getScreenPosition(p).y; trajSet.add(new Position(px, py)); } int influId = -1; double influScore = -1; for (Integer e : id2poi.keySet()) { double score = 0; HashSet<Position> poi = id2poi.get(e); for (Position p : poi) { if (trajSet.contains(p)) { score += 1; } } if (score > influScore) { influId = e; influScore = score; } } return influId; } private void write2file(HashMap<Integer, Integer> influId2Score, int delta, double rate) { // !!! String filePath = String.format("data/porto_test/color_%s_%d.txt", rate, delta); try { BufferedWriter writer = new BufferedWriter(new FileWriter(filePath)); for (Integer e : influId2Score.keySet()) { writer.write(e + "," + influId2Score.get(e)); writer.newLine(); } writer.close(); } catch (IOException e) { e.printStackTrace(); } } private String whiteMapPath = "https://api.mapbox.com/styles/v1/pacemaker-yc/ck4gqnid305z61cp1dtvmqh5y/tiles/512/{z}/{x}/{y}@2x?access_token=<KEY>"; private static UnfoldingMap map; public static void main(String[] args) { try { preProcess(); } catch (IOException e) { e.printStackTrace(); } String title = "origin.util.colorCal"; PApplet.main(new String[]{title}); } } <file_sep>/src/main/java/vqgs/origin/util/MyKeyboardHandler.java package vqgs.origin.util; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.interactions.KeyboardHandler; import processing.core.PApplet; import processing.event.KeyEvent; public class MyKeyboardHandler extends KeyboardHandler { private final PApplet pApplet; public MyKeyboardHandler(PApplet pApplet, UnfoldingMap... unfoldingMaps) { super(pApplet, unfoldingMaps); this.pApplet = pApplet; } @Override public void keyEvent(KeyEvent e) { if (e.getKey() == 'q') { pApplet.exit(); } } }<file_sep>/src/main/java/vqgs/origin/util/scoreFileCal.java package vqgs.origin.util; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.geo.Location; import de.fhpotsdam.unfolding.utils.MapUtils; import vqgs.origin.model.Position; import vqgs.origin.model.Trajectory; import org.apache.commons.io.FileUtils; import org.apache.commons.io.LineIterator; import processing.core.PApplet; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; /** * input: * porto_part.txt, original traj data * * output: * portoScore.txt, (score, traj) paris -> {@link deltaRecordCal} * * score: # of points in map for a specific traj (i.e. {@link #id2score}) * * change file and limit */ public class scoreFileCal extends PApplet { private static String dataPath = "data/porto_full.txt"; private static String outPath = "data/porto_test_old/__score_set.txt"; //"data/portoPartScore.txt"; public static final int LIMIT = 5_0000; private static UnfoldingMap map; private static ArrayList<Trajectory> TrajTotal = new ArrayList<>(); private HashMap<Integer, Integer> id2score = new HashMap<>(); @Override public void setup() { map = new UnfoldingMap(this); map.zoomAndPanTo(20, new Location(41.141412, -8.618499)); scoreCal(dataPath, outPath); map.setZoomRange(1, 20); MapUtils.createDefaultEventDispatcher(this, map); System.out.println("score cal done"); exit(); } // It doesn't matters @Override public void settings() { size(1200, 800, P2D); } private void scoreCal(String dataPath, String outPath) { HashSet<Position> trajSet = new HashSet<>(); try { File file = new File(outPath); file.createNewFile(); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); for (Trajectory traj : TrajTotal) { HashSet<Position> poi = new HashSet<>(); for (Location p : traj.getPoints()) { double px = map.getScreenPosition(p).x; double py = map.getScreenPosition(p).y; trajSet.add(new Position(px, py)); poi.add(new Position(px, py)); } id2score.put(traj.getTrajId(), poi.size()); } File theFile = new File(dataPath); LineIterator it = FileUtils.lineIterator(theFile, "UTF-8"); int i = 0; while (it.hasNext() && (LIMIT == -1 || i < LIMIT)) { String line = it.nextLine(); writer.write(id2score.get(i) + ";" + line.split(";")[1]); writer.newLine(); i++; } System.out.println(i); LineIterator.closeQuietly(it); writer.close(); } catch (IOException ignored) { } } private static void preProcess() throws IOException { File theFile = new File(dataPath); LineIterator it = FileUtils.lineIterator(theFile, "UTF-8"); String line; String[] data; int trajId = 0; try { while (it.hasNext() && (LIMIT == -1 || trajId < LIMIT)) { line = it.nextLine(); String[] item = line.split(";"); data = item[1].split(","); Trajectory traj = new Trajectory(trajId); trajId++; for (int i = 0; i < data.length - 2; i = i + 2) { traj.points.add(new Location(Double.parseDouble(data[i + 1]), Double.parseDouble(data[i]))); } TrajTotal.add(traj); } } finally { LineIterator.closeQuietly(it); System.out.println(TrajTotal.size()); } System.out.println("preProcessing done"); } public static void runCalFileScore(String in, String out) { dataPath = in; outPath = out; runCalFileScore(); } public static void runCalFileScore() { try { preProcess(); } catch (IOException e) { e.printStackTrace(); } String title = "origin.util.scoreFileCal"; PApplet.main(new String[]{title}); } public static void main(String[] args) { runCalFileScore(); } } <file_sep>/src/main/java/vqgs/app/ThreadMapAppPlus.java package vqgs.app; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.geo.Location; import de.fhpotsdam.unfolding.providers.MapBox; import de.fhpotsdam.unfolding.utils.MapUtils; import vqgs.draw.TrajDrawHandler2; import vqgs.model.Trajectory; import processing.core.PApplet; import processing.core.PGraphics; import vqgs.util.DM; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * Draw a FULL/<s>VFGS</s>/RAND traj map with multi-thread. * <p> * ThreadMapApp + support for switching in FULL/<s>VFGS</s>/RAND * (by keyboard input 1/2/3). * FULL/VFGS use loaded traj data with score. RAND peeks * traj without repetition from FULL. * <p> * JVM options: -Xmn2048m -Xms8192m -Xmx8192m * * @see DM * @see TrajDrawHandler2 */ public class ThreadMapAppPlus extends PApplet { private static final String APP_NAME = "ThreadMapAppPlus"; private static final String DATA_PATH = "data/porto_full.txt"; // traj limit when loading. -1 for no limit public static final int LIMIT = 1_0000; public static final int PEEK_SIZE = LIMIT / 1000; // recommend: core # * 2 or little higher public static final int THREAD_NUM = 10; public static final int WIDTH = 1200; public static final int HEIGHT = 800; // map params private static final Location PORTO_CENTER = new Location(41.14, -8.639); private static final String WHITE_MAP_PATH = "https://api.mapbox.com/styles/v1/pacemaker-yc/ck4gqnid305z61cp1dtvmqh5y/tiles/512/{z}/{x}/{y}@2x?access_token=<KEY>"; private UnfoldingMap map; private Trajectory[] trajShowNow = null; private Trajectory[] trajFull = null; private Trajectory[] trajVfgs = null; private Trajectory[] trajRand = null; // var to check changes private int nowZoomLevel; private Location nowCenter; private boolean mouseDown; // multi-thread for part image painting private final ExecutorService threadPool; private final TrajDrawHandler2[] handlers = new TrajDrawHandler2[THREAD_NUM]; // single thread pool for images controlling (may be redundant ?) private final ExecutorService controlPool; private Thread controlThread; private final PGraphics[] trajImages = new PGraphics[THREAD_NUM]; private final Vector<Long> newestId = new Vector<>(Collections.singletonList(0L)); private final int[] trajCnt = new int[THREAD_NUM]; public ThreadMapAppPlus() { // init pool threadPool = new ThreadPoolExecutor(THREAD_NUM, THREAD_NUM, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()) {{ // drop last thread this.setRejectedExecutionHandler(new DiscardOldestPolicy()); }}; controlPool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()) {{ // drop last thread and begin next this.setRejectedExecutionHandler(new DiscardOldestPolicy()); }}; } @Override public void settings() { // window settings size(WIDTH, HEIGHT, P2D); } @Override public void setup() { // frame settings textSize(20); // map settings map = new UnfoldingMap(this, APP_NAME, new MapBox.CustomMapBoxProvider(WHITE_MAP_PATH)); map.setZoomRange(1, 20); map.zoomAndPanTo(12, PORTO_CENTER); map.setBackgroundColor(255); // thread("loadTraj"); // looks not good (new Thread(this::loadTraj)).start(); // add mouse and keyboard interactions MapUtils.createDefaultEventDispatcher(this, map); refreshTitle(); } /** * Load trajectory data from file (FULL) * Then generate VFGS and RAND */ public void loadTraj() { // load features from text DM.loadRowData(DATA_PATH, LIMIT); trajFull = DM.trajFull; if (trajFull == null) { exit(); } System.out.println("Total load: " + trajFull.length); if (trajFull.length <= PEEK_SIZE) { // show all trajVfgs = trajFull; return; } // generate VFGS (temp version) trajVfgs = Arrays.copyOfRange(trajFull, 0, PEEK_SIZE); // generate RAND trajRand = new Trajectory[PEEK_SIZE]; HashSet<Integer> set = new HashSet<>(); Random rand = new Random(); int cnt = 0; while (cnt < PEEK_SIZE) { int idx = rand.nextInt(trajFull.length); if (set.contains(idx)) { continue; } set.add(idx); trajRand[cnt++] = trajFull[idx]; } // default trajShowNow = trajVfgs; } public void refreshTitle() { int loadCnt = 0; // # of painted traj int partCnt = 0; // # of part images that have finished painting. for (int i = 0; i < THREAD_NUM; ++i) { partCnt += (trajImages[i] == null) ? 0 : 1; loadCnt += trajCnt[i]; } double percentage = (trajShowNow == null) ? 0.0 : Math.min(100.0, 100.0 * loadCnt / trajShowNow.length); String shownSet = (trajShowNow == trajFull) ? "FULL" : (trajShowNow == trajVfgs) ? "VFGS" : (trajShowNow == trajRand) ? "RAND" : "----"; // main param str shown in title String str = String.format(APP_NAME + " [%5.2f fps] [%s] [%.1f%% loaded] [%d parts] ", frameRate, shownSet, percentage, partCnt); if (trajShowNow == null) { // generating traj data String dataName; if (trajFull == null) { dataName = "FULL"; } else if (trajVfgs == null) { dataName = "VFGS"; } else if (trajRand == null) { dataName = "RAND"; } else { dataName = "----"; } surface.setTitle(str + "Generate " + dataName + " set..."); return; } if (partCnt != THREAD_NUM) { // painting traj surface.setTitle(str + "Painting trajectories..."); return; } if (!map.allTilesLoaded()) { str += "Loading map..."; } else { str += "Completed"; } surface.setTitle(str); } @Override public void draw() { refreshTitle(); map.draw(); if (trajShowNow != null) { boolean changed = nowZoomLevel != map.getZoomLevel() || !nowCenter.equals(map.getCenter()); if (changed) { // use for delay verifying mouseDown = mousePressed; if (!mouseDown) { // is zoom. update now // otherwise update when mouse is released updateTrajImages(); } // drop all traj images Arrays.fill(trajImages, null); Arrays.fill(trajCnt, 0); } // show all valid traj images for (PGraphics pg : trajImages) { if (pg != null) { image(pg, 0, 0); } } } } @Override public void mouseReleased() { if (trajShowNow != null && !nowCenter.equals(map.getCenter())) { // was dragged and center changed mouseDown = false; updateTrajImages(); } } /** * Start multi-thread (by start a control thread) * and paint traj to flash images separately. */ public void updateTrajImages() { // update mark nowZoomLevel = map.getZoomLevel(); nowCenter = map.getCenter(); newestId.set(0, newestId.get(0) + 1); if (controlThread != null) { controlThread.interrupt(); } // create new control thread controlThread = new Thread(() -> { // kill all exist threads for (TrajDrawHandler2 tdh : handlers) { if (tdh != null) { tdh.interrupt(); } if (Thread.currentThread().isInterrupted()) { return; } } // add new threads for (int i = 0; i < THREAD_NUM; i++) { if (Thread.currentThread().isInterrupted()) { return; } trajImages[i] = null; TrajDrawHandler2 tdh = new TrajDrawHandler2(map, createGraphics(WIDTH, HEIGHT), trajImages, trajShowNow, newestId, false, 0, 0, trajCnt, i, THREAD_NUM, newestId.get(0)); handlers[i] = tdh; threadPool.submit(tdh); } }); controlThread.setPriority(10); controlPool.submit(controlThread); } @Override public void exit() { super.exit(); threadPool.shutdownNow(); controlPool.shutdownNow(); } @Override public void keyReleased() { switch (key) { case 'q': exit(); break; case '1': if (trajShowNow != trajFull) { trajShowNow = trajFull; updateTrajImages(); } break; case '2': if (trajShowNow != trajVfgs) { trajShowNow = trajVfgs; updateTrajImages(); } break; case '3': if (trajShowNow != trajRand) { trajShowNow = trajRand; updateTrajImages(); } break; } } public static void main(String[] args) { PApplet.main(new String[]{ThreadMapAppPlus.class.getName()}); } }<file_sep>/src/main/java/util/VfgsGps.java package util; import app.TimeProfileSharedObject; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.geo.Location; import de.fhpotsdam.unfolding.utils.ScreenPosition; import model.*; import java.util.Arrays; import java.util.HashSet; public class VfgsGps { public static TrajectoryMeta[] getVfgs(TrajectoryMeta[] trajFull, double rate, int delta, double minLat, double minLon, double latP, double lonP, StringBuilder sb, UnfoldingMap map) { map.zoomTo(20); System.out.println(minLat + ", " + minLon + ", " + latP + ", " + lonP); System.out.println(rate + ", " + delta); int trajNum = (int) (trajFull.length * rate); TrajectoryMeta[] trajectories = new TrajectoryMeta[trajNum]; try { long t0 = System.currentTimeMillis(); HashSet<GpsPosition> totalScoreSet = getTotalScore(trajFull, minLat, minLon, latP, lonP); // GpsPosition[] test = new GpsPosition[trajFull[0].getGpsPositions().length]; // int k = 0; // for (GpsPosition pos : trajFull[0].getGpsPositions()) { // test[k] = new GpsPosition(); // ScreenPosition screenPosition = map.getScreenPosition(new Location(pos.lat, pos.lon)); // test[k].x = (int) screenPosition.x; // test[k++].y = (int) screenPosition.y; // // } // System.out.println(Arrays.toString(trajFull[0].getGpsPositions())); // System.out.println(Arrays.toString(test)); // for (int i = 1; i < test.length; i++) { // System.out.print((trajFull[0].getGpsPositions()[i].x - trajFull[0].getGpsPositions()[i - 1].x) + " ," + // (trajFull[0].getGpsPositions()[i].y - trajFull[0].getGpsPositions()[i - 1].y)); // System.out.println("; " + (test[i].x - test[i - 1].x) + ", " + (test[i].y - test[i - 1].y)); // } sb.append((System.currentTimeMillis() - t0)).append(","); // System.out.println("total score time: " + (System.currentTimeMillis() - t0) + " ms"); System.out.println("total score: " + totalScoreSet.size()); long t1 = System.currentTimeMillis(); GreedyChooseMeta greedyChooseMeta = new GreedyChooseMeta(trajFull.length); trajScoreInit(trajFull, greedyChooseMeta); HashSet<GpsPosition> influScoreSet = new HashSet<>(); for (int i = 0; i < trajNum; i++) { while (true) { updateTrajScore(greedyChooseMeta.getHeapHead(), influScoreSet); if (greedyChooseMeta.GreetOrder()) { TrajectoryMeta traj = greedyChooseMeta.getMaxScoreTraj(); updateInfluScoreSet(traj, influScoreSet, totalScoreSet, delta); trajectories[i] = traj; break; } else { greedyChooseMeta.orderAdjust(); } } } sb.append((System.currentTimeMillis() - t1)).append(","); } catch (Exception e) { e.printStackTrace(); } System.out.println(trajFull.length + "-->" + trajNum); return trajectories; } private static void updateInfluScoreSet(TrajectoryMeta trajectoryMeta, HashSet<GpsPosition> influSet, HashSet<GpsPosition> totalSet, int delta) { // System.out.println(influSet.size()); // System.out.println(totalSet.size()); for (GpsPosition gpsPosition : trajectoryMeta.getGpsPositions()) { for (int i = -delta; i < delta + 1; i++) { for (int j = -delta; j < delta + 1; j++) { GpsPosition gpsPosition1 = new GpsPosition(gpsPosition.x + i, gpsPosition.y + j); if (totalSet.contains(gpsPosition1)) { influSet.add(gpsPosition); } } } } // System.out.println(influSet.size()); } private static void trajScoreInit(TrajectoryMeta[] trajectories, GreedyChooseMeta greedyChooseMeta) { for (TrajectoryMeta traj : trajectories) { traj.scoreInit(); greedyChooseMeta.addNewTraj(traj); } } private HashSet<Position> getTotalScoreSet(TrajectoryMeta[] trajFull) { HashSet<Position> totalScoreSet = new HashSet<>(trajFull.length); for (TrajectoryMeta traj : trajFull) { totalScoreSet.addAll(Arrays.asList(traj.getPositions())); } return totalScoreSet; } private static HashSet<GpsPosition> getTotalScore(TrajectoryMeta[] trajFull, double minLat, double minLon, double latP, double lonP) { HashSet<GpsPosition> totalScoreSet = new HashSet<>(); for (TrajectoryMeta traj : trajFull) { for (GpsPosition gpsPosition : traj.getGpsPositions()) { gpsPosition.x = (int) ((gpsPosition.lat - minLat) / latP); gpsPosition.y = (int) ((gpsPosition.lon - minLon) / lonP); totalScoreSet.add(gpsPosition); } // totalScoreSet.addAll(Arrays.asList(traj.getGpsPositions())); } // System.out.println(cnt + ", " + totalScoreSet.size()); return totalScoreSet; } private static void updateTrajScore(TrajectoryMeta TrajectoryMeta, HashSet<GpsPosition> influScoreSet) { double score = 0; for (GpsPosition gpsPosition : TrajectoryMeta.getGpsPositions()) { if (!influScoreSet.contains(gpsPosition)) { score++; } } TrajectoryMeta.updateScore(score); } } <file_sep>/src/main/java/select/SelectManager.java package select; import app.SharedObject; import de.fhpotsdam.unfolding.UnfoldingMap; import draw.TrajDrawManager; import model.BlockType; import model.RegionType; import model.TrajBlock; import model.Trajectory; import org.apache.commons.lang3.ArrayUtils; import util.PSC; import java.util.concurrent.*; /** * select thread pool manager, return the traj index array. */ public class SelectManager { private RegionType regionType; // ODW private UnfoldingMap[] mapList; private TrajBlock[] blockList; public SelectManager(RegionType regionType, UnfoldingMap[] mapList, TrajBlock[] blockList) { this.regionType = regionType; this.mapList = mapList; this.blockList = blockList; System.out.println(regionType); } private Trajectory[] startMapCal(TrajBlock trajBlock, int opIndex) { if (trajBlock.getBlockType() == BlockType.NONE) { return new Trajectory[0]; } int threadNum = trajBlock.getThreadNum(); // TODO Recreate thread pool? Create once may be a better choice. ExecutorService threadPool = new ThreadPoolExecutor(threadNum, threadNum, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); long startTime = System.currentTimeMillis(); Trajectory[] trajList = trajBlock.getTrajList(); int totLen = trajList.length; int segLen = totLen / threadNum; Trajectory[] resShowIndex = {}; if (segLen < PSC.MULTI_THREAD_BOUND) { // use single thread instead of multi thread threadNum = 1; segLen = totLen; } for (int i = 0; i < threadNum; i++) { SelectWorker sw = new SelectWorker(regionType, trajBlock.getTrajList(), i * segLen, (i + 1) * segLen, opIndex, i); threadPool.submit(sw); } threadPool.shutdown(); try { threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { System.err.println(e); } System.out.println("ALL Done"); for (int i = 0; i < threadNum; i++) { resShowIndex = ArrayUtils.addAll(resShowIndex, SharedObject.getInstance().getTrajSelectRes()[i]); } System.out.println(trajBlock.getBlockType() + " time: " + (System.currentTimeMillis() - startTime) + " select size: " + resShowIndex.length); return resShowIndex; } public void startRun() { TrajDrawManager tdm = SharedObject.getInstance().getTrajDrawManager(); for (int i = 0; i < 4; i++) { TrajBlock trajBlock = blockList[i]; SharedObject.getInstance().setTrajSelectRes(new Trajectory[trajBlock.getThreadNum()][]); Trajectory[] trajAry = startMapCal(trajBlock, i); trajBlock.setTrajSltList(trajAry); if (trajBlock.getMainColor() != PSC.GRAY) { // need to repaint trajBlock.setMainColor(PSC.GRAY); tdm.cleanImgFor(i, TrajDrawManager.MAIN); tdm.startNewRenderTaskFor(i, TrajDrawManager.MAIN); } tdm.cleanImgFor(i, TrajDrawManager.SLT); tdm.startNewRenderTaskFor(i, TrajDrawManager.SLT); } } } <file_sep>/src/main/java/app/TimeProfileGPU.java package app; import com.jogamp.opengl.GL3; import com.jogamp.opengl.util.GLBuffers; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.geo.Location; import de.fhpotsdam.unfolding.providers.MapBox; import de.fhpotsdam.unfolding.utils.MapUtils; import de.fhpotsdam.unfolding.utils.ScreenPosition; import model.RectRegion; import model.Trajectory; import processing.core.PApplet; import processing.opengl.PJOGL; import select.TimeProfileManager; import util.PSC; import java.awt.*; import java.io.*; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.*; public class TimeProfileGPU extends PApplet { UnfoldingMap map; UnfoldingMap mapClone; @Override public void settings() { size(1000, 800, P2D); PJOGL.profile = 3; } @Override public void setup() { map = new UnfoldingMap(this, new MapBox.CustomMapBoxProvider(PSC.WHITE_MAP_PATH)); map.setZoomRange(0, 20); map.zoomAndPanTo(ZOOMLEVEL, PRESENT); map.setBackgroundColor(255); MapUtils.createDefaultEventDispatcher(this, map); mapClone = new UnfoldingMap(this, new MapBox.CustomMapBoxProvider(PSC.WHITE_MAP_PATH)); mapClone.setZoomRange(0, 20); mapClone.zoomAndPanTo(20, PRESENT); int delta = 4; String filePath = "data/GPS/vfgs_" + delta + ".txt"; // loadData("data/GPS/Porto5w/Porto5w.txt"); loadData("data/GPS/porto_full.txt"); Trajectory[] trajectories = loadVfgs("data/GPS/dwt_24k.txt", 0.001); double[] rateList = {0.01, 0.005, 0.001, 0.0005, 0.0001/*, 0.00005, 0.00001*/}; for (Double rate : rateList) { long t0 = System.currentTimeMillis(); util.VFGS.getCellCover(trajFull, mapClone, rate, 16); System.out.println(rate + ", " + (System.currentTimeMillis() - t0)); } System.out.println(trajectories.length); new Thread() { @Override public void run() { for (int i = 11; i < 17; i++) { double quality = util.VFGS.getQuality(trajFull, trajectories, mapClone, i, 0); System.out.println(quality); } } }.start(); // //test lat lon /* double[] rate = {0.01, 0.005, 0.001, 0.0005, 0.0001}; new Thread() { @Override public void run() { for (int i = 0; i < rate.length; i++) { Trajectory[] trajectories = loadVfgs("data/GPS/dwt_24k.txt", rate[i]); double quality = util.VFGS.getQuality(trajFull, trajectories, mapClone, 14, 0); System.out.println(rate[i] + ", " + quality); } } }.start(); */ // loadData("data/GPS/Porto5w/Porto5w.txt"); // initRandomIdList(); loadRandomTrajList(); VFGSIdList = loadVfgs("data/GPS/vfgs_0.csv"); loadTrajList(); gl3 = ((PJOGL) beginPGL()).gl.getGL3(); endPGL();//? } private int ZOOMLEVEL = 11; private int rectRegionID = 0; private double recNumId = 1.0 / 64; private Location[] rectRegionLoc = {new Location(41.315205, -8.629877), new Location(41.275997, -8.365519), new Location(41.198544, -8.677942), new Location(41.213013, -8.54542), new Location(41.1882, -8.35178), new Location(41.137554, -8.596918), new Location(41.044403, -8.470575), new Location(40.971338, -8.591425)}; private Location PRESENT = rectRegionLoc[rectRegionID]/*new Location(41.206, -8.627)*/; private int alg = 2; private double[] rate = {0.01, 0.005, 0.001, 0.0005, 0.0001, 0.00005, 0.00001}; private int rateId = 0; private int[] deltaList = {0, 4, 8, 16, 32, 64}; private int deltaId = 0; private RectRegion rectRegion = new RectRegion(); @Override public void draw() { if (!map.allTilesLoaded()) { map.draw(); } else { map.zoomAndPanTo(ZOOMLEVEL, rectRegionLoc[rectRegionID]); map.draw(); if (alg == 0) { deltaList = new int[]{0}; // } else { // deltaList = new int[]{0, 4, 8, 16, 32, 64}; } float x = (float) (500 * recNumId); float y = (float) (400 * recNumId); rectRegion.setLeftTopLoc(map.getLocation(500 - x, 400 - y)); rectRegion.setRightBtmLoc(map.getLocation(500 + x, 400 + y)); long wayPointBegin = System.currentTimeMillis(); startCalWayPoint(); //waypoint long wayPointCost = (System.currentTimeMillis() - wayPointBegin); trajShow.clear(); ArrayList<Trajectory> trajShows = new ArrayList<>(); for (Trajectory[] trajList : TimeProfileSharedObject.getInstance().trajRes) { Collections.addAll(trajShows, trajList); } // Trajectory[] tmpRes = getRan(trajShows.toArray(new Trajectory[0]), rate[VFGS]); long algBegin = System.currentTimeMillis(); Trajectory[] tmpRes = {}; if (alg == 0) {//ran tmpRes = getRan(trajShows.toArray(new Trajectory[0]), rate[rateId]); } else if (alg == 1) {//vfgs tmpRes = util.VFGS.getCellCover(trajShows.toArray(new Trajectory[0]), mapClone, rate[rateId], deltaList[deltaId]); } long algCost = (System.currentTimeMillis() - algBegin); long qualityBegin = System.currentTimeMillis(); double quality = util.VFGS.getQuality(trajShows.toArray(new Trajectory[0]), tmpRes, map, deltaList[deltaId]); long qualityCost = (System.currentTimeMillis() - qualityBegin); this.trajShow.addAll(Arrays.asList(tmpRes)); /* long t0 = System.currentTimeMillis(); vertexInit(); long dataTime = (System.currentTimeMillis() - t0); System.out.println("data init time for rate : " + rate[VFGS] + " of VFGS: " + dataTime + "ms"); long t1 = System.currentTimeMillis(); drawGPU(); long renderTime = (System.currentTimeMillis() - t1); System.out.println("GPU draw time for rate : " + rate[VFGS] + " of VFGS: " + renderTime + "ms"); */ noFill(); strokeWeight(1); stroke(new Color(190, 46, 29).getRGB()); long[] timeRender = drawCPU(); drawRect(); //info StringBuilder info = new StringBuilder(); info.append(ZOOMLEVEL).append(",").append(rectRegionID).append(",").append(recNumId).append(",").append(alg).append(",") .append(rate[rateId]).append(",").append(deltaList[deltaId]).append(",") .append(wayPointCost).append(",").append(algCost).append(",").append(timeRender[0]).append(",") .append(timeRender[1]).append(",").append(quality).append(",").append(qualityCost); try { BufferedWriter writer = new BufferedWriter(new FileWriter("data/localRec/AllRecordV2.txt", true)); writer.write(info.toString()); writer.newLine(); writer.close(); System.out.println(trajShows.size() + "-->" + tmpRes.length); String[] infoList = info.toString().split(","); String[] titleList = "zoomlevel,regionId,regionSize,algorithm,rate,delta,waypointCost,computionCost,mappingCost,renderingCost,quality,qualityCost".split(","); for (int i = 0; i < titleList.length; i++) { System.out.print(titleList[i] + " = " + infoList[i] + ", "); } System.out.println(); } catch (IOException e) { e.printStackTrace(); } // try { // Thread.sleep(2000); // } catch (InterruptedException e) { // e.printStackTrace(); // } if (deltaId == deltaList.length - 1) {//delta full deltaId = 0; if (rateId == rate.length - 1) {//rate full rateId = 0; if (alg == 1) {//alg full alg = 0; if (recNumId == 0.5) { recNumId = 1.0 / 128; if (rectRegionID == rectRegionLoc.length - 1) { rectRegionID = 0; if (ZOOMLEVEL == 16) { System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>done>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); noLoop(); exit(); } else { ZOOMLEVEL++; } } else { rectRegionID++; } } else { recNumId *= 2; } } else { alg++; } } else { rateId++; } } else { deltaId++; } } } private void drawGPU() { shaderInit(); FloatBuffer vertexDataBuffer = GLBuffers.newDirectFloatBuffer(vertexData); vboHandles = new int[1]; gl3.glGenBuffers(1, vboHandles, 0); gl3.glBindBuffer(GL3.GL_ARRAY_BUFFER, vboHandles[0]); gl3.glBufferData(GL3.GL_ARRAY_BUFFER, vertexDataBuffer.capacity() * 4, vertexDataBuffer, GL3.GL_STATIC_DRAW); gl3.glBindBuffer(GL3.GL_ARRAY_BUFFER, 0); vertexDataBuffer = null; gl3.glGenVertexArrays(1, vao); gl3.glBindVertexArray(vao.get(0)); gl3.glUseProgram(shaderProgram); gl3.glBindBuffer(GL3.GL_ARRAY_BUFFER, vboHandles[0]); gl3.glEnableVertexAttribArray(0); gl3.glEnableVertexAttribArray(1); gl3.glVertexAttribPointer(0, 2, GL3.GL_FLOAT, false, 0, 0); gl3.glVertexAttribPointer(1, 2, GL3.GL_FLOAT, false, 0, 0); gl3.glDrawArrays(GL3.GL_LINES, 0, vertexData.length / 2); gl3.glDisableVertexAttribArray(0); gl3.glDisableVertexAttribArray(1); } private void drawRect() { noFill(); strokeWeight(2); stroke(new Color(19, 149, 186).getRGB()); ScreenPosition src1 = map.getScreenPosition(rectRegion.getLeftTopLoc()); ScreenPosition src2 = map.getScreenPosition(rectRegion.getRightBtmLoc()); rect(src1.x, src1.y, src2.x - src1.x, src2.y - src1.y); } boolean noLoop = false; boolean thread = false; @Override public void keyPressed() { if (key == 'q') { trajShow.clear(); noLoop = false; thread = false; loop(); } else if (key == 'w') { Collections.addAll(trajShow, trajFull); noLoop = true; } else if (key == 'e') { float x = (float) (500 * recNumId); float y = (float) (400 * recNumId); rectRegion.setLeftTopLoc(map.getLocation(500 - x, 400 - y)); rectRegion.setRightBtmLoc(map.getLocation(500 + x, 400 + y)); System.out.println(rectRegion.getLeftTopLoc()); System.out.println(rectRegion.getRightBtmLoc()); System.out.println("using: " + recNumId); recNumId *= 2; startCalWayPoint(); trajShow.clear(); noLoop = true; thread = true; loop(); } System.out.println(key); } Trajectory[] trajFull; ArrayList<Trajectory> trajShow = new ArrayList<>(); private void loadData(String filePath) { try { ArrayList<String> trajStr = new ArrayList<>(2400000); BufferedReader reader = new BufferedReader(new FileReader(filePath)); String line; while ((line = reader.readLine()) != null) { trajStr.add(line); } reader.close(); System.out.println("load done"); int j = 0; trajFull = new Trajectory[trajStr.size()]; for (String trajM : trajStr) { String[] item = trajM.split(";"); String[] data = item[1].split(","); Trajectory traj = new Trajectory(j); ArrayList<Location> locations = new ArrayList<>(); // Position[] metaGPS = new Position[data.length / 2 - 1]; for (int i = 0; i < data.length - 2; i = i + 2) { locations.add(new Location(Float.parseFloat(data[i + 1]), Float.parseFloat(data[i]))); // metaGPS[i / 2] = new Position(Float.parseFloat(data[i + 1]), Float.parseFloat(data[i])); } traj.setLocations(locations.toArray(new Location[0])); traj.setScore(Integer.parseInt(item[0])); // traj.setMetaGPS(metaGPS); trajFull[j++] = traj; } trajStr.clear(); System.out.println("load done"); System.out.println("traj number: " + trajFull.length); } catch (IOException e) { e.printStackTrace(); } } Trajectory[] selectTrajList; private void startCalWayPoint() { TimeProfileManager tm = new TimeProfileManager(1, trajFull, rectRegion); tm.startRun(); } int[][] VFGSIdList; int VFGS = 0; private Trajectory[] loadVfgs(String filePath, double rate) { int trajNum = (int) (trajFull.length * rate); ArrayList<String> idsSet = new ArrayList<>(); try { BufferedReader reader = new BufferedReader(new FileReader(filePath)); String line; for (int i = 0; i < trajNum; i++) { line = reader.readLine(); idsSet.add(line); } reader.close(); } catch (IOException e) { e.printStackTrace(); } Trajectory[] trajectories = new Trajectory[trajNum]; int i = 0; for (String str : idsSet) { trajectories[i++] = trajFull[Integer.parseInt(str.split(",")[0])]; } return trajectories; } private int[][] loadVfgs(String filePath) { int[][] resId = new int[8][]; try { BufferedReader reader = new BufferedReader(new FileReader(filePath)); String line; ArrayList<Integer> id = new ArrayList<>(); int i = 0; while ((line = reader.readLine()) != null) { if (!line.contains(",")) { resId[i] = new int[id.size()]; System.out.println(id.size()); int j = 0; for (Integer e : id) { resId[i][j++] = e; } i++; id.clear(); } else { id.add(Integer.parseInt(line.split(",")[0])); } } reader.close(); } catch (IOException e) { e.printStackTrace(); } return resId; } private void loadTrajList() { selectTrajList = new Trajectory[VFGSIdList[VFGS].length]; int i = 0; for (Integer e : VFGSIdList[VFGS]) { selectTrajList[i++] = trajFull[e]; } } int[][] randomIdList; private void initRandomIdList() { randomIdList = new int[rate.length][]; int i = 0; Random ran = new Random(1); HashSet<Integer> tmp = new HashSet<Integer>((int) (trajFull.length * 0.05)); for (double rate : rate) { tmp.clear(); int num = (int) (rate * trajFull.length); randomIdList[i] = new int[num]; int j = 0; while (tmp.size() < num) { tmp.add(ran.nextInt(trajFull.length - 1)); } for (Integer e : tmp) { randomIdList[i][j++] = e; } i++; } } private void loadRandomTrajList() { selectTrajList = new Trajectory[randomIdList[VFGS].length]; int i = 0; for (Integer e : randomIdList[VFGS]) { selectTrajList[i++] = trajFull[e]; } } GL3 gl3; int[] vboHandles; int shaderProgram, vertShader, fragShader; int vertexBufferObject; IntBuffer vao = GLBuffers.newDirectIntBuffer(1); float[] vertexData = {}; private void shaderInit() { // initializeProgram shaderProgram = gl3.glCreateProgram(); fragShader = gl3.glCreateShader(GL3.GL_FRAGMENT_SHADER); gl3.glShaderSource(fragShader, 1, new String[]{ "#ifdef GL_ES\n" + "precision mediump float;\n" + "precision mediump int;\n" + "#endif\n" + "\n" + "varying vec4 vertColor;\n" + "\n" + "void main() {\n" + " gl_FragColor = vec4(1.0,0.0,0.0,1.0);\n" + "}" }, null); gl3.glCompileShader(fragShader); vertShader = gl3.glCreateShader(GL3.GL_VERTEX_SHADER); gl3.glShaderSource(vertShader, 1, new String[]{ "#version 330 \n" + "layout (location = 0) in vec4 position;" + "layout (location = 1) in vec4 color;" + "smooth out vec4 theColor;" + "void main(){" + "gl_Position.x = position.x / 500.0 - 1;" + "gl_Position.y = -1 * position.y / 400.0 + 1;" + "theColor = color;" + "}" }, null); gl3.glCompileShader(vertShader); // attach and link gl3.glAttachShader(shaderProgram, vertShader); gl3.glAttachShader(shaderProgram, fragShader); gl3.glLinkProgram(shaderProgram); // program compiled we can free the object gl3.glDeleteShader(vertShader); gl3.glDeleteShader(fragShader); } private void vertexInit() { int line_count = 0; for (Trajectory traj : trajShow) { line_count += (traj.locations.length); } vertexData = new float[line_count * 2 * 2]; int j = 0; for (Trajectory traj : trajShow) { for (int i = 0; i < traj.locations.length - 2; i++) { ScreenPosition pos = map.getScreenPosition(traj.locations[i]); ScreenPosition pos2 = map.getScreenPosition(traj.locations[i + 1]); vertexData[j++] = pos.x; vertexData[j++] = pos.y; vertexData[j++] = pos2.x; vertexData[j++] = pos2.y; } } } private long[] drawCPU() { long[] timeList = new long[2]; ArrayList<ArrayList<Point>> trajPointList = new ArrayList<>(); long t0 = System.currentTimeMillis(); for (Trajectory traj : trajShow) { ArrayList<Point> pointList = new ArrayList<>(); for (Location loc : traj.getLocations()) { ScreenPosition pos = map.getScreenPosition(loc); pointList.add(new Point(pos.x, pos.y)); } trajPointList.add(pointList); } timeList[0] = (System.currentTimeMillis() - t0); long t1 = System.currentTimeMillis(); for (ArrayList<Point> traj : trajPointList) { beginShape(); for (Point pos : traj) { vertex(pos.x, pos.y); } endShape(); } timeList[1] = (System.currentTimeMillis() - t1); return timeList; } private Trajectory[] getRan(Trajectory[] trajectories, double rate) { int size = (int) (rate * trajectories.length); Trajectory[] res = new Trajectory[size]; HashSet<Integer> set = new HashSet<>(); Random ran = new Random(); while (set.size() != size) { set.add(ran.nextInt(trajectories.length - 1)); } int i = 0; for (Integer e : set) { res[i++] = trajectories[e]; } return res; } public static void main(String[] args) { PApplet.main(new String[]{TimeProfileGPU.class.getName()}); } class Point { float x; float y; public Point(float x, float y) { this.x = x; this.y = y; } } } <file_sep>/src/main/java/util/IOHandle.java package util; import de.fhpotsdam.unfolding.geo.Location; import model.Trajectory; import org.apache.commons.io.FileUtils; import org.apache.commons.io.LineIterator; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import static util.Util.translateRate; /** * IO util class */ public class IOHandle { /** * Load traj raw data or with score (version problem) * {@code #trajFull} from file {@link PSC#ORIGIN_PATH}. * <p> * format: (score;)double1,double2... */ public static Trajectory[] loadRowData(String filePath, int limit) { List<Trajectory> res = new ArrayList<>(); LineIterator it = null; int cnt = 0; System.out.print("Read raw data from " + filePath + " ..."); try { it = FileUtils.lineIterator(new File(filePath), "UTF-8"); while (it.hasNext() && (limit == -1 || cnt < limit)) { String line = it.nextLine(); String[] item = line.split(";"); String[] data = item[item.length - 1].split(","); Trajectory traj = new Trajectory(cnt); if (item.length == 2) { // when data contain "score;" traj.setScore(Integer.parseInt(item[0])); } ArrayList<Location> locations = new ArrayList<>(); for (int i = 0; i < data.length - 2; i = i + 2) { // FIXME // the longitude and latitude are reversed locations.add(new Location(Float.parseFloat(data[i + 1]), Float.parseFloat(data[i]))); } traj.setLocations(locations.toArray(new Location[0])); res.add(traj); ++ cnt; } System.out.println("\b\b\bfinished."); } catch (IOException | NoSuchElementException e) { System.out.println("\b\b\bfailed. \nProblem line: " + cnt); e.printStackTrace(); } finally { if (it != null) { LineIterator.closeQuietly(it); } } return res.toArray(new Trajectory[0]); } /** * Read vfgs result {@code #vfgsResList} from {@link PSC#RES_PATH} * <br> format: tid, score (not need for now) * <p> * Before calling it, the {@link #loadRowData(String, int)} * should be called first. */ public static Trajectory[][] loadVfgsResList(String filePath, Trajectory[] trajFull, int[] deltaList, double[] rateList) { int dLen = deltaList.length; Trajectory[][] ret = new Trajectory[dLen][]; int trajNum = trajFull.length; int[] rateCntList = translateRate(trajNum, rateList); LineIterator it = null; int lineNum = 0; System.out.print("Read vfgs result from " + filePath.replace("%d", "*")); try { for (int dIdx = 0; dIdx < dLen; ++dIdx) { int delta = deltaList[dIdx]; String path = String.format(filePath, delta); it = FileUtils.lineIterator(new File(path), "UTF-8"); // load the R / R+ for this delta Trajectory[] vfgsRes = new Trajectory[rateCntList[0]]; for (int i = 0; i < vfgsRes.length; i++) { String line = it.nextLine(); String[] data = line.split(","); vfgsRes[i] = trajFull[Integer.parseInt(data[0])]; ++lineNum; } ret[dIdx] = vfgsRes; } System.out.println(" finished."); } catch (IOException | NoSuchElementException e) { System.out.println(" failed. \nProblem line: " + lineNum); e.printStackTrace(); } finally { if (it != null) { LineIterator.closeQuietly(it); } } return ret; } } <file_sep>/src/main/java/vqgs/app/VFGSMapApp.java package vqgs.app; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.geo.Location; import de.fhpotsdam.unfolding.providers.MapBox; import de.fhpotsdam.unfolding.utils.MapUtils; import vqgs.draw.TrajDrawHandler2; import vqgs.draw.TrajShader; import vqgs.model.Trajectory; import processing.core.PApplet; import processing.core.PGraphics; import vqgs.util.DM; import vqgs.util.PSC; import java.awt.*; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static vqgs.util.PSC.*; /** * Draw a FULL / VFGS & VFGS+ / VFGS+(CE) / RAND traj map with multi-thread. * Support for switching in each mode. * Now, all the data with diff delta and simple rate will be loaded * <p> * Interaction: * <ul><li>'1/2/3/4': change data set.</li> * <li>'W/S/A/D': change delta or rate by keyboard input .</li> * <li>',' & '.': change to preset center {@link #presetCenter}[pid].</li> * <li>'/': reset to preset center of current pid.</li> * <li>'O': print location of center.</li> * <li>'P': get a screenshot and save to {@link PSC#PATH_PREFIX}.</li> * <li>'Esc': quit.</li></ul> * <p> * Use settings in {@link PSC} and these existed files: * <ul><li>{@link PSC#ORIGIN_PATH}: Raw data</li> * <li>{@link PSC#RES_PATH}: VFGS / VFGS+ result</li> * <li>{@link PSC#COLOR_PATH}: Color encoding result</li></ul> * <p> * JVM options: * -Xmn2048m -Xms8192m -Xmx8192m * -Xmn2g -Xms6g -Xmx6g * * @version 3.2 Multi-dataset & support for delta/rate changing. * @see DM * @see PSC * @see TrajDrawHandler2 * @see TrajShader */ public class VFGSMapApp extends PApplet { private static final String[] SET_NAMES = {"----", "FULL", "VFGS", "VFGS(CE)", "RAND"}; private UnfoldingMap map; private Trajectory[] trajShowNow = null; private Trajectory[] trajFull = null; private Trajectory[][][] trajVfgsMatrix = null; // trajVfgs for delta X rate private Trajectory[][] trajRandList = null; // trajRand for rate // traj color shader /*private TrajShader shader;*/ // drop it after init private boolean colored; // var to check changes private int nowZoomLevel; private Location nowCenter; private boolean mouseDown; private int mode; private int dPtr = 0; private int rPtr = 0; private final int[] deltaList = DELTA_LIST; private final double[] rateList = RATE_LIST; private final boolean loadVfgsRes = LOAD_VFGS; private final boolean loadColorRes = LOAD_COLOR; // because now color output doesn't cover all vfgs res, so need this option // multi-thread for part image painting private final ExecutorService threadPool; private final TrajDrawHandler2[] handlers = new TrajDrawHandler2[THREAD_NUM]; // single thread pool for images controlling private final ExecutorService controlPool; private Thread controlThread; private final PGraphics[] trajImages = new PGraphics[THREAD_NUM]; private final Vector<Long> newestId = new Vector<>(Collections.singletonList(0L)); private final int[] trajCnt = new int[THREAD_NUM]; private int pid = PSC.BEGIN_CENTER_ID; // use it to def. no the center in PSC private static final Location[] presetCenter = PSC.PRESET_CENTER; public VFGSMapApp() { // init pool threadPool = new ThreadPoolExecutor(THREAD_NUM, THREAD_NUM, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()) {{ // drop last thread this.setRejectedExecutionHandler(new DiscardOldestPolicy()); }}; controlPool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()) {{ // drop last thread and begin next this.setRejectedExecutionHandler(new DiscardOldestPolicy()); }}; } @Override public void settings() { // window settings size(WIDTH, HEIGHT, P2D); } @Override public void setup() { System.out.println(PSC.str()); // frame settings textSize(20); // map settings map = new UnfoldingMap(this, new MapBox.CustomMapBoxProvider(WHITE_MAP_PATH)); map.setZoomRange(1, 20); map.zoomAndPanTo(11, presetCenter[pid]); map.setBackgroundColor(255); // thread("loadTraj"); // looks not good (new Thread(this::initData)).start(); // add mouse and keyboard interactions MapUtils.createDefaultEventDispatcher(this, map); refreshTitle(); } /** * Load trajectory data from file (FULL) * Then generate VFGS and RAND */ public void initData() { mode = 1; System.out.println(); // load data from files. if load color res then load it boolean success = DM.loadRowData(ORIGIN_PATH, LIMIT) && (!loadVfgsRes || DM.loadResList(RES_PATH, deltaList, rateList)) && (!loadColorRes || DM.loadRepScoresMatrix(COLOR_PATH, deltaList, rateList)); if (!success) { exit(); return; } System.out.println(); trajFull = DM.trajFull; int[] rateCntList = DM.translateRate(trajFull.length, rateList); // generate VFGS: trajVfgsMatrix if (loadVfgsRes) { mode = 2; initTrajVfgsMatrix(rateCntList); } // generate VFGS (CE) if (loadColorRes) { mode = 3; initTrajColor(); } // generate RAND mode = 4; initTrajRandList(rateCntList); // default mode = 2; trajShowNow = trajVfgsMatrix[dPtr][rPtr]; updateTrajImages(); } /** * Init {@link #trajVfgsMatrix} from {@link DM#vfgsResList} */ private void initTrajVfgsMatrix(int[] rateCntList) { int dLen = deltaList.length; int rLen = rateList.length; trajVfgsMatrix = new Trajectory[dLen][rLen][]; for (int dIdx = 0; dIdx < dLen; dIdx++) { int[] vfgsRes = DM.vfgsResList[dIdx]; for (int rIdx = 0; rIdx < rLen; rIdx++) { int rateCnt = rateCntList[rIdx]; Trajectory[] trajVfgs = new Trajectory[rateCnt]; for (int i = 0; i < rateCnt; i++) { trajVfgs[i] = trajFull[vfgsRes[i]]; } trajVfgsMatrix[dIdx][rIdx] = trajVfgs; } } } private void initTrajColor() { int[][][] repScoresMatrix = DM.repScoresMatrix; TrajShader.initTrajColorMatrix(trajVfgsMatrix, repScoresMatrix, COLORS, BREAKS); // sort vfgs to show it properly for (int dIdx = 0; dIdx < deltaList.length; dIdx++) { for (int rIdx = 0; rIdx < rateList.length; rIdx++) { Trajectory[] trajVfgs = trajVfgsMatrix[dIdx][rIdx]; for (Trajectory trajVfg : trajVfgs) { Color c = trajVfg.getColorMatrix()[dIdx][rIdx]; int j; for (j = 0; j < 5; j++) { if (COLORS[j] == c) { break; } } trajVfg.setScore(j); // reuse this field. no special meaning } Arrays.sort(trajVfgs, Comparator.comparingInt(Trajectory::getScore)); } } } private void initTrajRandList(int[] rateCntList) { Random rand = new Random(); int dLen = rateCntList.length; trajRandList = new Trajectory[dLen][]; for (int dIdx = 0; dIdx < dLen; dIdx++) { int rateCnt = rateCntList[dIdx]; Trajectory[] trajRand = new Trajectory[rateCnt]; HashSet<Integer> set = new HashSet<>(rateCnt * 4 / 3 + 1); int cnt = 0; while (cnt < trajRand.length) { int idx = rand.nextInt(trajFull.length); if (set.contains(idx)) { continue; } set.add(idx); trajRand[cnt++] = trajFull[idx]; } trajRandList[dIdx] = trajRand; } } private void refreshTitle() { int loadCnt = 0; // # of painted traj int partCnt = 0; // # of part images that have finished painting. for (int i = 0; i < THREAD_NUM; ++i) { partCnt += (trajImages[i] == null) ? 0 : 1; loadCnt += trajCnt[i]; } double percentage = (trajShowNow == null) ? 0.0 : Math.min(100.0, 100.0 * loadCnt / trajShowNow.length); String shownSet = SET_NAMES[mode]; // main param str shown in title String str = String.format(this.getClass().getSimpleName() + " [%5.2f fps] [%s] [%.1f%%] [%d parts] [zoom=%d] [pid=%d] ", frameRate, shownSet, percentage, partCnt, map.getZoomLevel(), pid); if (trajShowNow == null) { // generating traj data surface.setTitle(str + "Generate " + shownSet + " set..."); return; } if (mode == 2 || mode == 3 || mode == 4) { // VFGS / VFGS+ or VFGS with CE str += String.format("[delta=%d rate=%s] ", deltaList[dPtr], rateList[rPtr]); } if (partCnt != THREAD_NUM) { // painting traj surface.setTitle(str + "Painting trajectories..."); return; } if (!map.allTilesLoaded()) { str += "Loading map..."; } else { str += "Completed"; } surface.setTitle(str); } @Override public void draw() { refreshTitle(); map.draw(); if (trajShowNow != null) { boolean changed = nowZoomLevel != map.getZoomLevel() || !nowCenter.equals(map.getCenter()); if (changed) { // use for delay verifying mouseDown = mousePressed; if (!mouseDown) { // is zoom. update now // otherwise update when mouse is released updateTrajImages(); } else { // drop all traj images first if drag Arrays.fill(trajImages, null); Arrays.fill(trajCnt, 0); } } // show all valid traj images for (PGraphics pg : trajImages) { if (pg != null) { image(pg, 0, 0); } } } } @Override public void mouseReleased() { if (trajShowNow != null && !nowCenter.equals(map.getCenter())) { // was dragged and center changed mouseDown = false; updateTrajImages(); } } /** * Start multi-thread (by start a control thread) * and paint traj to flash images separately. */ public void updateTrajImages() { // drop all traj images Arrays.fill(trajImages, null); Arrays.fill(trajCnt, 0); // update mark nowZoomLevel = map.getZoomLevel(); nowCenter = map.getCenter(); newestId.set(0, newestId.get(0) + 1); if (controlThread != null) { controlThread.interrupt(); } // create new control thread controlThread = new Thread(() -> { // kill all exist threads for (TrajDrawHandler2 tdh : handlers) { if (tdh != null) { tdh.interrupt(); } if (Thread.currentThread().isInterrupted()) { return; } } // add new threads for (int i = 0; i < THREAD_NUM; i++) { if (Thread.currentThread().isInterrupted()) { return; } trajImages[i] = null; TrajDrawHandler2 tdh = new TrajDrawHandler2(map, createGraphics(WIDTH, HEIGHT), trajImages, trajShowNow, newestId, colored, dPtr, rPtr, trajCnt, i, THREAD_NUM, newestId.get(0)); handlers[i] = tdh; threadPool.submit(tdh); } }); controlThread.setPriority(10); controlPool.submit(controlThread); } @Override public void exit() { threadPool.shutdownNow(); controlPool.shutdownNow(); super.exit(); } @Override public void keyReleased() { if (key == '\u001B') { // press default key: esc, quit exit(); return; } if (consumeMoveOpt()) { return; } if (consumeChangeDataSetOpt()) { return; } System.out.println("Unknown key operation: " + "key=" + key + ", keyCode=" + keyCode); } private boolean consumeMoveOpt() { Trajectory[] trajList; boolean consumed = true; switch (key) { case '1': // change to FULL if (trajShowNow != trajFull) { mode = 1; trajShowNow = trajFull; colored = false; updateTrajImages(); } break; case '2': // change to VFGS / VFGS+ trajList = trajVfgsMatrix[dPtr][rPtr]; if (trajShowNow != trajList || colored) { mode = 2; trajShowNow = trajList; colored = false; updateTrajImages(); } break; case '3': // change to VFGS / VFGS+ CE trajList = trajVfgsMatrix[dPtr][rPtr]; if (trajShowNow != trajList || !colored) { mode = 3; trajShowNow = trajList; colored = true; updateTrajImages(); } break; case '4': // change to RAND trajList = trajRandList[rPtr]; if (trajShowNow != trajList) { mode = 4; trajShowNow = trajList; colored = false; updateTrajImages(); } break; case 'd': // increase dPtr if (mode != 2 && mode != 3) { break; // not vfgs } if (dPtr != deltaList.length - 1) { dPtr++; trajShowNow = trajVfgsMatrix[dPtr][rPtr]; updateTrajImages(); } break; case 'a': // decrease dPtr if (mode != 2 && mode != 3) { break; // not vfgs } if (dPtr != 0) { dPtr--; trajShowNow = trajVfgsMatrix[dPtr][rPtr]; updateTrajImages(); } break; case 's': // increase rPtr if (rPtr != rateList.length - 1) { rPtr++; if (mode == 4) { // is rand now trajShowNow = trajRandList[rPtr]; } else { trajShowNow = trajVfgsMatrix[dPtr][rPtr]; } updateTrajImages(); } break; case 'w': // decrease rPtr if (rPtr != 0) { rPtr--; if (mode == 4) { // is rand now trajShowNow = trajRandList[rPtr]; } else { trajShowNow = trajVfgsMatrix[dPtr][rPtr]; } updateTrajImages(); } break; default: consumed = false; } return consumed; } private boolean consumeChangeDataSetOpt() { boolean consumed = true; switch (key) { case 'p': // save pic saveCurFrame(); break; case 'o': Location loc = map.getCenter(); System.out.println(loc.x + " " + loc.y); break; case ',': // next center if (pid != 0) { pid--; map.panTo(presetCenter[pid]); updateTrajImages(); } break; case '.': // last center if (pid != presetCenter.length - 1) { pid++; map.panTo(presetCenter[pid]); updateTrajImages(); } break; case '/': // reset to cur center map.panTo(presetCenter[pid]); updateTrajImages(); break; case '-': // zoom out if (map.getZoomLevel() > 11) { map.zoomToLevel(map.getZoomLevel() - 1); updateTrajImages(); } break; case '=': // zoom in if (map.getZoomLevel() < 20) { map.zoomToLevel(map.getZoomLevel() + 1); updateTrajImages(); } break; default: consumed = false; } return consumed; } public void saveCurFrame() { String path = PATH_PREFIX + SET_NAMES[mode].toLowerCase(); path += (mode == 1) ? "" : "_delta" + deltaList[dPtr]; path += (mode == 1 || mode == 4) ? "" : "_rate" + (rateList[rPtr]); path += "_zoom" + map.getZoomLevel() + "_pid" + pid + ".png"; saveFrame(path); System.out.println(path); } public static void main(String[] args) { PApplet.main(VFGSMapApp.class.getName()); } }<file_sep>/src/main/java/app/CircleRegionControl.java package app; import model.CircleRegionGroup; import model.CircleRegion; import model.RegionType; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; /** * The only interface to control the circle region. **/ public class CircleRegionControl { private static final CircleRegionControl circleRegionControl = new CircleRegionControl(); private CircleRegionControl() { } public static CircleRegionControl getCircleRegionControl() { return circleRegionControl; } public CircleRegion getCircleO() { return circleO; } public CircleRegion getCircleD() { return circleD; } public ArrayList<CircleRegionGroup> getCircleRegionGroups() { return circleRegionGroups; } public CircleRegion[] getCircleOList() { return circleOList; } public CircleRegion[] getCircleDList() { return circleDList; } public ArrayList<CircleRegionGroup>[] getCircleWayPointList() { return circleWayPointList; } public int getWayPointLayer() { return wayPointLayer; } public int getWayPointGroup() { return wayPointGroup; } // circle modified by the front-end, and only object to update the region list. private CircleRegion circleO = null; private CircleRegion circleD = null; private ArrayList<CircleRegionGroup> circleRegionGroups = new ArrayList<>(); // draw by the front-end, and back-end alg based. private CircleRegion[] circleOList = new CircleRegion[4]; private CircleRegion[] circleDList = new CircleRegion[4]; private ArrayList<CircleRegionGroup>[] circleWayPointList = new ArrayList[4]; private int wayPointLayer = 0; private int wayPointGroup = 0; public void setCircleO(CircleRegion circleO) { this.circleO = circleO; updateCircleOList(); } public void setCircleD(CircleRegion circleD) { this.circleD = circleD; updateCircleDList(); } public void addWayPoint(CircleRegion circle) { if (wayPointGroup == 0) { addNewGroup(); } circleRegionGroups.get(wayPointGroup - 1).addWayPoint(circle); updateCircleWayPointList(circle); } public void addNewGroup() { circleRegionGroups.add(new CircleRegionGroup(wayPointGroup++)); } private void updateCircleOList() { for (int i = 0; i < 4; i++) { circleOList[i] = circleO.getCrsRegionCircle(i); } } private void updateCircleDList() { for (int i = 0; i < 4; i++) { circleDList[i] = circleD.getCrsRegionCircle(i); } } private void updateCircleWayPointList(CircleRegion circle) { for (int i = 0; i < 4; i++) { if (circleWayPointList[i] == null) { circleWayPointList[i] = new ArrayList<>(); } if (circleWayPointList[i].size() == wayPointGroup - 1) { circleWayPointList[i].add(new CircleRegionGroup(wayPointGroup - 1)); } circleWayPointList[i].get(wayPointGroup - 1).addWayPoint(circle.getCrsRegionCircle(i)); } } public RegionType getRegionType() { if (circleRegionGroups.size() > 0) { if (circleO == null && circleD == null) { return RegionType.WAY_POINT; } else { return RegionType.O_D_W; } } else { return RegionType.O_D; } } public void updateMovedRegion(CircleRegion circle) { for (CircleRegion circleRegion : getAllCircleRegions()) { if (circle.getId() == circleRegion.getId()) { circleRegion.setCircleCenter(circle.getCircleCenter()); circleRegion.setRadiusLocation(circle.getRadiusLocation()); } } circleO = circleOList[0]; circleD = circleDList[0]; circleRegionGroups = circleWayPointList[0] == null ? new ArrayList<>() : circleWayPointList[0]; } public ArrayList<CircleRegion> getAllCircleRegions() { ArrayList<CircleRegion> allCircles = new ArrayList<>(); if (circleO != null) { allCircles.addAll(Arrays.asList(circleOList)); } if (circleD != null) { allCircles.addAll(Arrays.asList(circleDList)); } if (circleRegionGroups != null && circleRegionGroups.size() > 0) { for (ArrayList<CircleRegionGroup> circleRegionGroups : circleWayPointList) { for (CircleRegionGroup circleRegionGroup : circleRegionGroups) { allCircles.addAll(circleRegionGroup.getAllRegions()); } } } return allCircles; } public ArrayList<CircleRegion> getAllRegionsInOneMap() { ArrayList<CircleRegion> allCircles = new ArrayList<>(); if (circleO != null) { allCircles.add(circleO); } if (circleD != null) { allCircles.add(circleD); } if (circleRegionGroups != null && circleRegionGroups.size() > 0) { for (CircleRegionGroup circleRegionGroup : circleRegionGroups) { allCircles.addAll(circleRegionGroup.getAllRegions()); } } return allCircles; } public void updateLayer() { circleRegionGroups.get(wayPointGroup - 1).updateWayPointLayer(); } public int getWayLayer() { return circleRegionGroups.size() == 0 ? 0 : circleRegionGroups.get(wayPointGroup - 1).getWayPointLayer(); } public int getWayGroupId() { return circleRegionGroups.size() == 0 ? 0 : circleRegionGroups.get(wayPointGroup - 1).getGroupId(); } public void cleanCircleRegions() { circleO = null; circleD = null; circleRegionGroups.clear(); circleRegionGroups = new ArrayList<>(); circleOList = new CircleRegion[4]; circleDList = new CircleRegion[4]; circleWayPointList = new ArrayList[4]; wayPointGroup = 0; wayPointLayer = 0; } } <file_sep>/src/main/java/index/QuadTree.java package index; import app.TimeProfileSharedObject; import de.fhpotsdam.unfolding.geo.Location; import model.*; import org.apache.commons.io.FileUtils; import org.apache.commons.io.LineIterator; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class QuadTree { private static double minGLat = Float.MAX_VALUE; private static double maxGLat = -Float.MAX_VALUE; private static double minGLon = Float.MAX_VALUE; private static double maxGLon = -Float.MAX_VALUE; public static QuadRegion quadRegionRoot; public static TrajectoryMeta[] trajMetaFull; public QuadTree() { } private static double preSion = 10000.0; public static TrajectoryMeta[] loadData(double[] latLon, String filePath) { TrajectoryMeta[] trajFull; ArrayList<String> trajFullStr = new ArrayList<>(); try { BufferedReader reader = new BufferedReader(new FileReader(filePath)); String line; while ((line = reader.readLine()) != null) { trajFullStr.add(line); } reader.close(); System.out.println("Read done"); } catch (IOException e) { e.printStackTrace(); } // trajFull = new TrajectoryMeta[trajFullStr.size()]; ArrayList<TrajectoryMeta> res = new ArrayList<>(); int i = 0; for (String line : trajFullStr) { String[] metaData = line.split(";"); double score = Double.parseDouble(metaData[0]); String[] item = metaData[1].split(","); if (item.length % 2 == 1) { continue; } boolean next = false; Position[] positions = new Position[item.length / 2]; for (int j = 0; j < item.length - 1; j += 2) { // int srcX = Integer.parseInt(item[j]); // int srcY = Integer.parseInt(item[j + 1]); float lat = Float.parseFloat(item[j + 1]); float lon = Float.parseFloat(item[j]); //debug // if (lat > 42.184 || lat < 39.628 || lon < -9.095 || lon > -6.568) { // if (lat > 41.346 || lat < 40.948 || lon < -8.806 || lon > -8.229) { // debug // if (lat < 38.429 || lon > -6.595) { // j = item.length; // next = true; // continue; // } //debug done // if (i > 10){ // j = item.length; // next = true; // continue; // } try { positions[j / 2] = new Position((int) (lat * preSion), (int) (lon * preSion)); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(line); break; } minGLat = Math.min(lat, minGLat); maxGLat = Math.max(lat, maxGLat); minGLon = Math.min(lon, minGLon); maxGLon = Math.max(lon, maxGLon); } // if (next) { continue; } TrajectoryMeta traj = new TrajectoryMeta(i); traj.setScore(score); traj.setPositions(positions); traj.setBegin(0); traj.setEnd(positions.length - 1); // trajFull[i] = traj; i++; res.add(traj); } trajFull = res.toArray(new TrajectoryMeta[0]); System.out.println("Transfer done " + trajFull.length); System.out.println(minGLat + ", " + maxGLat + ", " + minGLon + ", " + maxGLon); latLon[0] = minGLat; latLon[1] = maxGLat; latLon[2] = minGLon; latLon[3] = maxGLon; trajFullStr.clear(); return trajFull; } private static QuadRegion createFromTrajList(double minLat, double maxLat, double minLon, double maxLon, int H, TrajectoryMeta[] trajFull) { RectRegion rectRegion = new RectRegion(); rectRegion.initLoc(new Location(minLat, minLon), new Location(maxLat, maxLon)); TimeProfileSharedObject.getInstance().addQuadRectRegion(rectRegion); QuadRegion quadRegion = new QuadRegion(minLat, maxLat, minLon, maxLon); TrajToQuality[] trajToQualities = VfgsForIndex.getVfgs(trajFull); quadRegion.setTrajQuality(trajToQualities); if (H > 1) { QuadRegion[] quadChildren = new QuadRegion[4]; double latOff = (maxLat - minLat) / 2; double lonOff = (maxLon - minLon) / 2; for (int i = 0; i < 4; i++) { int laxId = i / 2; int lonId = i % 2; double tmpLatMin = minLat + latOff * laxId; double tmpLonMin = minLon + lonOff * lonId; TrajectoryMeta[] wayPoint = getWayPointPos(trajFull, tmpLatMin, tmpLatMin + latOff, tmpLonMin, tmpLonMin + lonOff); quadChildren[i] = createFromTrajList(tmpLatMin, tmpLatMin + latOff, tmpLonMin, tmpLonMin + lonOff, H - 1, wayPoint); } quadRegion.setQuadRegionChildren(quadChildren); } return quadRegion; } /** * Generate the quad tree by {@link VfgsForIndexPart} */ private static QuadRegion createPartlyFromTrajList(double minLat, double maxLat, double minLon, double maxLon, int H, TrajectoryMeta[] trajMetaList, int delta) { RectRegion rectRegion = new RectRegion(); rectRegion.initLoc(new Location(minLat, minLon), new Location(maxLat, maxLon)); TimeProfileSharedObject.getInstance().addQuadRectRegion(rectRegion); QuadRegion quadRegion = new QuadRegion(minLat, maxLat, minLon, maxLon); TrajToSubpart[] trajToSubparts = VfgsForIndexPart.getVfgs(trajMetaList, delta); quadRegion.setTrajToSubparts(trajToSubparts); if (H > 1) { QuadRegion[] quadChildren = new QuadRegion[4]; double latOff = (maxLat - minLat) / 2; double lonOff = (maxLon - minLon) / 2; for (int i = 0; i < 4; i++) { int laxId = i / 2; int lonId = i % 2; double tmpLatMin = minLat + latOff * laxId; double tmpLonMin = minLon + lonOff * lonId; TrajectoryMeta[] wayPoint = getWayPointPos(trajMetaList, tmpLatMin, tmpLatMin + latOff, tmpLonMin, tmpLonMin + lonOff); quadChildren[i] = createPartlyFromTrajList(tmpLatMin, tmpLatMin + latOff, tmpLonMin, tmpLonMin + lonOff, H - 1, wayPoint, delta); } quadRegion.setQuadRegionChildren(quadChildren); } return quadRegion; } public static TrajectoryMeta[] getWayPointPos(TrajectoryMeta[] trajFull, double minLat, double maxLat, double minLon, double maxLon) { ArrayList<TrajectoryMeta> res = new ArrayList<>(); for (TrajectoryMeta traj : trajFull) { for (Position position : generatePosList(traj)) { if (inCheck(position, minLat, maxLat, minLon, maxLon)) { res.add(traj); break; } } } // return res.toArray(new TrajectoryMeta[0]); return cutTrajsPos(res.toArray(new TrajectoryMeta[0]), minLat, maxLat, minLon, maxLon); } private static boolean inCheck(Position position, double minLat, double maxLat, double minLon, double maxLon) { return position.x / preSion >= minLat && position.x / preSion <= maxLat && position.y / preSion >= minLon && position.y / preSion <= maxLon; } /** * Run {@link #getRegionInTrajPos} (which cut the traj into subpart) on all trajs. */ private static TrajectoryMeta[] cutTrajsPos(TrajectoryMeta[] trajectories, double minLat, double maxLat, double minLon, double maxLon) { ArrayList<TrajectoryMeta> res = new ArrayList<>(); for (TrajectoryMeta traj : trajectories) { res.addAll(getRegionInTrajPos(traj, minLat, maxLat, minLon, maxLon)); } return res.toArray(new TrajectoryMeta[0]); } /** * Divide traj into trajMeta according to the giving region. */ private static ArrayList<TrajectoryMeta> getRegionInTrajPos(TrajectoryMeta traj, double minLat, double maxLat, double minLon, double maxLon) { ArrayList<TrajectoryMeta> res = new ArrayList<>(); int trajId = traj.getTrajId(); List<Position> partPosList = generatePosList(traj); for (int i = 0; i < partPosList.size(); i++) { if (inCheck(partPosList.get(i), minLat, maxLat, minLon, maxLon)) { TrajectoryMeta trajTmp = new TrajectoryMeta(trajId); /* add */ int begin = i; // trajTmp.setBegin(i); trajTmp.setBegin(i + traj.getBegin()); /* add end */ Position position = partPosList.get(i++); while (inCheck(position, minLat, maxLat, minLon, maxLon) && i < partPosList.size()) { position = partPosList.get(i++); } /* add */ // if (i - 1 - begin != locTmp.size()) { // System.err.println("Error!"); // } trajTmp.setScore(i - 1 - begin); trajTmp.setEnd(i - 1 + traj.getBegin()); /* add end */ res.add(trajTmp); i = partPosList.size() + 1; } } return res; } public static QuadRegion getQuadIndex(String filePath, int height) { TrajectoryMeta[] trajectories = loadData(new double[4], filePath); return createFromTrajList(minGLat, maxGLat, minGLon, maxGLon, height, trajectories); } public static QuadRegion getQuadIndex(double minLat, double maxLat, double minLon, double maxLon, TrajectoryMeta[] trajectories, int height) { return createFromTrajList(minLat, maxLat, minLon, maxLon, height, trajectories); } public static QuadRegion getQuadIndexPart(String filePath, int height, int delta) { TrajectoryMeta[] trajectories = loadData(new double[4], filePath); return createPartlyFromTrajList(minGLat, maxGLat, minGLon, maxGLon, height, trajectories, delta); } public static QuadRegion getQuadIndexPart(double minLat, double maxLat, double minLon, double maxLon, TrajectoryMeta[] trajectories, int height, int delta) { return createPartlyFromTrajList(minLat, maxLat, minLon, maxLon, height, trajectories, delta); } private static List<Position> generatePosList(TrajectoryMeta trajMeta) { int trajId = trajMeta.getTrajId(); int begin = trajMeta.getBegin(); int end = trajMeta.getEnd(); // notice that the end is included return Arrays.asList(trajMetaFull[trajId].getPositions()).subList(begin, end + 1); } public static void saveTreeToFile(String filePath) { System.out.print("Write position info to " + filePath + " ..."); try { BufferedWriter writer = new BufferedWriter(new FileWriter(filePath)); QuadRegion[] parents = new QuadRegion[]{quadRegionRoot}; saveLevelRecurse(writer, parents); writer.close(); System.out.println("\b\b\bfinished."); } catch (IOException e) { System.out.println("\b\b\bfailed."); e.printStackTrace(); } } /** * Save all nodes in same level (they are the children of {@code parents}). * Suppose that the {@code parents} will never be invalid. */ private static void saveLevelRecurse(BufferedWriter writer, QuadRegion[] parents) throws IOException { boolean hasChildren = (parents[0].getQuadRegionChildren() != null); if (!hasChildren) { for (QuadRegion parent : parents) { // save parent List<String> strList = QuadRegion.serialize(parent); saveOneStrList(writer, strList); } return; } // has next level int cldIdx = 0; // index for children QuadRegion[] children = new QuadRegion[parents.length * 4]; for (QuadRegion parent : parents) { // save parent List<String> strList = QuadRegion.serialize(parent); saveOneStrList(writer, strList); // generate children System.arraycopy(parent.getQuadRegionChildren(), 0, children, cldIdx, 4); cldIdx += 4; } saveLevelRecurse(writer, children); } /** * Save full string data for one {@link QuadRegion}. */ private static void saveOneStrList(BufferedWriter writer, List<String> strList) throws IOException { for (String s : strList) { writer.write(s); writer.newLine(); } } /** * Load quad tree from file and save root to static field */ public static void loadTreeFromFile(String filePath) { LineIterator it = null; System.out.print("Read quad tree data from " + filePath + " ..."); try { it = FileUtils.lineIterator(new File(filePath), "UTF-8"); quadRegionRoot = loadLevelRecurse(it, null); System.out.println("\b\b\bfinished."); } catch (Exception e) { System.out.println("\b\b\bfailed."); e.printStackTrace(); } finally { if (it != null) { LineIterator.closeQuietly(it); } } } /** * Create tree by breath first iterate. Each recurse is one level. */ private static QuadRegion loadLevelRecurse(LineIterator lit, QuadRegion[] parents) { if (parents == null) { // is root List<String> strList = loadOneStrList(lit); QuadRegion root = QuadRegion.antiSerialize(strList); root.setLocation(minGLat, maxGLat, minGLon, maxGLon); RectRegion rectRegion = new RectRegion(); rectRegion.initLoc(new Location(minGLat, minGLon), new Location(maxGLat, maxGLon)); TimeProfileSharedObject.getInstance().addQuadRectRegion(rectRegion); if (lit.hasNext()) { // has next level QuadRegion[] nxtParents = new QuadRegion[]{root}; loadLevelRecurse(lit, nxtParents); } return root; } // not root, load whole level // lit.hasNext() must be true int prtCnt = 0; // idx for nxtParents QuadRegion[] nxtParents = new QuadRegion[parents.length * 4]; for (QuadRegion parent : parents) { double latOff = (parent.getMaxLat() - parent.getMinLat()) / 2; double lonOff = (parent.getMaxLon() - parent.getMinLon()) / 2; QuadRegion[] children = new QuadRegion[4]; for (int idx = 0; idx < 4; idx++) { int laxId = idx / 2; int lonId = idx % 2; double tmpLatMin = parent.getMinLat() + latOff * laxId; double tmpLonMin = parent.getMinLon() + lonOff * lonId; List<String> strList = loadOneStrList(lit); QuadRegion child = QuadRegion.antiSerialize(strList); child.setLocation(tmpLatMin, tmpLatMin + latOff, tmpLonMin, tmpLonMin + lonOff); RectRegion rectRegion = new RectRegion(); rectRegion.initLoc(new Location(tmpLatMin, tmpLonMin), new Location(tmpLatMin + latOff, tmpLonMin + lonOff)); TimeProfileSharedObject.getInstance().addQuadRectRegion(rectRegion); children[idx] = child; nxtParents[prtCnt++] = child; } parent.setQuadRegionChildren(children); } if (lit.hasNext()) { // has next level loadLevelRecurse(lit, nxtParents); } return null; // not root, no need to return anything } /** * Read full string data for one {@link QuadRegion}, but not to anti-serialize it */ private static List<String> loadOneStrList(LineIterator lit) { String str = lit.nextLine(); int lineNum = Integer.parseInt(str); List<String> ret = new ArrayList<>(lineNum); ret.add(str); // also add first line to result for (int i = 0; i < lineNum; i++) { ret.add(lit.nextLine()); } return ret; } //lat41 lon8 public static void main(String[] args) { String cdPath = "E:\\zcz\\dbgroup\\DTW\\data\\sz_cd\\cd_new_score.txt"; String szPath = "E:\\zcz\\dbgroup\\DTW\\data\\sz_cd\\sz_score.txt"; String partPortoPath = "data/GPS/Porto5w/Porto5w.txt"; String filePath = cdPath; String storeFilePath = "data/GPS/porto5w/sz_quad_tree_info.txt"; int height = 1; int delta = 0; if (args.length > 0) { filePath = args[0]; storeFilePath = args[1]; height = Integer.parseInt(args[2]); delta = Integer.parseInt(args[3]); preSion = Double.parseDouble(args[4]); } TrajectoryMeta[] trajectories = loadData(new double[4], filePath); TimeProfileSharedObject.getInstance().trajMetaFull = trajectories; trajMetaFull = trajectories; long t0 = System.currentTimeMillis(); System.out.println("begin index"); QuadTree.quadRegionRoot = createPartlyFromTrajList(minGLat, maxGLat, minGLon, maxGLon, height, trajectories, delta); System.out.println("index time: " + (System.currentTimeMillis() - t0)); // QuadTree.saveTreeToFile(storeFilePath); System.out.println("save done"); } } <file_sep>/src/main/java/index/IndexStructWorker.java package index; import model.QuadRegion; import model.TrajectoryMeta; public class IndexStructWorker extends Thread { private double minLat; private double maxLat; private double minLon; private double maxLon; private TrajectoryMeta[] trajFull; private int H; private IndexStructManager manager; private int id; public IndexStructWorker(double minLat, double maxLat, double minLon, double maxLon, TrajectoryMeta[] trajectoryMeta, int H, IndexStructManager manager, int id) { this.minLat = minLat; this.maxLat = maxLat; this.minLon = minLon; this.maxLon = maxLon; this.manager = manager; this.trajFull = trajectoryMeta; this.H = H; this.id = id; } @Override public void run() { QuadRegion quadRegion = QuadTree.getQuadIndex(minLat, maxLat, minLon, maxLon, trajFull, H); manager.setQuadRegion(quadRegion, id); } } <file_sep>/src/main/java/index/SearchRegion.java package index; import model.QuadRegion; import model.TrajToQuality; import model.TrajectoryMeta; import processing.core.PApplet; import java.util.ArrayList; import java.util.Stack; public class SearchRegion extends PApplet { public static TrajectoryMeta[] searchRegion(double minLat, double maxLat, double minLon, double maxLon, QuadRegion quadRegion, double quality) { ArrayList<TrajectoryMeta> trajectories = new ArrayList<>(); Stack<QuadRegion> regionStack = new Stack<QuadRegion>(); regionStack.push(quadRegion); while (!regionStack.isEmpty()) { QuadRegion quadRegionHead = regionStack.pop(); if (isContained(minLat, maxLat, minLon, maxLon, quadRegionHead)) {//全包含 if (quadRegionHead.getQuadRegionChildren() == null) { for (TrajToQuality trajToQuality : quadRegionHead.getTrajQuality()) { if (trajToQuality.getQuality() < quality) trajectories.add(trajToQuality.getTrajectory()); else break; } } else { for (QuadRegion quadRegionTmp : quadRegionHead.getQuadRegionChildren()) { regionStack.push(quadRegionTmp); } } } else { //full contain if (isFullContain(minLat, maxLat, minLon, maxLon, quadRegionHead)) { for (TrajToQuality trajToQuality : quadRegionHead.getTrajQuality()) { trajectories.add(trajToQuality.getTrajectory()); } } else if (isInteractive(minLat, maxLat, minLon, maxLon, quadRegionHead)) { //interact if (quadRegionHead.getQuadRegionChildren() == null) { for (TrajToQuality trajToQuality : quadRegionHead.getTrajQuality()) { trajectories.add(trajToQuality.getTrajectory()); } } else { for (QuadRegion quadRegionTmp : quadRegionHead.getQuadRegionChildren()) { regionStack.push(quadRegionTmp); } } } } } return trajectories.toArray(new TrajectoryMeta[0]); } private static boolean isContained(double minLat, double maxLat, double minLon, double maxLon, QuadRegion quadRegion) {//quadregion is large return minLat > quadRegion.getMinLat() && maxLat < quadRegion.getMaxLat() && minLon > quadRegion.getMinLon() && maxLon < quadRegion.getMaxLon(); } private static boolean isFullContain(double minLat, double maxLat, double minLon, double maxLon, QuadRegion quadRegion) {//quadregion is small return minLat <= quadRegion.getMinLat() && maxLat >= quadRegion.getMaxLat() && minLon <= quadRegion.getMinLon() && maxLon >= quadRegion.getMaxLon(); } private static boolean isInteractive(double minLat, double maxLat, double minLon, double maxLon, QuadRegion quadRegion) { double minx = Math.max(minLat, quadRegion.getMinLat()); double miny = Math.max(minLon, quadRegion.getMinLon()); double maxx = Math.min(maxLat, quadRegion.getMaxLat()); double maxy = Math.min(maxLon, quadRegion.getMaxLon()); return !(minx > maxx || miny > maxy); } public static void main(String[] args) { String partFilePath = "data/GPS/Porto5w/Porto5w.txt"; String fullFilePath = "data/GPS/porto_full.txt"; long t0 = System.currentTimeMillis(); QuadRegion quadRegionRoot = QuadTree.getQuadIndex(fullFilePath, 3); System.out.println("index time: " + (System.currentTimeMillis() - t0)); double minLat = 41.137554, maxLat = 41.198544, minLon = -8.596918, maxLon = -8.677942; TrajectoryMeta[] trajectories = searchRegion(minLat, maxLat, minLon, maxLon, quadRegionRoot, 1); PApplet.main(new String[]{SearchRegion.class.getName()}); } } <file_sep>/src/main/java/vqgs/draw/TrajDrawHandler2.java package vqgs.draw; import vqgs.app.ThreadMapApp; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.geo.Location; import de.fhpotsdam.unfolding.utils.ScreenPosition; import vqgs.model.Trajectory; import processing.core.PGraphics; import java.awt.*; import java.util.Vector; /** * Handler class for traj painting. * <p> * This class draw a part of trajectories to flash. * Now the thread interrupt mechanism works <s>but has bug</s>. * This bug has been fixed. Now drag or zoom fast won't lead * to the slow interaction. * <p> * It will be called when the map has be changed (zoom or drag). * <p> * Notice that the index points out which traj image * part will be calculate by this thread. * * @see ThreadMapApp#updateTrajImages() */ public class TrajDrawHandler2 extends Thread { private final UnfoldingMap map; private final PGraphics pg; // temp image that this thread paint on private final PGraphics[] trajImages; // all traj image parts private final Trajectory[] trajList; // all traj private final Vector<Long> newestId; // the newest id of outer frame private final boolean colored; // traj color shader for VFGS+ CE private final int dIdx, rIdx; // the param for select color private final int[] trajCnt; // record the # of painted traj private final int index, threadNum; // the param for select traj private final long selfId; // mark to check whether it is newest public TrajDrawHandler2(UnfoldingMap map, PGraphics pg, PGraphics[] trajImages, Trajectory[] trajList, Vector<Long> newestId, boolean colored, int dIdx, int rIdx, int[] trajCnt, int index, int threadNum, long selfId) { this.map = map; this.pg = pg; this.trajImages = trajImages; this.trajList = trajList; this.newestId = newestId; this.colored = colored; this.dIdx = dIdx; this.rIdx = rIdx; this.trajCnt = trajCnt; this.index = index; this.threadNum = threadNum; this.selfId = selfId; // init priority this.setPriority(index % 9 + 1); } @Override public void run() { pg.beginDraw(); pg.noFill(); pg.strokeWeight(1); int segLen = trajList.length / threadNum; int begin = segLen * index; int end = Math.min(begin + segLen, trajList.length); // exclude for (int i = begin; i < end; i++) { pg.beginShape(); // set color if (!colored) { pg.stroke(255, 0, 0); } else { Color c = trajList[i].getColorMatrix()[dIdx][rIdx]; pg.stroke(c.getRGB()); } // draw the traj for (Location loc : trajList[i].getLocations()) { // stop the thread if it is interrupted if (Thread.currentThread().isInterrupted() || newestId.get(0) != selfId) { pg.endShape(); pg.endDraw(); return; } ScreenPosition pos = map.getScreenPosition(loc); pg.vertex(pos.x, pos.y); } pg.endShape(); trajCnt[index] ++; } if (newestId.get(0) == selfId) { trajImages[index] = pg; } } } <file_sep>/src/main/java/model/QuadRegion.java package model; import java.util.ArrayList; import java.util.List; public class QuadRegion { double minLat; double maxLat; double minLon; double maxLon; QuadRegion[] quadRegionChildren; TrajToQuality[] trajQuality; /* add */ TrajToSubpart[] trajToSubparts; /* add end */ public QuadRegion() { } public QuadRegion(QuadRegion[] quadRegionChildren, TrajToQuality[] trajQuality) { this.quadRegionChildren = quadRegionChildren; this.trajQuality = trajQuality; } public QuadRegion(double minLat, double maxLat, double minLon, double maxLon) { this.minLat = minLat; this.maxLat = maxLat; this.minLon = minLon; this.maxLon = maxLon; } public void setLocation(double minLat, double maxLat, double minLon, double maxLon) { this.minLat = minLat; this.maxLat = maxLat; this.minLon = minLon; this.maxLon = maxLon; } public double getMinLat() { return minLat; } public void setMinLat(double minLat) { this.minLat = minLat; } public double getMaxLat() { return maxLat; } public void setMaxLat(double maxLat) { this.maxLat = maxLat; } public double getMinLon() { return minLon; } public void setMinLon(double minLon) { this.minLon = minLon; } public double getMaxLon() { return maxLon; } public void setMaxLon(double maxLon) { this.maxLon = maxLon; } public QuadRegion[] getQuadRegionChildren() { return quadRegionChildren; } public void setQuadRegionChildren(QuadRegion[] quadRegionChildren) { this.quadRegionChildren = quadRegionChildren; } public TrajToQuality[] getTrajQuality() { return trajQuality; } public void setTrajQuality(TrajToQuality[] trajQuality) { this.trajQuality = trajQuality; } public TrajToSubpart[] getTrajToSubparts() { return trajToSubparts; } public void setTrajToSubparts(TrajToSubpart[] trajToSubparts) { this.trajToSubparts = trajToSubparts; } public static List<String> serialize(QuadRegion qr) { TrajToSubpart[] trajToSubpartList = qr.trajToSubparts; List<String> ret = new ArrayList<>(trajToSubpartList.length + 1); ret.add(String.valueOf(trajToSubpartList.length)); for (TrajToSubpart tts : trajToSubpartList) { ret.add(TrajToSubpart.serialize(tts)); } return ret; } public static QuadRegion antiSerialize(List<String> strList) { QuadRegion ret = new QuadRegion(); TrajToSubpart[] trajToSubparts = new TrajToSubpart[Integer.parseInt(strList.get(0))]; for (int i = 0; i < trajToSubparts.length; i++) { String ttsStr = strList.get(i + 1); trajToSubparts[i] = TrajToSubpart.antiSerialize(ttsStr); trajToSubparts[i].quality = Double.parseDouble(ttsStr.split(",")[3]); } ret.setTrajToSubparts(trajToSubparts); return ret; } } <file_sep>/src/main/java/index/SearchRegionPart.java package index; import app.TimeProfileSharedObject; import de.fhpotsdam.unfolding.geo.Location; import model.*; import processing.core.PApplet; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Stack; public class SearchRegionPart extends PApplet { private static TrajectoryMeta[] trajMetaFull; public static TrajectoryMeta[] searchRegion(double minLat, double maxLat, double minLon, double maxLon, QuadRegion quadRegion, double quality) { ArrayList<TrajectoryMeta> trajectories = new ArrayList<>(); Stack<QuadRegion> regionStack = new Stack<QuadRegion>(); regionStack.push(quadRegion); trajMetaFull = TimeProfileSharedObject.getInstance().trajMetaFull; while (!regionStack.isEmpty()) { QuadRegion quadRegionHead = regionStack.pop(); if (isContained(minLat, maxLat, minLon, maxLon, quadRegionHead)) {//全包含 if (quadRegionHead.getQuadRegionChildren() == null) { // is leaf. addAllSubMetaTraj(trajectories, quadRegionHead, quality); RectRegion rec = new RectRegion(); rec.initLoc(new Location(quadRegionHead.getMinLat(), quadRegionHead.getMinLon()), new Location(quadRegionHead.getMaxLat(), quadRegionHead.getMaxLon())); TimeProfileSharedObject.getInstance().searchRegions.add(rec); } else { for (QuadRegion quadRegionTmp : quadRegionHead.getQuadRegionChildren()) { regionStack.push(quadRegionTmp); } } } else { //full contain if (isFullContain(minLat, maxLat, minLon, maxLon, quadRegionHead)) { addAllSubMetaTraj(trajectories, quadRegionHead, quality); RectRegion rec = new RectRegion(); rec.initLoc(new Location(quadRegionHead.getMinLat(), quadRegionHead.getMinLon()), new Location(quadRegionHead.getMaxLat(), quadRegionHead.getMaxLon())); TimeProfileSharedObject.getInstance().searchRegions.add(rec); } else if (isInteractive(minLat, maxLat, minLon, maxLon, quadRegionHead)) { //interact if (quadRegionHead.getQuadRegionChildren() == null) { addAllSubMetaTraj(trajectories, quadRegionHead, quality); RectRegion rec = new RectRegion(); rec.initLoc(new Location(quadRegionHead.getMinLat(), quadRegionHead.getMinLon()), new Location(quadRegionHead.getMaxLat(), quadRegionHead.getMaxLon())); TimeProfileSharedObject.getInstance().searchRegions.add(rec); } else { for (QuadRegion quadRegionTmp : quadRegionHead.getQuadRegionChildren()) { regionStack.push(quadRegionTmp); } } } } } return trajectories.toArray(new TrajectoryMeta[0]); } private static void addAllSubMetaTraj(List<TrajectoryMeta> trajectories, QuadRegion quadRegionHead, double quality) { for (TrajToSubpart trajToSubpart : quadRegionHead.getTrajToSubparts()) { if (trajToSubpart.quality >= quality) { break; } // now just create the part of it and not consider this traj in other cells. TrajectoryMeta trajTmp = new TrajectoryMeta(trajToSubpart.getTrajId()); trajTmp.setBegin(trajToSubpart.getBeginPosIdx()); trajTmp.setEnd(trajToSubpart.getEndPosIdx()); trajTmp.setPositions(generatePosList(trajToSubpart).toArray(new Position[0])); trajectories.add(trajTmp); // trajectories.add(trajMetaFull[trajToSubpart.getTrajId()]); } } private static boolean isContained(double minLat, double maxLat, double minLon, double maxLon, QuadRegion quadRegion) {//quadregion is large return minLat >= quadRegion.getMinLat() && maxLat <= quadRegion.getMaxLat() && minLon >= quadRegion.getMinLon() && maxLon <= quadRegion.getMaxLon(); } private static boolean isFullContain(double minLat, double maxLat, double minLon, double maxLon, QuadRegion quadRegion) {//quadregion is small return minLat <= quadRegion.getMinLat() && maxLat >= quadRegion.getMaxLat() && minLon <= quadRegion.getMinLon() && maxLon >= quadRegion.getMaxLon(); } private static boolean isInteractive(double minLat, double maxLat, double minLon, double maxLon, QuadRegion quadRegion) { double minx = Math.max(minLat, quadRegion.getMinLat()); double miny = Math.max(minLon, quadRegion.getMinLon()); double maxx = Math.min(maxLat, quadRegion.getMaxLat()); double maxy = Math.min(maxLon, quadRegion.getMaxLon()); return !(minx > maxx || miny > maxy); } private static List<Position> generatePosList(TrajToSubpart trajToSubpart) { int trajId = trajToSubpart.getTrajId(); int begin = trajToSubpart.getBeginPosIdx(); int end = trajToSubpart.getEndPosIdx(); // notice that the end is included return Arrays.asList(trajMetaFull[trajId].getPositions()).subList(begin, end + 1); } public static void main(String[] args) { String partFilePath = "data/GPS/Porto5w/Porto5w.txt"; String fullFilePath = "data/GPS/porto_full.txt"; long t0 = System.currentTimeMillis(); QuadRegion quadRegionRoot = QuadTree.getQuadIndex(fullFilePath, 3); System.out.println("index time: " + (System.currentTimeMillis() - t0)); double minLat = 41.137554, maxLat = 41.198544, minLon = -8.596918, maxLon = -8.677942; TrajectoryMeta[] trajectories = searchRegion(minLat, maxLat, minLon, maxLon, quadRegionRoot, 1); PApplet.main(new String[]{SearchRegionPart.class.getName()}); } } <file_sep>/src/main/java/app/RenderTimeCalculate.java package app; import com.jogamp.opengl.GL3; import com.jogamp.opengl.util.GLBuffers; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.geo.Location; import de.fhpotsdam.unfolding.providers.MapBox; import de.fhpotsdam.unfolding.utils.MapUtils; import de.fhpotsdam.unfolding.utils.ScreenPosition; import index.QuadTree; import model.Position; import model.TrajToSubpart; import model.Trajectory; import model.TrajectoryMeta; import processing.core.PApplet; import processing.opengl.PJOGL; import util.PSC; import javax.transaction.TransactionRequiredException; import java.awt.*; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.IOException; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.ArrayList; import java.util.HashSet; import java.util.Random; public class RenderTimeCalculate extends PApplet { UnfoldingMap map; int wight = 1200, hight = 800; private String fullFile = "data/GPS/porto_full.txt"; Trajectory[] trajFull; private String filePath = fullFile; @Override public void settings() { size(wight, hight, P2D); } @Override public void setup() { map = new UnfoldingMap(this, new MapBox.CustomMapBoxProvider(PSC.WHITE_MAP_PATH)); map.setZoomRange(0, 20); map.setBackgroundColor(255); // map.zoomAndPanTo(11, new Location(22.717, 114.269)); map.zoomAndPanTo(11, new Location(30.658524, 104.065747)); MapUtils.createDefaultEventDispatcher(this, map); new Thread() { @Override public void run() { String porto = "data/GPS/porto_full.txt"; String cdPath = "E:\\zcz\\dbgroup\\DTW\\data\\sz_cd\\cd_new_score.txt"; loadData(cdPath); vqgs = loadVqgs("data/GPS/cd/cd_vfgs_0.txt"); System.out.println("load done"); isTotalLoad = true; gl3 = ((PJOGL) beginPGL()).gl.getGL3(); endPGL();//? } }.start(); } int num = 1000000; double[] rateList = {0.01, 0.005, 0.001, 0.0005, 0.0001}; int rateId = 0; @Override public void draw() { if (!map.allTilesLoaded()) { map.draw(); } else { if (isTotalLoad) { // Trajectory[] traj = getRandomTraj(num); System.out.println("rendering......"); // Trajectory[] traj = trajFull; Trajectory[] traj = loadVqgsTraj(vqgs, rateList[rateId]); long t0 = System.currentTimeMillis(); int pointNum = vertexInit(traj); long mappingTime = System.currentTimeMillis() - t0; long t1 = System.currentTimeMillis(); drawGPU(); long renderTime = System.currentTimeMillis() - t1; System.out.println("trajectory number: " + traj.length + ", " + "point number: " + pointNum + ", mapping time: " + mappingTime + ", rendering time: " + renderTime + ", total time: " + (mappingTime + renderTime)); rateId++; if (rateId == rateList.length) { exit(); } // num *= 10; // if (num > 2000000) { // System.out.println("Done"); // exit(); // } // noLoop(); } } } boolean isTotalLoad = false; private void loadData(String filePath) { try { ArrayList<String> trajStr = new ArrayList<>(2400000); BufferedReader reader = new BufferedReader(new FileReader(filePath)); String line; while ((line = reader.readLine()) != null) { trajStr.add(line); } reader.close(); System.out.println("load done"); int j = 0; trajFull = new Trajectory[trajStr.size()]; for (String trajM : trajStr) { String[] item = trajM.split(";"); String[] data = item[1].split(","); Trajectory traj = new Trajectory(j); ArrayList<Location> locations = new ArrayList<>(); // Position[] metaGPS = new Position[data.length / 2 - 1]; for (int i = 0; i < data.length - 2; i = i + 2) { locations.add(new Location(Float.parseFloat(data[i + 1]), Float.parseFloat(data[i]))); } traj.setLocations(locations.toArray(new Location[0])); traj.setScore(Integer.parseInt(item[0])); trajFull[j++] = traj; } trajStr.clear(); System.out.println("load done"); System.out.println("traj number: " + trajFull.length); } catch (IOException e) { e.printStackTrace(); } } private Trajectory[] getRandomTraj(int number) { Trajectory[] trajectories = new Trajectory[number]; Random random = new Random(0); HashSet<Integer> idSet = new HashSet<>(number); while (idSet.size() != number) { idSet.add(random.nextInt(trajFull.length - 1)); } int i = 0; for (Integer id : idSet) { trajectories[i++] = trajFull[id]; } return trajectories; } int[] vqgs; private int[] loadVqgs(String filePath) { int[] vqgs = null; ArrayList<String> tmpList = new ArrayList<>(); try { BufferedReader reader = new BufferedReader(new FileReader(filePath)); String line; while ((line = reader.readLine()) != null) { tmpList.add(line); } } catch (IOException e) { e.printStackTrace(); } vqgs = new int[tmpList.size()]; int i = 0; for (String str : tmpList) { vqgs[i++] = Integer.parseInt(str.split(",")[0]); } System.out.println(trajFull.length + ", " + vqgs.length); return vqgs; } private Trajectory[] loadVqgsTraj(int[] vqgsList, double rate) { int trajNum = (int) (trajFull.length * rate); Trajectory[] traj = new Trajectory[trajNum]; for (int i = 0; i < trajNum; i++) { traj[i] = trajFull[vqgsList[i]]; } return traj; } private double[] drawTraj(Trajectory[] trajFull) { int pointNum = 0; double[] time = new double[2]; noFill(); strokeWeight(1); stroke(new Color(255, 0, 0).getRGB()); ArrayList<ArrayList<SolutionXTimeProfile.Point>> pointTraj = new ArrayList<>(); long t0 = System.currentTimeMillis(); for (Trajectory trajectory : trajFull) { pointNum += trajectory.locations.length; ArrayList<SolutionXTimeProfile.Point> tmpPointList = new ArrayList<>(); for (Location loc : trajectory.locations) { ScreenPosition screenPos = map.getScreenPosition(loc); tmpPointList.add(new SolutionXTimeProfile.Point(screenPos.x, screenPos.y)); } pointTraj.add(tmpPointList); } time[0] = (System.currentTimeMillis() - t0); long t1 = System.currentTimeMillis(); for (ArrayList<SolutionXTimeProfile.Point> points : pointTraj) { beginShape(); for (SolutionXTimeProfile.Point point : points) { vertex(point.x, point.y); } endShape(); } time[1] = (System.currentTimeMillis() - t1); System.out.println("trajectory number: " + trajFull.length + ", " + "point number: " + pointNum + ", mapping time: " + time[0] + ", rendering time: " + time[1] + ", total time: " + (time[0] + time[1])); return time; } GL3 gl3; int[] vboHandles; int shaderProgram, vertShader, fragShader; int vertexBufferObject; IntBuffer vao = GLBuffers.newDirectIntBuffer(1); float[] vertexData = {}; private void shaderInit() { // initializeProgram shaderProgram = gl3.glCreateProgram(); fragShader = gl3.glCreateShader(GL3.GL_FRAGMENT_SHADER); gl3.glShaderSource(fragShader, 1, new String[]{ "#ifdef GL_ES\n" + "precision mediump float;\n" + "precision mediump int;\n" + "#endif\n" + "\n" + "varying vec4 vertColor;\n" + "\n" + "void main() {\n" + " gl_FragColor = vec4(1.0,0.0,0.0,1.0);\n" + "}" }, null); gl3.glCompileShader(fragShader); vertShader = gl3.glCreateShader(GL3.GL_VERTEX_SHADER); gl3.glShaderSource(vertShader, 1, new String[]{ "#version 330 \n" + "layout (location = 0) in vec4 position;" + "layout (location = 1) in vec4 color;" + "smooth out vec4 theColor;" + "void main(){" + "gl_Position.x = position.x / 500.0 - 1;" + "gl_Position.y = -1 * position.y / 400.0 + 1;" + "theColor = color;" + "}" }, null); gl3.glCompileShader(vertShader); // attach and link gl3.glAttachShader(shaderProgram, vertShader); gl3.glAttachShader(shaderProgram, fragShader); gl3.glLinkProgram(shaderProgram); // program compiled we can free the object gl3.glDeleteShader(vertShader); gl3.glDeleteShader(fragShader); } private void drawGPU() { shaderInit(); FloatBuffer vertexDataBuffer = GLBuffers.newDirectFloatBuffer(vertexData); vboHandles = new int[1]; gl3.glGenBuffers(1, vboHandles, 0); gl3.glBindBuffer(GL3.GL_ARRAY_BUFFER, vboHandles[0]); gl3.glBufferData(GL3.GL_ARRAY_BUFFER, vertexDataBuffer.capacity() * 4, vertexDataBuffer, GL3.GL_STATIC_DRAW); gl3.glBindBuffer(GL3.GL_ARRAY_BUFFER, 0); vertexDataBuffer = null; gl3.glGenVertexArrays(1, vao); gl3.glBindVertexArray(vao.get(0)); gl3.glUseProgram(shaderProgram); gl3.glBindBuffer(GL3.GL_ARRAY_BUFFER, vboHandles[0]); gl3.glEnableVertexAttribArray(0); gl3.glEnableVertexAttribArray(1); gl3.glVertexAttribPointer(0, 2, GL3.GL_FLOAT, false, 0, 0); gl3.glVertexAttribPointer(1, 2, GL3.GL_FLOAT, false, 0, 0); gl3.glDrawArrays(GL3.GL_LINES, 0, vertexData.length / 2); gl3.glDisableVertexAttribArray(0); gl3.glDisableVertexAttribArray(1); } private int vertexInit(Trajectory[] trajShow) { int line_count = 0; for (Trajectory traj : trajShow) { line_count += (traj.locations.length); } vertexData = new float[line_count * 2 * 2]; int j = 0; for (Trajectory traj : trajShow) { for (int i = 0; i < traj.locations.length - 2; i++) { ScreenPosition pos = map.getScreenPosition(traj.locations[i]); ScreenPosition pos2 = map.getScreenPosition(traj.locations[i + 1]); vertexData[j++] = pos.x; vertexData[j++] = pos.y; vertexData[j++] = pos2.x; vertexData[j++] = pos2.y; } } return line_count; } @Override public void mousePressed() { Location location = new Location(mouseX, mouseY); System.out.println(location); } public static void main(String[] args) { PApplet.main(new String[]{ RenderTimeCalculate.class.getName() }); } } <file_sep>/src/main/java/vqgs/origin/util/draw_with_color_sz.java package vqgs.origin.util; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.geo.Location; import de.fhpotsdam.unfolding.providers.MapBox; import de.fhpotsdam.unfolding.utils.MapUtils; import de.fhpotsdam.unfolding.utils.ScreenPosition; import de.tototec.cmdoption.CmdlineParser; import org.apache.commons.io.FileUtils; import org.apache.commons.io.LineIterator; import processing.core.PApplet; import vqgs.origin.model.Trajectory; import vqgs.util.Config; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; public class draw_with_color_sz extends PApplet { private static final int ZOOMLEVEL = 11; private static final Location PortugalCenter = new Location(22.641, 113.835); private static UnfoldingMap map; private static List<List<Trajectory>> TrajShow = new ArrayList<>(); private static HashMap<Integer, Double> colorSet = new HashMap<>(); final static Integer[] COLORS = { 15, 91, 120, 19, 149, 186, 162, 184, 108, 235, 200, 68, 241, 108, 32, 190, 46, 29 }; private static final int[] ZOOMLIST = {11, 12, 13, 14, 15, 16, 17}; private static final Location[] porto_center = {new Location(41.144, -8.639), new Location(41.093, -8.589), new Location(41.112, -8.525), new Location(41.193, -8.520), new Location(41.23, -8.63), new Location(41.277, -8.281), new Location(41.18114, -8.414669), new Location(41.2037, -8.3045), new Location(41.2765, -8.3762), new Location(41.72913, -8.67484), new Location(41.529533, -8.676072), new Location(41.4784759, -8.404744), new Location(41.451811, -8.655799), new Location(41.215459, -7.70277508), new Location(41.14514, -7.996912), new Location(41.10344, -8.181597), new Location(41.4819594, -8.0645941) }; private static final Location[] sz_center = /*shenzhen*/ {/**/new Location(22.641, 113.835), new Location(22.523, 113.929), new Location(22.691, 113.929), new Location(22.533, 114.014), new Location(22.629, 114.029), new Location(22.535, 114.060), new Location(22.544, 114.117), new Location(22.717, 114.269)}; /*chengdu*/ // {new Location(30.670, 104.063), new Location(30.708, 104.068),new Location(30.691, 104.092), // new Location(30.704, 104.105), new Location(30.699, 104.049), new Location(30.669, 104.105)}; private static double sampleRate = 0.01; private static int delta = 128; private static int offset = 0; private static int zoomidx = 0; private static int centeridx = 0; // 119493 0.05 23898 0.01 11949 0.005 2389 0.001 1194 0.0005 238 0.0001 119 0.00005 23 0.00001 private static HashMap<Double, Integer> rate2num = new HashMap<Double, Integer>() { { put(0.01, 4285); put(0.005, 2142); } }; private static Double[] segmentPoint = {0.0, 0.0, 0.0, 0.0, 0.0}; private static double getMeans(ArrayList<Double> arr) { double sum = 0.0; for (double val : arr) { sum += val; } return sum / arr.size(); } private static double getStandadDiviation(ArrayList<Double> arr) { int len = arr.size(); double avg = getMeans(arr); double dVar = 0.0; for (double val : arr) { dVar += (val - avg) * (val - avg); } return Math.sqrt(dVar / len); } private static void initColorSet(String path) throws IOException { int num = rate2num.get(sampleRate); ArrayList<Double> valueArr = new ArrayList<>(); path = path + "color_" + delta + ".csv"; System.out.println(path); BufferedReader reader = new BufferedReader(new FileReader(path)); String line; for (int i = 0; i < num; i++) { line = reader.readLine(); try { String[] item = line.split(";"); int trajId = Integer.valueOf(item[0]); double value = Double.valueOf(item[1]); valueArr.add(value); colorSet.put(trajId, value); } catch (NullPointerException e) { System.out.println("......." + line); } } Collections.sort(valueArr); double outlier = getMeans(valueArr) + 3 * getStandadDiviation(valueArr); int i; for (i = 0; i < valueArr.size(); i++) { if (valueArr.get(i) > outlier) { break; } } i -= 1; i /= 5; segmentPoint[0] = valueArr.get(i); segmentPoint[1] = valueArr.get(i * 2); segmentPoint[2] = valueArr.get(i * 3); segmentPoint[3] = valueArr.get(i * 4); segmentPoint[4] = valueArr.get(i * 5); } private static void preProcess(String dataPath) { for (int i = 0; i < 6; i++) { TrajShow.add(new ArrayList<>()); } int trajId = 0; try { File theFile = new File(dataPath); LineIterator it = FileUtils.lineIterator(theFile, "UTF-8"); String line; String[] data; try { while (it.hasNext()) { line = it.nextLine(); data = line.split(";")[1].split(","); if (colorSet.containsKey(trajId)) { Trajectory traj = new Trajectory(trajId); for (int i = 0; i < data.length - 2; i = i + 2) { Location point = new Location(Double.parseDouble(data[i + 1]), Double.parseDouble(data[i])); traj.points.add(point); } double color = colorSet.get(traj.getTrajId()); if (color <= segmentPoint[0]) { TrajShow.get(0).add(traj); } else if (color <= segmentPoint[1]) { TrajShow.get(1).add(traj); } else if (color <= segmentPoint[2]) { TrajShow.get(2).add(traj); } else if (color <= segmentPoint[3]) { TrajShow.get(3).add(traj); } else if (color <= segmentPoint[4]) { TrajShow.get(4).add(traj); } else { TrajShow.get(5).add(traj); } } trajId++; } } finally { LineIterator.closeQuietly(it); } } catch (IOException e) { e.printStackTrace(); } } public void settings() { size(1200, 800, P2D); smooth(); } Location[] CENTERLIST = {}; public void setup() { CENTERLIST = type == 0 ? sz_center : porto_center; String whiteMapPath = "https://api.mapbox.com/styles/v1/pacemaker-yc/ck4gqnid305z61cp1dtvmqh5y/tiles/512/{z}/{x}/{y}@2x?access_token=<KEY>"; map = new UnfoldingMap(this, "draw_with_color2", new MapBox.CustomMapBoxProvider(whiteMapPath)); MapUtils.createDefaultEventDispatcher(this, map); map.setZoomRange(1, 20); map.zoomAndPanTo(ZOOMLEVEL, PortugalCenter); map.zoomAndPanTo(ZOOMLIST[zoomidx], CENTERLIST[centeridx]); System.out.println("SET UP DONE"); } private int done = 0; String temppaht = "data/figure_result/"; public void draw() { // 有地图 map.draw(); if (map.allTilesLoaded()) { map.draw(); map.draw(); map.draw(); map.draw(); map.draw(); if (done == 10) { done = 0; noFill(); strokeWeight(1); for (int i = 0; i < 6; i++) { stroke(COLORS[3 * i], COLORS[3 * i + 1], COLORS[3 * i + 2]); // set color here for (Trajectory traj : TrajShow.get(i)) { beginShape(); for (Location loc : traj.points) { ScreenPosition pos = map.getScreenPosition(loc); vertex(pos.x, pos.y); } endShape(); } } saveFrame(temppaht + "color/p" + (centeridx + offset) + "/sample_rate" + (sampleRate) + "_delta" + delta + "_zoom" + map.getZoomLevel() + "_center_p" + (centeridx + offset) + ".png"); if (zoomidx + 1 < ZOOMLIST.length) { zoomidx += 1; map.zoomToLevel(ZOOMLIST[zoomidx]); } else { zoomidx = 0; centeridx += 1; if (centeridx < CENTERLIST.length) { map.zoomAndPanTo(ZOOMLIST[zoomidx], CENTERLIST[centeridx]); } else { System.out.println("draw done"); noLoop(); } } } done += 1; } } private static int type = 0; public static void main(String[] args) { Config config = new Config(); CmdlineParser cp = new CmdlineParser(config); cp.setAggregateShortOptionsWithPrefix("-"); cp.setProgramName("Screenshot"); cp.parse(args); if (config.help) cp.usage(); else if (config.dataset == null || config.vfgs == null) { System.err.println("Dataset file path and VFGS/VFGS+ result file path is necessary!!!"); } else { type = config.type; try { initColorSet(config.vfgs); preProcess(config.dataset); delta = config.delta; System.out.println("init done"); } catch (IOException e) { e.printStackTrace(); } String title = "origin.util.draw_with_color_sz"; PApplet.main(new String[]{title}); } } } <file_sep>/src/main/java/app/SharedObject.java package app; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.geo.Location; import draw.TrajDrawManager; import model.*; import select.SelectManager; import util.IOHandle; import util.PSC; import java.awt.*; import java.util.ArrayList; import java.util.Arrays; import static util.Util.*; public class SharedObject { //public boolean drawingDone = false; private static final SharedObject instance = new SharedObject(); private SharedObject() { } public static SharedObject getInstance() { return instance; } public boolean isCircleRegion() { return circleRegion; } public void setCircleRegion(boolean circleRegion) { this.circleRegion = circleRegion; } private boolean circleRegion = true; public Trajectory[][] getTrajSelectRes() { return trajSelectRes; } public void setTrajSelectRes(Trajectory[][] trajSelectRes) { this.trajSelectRes = trajSelectRes; } private Trajectory[][] trajSelectRes; private static Trajectory[] trajFull; // total trajList private static Trajectory[][][] trajVfgsMtx = null; // trajVfgs for delta X rate private static Trajectory[][] trajRandList = null; // trajRand for rate private static Trajectory[][] trajArray = new Trajectory[3][]; private static TrajDrawManager trajDrawManager; private static TrajBlock[] blockList; private static boolean[] viewVisibleList; private int mapWidth; private int mapHeight; private Location[] mapCenter; public Location[] getMapCenter() { return mapCenter; } public void setMapCenter(Location[] mapCenter) { this.mapCenter = mapCenter; } public int getMapWidth() { return mapWidth; } public void setMapWidth(int mapWidth) { this.mapWidth = mapWidth; } public int getMapHeight() { return mapHeight; } public void setMapHeight(int mapHeight) { this.mapHeight = mapHeight; } // regions private static RectRegion regionO = null; private static RectRegion regionD = null; public ArrayList<WayPointGroup> getWayPointGroups() { return wayPointGroups; } private ArrayList<WayPointGroup> wayPointGroups = new ArrayList<>(); public int curGroupNum = 0; // private WayPointGroup curGroup = new WayPointGroup(curGroupNum); public void setWayPointGroupList(ArrayList<WayPointGroup>[] wayPointGroupList) { this.wayPointGroupList = wayPointGroupList; } public ArrayList<RectRegion> getAllRegionsOneMap() { ArrayList<RectRegion> allRegion = new ArrayList<>(); if (regionO != null) { allRegion.add(regionO); } if (regionD != null) { allRegion.add(regionD); } if (wayPointGroups != null && wayPointGroups.size() > 0) { for (WayPointGroup wayPointGroup : wayPointGroups) {//each group in each map allRegion.addAll(wayPointGroup.getAllRegions()); } } return allRegion; } private RectRegion[] regionOList = new RectRegion[4]; private RectRegion[] regionDList = new RectRegion[4]; private ArrayList<WayPointGroup>[] wayPointGroupList = new ArrayList[4]; // screen region for 4 map private float[][] mapLocInfo = new float[2][4]; public void setMapLocInfo(float[][] mapLocInfo) { this.mapLocInfo = mapLocInfo; } public float[][] getMapLocInfo() { return mapLocInfo; } private static boolean[] regionPresent = new boolean[3];// indicate the current region draw. // map private static UnfoldingMap[] mapList; private boolean finishSelectRegion; public boolean isScreenShot() { return screenShot; } private boolean screenShot; private boolean dragRegion = false; public int[][] getTrajSelectResList() { return trajSelectResList; } public void setTrajSelectResList(int[][] trajSelectResList) { this.trajSelectResList = trajSelectResList; } private int[][] trajSelectResList = new int[4][];//region select res public boolean isDragRegion() { return dragRegion; } // trajectory public Trajectory[] getTrajFull() { return trajFull; } public void setTrajFull(Trajectory[] trajFull) { SharedObject.trajFull = trajFull; } public Trajectory[][] getTrajRandList() { return trajRandList; } public void setTrajRandList(Trajectory[][] trajRandList) { SharedObject.trajRandList = trajRandList; } public Trajectory[][][] getTrajVfgsMtx() { return trajVfgsMtx; } public void setTrajVfgsMtx(Trajectory[][][] trajVfgsMtx) { SharedObject.trajVfgsMtx = trajVfgsMtx; } public TrajDrawManager getTrajDrawManager() { return trajDrawManager; } public void setTrajDrawManager(TrajDrawManager trajDrawManager) { SharedObject.trajDrawManager = trajDrawManager; } public TrajBlock[] getBlockList() { return blockList; } public boolean[] getViewVisibleList() { return viewVisibleList; } public void setViewVisibleList(boolean[] visibleList) { SharedObject.viewVisibleList = visibleList; } public Trajectory[][] getTrajArray() { return trajArray; } public void setTrajArray(Trajectory[][] trajArray) { SharedObject.trajArray = trajArray; } // regions public void setRegionO(RectRegion r) { regionO = r; updateRegionList(); } public RectRegion getRegionO() { return regionO; } public void setRegionD(RectRegion r) { regionD = r; updateRegionList(); } public RectRegion getRegionD() { return regionD; } // map & app public void setMapList(UnfoldingMap[] mapList) { mapCenter = new Location[mapList.length]; int i = 0; for (UnfoldingMap map : mapList) { mapCenter[i] = map.getCenter(); i++; } SharedObject.mapList = mapList; } public UnfoldingMap[] getMapList() { return mapList; } public void eraseRegionPren() { Arrays.fill(regionPresent, false); } public void updateRegionPreList(int regionId) { eraseRegionPren(); regionPresent[regionId] = true; } public boolean checkSelectRegion() { for (boolean f : regionPresent) { if (f) { return true; } } return false; } public void setFinishSelectRegion(boolean status) { finishSelectRegion = status; } public boolean isFinishSelectRegion() { return finishSelectRegion; } public void setDragRegion() { dragRegion = !dragRegion; } public void setScreenShot(boolean shot) { screenShot = shot; } public void cleanRegions() { regionO = regionD = null; // curGroup.cleanWayPointRegions(); wayPointGroups.clear(); wayPointGroups = new ArrayList<>(); // curGroup = new WayPointGroup(0); regionOList = new RectRegion[4]; regionDList = new RectRegion[4]; wayPointGroupList = new ArrayList[4]; curGroupNum = 0; } public int getCurGroupNum() { if (isCircleRegion()) { return CircleRegionControl.getCircleRegionControl().getWayGroupId(); } return wayPointGroups.size() == 0 ? 0 : wayPointGroups.get(curGroupNum - 1).getGroupId(); } public void setCurGroupNum(int curGroupNum) { this.curGroupNum = curGroupNum; } public void addWayPoint(RectRegion r) { if (curGroupNum == 0) addNewGroup(); wayPointGroups.get(curGroupNum - 1).addWayPoint(r); updateRegionList(); } public int getWayLayer() { if (isCircleRegion()) { return CircleRegionControl.getCircleRegionControl().getWayLayer(); } return wayPointGroups.size() == 0 ? 0 : wayPointGroups.get(curGroupNum - 1).getWayPointLayer(); } public ArrayList<RectRegion> getAllRegions() { ArrayList<RectRegion> allRegion = new ArrayList<>(); if (regionO != null) { allRegion.addAll(Arrays.asList(regionOList)); } if (regionD != null) { allRegion.addAll(Arrays.asList(regionDList)); } if (wayPointGroups != null && wayPointGroups.size() > 0) { for (ArrayList<WayPointGroup> wayPointGroupList : wayPointGroupList) {//for each map for (WayPointGroup wayPointGroup : wayPointGroupList) {//each group in each map allRegion.addAll(wayPointGroup.getAllRegions()); } } } return allRegion; } /** * Load trajectory data from file (FULL) * Then generate VFGS and RAND */ public void loadTrajData() { Trajectory[] trajFull = IOHandle.loadRowData(PSC.ORIGIN_PATH, PSC.LIMIT); instance.setTrajFull(trajFull); int[] rateCntList = translateRate(trajFull.length, PSC.RATE_LIST); instance.setTrajVfgsMtx(calTrajVfgsMatrix(trajFull, rateCntList)); instance.setTrajRandList(calTrajRandList(trajFull, rateCntList)); } public boolean checkRegion(int index) { return regionPresent[index]; } /** * This must be called before use {@link #setBlockAt} */ public void initBlockList() { blockList = new TrajBlock[5]; for (int mapIdx = 0; mapIdx < 5; mapIdx++) { blockList[mapIdx] = new TrajBlock(mapIdx); } } /** * Set the color of all main layers */ public void setAllMainColor(Color color) { for (TrajBlock tb : blockList) { tb.setMainColor(color); } } /** * Set the color of all double select result layers */ public void setAllSltColor(Color color) { for (TrajBlock tb : blockList) { tb.setSltColor(color); } } public void setBlockAt(int idx, BlockType type, int rateIdx, int deltaIdx) { System.out.println("Set block at : idx = " + idx + ", type = " + type + ", rateIdx = " + rateIdx + ", deltaIdx = " + deltaIdx); Trajectory[] trajList; int threadNum; switch (type) { case NONE: trajList = null; threadNum = -1; break; case FULL: trajList = this.getTrajFull(); threadNum = PSC.FULL_THREAD_NUM; break; case VFGS: trajList = this.getTrajVfgsMtx()[deltaIdx][rateIdx]; threadNum = PSC.SAMPLE_THREAD_NUM; break; case RAND: trajList = this.getTrajRandList()[rateIdx]; threadNum = PSC.SAMPLE_THREAD_NUM; break; default: // never go here throw new IllegalArgumentException("Can't handle t" + "this block type : " + type); } this.getBlockList()[idx].setNewBlock(type, trajList, threadNum, deltaIdx, rateIdx); } public void setBlockSltAt(int idx, Trajectory[] trajSltList) { System.out.println("Set block double select info at : idx = " + idx); this.getBlockList()[idx].setTrajSltList(trajSltList); } public void calTrajSelectResList() { RegionType regionType; if (isCircleRegion()) { regionType = CircleRegionControl.getCircleRegionControl().getRegionType(); } else { regionType = getRegionType(); } SelectManager slm = new SelectManager(regionType, mapList, blockList); slm.startRun(); setFinishSelectRegion(true); // finish select } private void updateRegionList() { // TODO add logic for one map for (int i = 0; i < 4; i++) { if (regionO != null) { regionOList[i] = regionO.getCorresRegion(i); } if (regionD != null) { regionDList[i] = regionD.getCorresRegion(i); } if (wayPointGroups.size() > 0) {//update the wayPointGroupList ArrayList<WayPointGroup> wayPointGroupTmp = new ArrayList<>(); for (WayPointGroup wayPointGroup : wayPointGroups) { wayPointGroupTmp.add(wayPointGroup.getCorrWayPointGroup(i)); } wayPointGroupList[i] = wayPointGroupTmp; } } } private RegionType getRegionType() { if (wayPointGroups.size() > 0) { if (regionO == null && regionD == null) { return RegionType.WAY_POINT; } else { return RegionType.O_D_W; } } else { return RegionType.O_D; } } public String getBlockInfo() { //TODO add store info StringBuilder info = new StringBuilder("Region info:"); if (regionO == null) { info.append("\nOrigin: NONE"); } else { info.append("\nOrigin:\n").append(regionO.toString()); } if (regionD == null) { info.append("\n\nDestination: NONE"); } else { info.append("\n\nDestination:\n").append(regionD.toString()); } if (wayPointGroups.size() > 0) { info.append("\n\nWay points:\n"); } // for ( : wayPointGroups) { // for (Region r : wList) { // info.append("\n").append(r.toString()); // } // } info.append("\nTrajectory info:"); for (int i = 0; i < 4; i++) { TrajBlock bt = blockList[i]; info.append("\n").append("map").append(i).append(bt.getBlockInfoStr(PSC.DELTA_LIST, PSC.RATE_LIST)); } return info.toString(); } public RectRegion[] getRegionOList() { return regionOList; } public void setRegionOList(RectRegion[] regionOList) { this.regionOList = regionOList; } public RectRegion[] getRegionDList() { return regionDList; } public void setRegionDList(RectRegion[] regionDList) { this.regionDList = regionDList; } public ArrayList<WayPointGroup>[] getWayPointGroupList() { return wayPointGroupList; } public void updateRegionList(RectRegion region) { for (RectRegion r : getAllRegions()) { if (r.id == region.id) { r.setLeftTopLoc(region.getLeftTopLoc()); r.setRightBtmLoc(region.getRightBtmLoc()); } } regionO = regionOList[0]; regionD = regionDList[0]; wayPointGroups = wayPointGroupList[0] == null ? new ArrayList<>() : wayPointGroupList[0]; } public void dropAllSelectRes() { // Only 4 is ok because last trajBlock is // a pointer of one of the first four block for (int i = 0; i < 4; i++) { this.getBlockList()[i].setTrajSltList(null); } } public void addNewGroup() {//增加新的region group //TODO new group logic wayPointGroups.add(new WayPointGroup(curGroupNum++)); // curGroup = wayPointGroups.get(curGroupNum - 1); } public void updateWLayer() { wayPointGroups.get(curGroupNum - 1).updateWayPointLayer(); } } <file_sep>/src/main/java/vqgs/model/Position.java package vqgs.model; /** * Pixel level position on the screen */ public final class Position { private final int x, y; public Position(int x, int y) { this.x = x; this.y = y; } public Position(double x, double y) { this.x = (int) x; this.y = (int) y; } public final int getX() { return x; } public final int getY() { return y; } @Override public final String toString() { return "Position{" + "x=" + x + ", y=" + y + '}'; } @Override public final boolean equals(Object obj) { if (this == obj) { return true; } /*if (!(obj instanceof Position)) { return false; }*/ Position p = (Position) obj; return (p.x == this.x && p.y == this.y); } @Override public final int hashCode() { long ln = (long) (0.5 * (x + y) * (x + y + 1) + y); return (int) (ln ^ (ln >>> 32)); } /** @deprecated */ public static int hashCode(int x, int y) { long ln = (long) (0.5 * (x + y) * (x + y + 1) + y); return (int) (ln ^ (ln >>> 32)); } } <file_sep>/src/main/java/model/WayPointGroup.java package model; import java.util.ArrayList; /** * different group of way point */ public class WayPointGroup { private int groupId; private int wayPointLayer = 0; private ArrayList<ArrayList<RectRegion>> wayPointLayerList; public WayPointGroup() { wayPointLayerList = new ArrayList<>(); } public WayPointGroup(int groupId) { this.groupId = groupId; wayPointLayerList = new ArrayList<>(); } public int getGroupId() { return groupId; } public void setGroupId(int groupId) { this.groupId = groupId; } public int getWayPointLayer() { return wayPointLayer; } public void setWayPointLayer(int wayPointLayer) { this.wayPointLayer = wayPointLayer; } public ArrayList<ArrayList<RectRegion>> getWayPointLayerList() { return wayPointLayerList; } public void setWayPointLayerList(ArrayList<ArrayList<RectRegion>> wayPointLayerList) { this.wayPointLayerList = wayPointLayerList; } public void cleanWayPointRegions() { wayPointLayerList.clear(); } public void updateWayPointLayer() { if (wayPointLayerList.size() == wayPointLayer + 1) { wayPointLayer++; } } public ArrayList<RectRegion> getAllRegions() { ArrayList<RectRegion> res = new ArrayList<>(); if (wayPointLayerList != null) { for (ArrayList<RectRegion> regionList : wayPointLayerList) { res.addAll(regionList); } } return res; } public void addWayPoint(RectRegion r) { if (wayPointLayerList.size() <= wayPointLayer) { wayPointLayerList.add(new ArrayList<>()); } wayPointLayerList.get(wayPointLayer).add(r); //TODO update the shared object } public WayPointGroup getCorrWayPointGroup(int mapId) { WayPointGroup wayPointGroup = new WayPointGroup(groupId); wayPointGroup.setWayPointLayer(wayPointLayer); for (ArrayList<RectRegion> wList : wayPointLayerList) { ArrayList<RectRegion> tmp = new ArrayList<>(); for (RectRegion r : wList) { tmp.add(r.getCorresRegion(mapId)); } wayPointGroup.getWayPointLayerList().add(tmp); } return wayPointGroup; } } <file_sep>/src/main/java/draw/TrajDrawWorkerSingleMap.java package draw; import app.TimeProfileSharedObject; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.geo.Location; import de.fhpotsdam.unfolding.utils.ScreenPosition; import model.Position; import model.Trajectory; import model.TrajectoryMeta; import processing.core.PGraphics; import java.awt.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class TrajDrawWorkerSingleMap extends Thread { private PGraphics pg; private UnfoldingMap map; private int begin; private int end; private Trajectory[] trajList; private TrajectoryMeta[] trajMetaList; private int id; private TrajectoryMeta[] trajMetaFull; public volatile boolean stop = false; public TrajDrawWorkerSingleMap(PGraphics pg, UnfoldingMap map, int begin, int end, Trajectory[] trajList) { this.pg = pg; this.map = map; this.begin = begin; this.end = end; this.trajList = trajList; this.stop = stop; this.setPriority(9); } public TrajDrawWorkerSingleMap(PGraphics pg, UnfoldingMap map, int begin, int end, TrajectoryMeta[] trajMetaList) { this.pg = pg; this.map = map; this.begin = begin; this.end = end; this.trajMetaList = trajMetaList; this.stop = stop; this.trajMetaFull = TimeProfileSharedObject.getInstance().trajMetaFull; this.setPriority(9); } @Override public void run() { try { long t0 = System.currentTimeMillis(); pg.beginDraw(); pg.noFill(); pg.strokeWeight(0.5f); pg.stroke(new Color(255, 0, 0).getRGB()); /* ArrayList<ArrayList<Point>> trajPointList = new ArrayList<>(); for (int i = begin; i < end; i++) { ArrayList<Point> pointList = new ArrayList<>(); for (Position position : trajList[i].getPositions()) { if (this.stop) { System.out.println(this.getName() + " cancel"); return; } Location loc = new Location(position.x / 10000.0, position.y / 10000.0); // System.out.println(loc); ScreenPosition pos = map.getScreenPosition(loc); pointList.add(new Point(pos.x, pos.y)); } trajPointList.add(pointList); } */ /* for (int i = begin; i < end; i++) { ArrayList<Point> pointList = new ArrayList<>(); for (Location loc : trajList[i].getLocations()) { if (this.stop) { System.out.println(this.getName() + " cancel"); return; } ScreenPosition pos = map.getScreenPosition(loc); pointList.add(new Point(pos.x, pos.y)); } trajPointList.add(pointList); } */ /* for (ArrayList<Point> traj : trajPointList) { pg.beginShape(); for (Point pos : traj) { if (this.stop) { System.out.println(this.getName() + " cancel"); pg.endShape(); pg.endDraw(); return; } pg.vertex(pos.x, pos.y); } pg.endShape(); } */ /* for (int i = begin; i < end; i++) { Trajectory traj = trajList[i]; pg.beginShape(); for (Position position : traj.getPositions()) { Location loc = new Location(position.x / 10000.0, position.y / 10000.0); ScreenPosition pos = map.getScreenPosition(loc); pg.vertex(pos.x, pos.y); } pg.endShape(); } */ /* for (int i = begin; i < end; i++) { TrajectoryMeta traj = trajMetaList[i]; pg.beginShape(); for (Position position : traj.getPositions()) { Location loc = new Location(position.x / 10000.0, position.y / 10000.0); ScreenPosition pos = map.getScreenPosition(loc); pg.vertex(pos.x, pos.y); } pg.endShape(); } */ /* for (int i = begin; i < end; i++) { TrajectoryMeta traj = trajMetaList[i]; pg.beginShape(); for (GpsPosition gpsPosition : traj.getGpsPositions()) { Location loc = new Location(gpsPosition.lat, gpsPosition.lon); ScreenPosition pos = map.getScreenPosition(loc); pg.vertex(pos.x, pos.y); } pg.endShape(); } */ int cnt = 0; ArrayList<ArrayList<ScreenPosition>> trajPointList = new ArrayList<>(); for (int i = begin; i < end; i++) { ArrayList<ScreenPosition> pointList = new ArrayList<>(); for (Position pos : generatePosList(trajMetaList[i])) { cnt += 1; if (this.stop) { System.out.println(this.getName() + " cancel"); return; } Location loc = new Location(pos.x / 10000.0, pos.y / 10000.0); ScreenPosition screenPos = map.getScreenPosition(loc); pointList.add(screenPos); } trajPointList.add(pointList); } for (ArrayList<ScreenPosition> traj : trajPointList) { pg.beginShape(); for (ScreenPosition pos : traj) { if (this.stop) { System.out.println(this.getName() + " cancel"); pg.endShape(); pg.endDraw(); return; } pg.vertex(pos.x, pos.y); // pg.point(pos.x, pos.y); // System.out.println(pos.x + ", " + pos.y); } pg.endShape(); } System.out.println("point num: " + cnt); System.out.println(">>>>render time: " + (System.currentTimeMillis() - t0) + " ms"); TimeProfileSharedObject.getInstance().drawDone = true; TimeProfileSharedObject.getInstance().setTrajMatrix(pg, id); } catch (Exception e) { e.printStackTrace(); } } private List<Position> generatePosList(TrajectoryMeta trajMeta) { int trajId = trajMeta.getTrajId(); int begin = trajMeta.getBegin(); int end = trajMeta.getEnd(); // notice that the end is included return Arrays.asList(trajMetaFull[trajId].getPositions()).subList(begin, end + 1); } public static class Point { public float x; public float y; public Point(float x, float y) { this.x = x; this.y = y; } @Override public String toString() { return "(" + x + ", " + y + ")"; } } } <file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>groupId</groupId> <artifactId>DemoSystem</artifactId> <version>1.0-SNAPSHOT</version> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <repositories> <repository> <id>arcgis</id> <url>https://esri.bintray.com/arcgis</url> </repository> </repositories> <dependencies> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>org.processing</groupId> <artifactId>core</artifactId> <version>3.3.7</version> </dependency> <dependency> <groupId>org.openjfx</groupId> <artifactId>javafx-controls</artifactId> <version>11</version> </dependency> <dependency> <groupId>org.openjfx</groupId> <artifactId>javafx-fxml</artifactId> <version>11</version> </dependency> <dependency> <groupId>org.openjfx</groupId> <artifactId>javafx-swing</artifactId> <version>11</version> </dependency> <dependency> <groupId>org.jogamp.gluegen</groupId> <artifactId>gluegen-rt-main</artifactId> <version>2.3.2</version> </dependency> <dependency> <groupId>org.jogamp.jogl</groupId> <artifactId>jogl-all-main</artifactId> <version>2.3.2</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>de.tototec</groupId> <artifactId>de.tototec.cmdoption</artifactId> <version>0.6.0</version> </dependency> <dependency> <groupId>org.processing</groupId> <artifactId>core</artifactId> <version>3.3.7</version> </dependency> <dependency> <groupId>org.jogamp.gluegen</groupId> <artifactId>gluegen-rt-main</artifactId> <version>2.3.2</version> </dependency> <dependency> <groupId>org.jogamp.jogl</groupId> <artifactId>jogl-all-main</artifactId> <version>2.3.2</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- unfolding map is added by lib settings--> <!-- test plugin --> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.1.0</version> <scope>test</scope> </dependency> <!-- for mail sender --> <dependency> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>RELEASE</version> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20160810</version> </dependency> <!-- test plugin --> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.1.0</version> <scope>test</scope> </dependency> <!-- for mail sender --> <dependency> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail</artifactId> <version>RELEASE</version> </dependency> <dependency> <groupId>org.processing</groupId> <artifactId>core</artifactId> <version>3.3.7</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- https://mvnrepository.com/artifact/org.lwjglx/lwjgl3-awt --> <dependency> <groupId>org.lwjglx</groupId> <artifactId>lwjgl3-awt</artifactId> <version>0.1.5</version> </dependency> <dependency> <groupId>org.apache.lucene</groupId> <artifactId>lucene-core</artifactId> <version>4.0.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.lwjgl/lwjgl --> <!-- <dependency>--> <!-- <groupId>org.lwjgl</groupId>--> <!-- <artifactId>lwjgl</artifactId>--> <!-- <version>3.2.3</version>--> <!-- </dependency>--> <!-- https://mvnrepository.com/artifact/org.slick2d/slick2d-core --> <!-- https://mvnrepository.com/artifact/org.lwjgl.lwjgl/lwjgl --> <dependency> <groupId>org.lwjgl.lwjgl</groupId> <artifactId>lwjgl</artifactId> <version>2.9.3</version> </dependency> <!-- <dependency>--> <!-- <groupId>org.slick2d</groupId>--> <!-- <artifactId>slick2d-core</artifactId>--> <!-- <version>1.0.2</version>--> <!-- </dependency>--> <!-- https://mvnrepository.com/artifact/org.slick2d/slick2d-core --> <!-- <dependency>--> <!-- <groupId>org.slick2d</groupId>--> <!-- <artifactId>slick2d-core</artifactId>--> <!-- <version>1.0.1</version>--> <!-- </dependency>--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.9</version> </dependency> <!-- https://mvnrepository.com/artifact/org.jogamp.jogl/jogl-all-main --> <dependency> <groupId>org.jogamp.jogl</groupId> <artifactId>jogl-all-main</artifactId> <version>2.3.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.jogamp.gluegen/gluegen-rt-main --> <dependency> <groupId>org.jogamp.gluegen</groupId> <artifactId>gluegen-rt-main</artifactId> <version>2.3.2</version> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>RELEASE</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>8</source> <target>8</target> </configuration> </plugin> </plugins> </build> </project><file_sep>/src/main/java/select/TimeProfileManager.java package select; import app.TimeProfileSharedObject; import model.RectRegion; import model.RegionType; import model.Trajectory; import model.TrajectoryMeta; import org.lwjgl.Sys; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class TimeProfileManager { ExecutorService threadPool; int threadNum; Trajectory[] trajFull; TrajectoryMeta[] trajMetaFull; RectRegion region; boolean isMeta = false; public TimeProfileManager(int threadNum, Trajectory[] trajFull, RectRegion region) { threadPool = new ThreadPoolExecutor(threadNum, threadNum, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); this.threadNum = threadNum; this.trajFull = trajFull; this.region = region; TimeProfileSharedObject.getInstance().trajRes = new Trajectory[threadNum][]; } public TimeProfileManager(int threadNum, TrajectoryMeta[] trajFull, RectRegion region) { threadPool = new ThreadPoolExecutor(threadNum, threadNum, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); this.threadNum = threadNum; this.trajMetaFull = trajFull; this.region = region; TimeProfileSharedObject.getInstance().trajMetaRes = new TrajectoryMeta[threadNum][]; isMeta = true; } public void startRun() { if (!isMeta) { startRunNoMeta(); } else { startRunMeta(); } } private void startRunNoMeta() { int totalLen = trajFull.length; int segLen = totalLen / threadNum; for (int i = 0; i < threadNum; i++) { TimeProfileWorker tw = new TimeProfileWorker(i * segLen, (i + 1) * segLen, trajFull, i, region); threadPool.submit(tw); } threadPool.shutdown(); try { threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { System.err.println(e); } } private void startRunMeta() { int totalLen = trajMetaFull.length; int segLen = totalLen / threadNum; for (int i = 0; i < threadNum; i++) { TimeProfileWorker tw = new TimeProfileWorker(i * segLen, (i + 1) * segLen, trajMetaFull, i, region); threadPool.submit(tw); } threadPool.shutdown(); try { threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { System.err.println(e); } } } <file_sep>/src/main/java/model/CircleRegionGroup.java package model; import java.util.ArrayList; public class CircleRegionGroup { private int groupId; private int wayPointLayer = 0; private ArrayList<ArrayList<CircleRegion>> wayPointLayerList; public CircleRegionGroup() { wayPointLayerList = new ArrayList<>(); } public CircleRegionGroup(int groupId) { this.groupId = groupId; wayPointLayerList = new ArrayList<>(); } public int getGroupId() { return groupId; } public void setGroupId(int groupId) { this.groupId = groupId; } public int getWayPointLayer() { return wayPointLayer; } public void setWayPointLayer(int wayPointLayer) { this.wayPointLayer = wayPointLayer; } public ArrayList<ArrayList<CircleRegion>> getWayPointLayerList() { return wayPointLayerList; } public void setWayPointLayerList(ArrayList<ArrayList<CircleRegion>> wayPointLayerList) { this.wayPointLayerList = wayPointLayerList; } public void cleanWayPointRegions() { wayPointLayerList.clear(); } public void updateWayPointLayer() { if (wayPointLayerList.size() == wayPointLayer + 1) { wayPointLayer++; } } public ArrayList<CircleRegion> getAllRegions() { ArrayList<CircleRegion> res = new ArrayList<>(); if (wayPointLayerList != null) { for (ArrayList<CircleRegion> circleRegionList : wayPointLayerList) { res.addAll(circleRegionList); } } return res; } public void addWayPoint(CircleRegion r) { if (wayPointLayerList.size() <= wayPointLayer) { wayPointLayerList.add(new ArrayList<>()); } wayPointLayerList.get(wayPointLayer).add(r); //TODO update the shared object } public CircleRegionGroup getCorrCircleWayPointGroup(int mapId) { CircleRegionGroup circleWayPointGroup = new CircleRegionGroup(groupId); circleWayPointGroup.setWayPointLayer(wayPointLayer); for (ArrayList<CircleRegion> wList : wayPointLayerList) { ArrayList<CircleRegion> tmp = new ArrayList<>(); for (CircleRegion r : wList) { tmp.add(r.getCrsRegionCircle(mapId)); } circleWayPointGroup.getWayPointLayerList().add(tmp); } return circleWayPointGroup; } }<file_sep>/src/main/java/model/BlockType.java package model; public enum BlockType { NONE(0), FULL(1), RAND(2), VFGS(3); int value; BlockType(int value) { this.value = value; } public int getValue() { return value; } } <file_sep>/src/main/java/model/EleButton.java package model; import processing.core.PApplet; import util.PSC; import static model.Colour.*; public class EleButton extends Element { public EleButton(int x, int y, int width, int height, int eleId, String eleName) { super(x, y, width, height); this.eleId = eleId; this.eleName = eleName; } @Override public void render(PApplet pApplet) { pApplet.noStroke(); pApplet.fill(PSC.COLOR_LIST[LIGHT_GREY.value].getRGB()); pApplet.rect(x, y, this.width, this.height); pApplet.fill(PSC.COLOR_LIST[WHITE.value].getRGB()); pApplet.textAlign(PApplet.CENTER, PApplet.CENTER); pApplet.text(eleName, x + (width / 2), y + (height / 2)); pApplet.textAlign(PApplet.LEFT, PApplet.TOP); } @Override public int getEleId() { return eleId; } public void colorExg() { } }<file_sep>/src/main/java/util/PSC.java package util; import model.Colour; import java.awt.*; /** * Parameter Setting Class */ public class PSC { public static final String WHITE_MAP_PATH = "https://api.mapbox.com/styles/v1/pacemaker-yc/ck4gqnid305z61cp1dtvmqh5y/tiles/512/{z}/{x}/{y}@2x?access_token=<KEY>"; // i.e. alpha. // These two settings must match the results public static double[] RATE_LIST = {0.05, 0.01, 0.005, /*0.001, 0.0005, 0.0001, 0.00005, 0.00001*/}; public static int[] DELTA_LIST = {0, 4, 8, 16, /*32, 50, 64, 128*/}; // origin data src path public static String ORIGIN_PATH = "data/GPS/Porto5w/Porto5w.txt"; public static String PATH_PREFIX = "data/GPS/porto5w/"; // traj limit for full set. -1 for no limit public static final int LIMIT = 5_0000; // recommend: core # * 2 or little higher public static final int FULL_THREAD_NUM = 8; // for both draw and select public static final int SAMPLE_THREAD_NUM = 2; // for both draw and select public static final int SELECT_THREAD_NUM = 2; // only for draw /** * When the traj num of one thread (tot traj # / thread num) * is lower than this, only one thread will run. * At least > max thread num * 10 * otherwise some traj may be disappeared in select / visualization. */ public static final int MULTI_THREAD_BOUND = 5000; /** * The pool size of control pool in {@link draw.TrajDrawManager}. */ public static final int CONTROL_POOL_SIZE = 8; /** * VFGS result set (i.e. R / R+ in paper). * <br>Must contain %d for delta. * <br>Format: traj id, score */ public static final String RES_PATH = PATH_PREFIX + "vfgs_%d.csv"; public static final String OUTPUT_PATH = "data/output/"; private static final int colorOff = 10; // six provided color to algorithm public static final Color[] COLOR_LIST = { new Color(15, 91, 120), new Color(19, 149, 186), new Color(162, 184, 108), new Color(235, 200, 68), new Color(241, 108, 32), new Color(190, 46, 29), new Color(79, 79, 79), new Color(0, 0, 0), new Color(255, 255, 255) }; public static Color[][] COLOT_TOTAL_LIST; public static final Color RED = new Color(255, 0, 0); public static final Color BLUE = new Color(2, 124, 255); public static final Color GRAY = new Color(150, 150, 150); private int groupNum = 5; public static void initRegionColorList() { COLOT_TOTAL_LIST = new Color[6][4]; Color[] pinkColor = new Color[4]; for (int i = 0; i < 120; i += 30) {//pink list pinkColor[i / 30] = new Color(115, 120 - i, 115); } COLOT_TOTAL_LIST[1] = pinkColor; Color[] greenColor = new Color[4]; for (int i = 0; i < 120; i += 30) { greenColor[i / 30] = new Color(25, 200 - i, 91); } COLOT_TOTAL_LIST[0] = greenColor; Color[] blueColor = new Color[4]; for (int i = 80; i < 240; i += 40) { blueColor[(i - 80) / 40] = new Color(65, 65, 240 - i); } COLOT_TOTAL_LIST[2] = blueColor; COLOT_TOTAL_LIST[3] = new Color[]{new Color(235, 200, 68), new Color(235, 200, 68), new Color(235, 200, 68), new Color(235, 200, 68)}; COLOT_TOTAL_LIST[4] = new Color[]{new Color(162, 184, 108), new Color(162, 184, 108), new Color(162, 184, 108), new Color(162, 184, 108),}; COLOT_TOTAL_LIST[5] = new Color[]{new Color(241, 108, 32), new Color(241, 108, 32), new Color(241, 108, 32), new Color(241, 108, 32),}; } }<file_sep>/src/main/java/vqgs/origin/util/UTIL.java package vqgs.origin.util; import de.fhpotsdam.unfolding.geo.Location; import vqgs.origin.model.Trajectory; import org.apache.commons.io.FileUtils; import org.apache.commons.io.LineIterator; import java.io.*; import java.util.List; public class UTIL { public static void totalListInit(List<Trajectory> TrajTotal, String dataPath) { int trajId = 0; try { File theFile = new File(dataPath); LineIterator it = FileUtils.lineIterator(theFile, "UTF-8"); String line; String[] data; try { while (it.hasNext()) { line = it.nextLine(); Trajectory traj = new Trajectory(trajId); trajId++; String[] item = line.split(";"); data = item[1].split(","); double score = Double.parseDouble(item[0]); int j = 0; for (; j < data.length - 2; j = j + 2) { Location point = new Location(Double.parseDouble(data[j + 1]), Double.parseDouble(data[j])); traj.points.add(point); } traj.setScore(score); TrajTotal.add(traj); } } finally { LineIterator.closeQuietly(it); } } catch (IOException e) { e.printStackTrace(); } } } <file_sep>/src/main/java/vqgs/vfgs/PreProcess.java package vqgs.vfgs; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.geo.Location; import de.fhpotsdam.unfolding.utils.ScreenPosition; import vqgs.model.Position; import vqgs.model.Trajectory; import processing.core.PApplet; import vqgs.util.DM; import vqgs.util.PSC; import vqgs.util.WF; import java.util.HashSet; import static vqgs.util.PSC.*; /** * Preprocessing class to provide necessary data * for following step. * <p> * The function of scoreFileCal is one of the parts here. * (originScores) * <p> * <br> Input: * <ul><li>Origin data. Read from {@link PSC#ORIGIN_PATH}</li></ul> * Output: * <ul><li>{@link DM#trajFull}</li> * <li>Positions field of traj, stored in {@link PSC#POS_INFO_PATH}</li></ul> */ public final class PreProcess extends PApplet { @Override public void setup() { UnfoldingMap map = new UnfoldingMap(this); DM.printAndLog(LOG_PATH, PSC.str()); main(map); exit(); } public static void main(UnfoldingMap map) { map.zoomAndPanTo(20, CELL_CENTER); map.setZoomRange(1, 20); WF.status = WF.PRE_PROCESS; try { run(map); } catch (Exception e) { e.printStackTrace(); WF.error = true; } } private static void run(UnfoldingMap map) { DM.printAndLog(LOG_PATH, "\n====== Begin " + WF.status + " ======\n"); /* load traj from file */ DM.loadRowData(ORIGIN_PATH, LIMIT); DM.printAndLog(LOG_PATH, "\nPrePrecess size: " + DM.trajFull.length + "\n"); Trajectory[] trajFull = DM.trajFull; /* cal position info */ HashSet<Position> totPosSet = new HashSet<>(); for (Trajectory traj : trajFull) { HashSet<Position> trajPos = new HashSet<>(); for (Location loc : traj.getLocations()) { ScreenPosition p = map.getScreenPosition(loc); int px = (int) p.x; int py = (int) p.y; Position pos = new Position(px, py); trajPos.add(pos); totPosSet.add(pos); } traj.setOriginScore(trajPos.size()); traj.setPositions(trajPos.toArray(new Position[0])); traj.setOriginScore(traj.getPositions().length); } /* save to DM */ DM.trajFull = trajFull; DM.totPosSet = totPosSet; System.out.println(); DM.printAndLog(LOG_PATH, "Preprocessing done\n"); /* save to files */ if (SAVE_TEMP) { DM.savePosInfo(POS_INFO_PATH); // temp output: for the input of origin.util.qualityCal DM.saveScoreFile(ORIGIN_PATH, SCORE_PATH, LIMIT); } } public static void main(String[] args) { if (args.length > 0) ORIGIN_PATH = args[0]; PApplet.main(PreProcess.class.getName()); } } <file_sep>/src/main/java/model/Trajectory.java package model; import de.fhpotsdam.unfolding.geo.Location; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; public class Trajectory { public Location[] locations; private double score; private double metaScore; private int trajId; private Position[] metaGPS; private int[] latOrder; private int[] lonOrder; public void setMetaGPS(Position[] metaGPS) { this.metaGPS = metaGPS; latOrder = new int[metaGPS.length]; lonOrder = new int[metaGPS.length]; } public Trajectory(int trajId) { score = 0; this.trajId = trajId; } public Trajectory(double score) { this.score = score; } Trajectory() { score = 0; } public void setScore(double score) { this.score = score; metaScore = score; } public void updateScore(double score){ this.score = score; } public double getScore() { return score; } public int getTrajId() { return trajId; } public void setLocations(Location[] locations) { this.locations = locations; } public Location[] getLocations() { return locations; } // public Location[] getSubTraj(RectRegion rectRegion) { // float leftLat = rectRegion.getLeftTopLoc().getLat(); // float leftLon = rectRegion.getLeftTopLoc().getLon(); // float rightLon = rectRegion.getRightBtmLoc().getLon(); // float rightLat = rectRegion.getRightBtmLoc().getLat(); // // HashSet<Integer> latSet = getLatSubTraj(leftLat, rightLat); // HashSet<Integer> lonSet = getLonSubTraj(leftLon, rightLon); // // latSet.retainAll(lonSet); // return timeOrder(latSet); // } // private HashSet<Integer> getLatSubTraj(float leftLat, float rightLat) { // int begion = getFirstSubId(leftLat, latOrder); // int end = getLastSubId(rightLat, latOrder); // // HashSet<Integer> latSet = new HashSet<>(); // for (int i = begion; i < end; i++) { // latSet.add(metaGPS[i].timeOrder); // } // return latSet; // } // private HashSet<Integer> getLonSubTraj(float leftLon, float rightLon) { // int begion = getFirstSubId(leftLon, latOrder); // int end = getLastSubId(rightLon, latOrder); // // HashSet<Integer> lonSet = new HashSet<>(); // for (int i = begion; i < end; i++) { // lonSet.add(metaGPS[i].timeOrder); // } // return lonSet; // } private int getFirstSubId(float x, int[] list) { int lo = 0, hi = locations.length - 1; while (lo <= hi) { int mi = (lo + hi) / 2; // 2 if (!(list[mi] >= x)) { lo = mi + 1; } else { hi = mi - 1; } } if (lo >= locations.length) { return -1; } return lo; } private int getLastSubId(float x, int[] list) { int lo = 0, hi = locations.length - 1; while (lo <= hi) { int mi = (lo + hi) / 2; // 2 if (list[mi] >= x) { lo = mi + 1; } else { hi = mi - 1; } } return hi; } // private Location[] timeOrder(HashSet<Integer> set) { // ArrayList<Position> tmp_list = new ArrayList<>(); // for (Integer e : set) { // tmp_list.add(metaGPS[e]); // } // Collections.sort(tmp_list); // Location[] loc = new Location[tmp_list.size()]; // int i = 0; // for (Position pos : tmp_list) { // loc[i++] = locations[pos.timeOrder]; // } // return loc; // } private Position[] positions; public void setPositions(Position[] posi){ positions = posi; } public Position[] getPositions(){ return positions; } @Override public String toString() { StringBuilder res = new StringBuilder(); for (Location p : this.locations) { res.append(",").append(p.y).append(",").append(p.x); } return res.substring(1); } public void scoreInit() { score = metaScore; } } <file_sep>/src/main/java/vqgs/draw/TrajShader.java package vqgs.draw; import vqgs.model.Trajectory; import java.awt.*; import java.util.Arrays; /** * The traj color selector * <p> * All color encoding info will be kept in the {@code colorMatrix} * field of {@link Trajectory}. * <p> * After initialization, this class obj can be release. */ public class TrajShader { /** * Call this to write colorMatrix to each traj. */ public static void initTrajColorMatrix(Trajectory[][][] trajVfgsMatrix, int[][][] repScoresMatrix, Color[] colors, int[] breaks) { int dLen = repScoresMatrix.length; int rLen = repScoresMatrix[0].length; boolean computeBreaks = (breaks == null); if (breaks == null) { // not have def breaks, compute it breaks = new int[5]; } for (int dIdx = 0; dIdx < dLen; dIdx++) { for (int rIdx = 0; rIdx < rLen; rIdx++) { // compute for one matrix element delta X rate Trajectory[] trajVfgs = trajVfgsMatrix[dIdx][rIdx]; int[] repScores = repScoresMatrix[dIdx][rIdx]; if (computeBreaks) { initBreaks(breaks, repScores.clone()); } for (int i = 0; i < trajVfgs.length; i++) { // for one traj in R Trajectory traj = trajVfgs[i]; Color[][] colorMatrix = traj.getColorMatrix(); if (colorMatrix == null) { colorMatrix = new Color[dLen][rLen]; traj.setColorMatrix(colorMatrix); } colorMatrix[dIdx][rIdx] = getColor(breaks, colors, repScores[i]); } // save all traj's color at delta X rate } } } /** * Here can be optimize by binary search. */ private static void initBreaks(int[] breaks, int[] repScores) { Arrays.sort(repScores); // can be changed because it is clone int idx; double out = getMeans(repScores) + 3 * getStandardDeviation(repScores); for (idx = 0; idx < repScores.length; idx++) { if (repScores[idx] > out) { break; } } idx -= 1; idx /= 5; for (int i = 0; i < 5; i++) { breaks[i] = repScores[idx * (i + 1)]; } } private static double getMeans(int[] arr) { double sum = 0.0; for (int val : arr) { sum += val; } return sum / arr.length; } private static double getStandardDeviation(int[] arr) { int len = arr.length; double avg = getMeans(arr); double dVar = 0.0; for (double val : arr) { dVar += (val - avg) * (val - avg); } return Math.sqrt(dVar / len); } public static Color getColor(int[] breaks, Color[] colors, int score) { for (int i = 0; i < breaks.length; ++i) { if (score <= breaks[i]) { return colors[i]; } } return colors[colors.length - 1]; } } <file_sep>/src/main/java/index/VfgsForIndex.java package index; import model.Position; import model.TrajToQuality; import model.TrajectoryMeta; import util.GreedyChooseMeta; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; public class VfgsForIndex { public static TrajToQuality[] getVfgs(TrajectoryMeta[] trajFull) { ArrayList<TrajToQuality> vfgsTraj = new ArrayList<>(); try { double totalScore = getTotalScore(trajFull); double lastScore = 0.0; GreedyChooseMeta greedyChooseMeta = new GreedyChooseMeta(trajFull.length); trajScoreInit(trajFull, greedyChooseMeta); HashSet<Position> influScoreSet = new HashSet<>(); for (int i = 0; i < trajFull.length; i++) { while (true) { updateTrajScore(greedyChooseMeta.getHeapHead(), influScoreSet); if (greedyChooseMeta.GreetOrder()) { TrajectoryMeta traj = greedyChooseMeta.getMaxScoreTraj(); updateInfluScoreSet(traj, influScoreSet); vfgsTraj.add(new TrajToQuality(traj, (traj.getScore() + lastScore) / totalScore)); lastScore += traj.getScore(); if (lastScore >= totalScore) { i = trajFull.length + 1; } break; } else { greedyChooseMeta.orderAdjust(); } } } } catch (Exception e) { e.printStackTrace(); } return vfgsTraj.toArray(new TrajToQuality[0]); } private static void updateInfluScoreSet(TrajectoryMeta TrajectoryMeta, HashSet<Position> influSet) { influSet.addAll(Arrays.asList(TrajectoryMeta.getPositions())); } private static void trajScoreInit(TrajectoryMeta[] trajectories, GreedyChooseMeta greedyChooseMeta) { for (TrajectoryMeta traj : trajectories) { traj.scoreInit(); greedyChooseMeta.addNewTraj(traj); } } private HashSet<Position> getTotalScoreSet(TrajectoryMeta[] trajFull) { HashSet<Position> totalScoreSet = new HashSet<>(trajFull.length); for (TrajectoryMeta traj : trajFull) { totalScoreSet.addAll(Arrays.asList(traj.getPositions())); } return totalScoreSet; } private static int getTotalScore(TrajectoryMeta[] trajFull) { HashSet<Position> totalScoreSet = new HashSet<>(trajFull.length); for (TrajectoryMeta traj : trajFull) { totalScoreSet.addAll(Arrays.asList(traj.getPositions())); } return totalScoreSet.size(); } private static void updateTrajScore(TrajectoryMeta TrajectoryMeta, HashSet<Position> influScoreSet) { double score = 0; for (Position position : TrajectoryMeta.getPositions()) { if (!influScoreSet.contains(position)) { score++; } } TrajectoryMeta.updateScore(score); } } <file_sep>/src/main/java/app/TimeProfileSharedObject.java package app; import model.RectRegion; import model.Trajectory; import model.TrajectoryMeta; import processing.core.PGraphics; import java.util.ArrayList; public class TimeProfileSharedObject { private static TimeProfileSharedObject instance = new TimeProfileSharedObject(); private ArrayList<RectRegion> qudaRegion = new ArrayList<>(); public boolean drawDone = false; public void addQuadRectRegion(RectRegion rectRegion) { qudaRegion.add(rectRegion); } public ArrayList<RectRegion> getQudaRegion() { return qudaRegion; } public static TimeProfileSharedObject getInstance() { return instance; } private TimeProfileSharedObject() { } public PGraphics[] trajImageMtx; public Trajectory[][] trajRes; public TrajectoryMeta[][] trajMetaRes; public Trajectory[] trajShow; public TrajectoryMeta[] trajectoryMetas; boolean calDone = false; public TrajectoryMeta[] trajMetaFull; public ArrayList<RectRegion> searchRegions = new ArrayList<>(); public void setTrajMatrix(PGraphics pg, int id) { trajImageMtx[id] = pg; } } <file_sep>/src/main/java/vqgs/util/DM.java package vqgs.util; import de.fhpotsdam.unfolding.geo.Location; import vqgs.model.Position; import vqgs.model.Trajectory; import org.apache.commons.io.FileUtils; import org.apache.commons.io.LineIterator; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.NoSuchElementException; /** * Data Manager Class for transferring common data * to different part of vfgs calculations. */ public final class DM { /** All original loaded trajs */ public static Trajectory[] trajFull; /** Set of all positions (in terns of hash) */ public static HashSet<Position> totPosSet; /** R / R+ according to delta & alpha. 1st dim: delta */ public static int[][] vfgsResList; /** The representativeness scores of the trajs. * 1st dim: delta, 2nd dim: rate. */ public static int[][][] repScoresMatrix; /** * Release all locations fields in traj object */ public static void releaseLocations() { for (Trajectory traj : trajFull) { traj.setLocations(null); } } /** * Release all positions field in traj object */ public static void releasePositions() { for (Trajectory traj : trajFull) { traj.setPositions(null); } } /** * Save log info to the {@link PSC#LOG_PATH}. * No newline adds. */ public static void printAndLog(String filePath, String msg) { try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) { System.out.print(msg); writer.write(msg); } catch (IOException | IllegalArgumentException e) { System.err.println("Save log failed."); e.printStackTrace(); } } /** * Load traj raw data or with score (version problem) * {@link #trajFull} from file {@link PSC#ORIGIN_PATH}. * <p> * format: (score;)double1,double2... */ public static boolean loadRowData(String filePath, int limit) { List<Trajectory> res = new ArrayList<>(); LineIterator it = null; boolean ret = true; int cnt = 0; System.out.print("Read raw data from " + filePath + " ..."); try { it = FileUtils.lineIterator(new File(filePath), "UTF-8"); while (it.hasNext() && (limit == -1 || cnt < limit)) { String line = it.nextLine(); String[] item = line.split(";"); String[] data = item[item.length - 1].split(","); Trajectory traj = new Trajectory(cnt); if (item.length == 2) { // when data contain "score;" traj.setOriginScore(Integer.parseInt(item[0])); } ArrayList<Location> locations = new ArrayList<>(); for (int i = 0; i < data.length - 2; i = i + 2) { // FIXME // the longitude and latitude are reversed locations.add(new Location(Double.parseDouble(data[i + 1]), Double.parseDouble(data[i]))); } traj.setLocations(locations.toArray(new Location[0])); res.add(traj); ++ cnt; } System.out.println("\b\b\bfinished."); } catch (IOException | NoSuchElementException e) { System.out.println("\b\b\bfailed. \nProblem line: " + cnt); e.printStackTrace(); ret = false; } finally { if (it != null) { LineIterator.closeQuietly(it); } } trajFull = res.toArray(new Trajectory[0]); return ret; } /** * Write positions field of traj & {@link #totPosSet} * to file {@link PSC#POS_INFO_PATH}. * <p> * Because {@link #totPosSet} can be produced by previous one, * so only save all positions. * The data will be kept in the memory. */ public static boolean savePosInfo(String filePath) { boolean ret = true; System.out.print("Write position info to " + filePath + " ..."); try { BufferedWriter writer = new BufferedWriter(new FileWriter(filePath)); /*writer.write(String.valueOf(trajFull.length)); // write the traj # writer.newLine();*/ for (Trajectory traj : trajFull) { Position[] ps = traj.getPositions(); int cnt = ps.length; for (Position p : ps) { writer.write(p.getX() + "," + p.getY() + ((cnt == 1) ? "" : ",")); cnt --; } writer.newLine(); } writer.close(); System.out.println("\b\b\bfinished."); } catch (IOException e) { System.out.println("\b\b\bfailed."); e.printStackTrace(); ret = false; } return ret; } /** * Temp output for old-version quality function {@link origin.util.qualityCal} */ public static boolean saveScoreFile(String srcPath, String toPath, int limit) { LineIterator it = null; boolean ret = true; System.out.print("Write temp score file data to " + toPath); try { BufferedWriter writer = new BufferedWriter(new FileWriter(toPath)); it = FileUtils.lineIterator(new File(srcPath), "UTF-8"); int cnt = 0; while (it.hasNext() && (limit == -1 || cnt < limit)) { String line = it.nextLine(); String[] data = line.split(";"); writer.write(trajFull[cnt].getOriginScore() + ";" + data[data.length - 1]); writer.newLine(); cnt++; } LineIterator.closeQuietly(it); writer.close(); System.out.println(" finished."); } catch (IOException | NoSuchElementException e) { System.out.println(" failed."); e.printStackTrace(); ret = false; } finally { if (it != null) { LineIterator.closeQuietly(it); } } return ret; } /** * Read positions field of traj & {@link #totPosSet} * from file {@link PSC#POS_INFO_PATH}. * <p> * The origin score (i.e. positions.length) and {@link #totPosSet} * will be also computed. * <p> * If {@link #trajFull} is null, create it. * Otherwise save positions in to traj's field, * and you should guarantee that the data is matched. */ public static boolean loadPosInfo(String filePath) { LineIterator it = null; int tid = 0; boolean ret = true; System.out.print("Load position info from " + filePath + " ..."); try{ it = FileUtils.lineIterator(new File(filePath), "UTF-8"); /*int trajNum = Integer.parseInt(it.nextLine());*/ totPosSet = new HashSet<>(); ArrayList<Position[]> positionsList = new ArrayList<>(); while (it.hasNext()){ String line = it.nextLine(); String[] data = line.split(","); Position[] positions = new Position[data.length / 2]; for (int i = 0, j = 0; i < positions.length; i += 1, j += 2) { Position pos = new Position(Integer.parseInt(data[j]), Integer.parseInt(data[j + 1])); positions[i] = pos; totPosSet.add(pos); } positionsList.add(positions); ++ tid; } // tie positions to the traj obj if (trajFull == null) { trajFull = new Trajectory[positionsList.size()]; for (int i = 0; i < trajFull.length; i++) { trajFull[i] = new Trajectory(i); } } for (int i = 0; i < trajFull.length; i++) { Position[] positions = positionsList.get(i); trajFull[i].setPositions(positions); trajFull[i].setOriginScore(positions.length); } System.out.print("\b\b\bfinished. \nLoaded size :" + tid); } catch (IOException | NoSuchElementException e) { System.out.println("\b\b\bfailed. \nProblem line: " + tid); e.printStackTrace(); ret = false; } finally { if (it != null) { LineIterator.closeQuietly(it); } } return ret; } /** * Save vfgs result {@link #vfgsResList} to {@link PSC#RES_PATH} * <br> format: tid, score (not need for now) */ public static boolean saveResList(String filePath, int[] deltaList) { boolean ret = true; System.out.print("Write vfgs result to " + filePath.replace("%d", "*")); try { for (int dIdx = 0; dIdx < deltaList.length; dIdx++) { String path = String.format(filePath, deltaList[dIdx]); BufferedWriter writer = new BufferedWriter(new FileWriter(path)); for (int tid : vfgsResList[dIdx]) { writer.write(tid + "," + 0); writer.newLine(); } writer.close(); } System.out.println(" finished."); } catch (IOException e) { System.out.println(" failed."); e.printStackTrace(); ret = false; } return ret; } /** * Read vfgs result {@link #vfgsResList} from {@link PSC#RES_PATH} * <br> format: tid, score (not need for now) * <p> * Before calling it, the {@link #trajFull} * should have been loaded. */ public static boolean loadResList(String filePath, int[] deltaList, double[] rateList) { int dLen = deltaList.length; vfgsResList = new int[dLen][]; int trajNum = trajFull.length; int[] rateCntList = translateRate(trajNum, rateList); LineIterator it = null; int lineNum = 0; boolean ret = true; System.out.print("Read vfgs result from " + filePath.replace("%d", "*")); try { for (int dIdx = 0; dIdx < dLen; ++dIdx) { int delta = deltaList[dIdx]; String path = String.format(filePath, delta); it = FileUtils.lineIterator(new File(path), "UTF-8"); // load the R / R+ for this delta int[] vfgsRes = new int[rateCntList[0]]; for (int i = 0; i < vfgsRes.length; i++) { String line = it.nextLine(); String[] data = line.split(","); vfgsRes[i] = Integer.parseInt(data[0]); ++lineNum; } vfgsResList[dIdx] = vfgsRes; } System.out.println(" finished."); } catch (IOException | NoSuchElementException e) { System.out.println(" failed. \nProblem line: " + lineNum); e.printStackTrace(); ret = false; } finally { if (it != null) { LineIterator.closeQuietly(it); } } return ret; } /** * Save represent traj result {@link #repScoresMatrix} to {@link PSC#COLOR_PATH} * <br> format: tid, repScore * <br> <s>a blank line when a matrix element ends.</s> No blank line now. */ public static boolean saveRepScoresMatrix(String filePath, int[] deltaList) { boolean ret = true; int dLen = repScoresMatrix.length; int rLen = repScoresMatrix[0].length; System.out.print("Write rep score to " + filePath.replace("%d", "*")); try { for (int dIdx = 0; dIdx < dLen; dIdx++) { String path = String.format(filePath, deltaList[dIdx]); BufferedWriter writer = new BufferedWriter(new FileWriter(path)); int[] vfgsRes = vfgsResList[dIdx]; for (int rIdx = 0; rIdx < rLen; rIdx++) { // write score data for this delta-rate cell int[] repScores = repScoresMatrix[dIdx][rIdx]; for (int i = 0; i < repScores.length; i++) { writer.write(vfgsRes[i] + "," + repScores[i]); writer.newLine(); } /*writer.newLine();*/ } writer.close(); } System.out.println(" finished."); } catch (IOException e) { System.out.println(" failed."); e.printStackTrace(); ret = false; } return ret; } /** * Read rep data {@link #repScoresMatrix}from {@link PSC#COLOR_PATH}. * <br> The score will also be written into traj obj * <br> format: tid, repScore * <p> * Before call it, the {@link #trajFull} must have been loaded. */ public static boolean loadRepScoresMatrix(String filePath, int[] deltaList, double[] rateList) { LineIterator it = null; int lineNum = 0; boolean ret = true; int dLen = deltaList.length; int rLen = rateList.length; int[] rateCntList = DM.translateRate(trajFull.length, rateList); repScoresMatrix = new int[dLen][rLen][]; System.out.print("Read rep score from " + filePath.replace("%d", "*")); try { for (int dIdx = 0; dIdx < dLen; dIdx++) { String path = String.format(filePath, deltaList[dIdx]); it = FileUtils.lineIterator(new File(path), "UTF-8"); for (int rIdx = 0; rIdx < rLen; rIdx++) { // read score data for this delta-rate cell String line; ArrayList<Integer> repScores = new ArrayList<>(); for (int i = 0; i < rateCntList[rIdx]; i++) { line = it.nextLine(); String[] data = line.split(","); int rep = Integer.parseInt(data[1]); // the order is same in vfgs res /*trajFull[Integer.parseInt(data[0])].setScore(rep);*/ repScores.add(rep); } repScoresMatrix[dIdx][rIdx] = repScores.stream() .mapToInt(Integer::valueOf).toArray(); } LineIterator.closeQuietly(it); } System.out.println(" finished."); } catch (IOException | IllegalArgumentException e) { System.out.println(" failed. \nProblem line: " + lineNum); e.printStackTrace(); ret = false; } finally { if (it != null) { LineIterator.closeQuietly(it); } } return ret; } /** * Save quality result to file {@link PSC#QUALITY_PATH} * <br> format: zoom, delta, rate, score, tot_score, quality */ public static boolean saveQualityResult(String filePath, int[] zoomRange, int[] deltaList, double[] rateList, int[][][] qualityCube, int[] totScoreList) { boolean ret = true; int dLen = deltaList.length; int rLen = rateList.length; System.out.print("Write quality record to " + filePath); try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) { writer.write("zoom,delta,rate,score,tot_score,quality"); writer.newLine(); for (int zoom = zoomRange[0], zIdx = 0; zoom <= zoomRange[1]; zoom++, zIdx++) { int totScore = totScoreList[zIdx]; for (int dIdx = 0; dIdx < dLen; dIdx++) { int delta = deltaList[dIdx]; for (int rIdx = 0; rIdx < rLen; rIdx++) { double rate = rateList[rIdx]; int score = qualityCube[zIdx][dIdx][rIdx]; writer.write(String.format("%d,%d,%s,%d,%d,%.10f", zoom, delta, rate, score, totScore, 1.0 * score / totScore)); writer.newLine(); } } } System.out.println(" finished."); } catch (IOException | IllegalArgumentException e) { System.out.println(" failed."); e.printStackTrace(); ret = false; } return ret; } /** @deprecated */ public static Trajectory binarySearch(Trajectory[] list, int tid) throws IllegalArgumentException { int lo = 0, hi = list.length - 1; while (lo <= hi) { int mi = lo + (hi - lo) / 2; int cmp = list[mi].getTid() - tid; if (cmp < 0) { lo = mi + 1; } else if (cmp > 0) { hi = mi - 1; } else { return list[mi]; } } throw new IllegalArgumentException("Data of vfgs_*.txt and color_*.txt " + "are not matched. Please check.\n Problem tid: " + tid); } /** * Translate simple rate to real traj count. */ public static int[] translateRate(int trajNum, double[] rateList) { int len = rateList.length; int[] ret = new int[len]; for (int i = 0; i < len; i++) { ret[i] = (int) Math.round(trajNum * rateList[i]); } return ret; } }
c67f5f06cfa52111befc5f50b587c30c1dbcbf3e
[ "Markdown", "Java", "Maven POM" ]
39
Java
ChrisZcu/CheetahTraj
71409115c11ce39d0fed121662409ef669dae792
31fa9106b2238a3c23b99bf4116aad421e047067
refs/heads/master
<repo_name>w-A-L-L-e/ldap2deewee<file_sep>/tests/unit/test_app.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- import pytest from unittest.mock import patch from datetime import datetime from ldap3.core.exceptions import LDAPExceptionError from psycopg2 import OperationalError as PSQLError from app.app import App from app.comm.deewee import DeeweeClient from app.comm.ldap import LdapClient class TestApp: @patch.object(App, '_sync', return_value=None) @patch.object( DeeweeClient, 'max_last_modified_timestamp', return_value=None ) def test_main_full(self, max_last_modified_timestamp_mock, sync_mock): app = App() app.main() assert sync_mock.call_count == 1 assert max_last_modified_timestamp_mock.call_count == 1 call_arg = sync_mock.call_args[0][0] assert call_arg is None @patch.object(App, '_sync', return_value=None) @patch.object( DeeweeClient, 'max_last_modified_timestamp', return_value=datetime.now() ) def test_main_diff(self, max_last_modified_timestamp_mock, sync_mock): app = App() app.main() assert sync_mock.call_count == 1 assert max_last_modified_timestamp_mock.call_count == 1 call_arg = sync_mock.call_args[0][0] assert type(call_arg) == datetime @patch.object(LdapClient, 'search_orgs', return_value=['org1']) @patch.object(LdapClient, 'search_people', return_value=['person1']) @patch.object(DeeweeClient, 'upsert_ldap_results_many', return_value=None) def test_sync(self, upsert_ldap_results_many_mock, search_people_mock, search_orgs_mock): app = App() app._sync() assert search_orgs_mock.call_count == 1 assert search_people_mock.call_count == 1 assert upsert_ldap_results_many_mock.call_count == 1 assert search_orgs_mock.call_args[0][0] is None assert search_people_mock.call_args[0][0] is None assert upsert_ldap_results_many_mock.call_args[0][0] == [ (['org1'], 'org'), (['person1'], 'person') ] @patch.object(DeeweeClient, 'max_last_modified_timestamp', side_effect=PSQLError) def test_main_psql_error(self, should_do_full_sync_mock): app = App() with pytest.raises(PSQLError): app.main() @patch.object(App, '_sync', side_effect=LDAPExceptionError) @patch.object(DeeweeClient, 'max_last_modified_timestamp', return_value=None) def test_main_ldap_error(self, should_do_full_sync_mock, sync_mock): app = App() with pytest.raises(LDAPExceptionError): app.main() <file_sep>/tests/integration/comm/test_deewee.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- import pytest import psycopg2 import uuid from datetime import datetime from ldap3 import Server, Connection, MOCK_SYNC, ALL_ATTRIBUTES, OFFLINE_SLAPD_2_4 from testing.postgresql import PostgresqlFactory import os from app.comm.deewee import ( PostgresqlWrapper, DeeweeClient, COUNT_ENTITIES_SQL, TABLE_NAME ) EXECUTE_SQL = f'SELECT version();' INSERT_ENTITIES_SQL = f'INSERT INTO {TABLE_NAME} (ldap_uuid) VALUES (%s);' # create initial data on create as fixtures into the database def handler(postgresql): with open(f'{os.getcwd()}/additional_containers/postgresql/init.sql') as file: init_sql = file.read() conn = psycopg2.connect(**postgresql.dsn()) cursor = conn.cursor() cursor.execute(init_sql) cursor.close() conn.commit() conn.close() # Generate Postgresql class which shares the generated database Postgresql = PostgresqlFactory(cache_initialized_db=True, on_initialized=handler) def teardown_module(module): # clear cached database at end of tests Postgresql.clear_cache() class TestPostgresqlWrapper: @classmethod def setup_class(cls): cls.postgresql = Postgresql() @classmethod def teardown_class(cls): cls.postgresql.stop() @pytest.fixture def postgresql_wrapper(self): """Returns a PostgresqlWrapper initiliazed by the parameters in config.yml""" return PostgresqlWrapper(self.postgresql.dsn()) @pytest.fixture def postgresql_wrapper_invalid_credentials(self): """Returns a PostgresqlWrapper with invalid credentials""" params = self.postgresql.dsn() params['user'] = 'wrong_user' return PostgresqlWrapper(params) def test_execute(self, postgresql_wrapper): assert postgresql_wrapper.execute(EXECUTE_SQL) is not None def test_executemany(self, postgresql_wrapper): values = [(str(uuid.uuid4()),), (str(uuid.uuid4()),)] count_before = postgresql_wrapper.execute(COUNT_ENTITIES_SQL)[0][0] postgresql_wrapper.executemany(INSERT_ENTITIES_SQL, values) count_after = postgresql_wrapper.execute(COUNT_ENTITIES_SQL)[0][0] assert count_after == count_before + 2 def test_invalid_credentials(self, postgresql_wrapper_invalid_credentials): with pytest.raises(psycopg2.OperationalError): postgresql_wrapper_invalid_credentials.execute(EXECUTE_SQL) class TestDeeweeClient: @classmethod def setup_class(cls): cls.postgresql = Postgresql() @classmethod def teardown_class(cls): cls.postgresql.stop() @pytest.fixture def deewee_client(self): """Returns a DeeweeClient initiliazed linked to the temporary test DB Also truncates the target table. """ deewee_client = DeeweeClient(self.postgresql.dsn()) deewee_client.truncate_table() return deewee_client def _mock_orgs_people(self): """Creates and returns some LDAP entries via ldap3 mock functionality""" # Create mock server with openLDAP schema server = Server('mock_server', get_info=OFFLINE_SLAPD_2_4) conn = Connection( server, 'uid=admin,dc=hetarchief,dc=be', 'Secret123', client_strategy=MOCK_SYNC ) conn.strategy.add_entry( 'uid=admin,dc=hetarchief,dc=be', {'userPassword': '<PASSWORD>', 'sn': 'admin_sn'} ) now = datetime.now() conn.bind() # Create orgs OU conn.add('ou=orgs,dc=hetarchief,dc=be', 'organizationalUnit') # Create 2 orgs conn.add('o=1,ou=orgs,dc=hetarchief,dc=be', 'organization', {'o': '1', 'entryuuid': str(uuid.uuid4()), 'modifyTimestamp': now, 'sn': 'test1', 'telephoneNumber': 1111}) conn.add('o=2,ou=orgs,dc=hetarchief,dc=be', 'organization', {'o': '2', 'entryuuid': str(uuid.uuid4()), 'modifyTimestamp': now, 'sn': 'test2', 'telephoneNumber': 1112}) # Create people OU conn.add('ou=people,dc=hetarchief,dc=be', 'organizationalUnit') # create 2 people conn.add('mail=<EMAIL>,ou=people,dc=hetarchief,dc=be', 'inetOrgPerson', {'mail': '<EMAIL>', 'entryuuid': str(uuid.uuid4()), 'modifyTimestamp': now, 'sn': 'test1', 'telephoneNumber': 1111}) conn.add('mail=<EMAIL>,ou=people,dc=hetarchief,dc=be', 'inetOrgPerson', {'mail': '<EMAIL>', 'entryuuid': str(uuid.uuid4()), 'modifyTimestamp': now, 'sn': 'test2', 'telephoneNumber': 1112}) attrs = [ALL_ATTRIBUTES, 'modifyTimestamp', 'entryUUID'] conn.search( 'ou=orgs,dc=hetarchief,dc=be', '(&(objectClass=*)(!(ou=orgs)))', attributes=attrs ) orgs = conn.entries conn.search( 'ou=people,dc=hetarchief,dc=be', '(&(objectClass=*)(!(ou=people)))', attributes=attrs ) people = conn.entries return (orgs, people) def test_max_last_modified_timestamp(self, deewee_client): now = datetime.now() assert deewee_client.max_last_modified_timestamp() is None deewee_client.insert_entity(now) assert deewee_client.max_last_modified_timestamp() == now def test_upsert_ldap_results_many(self, deewee_client): orgs, people = self._mock_orgs_people() assert deewee_client.count() == 0 deewee_client.upsert_ldap_results_many([(orgs, 'org'), (people, 'person')]) assert deewee_client.count_type('org') == 2 assert deewee_client.count_type('person') == 2 def insert_count(self, deewee_client): assert deewee_client.count() == 0 deewee_client.insert_entity() assert deewee_client.count() == 1 <file_sep>/app/comm/deewee.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- import psycopg2 import uuid from datetime import datetime from functools import wraps TABLE_NAME = 'entities' UPSERT_ENTITIES_SQL = f'''INSERT INTO {TABLE_NAME} (ldap_uuid, type, content, last_modified_timestamp) VALUES (%s, %s, %s, %s) ON CONFLICT (ldap_uuid) DO UPDATE SET content = EXCLUDED.content, last_modified_timestamp = EXCLUDED.last_modified_timestamp;''' TRUNCATE_ENTITIES_SQL = f'TRUNCATE TABLE {TABLE_NAME};' COUNT_ENTITIES_SQL = f'SELECT COUNT(*) FROM {TABLE_NAME}' MAX_LAST_MODIFIED_TIMESTAMP_SQL = f'SELECT max(last_modified_timestamp) FROM {TABLE_NAME}' class PostgresqlWrapper: """Allows for executing SQL statements to a postgresql database""" def __init__(self, params: dict): self.params_postgresql = params def _connect_curs_postgresql(function): """Wrapper function that connects and authenticates to the PostgreSQL DB. The passed function will receive the open cursor. """ @wraps(function) def wrapper_connect(self, *args, **kwargs): with psycopg2.connect(**self.params_postgresql) as conn: with conn.cursor() as curs: val = function(self, cursor=curs, *args, **kwargs) return val return wrapper_connect @_connect_curs_postgresql def execute(self, query: str, vars=None, cursor=None): """Connects to the postgresql DB and executes the statement. Returns all results of the statement if applicable. """ cursor.execute(query, vars) if cursor.description is not None: return cursor.fetchall() @_connect_curs_postgresql def executemany(self, query: str, vars_list: list, cursor=None): """Connects to the postgresql DB and executes the many statement""" cursor.executemany(query, vars_list) class DeeweeClient: """Acts as a client to query and modify information from and to DEEWEE""" def __init__(self, params: dict): self.postgresql_wrapper = PostgresqlWrapper(params) def _prepare_vars_upsert(self, ldap_result, type: str) -> tuple: """Transforms an LDAP entry to pass to the psycopg2 execute function. Transform it to a tuple containing the parameters to be able to upsert. """ return ( str(ldap_result.entryUUID), type, ldap_result.entry_to_json(), ldap_result.modifyTimestamp.value ) def upsert_ldap_results_many(self, ldap_results: list): """Upsert the LDAP entries into PostgreSQL. Transforms and flattens the LDAP entries to one list, in order to execute in one transaction. Arguments: ldap_results -- list of Tuple[list[LDAP_Entry], str]. The tuple contains a list of LDAP entries and a type (str) """ vars_list = [] for ldap_result_tuple in ldap_results: type = ldap_result_tuple[1] # Parse and flatten the SQL values from the ldap_results as a passable list vars_list.extend( [ self._prepare_vars_upsert(ldap_result, type) for ldap_result in ldap_result_tuple[0] ] ) self.postgresql_wrapper.executemany(UPSERT_ENTITIES_SQL, vars_list) def max_last_modified_timestamp(self) -> datetime: """Returns the highest last_modified_timestamp""" return self.postgresql_wrapper.execute(MAX_LAST_MODIFIED_TIMESTAMP_SQL)[0][0] def insert_entity(self, date_time: datetime = datetime.now()): vars = (str(uuid.uuid4()), 'person', '{"key": "value"}', date_time) self.postgresql_wrapper.execute(UPSERT_ENTITIES_SQL, vars) def count(self) -> int: return self.postgresql_wrapper.execute(COUNT_ENTITIES_SQL)[0][0] def count_where(self, where_clause: str, vars: tuple = None) -> int: """Constructs and executes a 'select count(*) where' statement. The where clause can contain zero or more paremeters. If there are no parameters e.g. clause = "column is null", vars should be None. If there are one or more parameters e.g. where_clause = "column = %s", vars should be a tuple containing the parameters. Arguments: where_clause -- represents the clause that comes after the where keyword vars -- see above Returns: int -- the amount of records """ select_sql = f'{COUNT_ENTITIES_SQL} where {where_clause};' return self.postgresql_wrapper.execute(select_sql, vars)[0][0] def count_type(self, type: str) -> int: return self.count_where('type = %s', (type,)) def truncate_table(self): self.postgresql_wrapper.execute(TRUNCATE_ENTITIES_SQL) <file_sep>/docker-compose.yml version: "3.3" services: postgresql: image: deewee_postgresql:latest env_file: ./additional_containers/postgresql/env container_name: deewee_postgresql ports: - "5432:5432" networks: - backend ldap: image: sc_openldap:latest env_file: ./additional_containers/openldap/env container_name: archief_ldap ports: - "8389:8389" networks: - backend application: build: . image: ldap2deewee:latest container_name: ldap2deewee depends_on: - postgresql - ldap networks: - backend networks: backend: driver: bridge <file_sep>/tests/unit/comm/test_ldap.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- import pytest from unittest.mock import patch from datetime import datetime from viaa.configuration import ConfigParser from app.comm.ldap import LdapWrapper, LdapClient class TestLdapWrapper: @pytest.fixture @patch('ldap3.Connection') def ldap_wrapper(self, mock_connection): """Returns a LdapWrapper initiliazed by the parameters in config.yml""" return LdapWrapper(ConfigParser().config['ldap']) def test_search(self, ldap_wrapper): ldap_wrapper.connection.entries.return_value = 'entry' result = ldap_wrapper.search('orgs') mock = ldap_wrapper.connection assert mock.search.call_args[0][0] == 'orgs' assert mock.search.call_count == 1 assert result.return_value == 'entry' def test_add(self, ldap_wrapper): ldap_wrapper.connection.add.return_value = True result = ldap_wrapper.add('dn') mock = ldap_wrapper.connection assert mock.add.call_args[0][0] == 'dn' assert mock.add.call_count == 1 assert result def test_delete(self, ldap_wrapper): ldap_wrapper.connection.delete.return_value = True result = ldap_wrapper.delete('dn') mock = ldap_wrapper.connection assert mock.delete.call_args[0][0] == 'dn' assert mock.delete.call_count == 1 assert result class TestLdapClient: @patch('app.comm.ldap.LdapWrapper') @patch.object(LdapClient, '_search', return_value=None) def test_search_orgs(self, _search_mock, ldap_wrapper): dt = datetime.now() ldap_client = LdapClient({}) ldap_client.search_orgs(dt) assert _search_mock.call_count == 1 assert _search_mock.call_args[0][0] == 'ou=orgs' assert _search_mock.call_args[0][1] == '(!(ou=orgs))' assert _search_mock.call_args[0][2] == dt @patch('app.comm.ldap.LdapWrapper') @patch.object(LdapClient, '_search', return_value=None) def test_search_people(self, _search_mock, ldap_wrapper): dt = datetime.now() ldap_client = LdapClient({}) ldap_client.search_people(dt) assert _search_mock.call_count == 1 assert _search_mock.call_args[0][0] == 'ou=people' assert _search_mock.call_args[0][1] == '(!(ou=people))' assert _search_mock.call_args[0][2] == dt @patch('app.comm.ldap.LdapWrapper') def test_search(self, ldap_wrapper_mock): prefix = 'prefix' partial_filter = 'partial' dt = datetime(2020, 2, 2) ldap_client = LdapClient({}) ldap_client._search(prefix, partial_filter, dt) assert ldap_wrapper_mock.return_value.search.call_count == 1 expected_search = f'{prefix},dc=hetarchief,dc=be' expected_filter = f'(&(objectClass=*){partial_filter}(!(modifyTimestamp<=20200202000000Z)))' assert ldap_wrapper_mock.return_value.search.call_args[0][0] == expected_search assert ldap_wrapper_mock.return_value.search.call_args[0][1] == expected_filter <file_sep>/app/comm/ldap.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- import ldap3 from datetime import datetime from functools import wraps LDAP_SUFFIX = 'dc=hetarchief,dc=be' LDAP_PEOPLE_PREFIX = 'ou=people' LDAP_ORGS_PREFIX = 'ou=orgs' SEARCH_ATTRIBUTES = [ldap3.ALL_ATTRIBUTES, 'modifyTimestamp', 'entryUUID'] class LdapWrapper: """Allows for communicating with an LDAP server""" def __init__(self, params: dict, search_attributes=ldap3.ALL_ATTRIBUTES, get_info=ldap3.SCHEMA, client_strategy=ldap3.SYNC): self.search_attributes = search_attributes # These can potentially be absent so that anonymous access is allowed user = params.get('bind') password = <PASSWORD>('<PASSWORD>') server = ldap3.Server(params['URI'], get_info=get_info) self.connection = ldap3.Connection( server, user, password, client_strategy=client_strategy ) def _connect_auth_ldap(function): """Wrapper function that connects and authenticates to the LDAP server. The passed function will receive the open connection. """ @wraps(function) def wrapper_connect(self, *args, **kwargs): try: self.connection.bind() val = function(self, *args, **kwargs) except ldap3.core.exceptions.LDAPException as exception: raise exception finally: self.connection.unbind() return val return wrapper_connect @_connect_auth_ldap def search(self, search_base: str, filter: str = '(objectClass=*)'): self.connection.search( search_base, filter, attributes=self.search_attributes ) return self.connection.entries @_connect_auth_ldap def add(self, dn: str, object_class=None, attributes=None): return self.connection.add(dn, object_class, attributes) @_connect_auth_ldap def delete(self, dn: str): return self.connection.delete(dn) class LdapClient: """Acts as a client to query relevant information from LDAP""" def __init__(self, params: dict,): self.ldap_wrapper = LdapWrapper(params, SEARCH_ATTRIBUTES) def _search(self, prefix: str, partial_filter: str, modified_at: datetime = None) -> list: # Format modify timestamp to an LDAP filter string modify_filter_string = ( '' if modified_at is None else f'(!(modifyTimestamp<={modified_at.strftime("%Y%m%d%H%M%SZ")}))' ) # Construct the LDAP filter string filter = f'(&(objectClass=*){partial_filter}{modify_filter_string})' return self.ldap_wrapper.search(f'{prefix},{LDAP_SUFFIX}', filter) def search_orgs(self, modified_at: datetime = None) -> list: return self._search( LDAP_ORGS_PREFIX, f'(!({LDAP_ORGS_PREFIX}))', modified_at ) def search_people(self, modified_at: datetime = None) -> list: return self._search( LDAP_PEOPLE_PREFIX, f'(!({LDAP_PEOPLE_PREFIX}))', modified_at ) <file_sep>/openshift/scripts/build.sh REGISTRY=$1 IMAGE_NAME=$2 VERSION=$3 cp ./config.yml.example ./config.yml docker build -t "${REGISTRY}/${IMAGE_NAME}:${VERSION}" .<file_sep>/openshift/scripts/lint.sh REGISTRY=$1 IMAGE_NAME=$2 VERSION=$3 docker container run --name ldap2deewee_lint \ --entrypoint flake8 "${REGISTRY}/${IMAGE_NAME}:${VERSION}" \ --exit-zero \ --max-line-length=88 <file_sep>/openshift/multi-stage/scripts/lint.sh REGISTRY=$1 BRANCH=$2 VERSION=$3 docker container run --name ldap2deewee_builder_lint "${REGISTRY}/ldap2deewee_lint:${BRANCH}-${VERSION}" <file_sep>/tests/unit/comm/test_deewee.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- import pytest import uuid from unittest.mock import patch import json from dataclasses import dataclass, field from datetime import datetime from viaa.configuration import ConfigParser from app.comm.deewee import ( PostgresqlWrapper, DeeweeClient, COUNT_ENTITIES_SQL, UPSERT_ENTITIES_SQL, MAX_LAST_MODIFIED_TIMESTAMP_SQL ) class TestPostgresqlWrapper: @pytest.fixture def postgresql_wrapper(self): """Returns a PostgresqlWrapper initiliazed by the parameters in config.yml""" return PostgresqlWrapper(ConfigParser().config['postgresql']) @patch('psycopg2.connect') def test_execute(self, mock_connect, postgresql_wrapper): connect = mock_connect.return_value.__enter__.return_value connect.cursor.return_value.__enter__.return_value.fetchall.return_value = 5 result = postgresql_wrapper.execute(COUNT_ENTITIES_SQL) assert result == 5 @patch('psycopg2.connect') def test_execute_insert(self, mock_connect, postgresql_wrapper): key = <KEY> mock_connect.cursor.return_value.description = None postgresql_wrapper.execute(UPSERT_ENTITIES_SQL, [key]) connect = mock_connect.return_value.__enter__.return_value cursor = connect.cursor.return_value.__enter__.return_value assert cursor.execute.call_count == 1 assert cursor.execute.call_args[0][0] == UPSERT_ENTITIES_SQL assert cursor.execute.call_args[0][1] == [key] @patch('psycopg2.connect') def test_executemany(self, mock_connect, postgresql_wrapper): values = [(str(uuid.uuid4()),), (str(uuid.uuid4()),)] postgresql_wrapper.executemany(UPSERT_ENTITIES_SQL, values) connect = mock_connect.return_value.__enter__.return_value cursor = connect.cursor.return_value.__enter__.return_value assert cursor.executemany.call_count == 1 assert cursor.executemany.call_args[0][0] == UPSERT_ENTITIES_SQL assert cursor.executemany.call_args[0][1] == values @dataclass class ModifyTimestampMock: """Mock class of the returned modifyTimestamp by LDAP server""" value: datetime = datetime.now() @dataclass class LdapEntryMock: '''Mock class of LDAP3 Entry of ldap3 library''' entryUUID: uuid.UUID = uuid.uuid4() modifyTimestamp: ModifyTimestampMock = ModifyTimestampMock() atttributes: dict = field(default_factory=dict) def entry_to_json(self) -> str: return json.dumps(self.atttributes) class TestDeeweeClient: @pytest.fixture @patch('app.comm.deewee.PostgresqlWrapper') def deewee_client(self, postgresql_wrapper_mock): return DeeweeClient({}) def test_prepare_vars_upsert(self, deewee_client): ldap_result = LdapEntryMock() ldap_result.atttributes['dn'] = 'dn' value = deewee_client._prepare_vars_upsert(ldap_result, 'org') assert value == ( str(ldap_result.entryUUID), 'org', ldap_result.entry_to_json(), ldap_result.modifyTimestamp.value ) def test_upsert_ldap_results_many(self, deewee_client): psql_wrapper_mock = deewee_client.postgresql_wrapper # Create 2 Mock LDAP results ldap_result_1 = LdapEntryMock() ldap_result_1.atttributes['dn'] = 'dn1' ldap_result_2 = LdapEntryMock() ldap_result_2.atttributes['dn'] = 'dn2' # Prepare to pass ldap_results = [([ldap_result_1], 'org'), ([ldap_result_2], 'person')] deewee_client.upsert_ldap_results_many(ldap_results) # The transformed mock LDAP result as tuple val1 = deewee_client._prepare_vars_upsert(ldap_result_1, 'org') val2 = deewee_client._prepare_vars_upsert(ldap_result_2, 'person') assert psql_wrapper_mock.executemany.call_count == 1 assert psql_wrapper_mock.executemany.call_args[0][0] == UPSERT_ENTITIES_SQL assert psql_wrapper_mock.executemany.call_args[0][1] == [val1, val2] def test_max_last_modified_timestamp(self, deewee_client): psql_wrapper_mock = deewee_client.postgresql_wrapper dt = datetime.now() psql_wrapper_mock.execute.return_value = [[dt]] value = deewee_client.max_last_modified_timestamp() assert psql_wrapper_mock.execute.call_args[0][0] == MAX_LAST_MODIFIED_TIMESTAMP_SQL assert value == dt def test_count(self, deewee_client): psql_wrapper_mock = deewee_client.postgresql_wrapper psql_wrapper_mock.execute.return_value = [[5]] value = deewee_client.count() assert psql_wrapper_mock.execute.call_args[0][0] == COUNT_ENTITIES_SQL assert value == 5 <file_sep>/openshift/scripts/push.sh REGISTRY=$1 IMAGE_NAME=$2 login_oc.sh https://c100-e.eu-de.containers.cloud.ibm.com:31240/ docker push "${REGISTRY}/${IMAGE_NAME}:latest"<file_sep>/openshift/scripts/test.sh REGISTRY=$1 IMAGE_NAME=$2 VERSION=$3 docker container run --name ldap2deewee_test "${REGISTRY}/${IMAGE_NAME}:${VERSION}" \ "-m" "pytest" "--cov=app.app" "--cov=app.comm"<file_sep>/app/app.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- from datetime import datetime from ldap3.core.exceptions import LDAPExceptionError from psycopg2 import OperationalError as PSQLError from viaa.configuration import ConfigParser from viaa.observability import logging from app.comm.ldap import LdapClient from app.comm.deewee import DeeweeClient # Initialize the logger and the configuration config = ConfigParser() logger = logging.get_logger(__name__, config=config) class App: def __init__(self): # Initialize ldap and deewee clients self.ldap_client = LdapClient(config.config["ldap"]) self.deewee_client = DeeweeClient(config.config["postgresql"]) def _sync(self, modified_since: datetime = None): """"Will sync the information in LDAP to the PostgreSQL DB. Executes an LDAP search per type. Those results will be send through in one transaction. If the transaction fails, rollback so that the DB will not be in an incomplete state. Arguments: modified_since -- Searches the LDAP results based on this parameter. If None, it will retrieve all LDAP entries. """ # Orgs logger.info("Searching for orgs") ldap_orgs = self.ldap_client.search_orgs(modified_since) logger.info(f"Found {len(ldap_orgs)} org(s) to sync") # People logger.info("Searching for people") ldap_people = self.ldap_client.search_people(modified_since) logger.info(f"Found {len(ldap_people)} people to sync") self.deewee_client.upsert_ldap_results_many( [(ldap_orgs, "org"), (ldap_people, "person")] ) def main(self): try: modified_since = self.deewee_client.max_last_modified_timestamp() if modified_since is None: logger.info("Start full sync") else: logger.info( f"Start sync of difference since last sync - {modified_since.isoformat()}" ) self._sync(modified_since) except (PSQLError, LDAPExceptionError) as e: logger.error(e) raise e logger.info("sync successful") if __name__ == "__main__": App().main() <file_sep>/tests/integration/comm/test_ldap.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- import pytest import ldap3 from datetime import timedelta, datetime import time import copy from viaa.configuration import ConfigParser from app.comm.ldap import ( LdapWrapper, LdapClient, SEARCH_ATTRIBUTES, LDAP_PEOPLE_PREFIX, LDAP_ORGS_PREFIX ) LDAP_SUFFIX = 'dc=hetarchief,dc=be' LDAP_PEOPLE = f'{LDAP_PEOPLE_PREFIX},{LDAP_SUFFIX}' LDAP_ORGS = f'o{LDAP_ORGS_PREFIX},{LDAP_SUFFIX}' DN_ORG1 = f'o=meemoo_org1,{LDAP_ORGS}' DN_ORG2 = f'o=meemoo_org2,{LDAP_ORGS}' DN_PERSON1 = f'mail=<EMAIL>[email protected],{LDAP_PEOPLE}' DN_PERSON2 = f'mail=<EMAIL>.meemoo,{LDAP_PEOPLE}' ldap_config_dict = ConfigParser().config['ldap'] class LdapWrapperMock(LdapWrapper): def __init__(self, params: dict, search_attributes=ldap3.ALL_ATTRIBUTES): super().__init__( params, get_info=ldap3.OFFLINE_SLAPD_2_4, client_strategy=ldap3.MOCK_SYNC ) user = params.get('bind') password = params.get('password') # Allow for anonymous access if user is not None and password is not None: self.connection.strategy.add_entry( user, {'userPassword': password, 'sn': 'admin_sn'} ) class LdapClientMock(LdapClient): def __init__(self, params: dict): self.ldap_wrapper = LdapWrapperMock(params, SEARCH_ATTRIBUTES) class TestLdapWrapperMock: @pytest.fixture def ldap_wrapper(self): """Returns a LdapWrapperMock initiliazed by the parameters in config.yml""" return LdapWrapperMock(ldap_config_dict) def test_search(self, ldap_wrapper): search_result = ldap_wrapper.search(LDAP_ORGS) assert search_result is not None def test_search_invalid_search(self, ldap_wrapper): with pytest.raises(ldap3.core.exceptions.LDAPInvalidDnError) as ldap_error: ldap_wrapper.search('invalid') assert ldap_error.value.args[0] is not None def test_add_invalid(self, ldap_wrapper): with pytest.raises(ldap3.core.exceptions.LDAPInvalidDnError) as ldap_error: ldap_wrapper.add('dn') assert ldap_error.value.args[0] is not None def test_add_delete(self, ldap_wrapper): dn = f'o=test1,{LDAP_ORGS}' add_result = ldap_wrapper.add(dn, 'organization', {'o': 'test1'}) assert add_result delete_result = ldap_wrapper.delete(f'o=test1,{LDAP_ORGS}') assert delete_result class TestLdapWrapperMockAnonymous(TestLdapWrapperMock): @pytest.fixture def ldap_wrapper(self): """Returns a LdapWrapperMock with anonymous access. Non-credentials parameters are parsed from the config.yml file. """ ldap_config_dict_anonymous = copy.deepcopy(ldap_config_dict) del ldap_config_dict_anonymous['bind'] del ldap_config_dict_anonymous['password'] return LdapWrapperMock(ldap_config_dict_anonymous) class TestLdapClientMock: """Tests if the client can communicate with an LDAP mock server""" @classmethod def setup_class(cls): """ Create two orgs and two people""" cls.ldap_client = LdapClientMock(ldap_config_dict) ldap_wrapper = cls.ldap_client.ldap_wrapper ldap_wrapper.add( DN_ORG1, 'organization', {'o': 'meemoo_org1', 'modifyTimestamp': datetime.now()} ) time.sleep(1) ldap_wrapper.add( DN_ORG2, 'organization', {'o': 'meemoo_org2', 'modifyTimestamp': datetime.now()} ) ldap_wrapper.add( DN_PERSON1, 'inetOrgPerson', { 'mail': '<EMAIL>', 'cn': 'meemoo1', 'sn': 'meemoo1', 'modifyTimestamp': datetime.now() } ) time.sleep(1) ldap_wrapper.add( DN_PERSON2, 'inetOrgPerson', { 'mail': '<EMAIL>', 'cn': 'meemoo2', 'sn': 'meemoo2', 'modifyTimestamp': datetime.now() } ) def _modifytimestamp_value(self, ldap_entry): """Returns the modifyTimestamp value of the LDAP entry""" return ldap_entry.modifyTimestamp.value def test_search_orgs(self): ldap_orgs = self.ldap_client.search_orgs() assert len(ldap_orgs) == 2 assert any(ldap_entry.entry_dn == DN_ORG2 for ldap_entry in ldap_orgs) last_modified_entry = max(ldap_orgs, key=self._modifytimestamp_value) max_timestamp = last_modified_entry.modifyTimestamp.value # Timestamp greater than last modified should result in no results search_timestamp = max_timestamp + timedelta(microseconds=1) assert len(self.ldap_client.search_orgs(search_timestamp)) == 0 # Timestamp lesser than last modified should result in DN_ORG2 search_timestamp = max_timestamp - timedelta(microseconds=1) ldap_orgs_filtered = self.ldap_client.search_orgs(search_timestamp) assert len(ldap_orgs_filtered) == 1 assert ldap_orgs_filtered[0].entry_dn == DN_ORG2 def test_search_people(self): ldap_people = self.ldap_client.search_people() assert len(ldap_people) == 2 assert any(ldap_entry.entry_dn == DN_PERSON2 for ldap_entry in ldap_people) last_modified_entry = max(ldap_people, key=self._modifytimestamp_value) max_timestamp = last_modified_entry.modifyTimestamp.value # Timestamp greater than last modified should result in no results search_timestamp = max_timestamp + timedelta(microseconds=1) assert len(self.ldap_client.search_people(search_timestamp)) == 0 # Timestamp lesser than last modified should result in DN_PERSON2 search_timestamp = max_timestamp - timedelta(microseconds=1) ldap_people_filtered = self.ldap_client.search_people(search_timestamp) assert len(ldap_people_filtered) == 1 assert ldap_people_filtered[0].entry_dn == DN_PERSON2 <file_sep>/additional_containers/postgresql/Dockerfile FROM postgres:11.7 EXPOSE 5432 COPY init.sql /docker-entrypoint-initdb.d/<file_sep>/openshift/multi-stage/scripts/build.sh REGISTRY=$1 BRANCH=$2 VERSION=$3 cp ./config.yml.example ./config.yml docker build -t Dockerfile_multi --target builder "${REGISTRY}/ldap2deewee_builder:${BRANCH}-${VERSION}" . docker build -f Dockerfile_multi --target app -t "${REGISTRY}/ldap2deewee_app:${BRANCH}-${VERSION}" . docker build -f Dockerfile_multi --target test -t "${REGISTRY}/ldap2deewee_test:${BRANCH}-${VERSION}" . docker build -f Dockerfile_multi --target lint -t "${REGISTRY}/ldap2deewee_lint:${BRANCH}-${VERSION}" .<file_sep>/openshift/multi-stage/scripts/test.sh REGISTRY=$1 BRANCH=$2 VERSION=$3 docker container run --name ldap2deewee_builder_test "${REGISTRY}/ldap2deewee_test:${BRANCH}-${VERSION}"<file_sep>/additional_containers/postgresql/init.sql CREATE TABLE IF NOT EXISTS entities( id serial PRIMARY KEY, ldap_uuid UUID NOT NULL UNIQUE, type VARCHAR, content JSON, last_modified_timestamp timestamp );<file_sep>/openshift/scripts/tag.sh REGISTRY=$1 IMAGE_NAME=$2 VERSION=$3 docker tag "${REGISTRY}/${IMAGE_NAME}:${VERSION}" "${REGISTRY}/${IMAGE_NAME}:latest"<file_sep>/README.md # ldap2deewee Component that one-way syncs data from LDAP to a PostgreSQL DB in the deewee space. This allows for reporting further downstream. The app is designed to sync changed (new/updated) LDAP entries to the PostgreSQL DB based on the `modifyTimestamp` attribute from LDAP. The identifying key between the two systems is the LDAP attribute `EntryUUID`. Do note that the service is not able to handle deletes. A full load from LDAP can be achieved if the target database table is empty. So in case of known deleted LDAP entries that should reflect in the database, this mechanism can be used to "sync" up. ## Prerequisites * Python >= 3.7 (when working locally) * The package `python3-venv` (when working locally) * The package `PostgreSQL` (when running integration tests locally) * LDAP Server with appropriate structure * PostgreSQL DB with appropriate schema * Docker (optional) * Access to the [meemoo PyPi](http://do-prd-mvn-01.do.viaa.be:8081/) ## Used libraries * `viaa-chassis` * `ldap3` - communicates with the LDAP server * `psycopg2` - communicates with the PostgreSQL server ### Testing * `pytest` - runs automated tests * `pytest-cov` - produces coverage reports * `testing.postgresql` - creates temporary PostgreSQL databases and cleans up afterwards ## Usage First clone this repository with `git clone` and change into the new directory. If you have no access to an LDAP and/or PostgreSQL server they can easily be set up internally by using Docker containers, explained in section [external servers via containers](#external-servers-via-containers). ### Locally Running the app locally is recommended when developing/debugging and running tests. First create the virtual environment: ```shell python3 -m venv ./venv ``` Be sure to activate said environment: ```shell source ./venv/bin/activate ``` Now we can install the required packages: ```shell pip3 install -r requirements.txt ``` Copy the `config.yml.example` file: ```shell cp ./config.yml.example ./config.yml ``` Be sure to fill in the correct configuration parameters in `config.yml` in order to communicate with the LDAP server and PostgreSQL database. Run the app: ```shell python3 -m app.app ``` #### Testing To run the tests, first install the testing dependencies: ```shell pip3 install -r requirements-test.txt ``` Run the tests: ```shell python3 -m pytest ``` The deewee integration tests make use of the PostgreSQL command `initdb` to create a temporary database. Thus, in order the run those integration tests you need to have `PostgreSQL` installed. If desired, you can also run coverage reports: ```shell python3 -m pytest "--cov=app.app" "--cov=app.comm" ``` ### External servers via containers If you have no access to an LDAP and/or PostgreSQL server they can easily be set up internally by using Docker containers. #### LDAP Container A container which runs an LDAP server with an empty structure can be found [here](https://github.com/viaacode/docker-openldap-sc-idm "docker-openldap-sc-idm"). The custom `objectClasses` and `attributeTypes` can be found [here](https://github.com/viaacode/viaa-ldap-schema "viaa-ldap-schema"). The latter repository also contains a `sample.ldif` file with some `orgs` and `persons`. #### PostgreSQL Container A Dockerfile can be found in `./additional_containers/postgresql`. The schema is defined in the `init.sql` file of said folder. Create an `env` file and fill in the parameters: ```shell cp ./additional_containers/postgresql/env.example ./additional_containers/postgresql/env ``` Afterwards build and run the container: ```shell docker build -f ./additional_containers/postgresql/Dockerfile -t deewee_postgresql . docker run --name deewee_postgresql -p 5432:5432 --env-file=./additional_containers/postgresql/env -d deewee_postgresql ``` If desired, test the connection with the following statement in terminal: ```shell psql -h localhost -U {postgresql_user} -d {postgresql_database} ``` ### Container If you just want to execute the app it might be easier to run the container instead of installing python and dependencies. Copy the config file (`cp ./config.yml.example ./config.yml`) and fill in the correct parameters: If the app connects to external servers just build the image: ```shell docker build -t ldap2deewee . ``` If the build succeeded, you should be able to find the image via: ```shell docker image ls ``` To run the app in the container, just execute: ```shell docker run --name ldap2deewee -d ldap2deewee ``` If you want to run the tests in the container, you can run the container in interactive mode: ```shell docker run -it --rm --entrypoint=/bin/sh ldap2deewee ``` You can then run the tests as described in section [testing](#testing-1). However, if you make use of the other (LDAP and PostgreSQL) containers as described above, the app container needs to able to communicate with them. In order to do so you can connect them via a `Docker Network`. We can do this manually by creating a Docker Network and connecting them. Another more automatic option is via `Docker Compose`. #### Docker Network We'll need to create a network and connect the containers together: ```shell docker network create ldap2deewee_network docker network connect ldap2deewee_network deewee_postgresql docker network connect ldap2deewee_network archief_ldap ``` Now we just need to build the ldap2deewee container and run in the Docker Network. Make sure that the host parameters in the `config.yml` file actually point to within the Docker Network. ```shell docker build -t ldap2deewee . docker run --name ldap2deewee --network=ldap2deewee_network -d ldap2deewee ``` Check the status via `docker container ls -a` and/or check the logs via `docker logs ldap2deewee`. #### Docker Compose Instead of manually creating a network and coupling the containers together, Docker Compose can be used as a more automatic alternative. Do **note** that how the docker-compose file is set up, the process expects the PostgreSQL and LDAP images to have been build locally. However, as the Docker Compose process will also run the containers, make sure that they do not exist yet. If you haven't already, be sure to create an `env` file for OpenLDAP and PostgreSQL containers as the Docker Compose process depends on such files. See the respective `env.example` files for the desired structure. ```shell docker-compose up -d ``` Check the status via `docker container ls -a` and/or check the logs via `docker logs ldap2deewee`<file_sep>/requirements-test.txt pytest==5.3.5 pytest-cov==2.8.1 testing.postgresql==1.3.0<file_sep>/requirements.txt viaa-chassis==0.0.4 ldap3==2.6.1 psycopg2==2.8.4<file_sep>/openshift/multi-stage/scripts/app.sh REGISTRY=$1 BRANCH=$2 VERSION=$3 docker container run --name ldap2deewee_builder_app "${REGISTRY}/ldap2deewee_app:${BRANCH}-${VERSION}"<file_sep>/Dockerfile FROM python:3.7.6-alpine3.11 # Install postgresql-dev, gcc and musl-dev to be able to pip install psycopg2. # Install postgresql to use in integration testing. RUN apk add --no-cache postgresql-dev gcc musl-dev postgresql # Copy all files WORKDIR /src/usr/app COPY . . # Install packages RUN pip3 install http://do-prd-mvn-01.do.viaa.be:8081/repository/pypi-internal/packages/viaa-chassis/0.0.4/viaa_chassis-0.0.4-py3-none-any.whl && \ pip3 install -r requirements.txt && \ pip3 install -r requirements-test.txt && \ pip3 install flake8 # Postgresql initdb cannot be run as root. RUN chown -R postgres:postgres /src && \ chmod 777 /src # Switch USER to non-root to be able to run initdb. USER postgres # Run the application ENTRYPOINT ["python3"] CMD ["-m", "app.app"]
48c025799d84a397d8e293c590680e3162683d90
[ "SQL", "YAML", "Markdown", "Python", "Text", "Dockerfile", "Shell" ]
24
Python
w-A-L-L-e/ldap2deewee
22ecd77e4e8795a95d8d269ca86b8a4d50202ce1
f3e16e2716df1c0083cdd750809c8e53a1ae241c
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { FormProperty } from '../../model'; import { SFButtonItem } from '../../schema/button'; @Component({ selector: 'nz-sf-button-widget', template: ` <button nz-button [nzType]="type" [disabled]="button.submit && !formProperty.valid" [nzSize]="size" (click)="button.action($event)">{{button.label}}</button> ` }) export class ButtonWidget implements OnInit { button: SFButtonItem; formProperty: FormProperty; type: string = null; ngOnInit(): void { this.type = this.button.type ? this.button.type : this.button.submit ? 'primary' : null; } get size() { return this.button.size || 'large'; } } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { CommonModule } from '@angular/common'; import { HttpClientModule } from '@angular/common/http'; import { RouterModule } from '@angular/router'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { MarkdownModule } from 'ngx-md'; import { AceEditorModule } from 'ng2-ace-editor'; import { NgZorroAntdModule } from 'ng-zorro-antd'; import { NzSchemaFormModule } from 'nz-schema-form'; import { AppComponent } from './app.component'; import { HomeComponent } from './home/home.component'; import { ExampleComponent } from './example/example.component'; import { ValidatorComponent } from './validator/validator.component'; import { DocumentComponent } from './document/document.component'; @NgModule({ declarations: [ AppComponent, HomeComponent, ExampleComponent, ValidatorComponent, DocumentComponent ], imports: [ BrowserModule, BrowserAnimationsModule, CommonModule, FormsModule, ReactiveFormsModule, HttpClientModule, AceEditorModule, RouterModule.forRoot([ { path: '', component: HomeComponent }, { path: 'example', component: ExampleComponent }, { path: 'validator', component: ValidatorComponent }, { path: 'document', redirectTo: 'document/getting-started', pathMatch: 'full' }, { path: 'document/:id', component: DocumentComponent } ], { useHash: true }), NgZorroAntdModule.forRoot(), NzSchemaFormModule.forRoot({ }), MarkdownModule.forRoot() ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { Component } from '@angular/core'; import { ObjectLayoutWidget } from '../../widget'; @Component({ selector: 'nz-sf-object', template: ` <ng-container *ngFor="let i of formProperty.schema.fieldsets"> <ng-container *ngIf="grid; else noGrid"> <div nz-row [nzGutter]="grid.gutter"> <div *ngFor="let fid of i.fields" nz-col [nzSpan]="getGrid(fid).span" [nzOffset]="getGrid(fid).offset" [nzXs]="getGrid(fid).xs" [nzSm]="getGrid(fid).sm" [nzMd]="getGrid(fid).md" [nzLg]="getGrid(fid).lg" [nzXl]="getGrid(fid).xl"> <div nz-row nz-form-item [ngClass]="{'array-field': isArray(fid)}"> <nz-sf-item *ngIf="formProperty.visible" [formProperty]="formProperty.getProperty(fid)"></nz-sf-item> </div> </div> </div> </ng-container> <ng-template #noGrid> <div *ngFor="let fid of i.fields" nz-row nz-form-item> <nz-sf-item *ngIf="formProperty.visible" [formProperty]="formProperty.getProperty(fid)"></nz-sf-item> </div> </ng-template> </ng-container>` }) export class ObjectWidget extends ObjectLayoutWidget { // TODO: no yet ` [nzXXl]="grid.xxl"` get grid() { return this.formProperty.schema.grid; } getGrid(fieldId: string) { return this.formProperty.getProperty(fieldId).schema.grid || this.grid; } isArray(fieldId: string) { return this.formProperty.getProperty(fieldId).schema.type === 'array'; } }
c6ce20079d89c52f216fabc6b6d08ff075e4cff7
[ "TypeScript" ]
3
TypeScript
canaanjin/nz-schema-form
e9707174078ff1bd9ce5b75c890bf8400f275797
b6c50489ff5d06645b5d54688bf8f03fc6d98005
refs/heads/master
<file_sep><?php use Illuminate\Database\Seeder; class ComponentesTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('componentes')->insert([ 'componente' => 'Bateria' ]); DB::table('componentes')->insert([ 'componente' => 'Cargador' ]); DB::table('componentes')->insert([ 'componente' => 'Disco Duro' ]); DB::table('componentes')->insert([ 'componente' => 'Pantalla' ]); DB::table('componentes')->insert([ 'componente' => 'Teclado' ]); DB::table('componentes')->insert([ 'componente' => 'Memoria' ]); DB::table('componentes')->insert([ 'componente' => 'Placa Madre' ]); DB::table('componentes')->insert([ 'componente' => 'Procesador' ]); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Input; use Storage; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; use App\Cliente; use App\Rol; use Validator; use Yajra\Datatables\Datatables; class ClienteController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $data['titulo'] = "Lista de Clientes"; return view("admin.clientes.clientes",$data); } public function modal($modal='new'){ if($modal=="new") return view('admin.clientes.nuevo_cliente'); else{ return view('admin.clientes.edit_cliente'); } } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $validator = Validator::make($request->all(), [ 'nombre' => 'required|min:4|max:40|string', 'rucdni' => 'required|dni_ruc|numeric', 'correo' => 'email|unique:clientes,correo', 'telefono' => 'required|digits_between:7,9|numeric|unique:clientes,telefono', 'direccion' => 'required|min:4|max:60|string' ]); if ($validator->fails()) { $messages = $validator->errors(); return response()->json($messages); }else{ $Cliente = new Cliente; $Cliente->nombre = $request->nombre; $Cliente->dni_ruc = $request->rucdni; $Cliente->correo = $request->correo; $Cliente->telefono = $request->telefono; $Cliente->direccion = $request->direccion; $Cliente->estado_cliente = 1; return response()->json($Cliente->save()); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $validator = Validator::make($request->all(), [ 'nombre' => 'required|min:4|max:40|string', 'dni_ruc' => 'required|dni_ruc|numeric', 'correo' => 'email|unique:clientes,correo,'.$id.',idcliente', 'telefono' => 'required|digits_between:7,9|numeric', 'direccion' => 'required|min:4|max:60|string' ]); if ($validator->fails()) { $messages = $validator->errors(); return response()->json($messages); }else{ $Cliente = Cliente::find($id); $Cliente->nombre = $request->nombre; $Cliente->dni_ruc = $request->dni_ruc; $Cliente->correo = $request->correo; $Cliente->telefono = $request->telefono; $Cliente->direccion = $request->direccion; return response()->json($Cliente->save()); } } public function anyDataCliente(){ //$datos = User::select([])->get(); return Datatables::of(Cliente::where('estado_cliente','=',1)) ->addColumn('check',function($cliente){ return '<label class="pos-rel"><input type="checkbox" class="ace"><span class="lbl" id="'.$cliente->idcliente.'"></span></label>'; }) ->addColumn('edit',function($cliente){ return '<a href="javascript:void(0)" ng-click="modalCliente(2,'.$cliente->idcliente.')" class="blue"><i class="ace-icon fa fa-pencil bigger-130"></i></a> <a href="javascript:void(0)" ng-click="delete(2,'.$cliente->idcliente.')" class="red"><i class="glyphicon glyphicon-trash"></i></a>'; }) ->make(true); } public function dataCliente($id=null){ if(empty($id)) return response()->json(Cliente::all()); else return response()->json(Cliente::where('idcliente', $id)->first()); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } public function bajacliente($id){ $Cliente = Cliente::find($id); $Cliente->estado_cliente = 0; return response()->json($Cliente->save()); } public function getCliente($field='nombre',$value){ //$value = Input::get('term'); //return Cliente::select('idcliente as id', 'nombre as value')->where($field,'like','%'.$value.'%')->get(); return Cliente::select('idcliente as id', 'nombre as value','dni_ruc','telefono','direccion')->where($field,'like','%'.$value.'%')->where('estado_cliente','=',1)->get(); // return $field.' '.$value; } } <file_sep><?php use Illuminate\Database\Seeder; class EstadosTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('estados')->insert([ 'nombre_estado' => 'Abierta' ]); DB::table('estados')->insert([ 'nombre_estado' => 'En Curso' ]); DB::table('estados')->insert([ 'nombre_estado' => 'Cerrada' ]); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; use App\Componente; use App\User; use App\Cliente; use App\Incidencia; use App\Estado; use App\IncidenciaComponente; use DB; use Illuminate\Support\Facades\Auth; use Symfony\Component\Console\Input\Input; use Validator; use Yajra\Datatables\Datatables; class IncidenciaController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function __construct() { $this->middleware('role', ['only' => ['create']]); } public function index(Request $request) { if ($request->user()->idrol == 1 || $request->user()->idrol == 3) { return view("admin.incidencias.incidencias"); } else { return view("admin.incidencias.incidencias-tecnico"); } } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { $data['tecnicos'] = User::where('idrol', 2)->where('estado',1)->get(); //print_r($data['tecnicos']); $data['componentes'] = Componente::all(); $data['titulo'] = "Registrar Atención"; return view("admin.incidencias.nuevo", $data); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // print_r($request->all()); exit('stop'); $datavalidate = array(); $messages = [ 'digits_between' => 'El campo debe tener entre :min - :max dígitos' ]; if (empty($request->idcliente)) { $datavalidate = array( 'cliente' => 'required|min:4|max:40|string', 'ruc_dni' => 'required|dni_ruc|numeric', 'telefono' => 'required|digits_between:7,9|numeric|unique:clientes,telefono', 'direccion' => 'required|min:4|max:40|string', 'marca' => 'required|min:2|max:40|alpha_num', 'modelo' => 'required|min:2|max:40|alpha_num', 'serie' => 'required|min:2|max:40|alpha_num', 'descripcion_servicio' => 'required|min:2|max:40|string', 'tipo_equipo' => 'required|min:2|max:20|alpha', 'condicion' => 'required|min:2|max:20|alpha', //'componente' => 'required', 'tecnico' => 'required|numeric', 'prioridad' => 'required|digits_between:1,2|numeric', 'precioestimado' => 'required|numeric'); } else{ $datavalidate = array( 'marca' => 'required|min:2|max:40|alpha_num', 'modelo' => 'required|min:2|max:40|alpha_num', 'serie' => 'required|min:2|max:40|alpha_num', 'descripcion_servicio' => 'required|min:2|max:40|string', 'tipo_equipo' => 'required|min:2|max:20|alpha', 'condicion' => 'required|min:2|max:20|alpha', //'componente' => 'required', 'tecnico' => 'required|numeric', 'prioridad' => 'required|digits_between:1,2|numeric', 'precioestimado' => 'required|numeric'); } $validator = Validator::make($request->all(), $datavalidate, $messages); if ($validator->fails()) { /*si hay errores devuelve a la vista*/ //return redirect('incidencia/create')->withErrors($validator)->withInput(); return json_encode(array('error'=> $validator->errors() ) ); } else { /*si no hay eerores crear el registro*/ // DB::transaction(function () { if (empty($request->idcliente)) {/*si no existe un cliente lo registra*/ $Cliente = new Cliente; $Cliente->nombre = $request->cliente; $Cliente->dni_ruc = $request->ruc_dni; $Cliente->telefono = $request->telefono; $Cliente->direccion = $request->direccion; $Cliente->estado_cliente = 1; $Cliente->save(); $idcliente = $Cliente::select('idcliente')->orderBy('idcliente', 'desc')->take(1)->first(); $idcliente = $idcliente->idcliente; } else { $idcliente = $request->idcliente; /*si ya existe retorna su id de cliente */ } if (!empty($idcliente)) { /*requeste es la data que manda el formulario*/ $Incidencia = new Incidencia; $Incidencia->idcliente = $idcliente; $Incidencia->marca = $request->marca; $Incidencia->modelo = $request->modelo; $Incidencia->serie = $request->serie; $Incidencia->descripcion = $request->descripcion_servicio; $Incidencia->tipo = $request->tipo_equipo; $Incidencia->condicion = $request->condicion; $Incidencia->prioridad = $request->prioridad; $Incidencia->idtecnico = $request->tecnico; $Incidencia->precio_estimado = $request->precioestimado; $Incidencia->estado = 1; if ($Incidencia->save()) { /*aca hace el registro o insert */ if(!empty($request->componente)){ $idincidencia = $Incidencia::select('idincidencia')->orderBy('idincidencia', 'desc')->take(1)->first(); foreach ($request->componente as $key => $componente) { $IncidenciaComponente = new IncidenciaComponente; $IncidenciaComponente->idcomponente = $componente; $IncidenciaComponente->idincidencia = $idincidencia->idincidencia; $IncidenciaComponente->serie_componente = $request->serie_componente[$componente]; $IncidenciaComponente->save(); /*aca regista a la base de datos los componentes del equipo*/ } } } } // }); //return redirect('incidencia'); /*cunado termina de registrar te envia a la lista de registros*/ return json_encode(array('ok'=>'ok')); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $datavalidate = array(); if ($request->estado==3) { $datavalidate = array('diagnostico' =>'required' ); $datavalidate = array('descripcion' =>'required' ); $datavalidate = array('preciofinal' =>'required|numeric' ); } $validator = Validator::make($request->all(), $datavalidate); if ($validator->fails()) { $messages = $validator->errors(); return response()->json($messages); }else{ $Incidencia = Incidencia::find($id); $Incidencia->estado = $request->estado; if($request->estado==2) { $Incidencia->diagnostico = $request->diagnostico; $Incidencia->fecha_curso = date('Y-m-d H:i:s'); } if ($request->estado==3) { $Incidencia->descripcion_tecnico = $request->descripcion; $Incidencia->fecha_completa = date('Y-m-d H:i:s'); $Incidencia->precio_final = $request->preciofinal; } return response()->json($Incidencia->save()); } } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { /* * $users = DB::table('users') ->join('contacts', 'users.id', '=', 'contacts.user_id') ->join('orders', 'users.id', '=', 'orders.user_id') ->select('users.*', 'contacts.phone', 'orders.price') ->get();*/ } public function anyData() { //$datos = User::select([])->get(); return Datatables::of(Incidencia::select(DB::raw('incidencia.idincidencia, incidencia.idcliente, incidencia.marca, incidencia.modelo, incidencia.serie, incidencia.prioridad, incidencia.estado, clientes.nombre, users.name, users.apellido, DATE_FORMAT(cast(incidencia.created_at as datetime),"%d-%m-%Y %H:%i:%s") fecha_creacion, DATE_FORMAT(incidencia.fecha_completa,"%d-%m-%Y %H:%i:%s") fecha_completa')) ->join('clientes', 'clientes.idcliente', '=', 'incidencia.idcliente') ->join('users', 'users.id', '=', 'incidencia.idtecnico') ->orderBy('incidencia.idincidencia','desc')) ->addColumn('check', function ($incidencia) { return '<label class="pos-rel"><input type="checkbox" class="ace"><span class="lbl" id="' . $incidencia->idincidencia . '"></span></label>'; }) ->addColumn('idincidencia', function ($incidencia) { return '<a href="' . url('incidencia/edit' . $incidencia->idincidencia) . '">' . $incidencia->idincidencia . '</a>'; }) ->addColumn('tecnico', function ($incidencia) { return $incidencia->name . ' ' . $incidencia->apellido; }) ->addColumn('estado', function ($incidencia) { $estado = ''; if ($incidencia->estado == 1) { $estado = '<span class="label label-info">Abierta</span>'; } elseif ($incidencia->estado == 2) { $estado = '<span class="label label-warning">En Curso</span>'; } elseif ($incidencia->estado == 3) { $estado = '<span class="label label-success">Cerrada</span>'; } return $estado; }) ->addColumn('prioridad', function ($incidencia) { if ($incidencia->prioridad == '1') { $estado = '<span class="label label-info">Baja</span>'; } elseif ($incidencia->prioridad == '2') { $estado = '<span class="label label-warning">Media</span>'; } elseif ($incidencia->prioridad == '3') { $estado = '<span class="label label-danger">Alta</span>'; } return $estado; }) ->addColumn('edit', function ($incidencia) { return '<a href="javascript:void(0)" ng-click="modalIncidencia(2,' . $incidencia->idincidencia . ')" class="green"><i class="glyphicon glyphicon-search"></i></a>'; }) ->make(true); } public function incidenciasAsignadas() { //$datos = User::select([])->get(); return Datatables::of(Incidencia::select( 'incidencia.idincidencia', 'incidencia.idcliente', 'incidencia.marca', 'incidencia.modelo', 'incidencia.serie', 'incidencia.prioridad', 'incidencia.estado', 'clientes.nombre') ->join('clientes', 'clientes.idcliente', '=', 'incidencia.idcliente') ->join('users', 'users.id', '=', 'incidencia.idtecnico') ->where('users.id', Auth::user()->id) ->orderBy('prioridad', 'desc') ->orderBy('incidencia.idincidencia','desc')) ->addColumn('check', function ($incidencia) { return '<label class="pos-rel"><input type="checkbox" class="ace"><span class="lbl" id="' . $incidencia->idincidencia . '"></span></label>'; }) ->addColumn('idincidencia', function ($incidencia) { return '<a href="' . url('incidencia/edit' . $incidencia->idincidencia) . '">' . $incidencia->idincidencia . '</a>'; }) ->addColumn('tecnico', function ($incidencia) { return $incidencia->name . ' ' . $incidencia->apellido; }) ->addColumn('estado', function ($incidencia) { if ($incidencia->estado == 1) { $estado = '<span class="label label-info">Abierta</span>'; } elseif ($incidencia->estado == 2) { $estado = '<span class="label label-warning">En Curso</span>'; } elseif ($incidencia->estado == 3) { $estado = '<span class="label label-success">Cerrada</span>'; } return $estado; }) ->addColumn('prioridad', function ($incidencia) { if ($incidencia->prioridad == '1') { $prioridad = '<span class="label label-info">Baja</span>'; } elseif ($incidencia->prioridad == '2') { $prioridad = '<span class="label label-warning">Media</span>'; } elseif ($incidencia->prioridad == '3') { $prioridad = '<span class="label label-danger">Alta</span>'; } return $prioridad; }) ->addColumn('edit', function ($incidencia) { return '<a ng-click="modalIncidencia(2,' . $incidencia->idincidencia . ')" class="green"><i class="ace-icon fa fa-pencil bigger-130"></i></a>'; }) ->make(true); } public function modal($modal = 'new') { $data['estados'] = Estado::all(); if ($modal == "new") return view('admin.incidencias.nuevo_cliente'); else { return view('admin.incidencias.editar',$data); } } public function dataIncidencia($id = null) { if (empty($id)) return response()->json(Incidencia::all()); else return response()->json( Incidencia::join('clientes', 'clientes.idcliente', '=', 'incidencia.idcliente') ->leftjoin('incidencia-componente','incidencia-componente.idincidencia','=','incidencia.idincidencia') ->leftjoin('componentes','incidencia-componente.idcomponente','=','componentes.idcomponente') ->where('incidencia.idincidencia', $id) ->get()); } public function registrados(){ $data['titulo'] = "Reporte de Atenciones Registradas"; return view('admin.incidencias.reporte_registrado',$data); } public function procesarregistrado(Request $request){ $fechaini = $this->fecha($request->fechaini); $fechafin = $this->fecha($request->fechafin); $data['incidencias'] = Incidencia::select(DB::raw('count(idincidencia) cantidad,concat(day(cast(created_at as DATE)),"/",month(cast(created_at as DATE))) dia')) ->groupBy(DB::raw('day(cast(created_at as DATE))')) ->whereBetween(DB::raw('date(cast(created_at as Date))'), [$fechaini, $fechafin]) ->get(); $data['tipo'] = 'Registrados'; return view('admin.incidencias.reportes.procesar_registrados',$data); } public function atendidos(){ $data['titulo'] = "Reporte de Atenciones Completas "; return view('admin.incidencias.reporte_atendido',$data); } public function procesaratendido(Request $request){ $fechaini = $this->fecha($request->fechaini); $fechafin = $this->fecha($request->fechafin); $data['incidencias'] = Incidencia::select(DB::raw('count(idincidencia) cantidad,concat(day(fecha_completa),"/",month(fecha_completa)) dia')) ->groupBy(DB::raw('day(fecha_completa)')) ->whereBetween(DB::raw('date(fecha_completa)'), [$fechaini, $fechafin]) ->where('incidencia.estado','3') ->get(); $data['tipo'] = 'atendidos'; return view('admin.incidencias.reportes.procesar_registrados',$data); } public function atendidosxtecnico(){ $data['titulo'] = "Reporte de Atenciones por técnico"; return view('admin.incidencias.reporte_atendido_tecnico',$data); } public function procesaratendidoxtecnico(Request $request){ $fechaini = $this->fecha($request->fechaini); $fechafin = $this->fecha($request->fechafin); /* return Datatables::of(Incidencia::join('clientes', 'clientes.idcliente', '=', 'incidencia.idcliente') ->join('users', 'users.id', '=', 'incidencia.idtecnico'))*/ $data['incidencias'] = Incidencia::select(DB::raw('count(idincidencia) cantidad,concat(users.name," ",users.apellido) as tecnico')) ->join('users', 'users.id', '=', 'incidencia.idtecnico') ->groupBy('incidencia.idtecnico') ->whereBetween(DB::raw('date(fecha_completa)'), [$fechaini, $fechafin]) ->where('incidencia.estado','3') ->get(); $data['tipo'] = 'atendidos por técnico'; //print_r($data['incidencias']); return view('admin.incidencias.reportes.procesar_atendidos_tecnico',$data); } public function eficiencia(){ $data['titulo'] = "Grado de cumplimiento"; return view('admin.incidencias.reporte_eficiencia',$data); } public function procesareficiencia(Request $request){ $fechaini = $this->fecha($request->fechaini); $fechafin = $this->fecha($request->fechafin); $data['incidencias'] = Incidencia::select( DB::raw('incidencia.idincidencia,DATE_FORMAT(cast(incidencia.created_at as DATE),"%d-%m-%Y") fecha_creacion, DATE_FORMAT(incidencia.fecha_completa,"%d-%m-%Y") fecha_completa') ) ->join('clientes', 'clientes.idcliente', '=', 'incidencia.idcliente') ->join('users', 'users.id', '=', 'incidencia.idtecnico') ->whereBetween(DB::raw('cast(incidencia.created_at as DATE)'), [$fechaini, $fechafin]) ->get(); $data['cantidade'] = $request->registroe; $data['costoe'] = $request->costoe; $data['tiempoe'] = $request->tiempoe; return view('admin.incidencias.reportes.procesar_eficiencia',$data); } public function eficacia(){ $data['titulo'] = "Reporte Indicador eficacia"; return view('admin.incidencias.reporte_eficacia',$data); } public function procesareficacia(Request $request){ $fechaini = $this->fecha($request->fechaini); $fechafin = $this->fecha($request->fechafin); $data['incidencias'] = Incidencia::select(DB::raw(' incidencia.idincidencia, count(incidencia.idincidencia) cantidad, DATE_FORMAT(cast(incidencia.created_at as DATE),"%d-%m-%Y") fecha')) ->join('clientes', 'clientes.idcliente', '=', 'incidencia.idcliente') ->groupBy(DB::raw('day(cast(incidencia.created_at as DATE))')) ->whereBetween(DB::raw('cast(incidencia.created_at as DATE)'), [$fechaini, $fechafin]) //->where('incidencia.estado','1') ->get(); $data['cantidade'] = $request->registroe; return view('admin.incidencias.reportes.procesar_eficacia',$data); } public function reportetecnico(){ $data['titulo'] = "Reporte detallado por técnico"; return view('admin.incidencias.reporte_tecnico',$data); } public function procesartecnico(Request $request){ $fechaini = $this->fecha($request->fechaini); $fechafin = $this->fecha($request->fechafin); $idtecnico = $this->fecha($request->fechafin); $data['incidencias'] = Incidencia::select(DB::raw('count(incidencia.idincidencia) cantidad,sum(incidencia.precio_final) precio,((TIMESTAMPDIFF(SECOND,date(cast(incidencia.created_at as Date)),incidencia.fecha_completa ))/3600)horas,DATE_FORMAT(incidencia.fecha_completa,"%d-%m-%Y") fecha')) ->join('clientes', 'clientes.idcliente', '=', 'incidencia.idcliente') ->join('users', 'users.id', '=', 'incidencia.idtecnico') ->groupBy(DB::raw('day(fecha_completa)')) ->whereBetween(DB::raw('date(fecha_completa)'), [$fechaini, $fechafin]) ->where('incidencia.estado','3') ->get(); $data['cantidade'] = $request->registroe; return view('admin.incidencias.reportes.procesar_tecnico',$data); } private function fecha($string){ $fecha_array = explode('/',$string); return $fecha_array[2].'-'.$fecha_array[1].'-'.$fecha_array[0]; } } <file_sep><?php Route::get('/', function () { return view('admin.login'); }); Route::group(['middleware' => 'auth'], function() { Route::get('blank', function () { return view('admin.blank'); }); Route::get('usuario/data',['as'=>'usuariodata','uses'=>'UsuarioController@anyData']); Route::post('usuario/perfil', 'UsuarioController@editprofile'); Route::get('usuario/perfil', 'UsuarioController@perfil'); Route::post('usuario/image', 'UsuarioController@editimage'); Route::get('usuario/modal/{modal}/{id?}', 'UsuarioController@modal'); Route::get('usuario/getdata/{id?}', 'UsuarioController@dataUser'); Route::group(['middleware' => 'role'], function() { Route::get('cliente/data',['as'=>'clientedata','uses'=>'ClienteController@anyDataCliente']); Route::get('cliente/modal/{modal}/{id?}', 'ClienteController@modal'); Route::get('cliente/getdata/{id?}', 'ClienteController@dataCliente'); Route::get('cliente/getcliente/{field}/{value}', 'ClienteController@getCliente'); Route::get('cliente/bajacliente/{id?}','ClienteController@bajacliente'); Route::resource('cliente', 'ClienteController'); Route::resource('usuario', 'UsuarioController'); }); Route::post('incidencia/reporte/procesarregistrado', 'IncidenciaController@procesarregistrado'); Route::get('reporte/registrados', 'IncidenciaController@registrados'); Route::post('incidencia/reporte/procesaratendido', 'IncidenciaController@procesaratendido'); Route::get('reporte/atendidos', 'IncidenciaController@atendidos'); Route::post('incidencia/reporte/procesaratendidoxtecnico', 'IncidenciaController@procesaratendidoxtecnico'); Route::get('reporte/atendidosxtecnico', 'IncidenciaController@atendidosxtecnico'); Route::post('incidencia/reporte/procesareficiencia', 'IncidenciaController@procesareficiencia'); Route::get('reporte/eficiencia', 'IncidenciaController@eficiencia'); Route::post('incidencia/reporte/procesareficacia', 'IncidenciaController@procesareficacia'); Route::get('reporte/eficacia', 'IncidenciaController@eficacia'); Route::post('incidencia/reporte/tecnico', 'IncidenciaController@procesartecnico'); Route::get('reporte/tecnico', 'IncidenciaController@reportetecnico'); Route::get('incidencia/getdata/{id?}', 'IncidenciaController@dataIncidencia'); Route::get('incidencia/modal/{modal}/{id?}', 'IncidenciaController@modal'); Route::get('incidencia/data',['as'=>'incidenciadata','uses'=>'IncidenciaController@anyData']); Route::get('incidencia/asignada',['as'=>'incidenciaasignada','uses'=>'IncidenciaController@incidenciasAsignadas']); Route::resource('incidencia', 'IncidenciaController'); Route::get('estado/getdata','EstadoController@getEstados'); }); // Authentication routes... Route::get('login',['uses'=>'Auth\AuthController@getLogin','as'=>'login'] ); Route::post('login', ['uses'=>'Auth\AuthController@postLogin','as'=>'login']); Route::get('logout', 'Auth\AuthController@getLogout'); // Registration routes... Route::get('auth/register', 'Auth\AuthController@getRegister'); Route::post('auth/register', 'Auth\AuthController@postRegister');<file_sep><script> $(function () { $(function () { $('#container').highcharts({ chart: { type: 'column' }, title: { text: 'Atendidos por Técnico' }, subtitle: { text: '' }, xAxis: { type: 'category', labels: { rotation: -45, style: { fontSize: '13px', fontFamily: 'Verdana, sans-serif' } } }, yAxis: { min: 0, title: { text: 'Cantidad de Atenciones' } }, legend: { enabled: false }, tooltip: { pointFormat: 'Cantidad de Atenciones' }, series: [{ name: 'Population', data: [ <?php $i=1; foreach ($incidencias as $key => $incidencia) { ?> ['<?= $incidencia->tecnico ?>', <?= $incidencia->cantidad ?>] <?= ($i==count($incidencias))?'':',' ?> <?php $i++;} ?> ], dataLabels: { enabled: true, rotation: -90, color: '#FFFFFF', align: 'right', format: '{point.y:.1f}', // one decimal y: 10, // 10 pixels down from the top style: { fontSize: '13px', fontFamily: 'Verdana, sans-serif' } } }] }); }); }); </script> <div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div><file_sep># incidencias Sistema de incidencias para reparación de equipos de computo <file_sep><?php namespace App\Providers; use Validator; use Illuminate\Support\ServiceProvider; class MyvalidateServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { Validator::extend('dni_ruc',function($attribute,$value,$parameters){ $return = FALSE; $lenval = strlen($value); if( $lenval==8 || $lenval==11 ) { $return = TRUE; } return $return; }); } /** * Register the application services. * * @return void */ public function register() { // } } <file_sep>var app = angular.module('appincidencia', [],function($interpolateProvider){ $interpolateProvider.startSymbol('<%'); $interpolateProvider.endSymbol('%>'); }).constant('API_URL', 'http://incidencias.app/'); app.directive('calendar', function () { return { require: 'ngModel', link: function (scope, el, attr, ngModel) { $(el).datepicker({ dateFormat: 'yy-mm-dd', monthNamesShort: [ "Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic" ], dayNamesMin: [ "Do", "Lu", "Ma", "Mie", "Jue", "Vie", "Sa" ], onSelect: function (dateText) { scope.$apply(function () { ngModel.$setViewValue(dateText); }); }, changeMonth: true, changeYear:true, }); } }; })<file_sep>app.controller('ClientesController', function ($scope, $compile, $http, API_URL, ClientesFactory) { var rowCompiler = function (nRow, aData, iDataIndex) { var element, linker; linker = $compile(nRow); element = linker($scope); return nRow = element; }; var options = { autoWidth: false, processing: true, serverSide: true, ajax: ClientesFactory.ajax, fnCreatedRow: rowCompiler, columns: ClientesFactory.columns, language: { "url": ClientesFactory.idioma } }; $scope.guardarCliente = function () { var url = API_URL + "cliente"; $scope.errorNombre = ''; $scope.errorRucDni = ''; $scope.errorCorreo = ''; $scope.errorTelefono = ''; $scope.errorDireccion = ''; console.log($scope.cliente.nombre); $http({ method: 'POST', url: url, data: $.param($scope.cliente), headers: {'Content-Type': 'application/x-www-form-urlencoded'} }).success(function (response) { console.log(response); //alert(response.nombre); if (response === true) { $.gritter.add({ title: 'Notificación', text: '¡El Cliente se guardó correctamente!', //sticky: true, class_name: 'gritter-info' }); $('#modalEdit').modal('hide'); var table = $('#clientes-table').DataTable(); table.ajax.reload(); } else { $scope.errorNombre = response.nombre; $scope.errorRucDni = response.rucdni; $scope.errorCorreo = response.correo; $scope.errorTelefono = response.telefono; $scope.errorDireccion = response.direccion; } }).error(function (response) { alert('Ha Ocurrido un error'); }); } $scope.editarCliente = function(){ var url = API_URL + "cliente/" + $scope.cliente.idcliente; $scope.errorNombre = ''; $scope.errorRucDni = ''; $scope.errorCorreo = ''; $scope.errorTelefono = ''; $scope.errorDireccion = ''; //console.log($.param($scope.usuario)); var datos = $( "#frmcliente" ).serialize(); //console.log(str); $http({ method: 'POST', url: url, data: datos, headers: {'Content-Type': 'application/x-www-form-urlencoded'} }).success(function (response) { console.log(response); if (response === true) { //alert("Se actualizó usuario correctamente"); //$('#gritter-center').on(ace.click_event, function(){ $.gritter.add({ title: 'Notificación', text: '!El cliente se actualizó correctamente', //sticky: true, class_name: 'gritter-info' }); //return false; //}); $('#modalEdit').modal('hide'); var table = $('#clientes-table').DataTable(); table.ajax.reload(); } else { $scope.errorNombre = response.nombre; $scope.errorRucDni = response.dni_ruc; $scope.errorCorreo = response.correo; $scope.errorTelefono = response.telefono; $scope.errorDireccion = response.direccion; } }).error(function (response) { alert('Ha Ocurrido un error'); console.log(response); }); } $scope.modalCliente = function (modal, idcliente) { $scope.cliente = ""; var time = new Date().getTime(); if (modal == "new") { $scope.urlmodal = API_URL + "cliente/modal/new?" + time; } else { $http.get(API_URL + 'cliente/getdata/' + idcliente).success(function (data, status) { $scope.cliente = data; }); $scope.urlmodal = API_URL + "cliente/modal/edit/" + idcliente + "?" + time; } $('#modalEdit').modal('show'); } $scope.loadTable = function () { $('#clientes-table').dataTable(options); } $scope.delete = function(v,idcliente){ /*if(confirm("¿Está seguro de eliminar este cliente" + id + " ?" )){ alert("cliente eliminado"); }*/ $( "#dialog-confirm" ).removeClass('hide').dialog({ resizable: false, width: '320', modal: true, title: "Dar de baja usuario", title_html: true, buttons: [ { html: "<i class='ace-icon fa fa-trash-o bigger-110'></i>&nbsp; Aceptar", "class" : "btn btn-danger btn-minier", click: function() { $http.get(API_URL + 'cliente/bajacliente/' + idcliente).success(function (data, status) { //table.ajax.reload(); if(data===true){ $.gritter.add({ title: 'Notificación', text: '!El cliente fue dado de baja', //sticky: true, class_name: 'gritter-error' }); var table = $('#clientes-table').DataTable(); table.ajax.reload(); } }); $( this ).dialog( "close" ); } } , { html: "<i class='ace-icon fa fa-times bigger-110'></i>&nbsp; Cancelar", "class" : "btn btn-minier", click: function() { $( this ).dialog( "close" ); } } ] }); } });<file_sep><?php if(count($incidencias)>0){ ?> <table class="table table-bordered table-condensed table-striped"> <thead class="text-primary"> <th class="text-primary" style="text-align: center;">Cantidad Registros</th> <th class="text-primary" style="text-align: center;">Horas</th> <th class="text-primary" style="text-align: center;">Precio</th> <th class="text-primary" style="text-align: center;">Fecha</th> </thead> <tbody> <?php $cantidadtotal=''; $horastotal=''; $preciototal=''; ?> <?php foreach ($incidencias as $key => $incidencia) { ?> <tr class="text-primary" style="text-align: center;"> <td><?= $incidencia->cantidad ?></td> <td><?= $incidencia->horas ?></td> <td><?= $incidencia->precio ?></td> <td><?= $incidencia->fecha ?></td> </tr> <?php $cantidadtotal+= $incidencia->cantidad; $horastotal+= $incidencia->horas; $preciototal+= $incidencia->precio; } ?> <tr class="text-danger" style="text-align: center;"> <td><strong> Total: <?= $cantidadtotal ?></strong></td> <td><strong>Total: <?= $horastotal ?></strong></td> <td><strong>Total: <?= $preciototal ?></strong></td> <td></td> </tr> </tbody> </table> <br> <?php } else { echo "<br><br><div class='alert alert-danger text-center'><h2 >¡No existen datos en la fecha seleccionada!</h2></div>" ;} ?><file_sep>app.controller('IncidenciasController', function ($scope, $compile, $http, API_URL, IncidenciasFactory) { var rowCompiler = function (nRow, aData, iDataIndex) { var element, linker; linker = $compile(nRow); element = linker($scope); return nRow = element; }; var options = { autoWidth: false, processing: true, serverSide: true, ajax: IncidenciasFactory.ajax, fnCreatedRow: rowCompiler, columns: IncidenciasFactory.columns, language: { "url": IncidenciasFactory.idioma } }; $scope.guardarIncidencia = function () { var url = API_URL + "incidencia/" + $scope.incidencia.idincidencia; var frmdatos = $( "#frmincidencia" ).serialize(); $http({ method: 'POST', url: url, data: frmdatos, headers: {'Content-Type': 'application/x-www-form-urlencoded'} }).success(function (response) { console.log(response); //alert(response.nombre); if (response === true) { console.log(response); $.gritter.add({ title: 'Notificación', text: '¡Se actualizó Atención correctamente!', time: 1000, class_name: 'gritter-info' }); //alert('Se Registro correctamente'); $('#modalEdit').modal('hide'); var table = $('#data-table').DataTable(); table.ajax.reload(); } else { $scope.error = response; } }).error(function (response) { alert('Ha Ocurrido un error'); }); } $scope.modalIncidencia = function (modal, idincidencia) { $scope.incidencia = ""; $scope.estados = ""; $scope.selectincidencia = ""; var time = new Date().getTime(); if (modal == "new") { $scope.urlmodal = API_URL + "incidencia/modal/new?" + time; } else { $http.get(API_URL + 'incidencia/getdata/' + idincidencia).success(function (data, status) { console.log(data); $scope.incidencia = data[0]; var allincidencias = $scope.incidencia; $scope.incidenciacomponente = data; $scope.selectincidencia = {idestado: data[0].estado }; if(data[0].prioridad == 1){ $scope.nombreprioridad = 'Baja' ; }else if(data[0].prioridad==2){ $scope.nombreprioridad = 'Media' ; }else{ $scope.nombreprioridad = 'Alta' ; } if(allincidencias.precio_final=='' || allincidencias.precio_final<='0.00'){ $scope.preciofinal = allincidencias.precio_estimado; }else{ $scope.preciofinal = allincidencias.precio_final; } console.log(allincidencias); }); $http.get(API_URL + 'estado/getdata').success(function (data, status) { $scope.estados = data; }); $scope.urlmodal = API_URL + "incidencia/modal/edit/" + idincidencia + "?" + time; } $('#modalEdit').modal('show'); } $scope.loadTable = function () { $('#data-table').dataTable(options); } $scope.isdiagnostico=true; $scope.isdescripcion=true; $scope.ispreciofinal=true; $scope.estadoclick = function () { $scope.isdiagnostico=true; $scope.isdescripcion=true; $scope.ispreciofinal=true; var idestado = $scope.selectincidencia.idestado; console.log(idestado); if(idestado == 2){ $scope.isdiagnostico=false; } if(idestado == 3){ $scope.isdescripcion=false; $scope.ispreciofinal=false; } } $scope.verreporte = function (){ var time = new Date().getTime(); $scope.urlreporte = API_URL + "incidencia/reporte/procesarregistrado?" + time; } });<file_sep><script> $(function () { $('#container').highcharts({ chart: { type: 'area' }, title: { text: 'Reporte' }, subtitle: { text: 'Incidencias <?= $tipo ?>' }, xAxis: { categories: [ <?php $i=1; foreach ($incidencias as $incidencia){ echo "'".$incidencia->dia."'"; if($i!=count($incidencias)){echo ",";} $i++; } ?> ], tickmarkPlacement: 'on', title: { enabled: false } }, yAxis: { title: { text: 'Cantidad de Registros' }, labels: { formatter: function () { return this.value; } } }, tooltip: { shared: true, valueSuffix: ' Registros' }, plotOptions: { area: { stacking: 'normal', lineColor: '#666666', lineWidth: 1, marker: { lineWidth: 1, lineColor: '#666666' } } }, series: [{ name: 'Cantidad', data: [ <?php $x=1; foreach ($incidencias as $incidencia){ echo $incidencia->cantidad; if($x!=count($incidencias)){echo ",";} $x++; } ?>] }] }); }); </script> <div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div><file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Componente extends Model { protected $primaryKey = 'idcomponente'; protected $table = 'componentes'; protected $fillable = ['idcomponente','componente']; } <file_sep><?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Illuminate\Http\Request; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ private $menu=1; private $submenu; public function boot(Request $request) { if ($request->is('usuario') || $request->is('usuario/*')) { $this->menu = 1 ; } elseif($request->is('incidencia') || $request->is('incidencia/*')){ $this->menu = 2 ; if($request->is('incidencia/create')){ $this->submenu = '2.1' ; } elseif($request->is('incidencia')){ $this->submenu = '2.2' ; } } elseif ($request->is('cliente') || $request->is('cliente/*')){ $this->menu = 3 ; } elseif($request->is('reporte') || $request->is('reporte/*')){ $this->menu = 4 ; } view()->share(['menu'=>$this->menu,'submenu'=>$this->submenu]); } /** * Register any application services. * * @return void */ public function register() { // } } <file_sep><?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateIncidenciaTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('incidencia', function (Blueprint $table) { $table->engine = 'InnoDB'; $table->increments('idincidencia'); $table->integer('idcliente'); $table->string('marca', 40); $table->string('modelo', 40); $table->string('serie', 40); $table->string('descripcion', 200); $table->string('tipo', 40); $table->string('condicion', 40); $table->string('prioridad', 40); $table->integer('estado'); $table->integer('idtecnico'); $table->string('diagnostico',200); $table->string('descripcion_tecnico',200); $table->decimal('precio_estimado',9,2); $table->decimal('precio_final', 9, 2); $table->dateTime('fecha_curso'); $table->dateTime('fecha_completa'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('incidencia'); } } <file_sep><?php if(count($incidencias)>0){ ?> <table class="table table-bordered table-condensed table-striped"> <thead class="text-primary"> <th class="text-primary" style="text-align: center;">Item</th> <th class="text-primary" style="text-align: center;">Fecha Realizada</th> <th class="text-primary" style="text-align: center;">N° Atención Realizada</th> <th class="text-primary" style="text-align: center;">N° Atención Previsto</th> <th class="text-primary" style="text-align: center;">Grado de eficacia</th> </thead> <tbody> <?php $totalatenciones=''; $cantidadtotal=''; $preciototal=''; ?> <?php foreach ($incidencias as $key => $incidencia) { ?> <tr class="text-primary" style="text-align: center;"> <td><?= $key+1 ?></td> <td><?= $incidencia->fecha ?></td> <td><?= $incidencia->cantidad?></td> <td><?= $cantidade ?></td> <td><?= round(($incidencia->cantidad/$cantidade)*100,2) ?>%</td> </tr> <?php $cantidadtotal+= $incidencia->cantidad; } ?> <tr class="text-danger" style="text-align: center;"> <td><strong> Total:</strong></td> <td></td> <td><?= $cantidadtotal ?></td> <td><?= $totalatenciones=$cantidade * count($incidencias)?></td> <td><?= round(($cantidadtotal/$totalatenciones)*100,2)?>%</td> </tr> </tbody> </table> <?php /* <br> <table class="table table-bordered table-condensed" style="text-align: center;"> <thead> <th style="text-align: center;">Eficacia</th> </thead> <tr> <td> <strong>(RA/RE)</strong> / <strong>(RA/RE)</strong> </td> </tr> <tr> <td> (<?=$cantidadtotal?>/<?= $cantidade?>) = <?php echo round( ($cantidadtotal / $cantidade ),4) ?> </td> </tr> <tr> <td class="text-info"><strong>Dónde:</strong><br>R= Registro de equipo de cómputo <br> A=Alcanzado<br> E=Esperado.</td> </tr> </table> */ ?> <?php } else { echo "<br><br><div class='alert alert-danger text-center'><h2 >¡No existen datos en la fecha seleccionada!</h2></div>" ;} ?><file_sep><?php if(count($incidencias)>0){ ?> <table class="table table-bordered table-condensed table-striped"> <thead class="text-primary"> <th class="text-primary" style="text-align: center;">Item</th> <th class="text-primary" style="text-align: center;">Fecha Límite</th> <th class="text-primary" style="text-align: center;">Fecha Entrega</th> <th class="text-primary" style="text-align: center;">N° Atención Realizada</th> <th class="text-primary" style="text-align: center;">N° Atención Terminada</th> <th class="text-primary" style="text-align: center;">Grado de Cumplimiento</th> </thead> <tbody> <?php $cantidadAT=''; $totalR=''; $preciototal=''; ?> <?php foreach ($incidencias as $key => $incidencia) { ?> <tr class="text-primary" style="text-align: center;"> <td><?= $incidencia->idincidencia ?></td> <td><?= $incidencia->fecha_creacion ?></td> <td><?= $incidencia->fecha_completa ?></td> <td>1</td> <td><?= $at=($incidencia->fecha_completa==$incidencia->fecha_creacion)?'1':'0' ?></td> <td><?= ($incidencia->fecha_completa==$incidencia->fecha_creacion)?'100':'0' ?>%</td> </tr> <?php $cantidadAT = $cantidadAT+$at; } ?> <tfoot> <tr class="text-danger" style="text-align: center;"> <td><strong> Total:</strong></td> <td><strong></strong></td> <td><strong></strong></td> <td><strong><?= $totalR = count($incidencias)?></strong></td> <td><strong><?= $cantidadAT ?></strong></td> <td><strong><?= round(($cantidadAT/$totalR)*100,2) ?>%</strong></td> </tr> </tfoot> </tbody> </table> <?php /* <br> <table class="table table-bordered table-condensed" style="text-align: center;"> <thead> <th style="text-align: center;">Grado de cumplimiento</th> </thead> <tr> <td> <strong>(RA/CA*TA)</strong> / <strong>(RE/CE*TE)</strong> </td> </tr> <tr> <td> </td> </tr> <tr> <td class="text-info"><strong>Dónde:</strong><br>R= Registro de equipo de cómputo <br> C = Costo<br> T= Tiempo<br> A=Alcanzado<br> E=Esperado.</td> </tr> </table>*/ ?> <?php } else { echo "<br><br><div class='alert alert-danger text-center'><h2 >¡No existen datos en la fecha seleccionada!</h2></div>" ;} ?><file_sep><?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateComponentesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('componentes', function (Blueprint $table) { $table->engine = 'InnoDB'; $table->increments('idcomponente'); $table->string('componente', 50); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('componentes'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Incidencia extends Model { protected $primaryKey = 'idincidencia'; protected $table = 'incidencia'; protected $fillable = ['idincidencia', 'idcliente', 'marca', 'modelo', 'serie', 'descripcion',/*cambiar por descripcion*/ 'tipo', 'condicion', 'prioridad', 'estado', 'idtecnico', 'diagnostico', 'descripcion_tecnico']; } <file_sep><?php namespace App\Http\Controllers; use Storage; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; use App\User; use App\Rol; use Validator; use Yajra\Datatables\Datatables; class UsuarioController extends Controller { public function index() { $data['titulo'] = "Lista de Usuarios"; return view("admin.usuarios.usuarios",$data); } public function perfil(){ $data['titulo'] = "Perfil de Usuario"; return view("admin.usuarios.perfil",$data); } public function modal($modal='new',$iduser=null){ $data['roles'] = Rol::all(); if($modal=="new") return view('admin.usuarios.nuevo_usuario',$data); else{ $data['user'] = User::find($iduser); $data['idrol'] = $data['user']->idrol; return view('admin.usuarios.edit_usuario',$data); } } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $validator = Validator::make($request->all(), [ 'nombre' => 'required|min:4|max:40|string', 'apellido' => 'required|min:4|max:40|string', 'correo' => 'required|email|unique:users,email', 'usuario' => 'required|min:4|max:40|alpha_num|unique:users,usuario', 'password' => '<PASSWORD>', 'rol' => 'required|digits_between:1,2|numeric' ]); if ($validator->fails()) { $messages = $validator->errors(); return response()->json($messages); }else{ $User = new User; $User->name = $request->nombre; $User->apellido = $request->apellido; $User->email = $request->correo; $User->usuario = $request->usuario; $User->password = <PASSWORD>($request->password); $User->idrol = $request->rol; $User->estado = 1; return response()->json($User->save()); } } public function editprofile(Request $request) { $validator = Validator::make($request->all(), [ 'nombre' => 'required|min:4|max:40|string', 'apellido' => 'required|min:4|max:40|string', 'correo' => 'required|email|unique:users,email,'.$request->user()->id, 'usuario' => 'required|min:4|max:40|alpha_num', ]); if ($validator->fails()) { $messages = $validator->errors(); return response()->json($messages); }else{ $User = User::find($request->user()->id); $User->name = $request->nombre; $User->apellido = $request->apellido; $User->email = $request->correo; $User->usuario = $request->usuario; return response()->json($User->save()); } } public function editimage(Request $request){ $validator = Validator::make($request->all(), [ 'file-input' => 'required|mimes:jpeg,bmp,png,gif|max:20000' ]); if ($validator->fails()) { $messages = $validator->errors(); return response()->json($messages); }else{ $uniq = uniqid(); $img =Storage::put( 'avatars/'.$request->user()->id.'-'.$uniq.'.jpg', file_get_contents($request->file('file-input')->getRealPath()) ); if($img){ $User = User::find($request->user()->id); $User->image = 'storage/avatars/'.$request->user()->id.'-'.$uniq.'.jpg'; $User->save(); } } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { //print_r($request->all()); $validator = Validator::make($request->all(), [ 'nombre' => 'required|min:4|max:40|string', 'apellido' => 'required|min:4|max:40|string', 'correo' => 'required|email|unique:users,email,'.$id, 'usuario' => 'required|min:4|max:40|alpha_num|unique:users,usuario,'.$id, 'password' => '<PASSWORD>', 'rol' => 'required|digits_between:1,2|numeric', 'estado' => 'required|digits_between:0,1|numeric' ]); if ($validator->fails()) { $messages = $validator->errors(); return response()->json($messages); }else{ $User = User::find($id); $User->name = $request->nombre; $User->apellido = $request->apellido; $User->email = $request->correo; $User->usuario = $request->usuario; if(!empty($request->password)){ $User->password = <PASSWORD>($request->password); } $User->idrol = $request->rol; $User->estado = $request->estado; return response()->json($User->save()); } } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } public function anyData(){ //$datos = User::select([])->get(); return Datatables::of(User::all()) ->addColumn('check',function($user){ return '<label class="pos-rel"><input type="checkbox" class="ace"><span class="lbl" id="'.$user->id.'"></span></label>'; }) ->addColumn('rol',function($user){ if($user->idrol==1){ $rol = "Administrador"; } elseif ($user->idrol==2) { $rol = "Técnico"; } elseif ($user->idrol==3) { $rol = "Recepcionista"; } return $rol; }) ->addColumn('estado',function($user){ if($user->estado==1){ $estado = '<span class="label label-info">Activo</span>'; } elseif ($user->estado==0) { $estado = '<span class="label label-warning">Inactivo</span>'; } return $estado; }) /*->addColumn('avatar',function($user){ return '<img src="'.$user->image.'" width="40">'; })*/ ->addColumn('edit',function($user){ return '<a ng-click="modalUser(2,'.$user->id.')" class="green"><i class="ace-icon fa fa-pencil bigger-130"></i></a>'; }) ->make(true); } public function dataUser($id=null){ if(empty($id)) return response()->json(User::all()); else return response()->json(User::find($id)); } public function getUser($field,$value){ return User::where($field,'like','%{$value}')->get(); } } <file_sep>app.controller('UsuariosController', function ($scope, $compile, $http, API_URL, UsuariosFactory) { var rowCompiler = function (nRow, aData, iDataIndex) { var element, linker; linker = $compile(nRow); element = linker($scope); return nRow = element; }; var options = { autoWidth: false, processing: true, serverSide: true, ajax: UsuariosFactory.ajax, fnCreatedRow: rowCompiler, columns: UsuariosFactory.columns, language: { "url": UsuariosFactory.idioma } }; $scope.save = function () { var url = API_URL + "usuario/perfil"; $scope.errorNombre = ''; $scope.errorNombreShow = ''; $scope.errorApellido = ''; $scope.errorCorreo = ''; $scope.errorUsuario = ''; $http({ method: 'POST', url: url, data: $.param($scope.usuario), headers: {'Content-Type': 'application/x-www-form-urlencoded'} }).success(function (response) { console.log(response); //alert(response.nombre); if (response === true) { alert("Se actualizo correctamente"); $scope.nombreTitulo = $scope.usuario.nombre + ' ' + $scope.usuario.apellido; } else { $scope.errorNombre = response.nombre; $scope.errorNombreShow = response.nombre; $scope.errorApellido = response.apellido; $scope.errorCorreo = response.correo; $scope.errorUsuario = response.usuario; } }).error(function (response) { console.log(response); alert('Ha Ocurrido un error'); }); } $scope.guardarUsuario = function () { var url = API_URL + "usuario"; $scope.errorNombre = ''; $scope.errorApellido = ''; $scope.errorCorreo = ''; $scope.errorUsuario = ''; $scope.errorPassword = ''; $scope.errorRol = ''; console.log($scope.usuario.nombre); $http({ method: 'POST', url: url, data: $.param($scope.usuario), headers: {'Content-Type': 'application/x-www-form-urlencoded'} }).success(function (response) { console.log(response); //alert(response.nombre); if (response === true) { $.gritter.add({ title: 'Notificación', text: '¡El Usuario se guardó correctamente!', //sticky: true, class_name: 'gritter-info' }); $('#modalEdit').modal('hide'); var table = $('#users-table').DataTable(); table.ajax.reload(); } else { $scope.errorNombre = response.nombre; $scope.errorApellido = response.apellido; $scope.errorCorreo = response.correo; $scope.errorUsuario = response.usuario; $scope.errorPassword = <PASSWORD>; $scope.errorRol = response.rol; } }).error(function (response) { alert('Ha Ocurrido un error'); }); } $scope.editarUsuario = function(){ var url = API_URL + "usuario/" + $scope.usuario.id; $scope.errorNombre = ''; $scope.errorApellido = ''; $scope.errorCorreo = ''; $scope.errorUsuario = ''; $scope.errorPassword = ''; $scope.errorRol = ''; $scope.errorEstado = ''; //console.log($.param($scope.usuario)); var datos = $( "#frmusuario" ).serialize(); //console.log(str); $http({ method: 'POST', url: url, data: datos, headers: {'Content-Type': 'application/x-www-form-urlencoded'} }).success(function (response) { console.log(response); if (response === true) { //alert("Se actualizó usuario correctamente"); //$('#gritter-center').on(ace.click_event, function(){ $.gritter.add({ title: 'Notificación', text: '!El Usuario se actualizó correctamente', //sticky: true, class_name: 'gritter-info' }); //return false; //}); $('#modalEdit').modal('hide'); var table = $('#users-table').DataTable(); table.ajax.reload(); } else { $scope.errorNombre = response.nombre; $scope.errorApellido = response.apellido; $scope.errorCorreo = response.correo; $scope.errorUsuario = response.usuario; $scope.errorPassword = <PASSWORD>; $scope.errorRol = response.rol; $scope.errorEstado = response.estado; } }).error(function (response) { alert('Ha Ocurrido un error'); console.log(response); }); } $scope.modalUser = function (modal, iduser) { $scope.usuario = ""; var time = new Date().getTime(); if (modal == "new") { $scope.urlmodal = API_URL + "usuario/modal/new?" + time; } else { $http.get(API_URL + 'usuario/getdata/' + iduser).success(function (data, status) { $scope.usuario = data; }); $scope.urlmodal = API_URL + "usuario/modal/edit/" + iduser + "?" + time; } $('#modalEdit').modal('show'); } $scope.loadTable = function () { $('#users-table').dataTable(options); } });
f0c4653e855456c0ded1da1ad12ac9b8dd375182
[ "Markdown", "JavaScript", "PHP" ]
22
PHP
garevalo/incidencias
903dacbc5ef84426206af500095c383d53ffa243
4e7cb2c4bde05a953363b9fa615f8daa9909133b
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Graphics; namespace Ricardo15.Droid { /// <summary> /// inherits Category and handles image for Android platform /// </summary> public class CategoryD : Category { protected override void SetImage() { byte[] imageBytes = Convert.FromBase64String(imgbase); img = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length); } } }<file_sep>using Foundation; using UIKit; namespace Ricardo15.iOS { [Register ("AppDelegate")] public class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { Config.data = new Data(); Window = new UIWindow(UIScreen.MainScreen.Bounds); var controller = new VCCategoryList(); var navController = new UINavigationController(controller); //navController.NavigationBar.SetBackgroundImage(new UIImage(), UIBarMetrics.Default); //navController.NavigationBar.ShadowImage = new UIImage(); //navController.NavigationBar.BackgroundColor = UIColor.Clear; //navController.NavigationBar.Translucent = true; Window.RootViewController = navController; Window.MakeKeyAndVisible(); return true; } public override void OnResignActivation (UIApplication application) { // Invoked when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) // or when the user quits the application and it begins the transition to the background state. // Games should use this method to pause the game. } public override void DidEnterBackground (UIApplication application) { // Use this method to release shared resources, save user data, invalidate timers and store the application state. // If your application supports background exection this method is called instead of WillTerminate when the user quits. } public override void WillEnterForeground (UIApplication application) { // Called as part of the transiton from background to active state. // Here you can undo many of the changes made on entering the background. } public override void OnActivated (UIApplication application) { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } public override void WillTerminate (UIApplication application) { // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. } } } <file_sep>using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using Android.Content.PM; namespace Ricardo15.Droid { /// <summary> /// Main activity - shows categories and search textbox /// </summary> [Activity (Label = "Ricardo15.Android", MainLauncher = true, Icon = "@drawable/icon", Theme = "@style/Theme.Splash", LaunchMode = Android.Content.PM.LaunchMode.SingleInstance, ScreenOrientation = ScreenOrientation.Portrait)] public class MainActivity : Activity { private ListView lstCategories; private EditText txtSearch; protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); Config.data = new Data(); SetContentView(Resource.Layout.Base); lstCategories = FindViewById<ListView>(Resource.Id.listviewCategories); txtSearch = FindViewById<EditText>(Resource.Id.editextSearch); var categoriesAdapter = new Adapters.CategoriesAdapter(this, Config.data); lstCategories.Adapter = categoriesAdapter; txtSearch.KeyPress += TxtSearch_KeyPress; lstCategories.ItemClick += LstCategories_ItemClick; Window.SetSoftInputMode(SoftInput.StateHidden); } private void TxtSearch_KeyPress(object sender, View.KeyEventArgs e) { string s = txtSearch.Text.Trim(); if(e.KeyCode == Keycode.Enter && s != "") ShowDeals("", s); } private void LstCategories_ItemClick(object sender, AdapterView.ItemClickEventArgs e) { Category c = Config.data._categories[e.Position]; ShowDeals(c.ID, ""); } private async void ShowDeals(string categoryID, string searchCriteria) { Config.data.FillDeals(categoryID, searchCriteria); var activityDL = new Intent(this, typeof(DealListActivity)); StartActivity(activityDL); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Content.PM; namespace Ricardo15.Droid { /// <summary> /// Shows list of deals based on search or chosen category /// </summary> [Activity(Label = "DealList", Theme = "@style/Theme.Splash", ScreenOrientation = ScreenOrientation.Portrait)] public class DealListActivity : Activity { private ListView lstDeals; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.DealList); lstDeals = FindViewById<ListView>(Resource.Id.listviewDealList); var deallistAdapter = new Adapters.DealListAdapter(this, Config.data); lstDeals.Adapter = deallistAdapter; lstDeals.ItemClick += LstDeals_ItemClick; } private void LstDeals_ItemClick(object sender, AdapterView.ItemClickEventArgs e) { Config.data.SelectedDeal = e.Position; var activityDL = new Intent(this, typeof(DealActivity)); StartActivity(activityDL); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Content.PM; namespace Ricardo15.Droid { /// <summary> /// Shows chosen deal /// </summary> [Activity(Label = "DealActivity", Theme = "@style/Theme.Deal", ScreenOrientation = ScreenOrientation.Portrait)] public class DealActivity : Activity { private TextView lblTitle, lblDescription; private ImageView imgView; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.Deal); lblTitle = FindViewById<TextView>(Resource.Id.titleDeal); lblDescription = FindViewById<TextView>(Resource.Id.descriptionDeal); imgView = FindViewById<ImageView>(Resource.Id.imageDeal); DealObject d = Config.data.GetSelectedDeal(); lblTitle.Text = d.Title; lblDescription.Text = d.Description; imgView.SetImageBitmap((Android.Graphics.Bitmap)d.BMP); } } }<file_sep>using System; using System.Drawing; using CoreFoundation; using UIKit; using Foundation; using CoreGraphics; namespace Ricardo15.iOS { /// <summary> /// Main controller - shows categories and search textbox /// </summary> [Register("VCCategoryList")] public class VCCategoryList : TransparentViewController { public VCCategoryList() { } public override void DidReceiveMemoryWarning() { base.DidReceiveMemoryWarning(); } public override void ViewDidLoad() { base.ViewDidLoad(); nfloat w = View.Bounds.Width; nfloat h = View.Bounds.Height; int cellh = Convert.ToInt32((h - 182) / 6); //105; View.BackgroundColor = UIColor.White; UIGraphics.BeginImageContext(this.View.Frame.Size); UIImage i = UIImage.FromBundle("Splash"); i = i.Scale(this.View.Frame.Size); View.BackgroundColor = UIColor.FromPatternImage(i); UITextField searchField = new UITextField { Placeholder = "Search", BorderStyle = UITextBorderStyle.RoundedRect, Frame = new CGRect(20, 90, w - 40, 31.0f) }; searchField.ShouldReturn += SearchDeals; View.AddSubview(searchField); for (int j = 0; j < Config.data._categories.Count; j++) { int y = 125 + j * cellh; Category c = Config.data._categories[j]; UIButton btnCategory = UIButton.FromType(UIButtonType.Custom); btnCategory.Frame = new CoreGraphics.CGRect(20, y, 128, cellh); btnCategory.SetImage((UIImage)c.BMP, UIControlState.Normal); btnCategory.Tag = Convert.ToInt32(c.ID); btnCategory.TouchUpInside += BtnCategory_TouchUpInside; View.AddSubview(btnCategory); UILabel lblTitle = new UILabel(new CoreGraphics.CGRect(150, y, w - 170, 34)); lblTitle.Text = c.Name; View.AddSubview(lblTitle); if (cellh > 79) { UILabel lblCount = new UILabel(new CoreGraphics.CGRect(150, y + 45, w - 170, 34)); lblCount.Text = c.Count.ToString() + " deals"; View.AddSubview(lblCount); } } } private void BtnCategory_TouchUpInside(object sender, EventArgs e) { UIButton btnClicked = (UIButton)sender; nint k = btnClicked.Tag; ShowDeals(k.ToString(), ""); } private bool SearchDeals(UITextField textField) { string srch = textField.Text.Trim(); ShowDeals("", srch); return false; } private async void ShowDeals(string categoryID, string searchCriteria) { Config.data.FillDeals(categoryID, searchCriteria); var controller2 = new VCDealList(); this.NavigationController.PushViewController(controller2, true); } } }<file_sep>using System; using System.Collections.Generic; using System.Text; namespace Ricardo15 { public static class Config { public static Data data; } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace Ricardo15 { public class DealObject { protected string imgbase; protected object img; public string ID { get; set; } public string CategoryID { get; set; } public string Title { get; set; } public string Description { get; set; } public string ImageBase { get { return imgbase; } set { imgbase = value; SetImage(); } } public object BMP { get { return img; } } protected virtual void SetImage() { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace Ricardo15.Droid.Adapters { class CategoriesAdapter : BaseAdapter { private Activity _activity; private Data _dat; public CategoriesAdapter(Activity activity, Data dat) { _activity = activity; _dat = dat; } public override int Count { get { return _dat._categories.Count; } } public override Java.Lang.Object GetItem(int position) { return null; } public override long GetItemId(int position) { return position; } public override View GetView(int position, View convertView, ViewGroup parent) { int n = position; var view = convertView ?? _activity.LayoutInflater.Inflate(Resource.Layout.CategoryItem, parent, false); var item1 = view.FindViewById<ImageView>(Resource.Id.imageCategory); var item2 = view.FindViewById<TextView>(Resource.Id.titleCategory); var item3 = view.FindViewById<TextView>(Resource.Id.noteCategory); if (n > -1) { Category z = _dat._categories[n]; item1.SetImageBitmap((Android.Graphics.Bitmap)z.BMP); item2.Text = z.Name; item3.Text = z.Count.ToString() + " deals"; } return view; } } }<file_sep>using System; using System.Drawing; using CoreFoundation; using UIKit; using Foundation; namespace Ricardo15.iOS { [Register("TransparentViewController")] public class TransparentViewController : UIViewController { public TransparentViewController() { } public override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); if (NavigationController != null) { NavigationController.NavigationBar.SetBackgroundImage(new UIImage(), UIBarMetrics.Default); NavigationController.NavigationBar.ShadowImage = new UIImage(); NavigationController.NavigationBar.Translucent = true; NavigationController.View.BackgroundColor = UIColor.Clear; NavigationController.NavigationBar.BackgroundColor = UIColor.Clear; } } public override void ViewWillDisappear(bool animated) { base.ViewWillDisappear(animated); if (NavigationController != null) { NavigationController.NavigationBar.SetBackgroundImage(null, UIBarMetrics.Default); NavigationController.NavigationBar.ShadowImage = null; NavigationController.NavigationBar.BarTintColor = UIColor.White; } } } }<file_sep>using Foundation; using System; using UIKit; namespace Ricardo15.iOS { /// <summary> /// inherits Category and handles image for iOS platform /// </summary> public class CategoryI : Category { protected override void SetImage() { byte[] imageBytes = Convert.FromBase64String(imgbase); NSData data = NSData.FromArray(imageBytes); img = UIImage.LoadFromData(data); } } } <file_sep>using System; using System.Drawing; using CoreFoundation; using UIKit; using Foundation; namespace Ricardo15.iOS { /// <summary> /// Shows list of deals based on search or chosen category /// </summary> [Register("VCDealList")] public class VCDealList : TransparentViewController { public VCDealList() { } public override void DidReceiveMemoryWarning() { base.DidReceiveMemoryWarning(); } public override void ViewDidLoad() { base.ViewDidLoad(); nfloat w = View.Bounds.Width; nfloat h = View.Bounds.Height; int cellh = Convert.ToInt32((h - 182) / 6); View.BackgroundColor = UIColor.White; UIGraphics.BeginImageContext(this.View.Frame.Size); UIImage i = UIImage.FromBundle("Splash"); i = i.Scale(this.View.Frame.Size); View.BackgroundColor = UIColor.FromPatternImage(i); for (int j = 0; j < Config.data._deals.Count; j++) { int y = 100 + j * cellh; DealObject d = Config.data._deals[j]; UIButton btnDeal = UIButton.FromType(UIButtonType.Custom); btnDeal.Frame = new CoreGraphics.CGRect(20, y, 128, cellh); btnDeal.SetImage((UIImage)d.BMP, UIControlState.Normal); btnDeal.Tag = j; btnDeal.TouchUpInside += btnDeal_TouchUpInside; View.AddSubview(btnDeal); UILabel lblTitle = new UILabel(new CoreGraphics.CGRect(150, y, w - 170, cellh)); lblTitle.Lines = 3; lblTitle.Text = d.Title; View.AddSubview(lblTitle); } } private void btnDeal_TouchUpInside(object sender, EventArgs e) { UIButton btnClicked = (UIButton)sender; nint k = btnClicked.Tag; Config.data.SelectedDeal = (int)k; var controller2 = new VCDeal(); this.NavigationController.PushViewController(controller2, true); } } }<file_sep>using System; using System.Drawing; using CoreFoundation; using UIKit; using Foundation; namespace Ricardo15.iOS { /// <summary> /// Shows chosen deal /// </summary> [Register("VCDeal")] public class VCDeal : TransparentViewController { public VCDeal() { } public override void ViewDidLoad() { base.ViewDidLoad(); nfloat w = View.Bounds.Width; nfloat h = View.Bounds.Height; View.BackgroundColor = UIColor.White; View.TintColor = UIColor.Black; DealObject d = Config.data.GetSelectedDeal(); UILabel lblTitle = new UILabel(new CoreGraphics.CGRect(20, 65, w - 40, 60)); lblTitle.Lines = 2; lblTitle.Text = d.Title; View.AddSubview(lblTitle); UIImageView imageView = new UIImageView(); imageView.Image = (UIImage)d.BMP; imageView.Frame = new CoreGraphics.CGRect(40, 130, 128, 128); View.AddSubview(imageView); UILabel lblDescription = new UILabel(new CoreGraphics.CGRect(10, 270, w - 20, h - 270)); lblDescription.Lines = 25; lblDescription.Text = d.Description; View.AddSubview(lblDescription); } } }<file_sep># RicardoCodeChallenge Code Challenge for job position "Mobile Software Engineer" iOS version tested on simulators : iPhone X, iPhone 8 plus and iPad Air 2 Android version tested on devices: LG G5 (LG-H850) and Samsung S5 (G900F) Could not implement MVVM binding without Xamarin Forms Included: - Cross-platform project "Ricardo15" for VisualStudio 2015 - sql script for the database used as a model - pdf with code challenge <file_sep>using System; namespace Ricardo15 { public class Category { protected string imgbase; protected object img; protected int numberofitems = 0; public string ID { get; set; } public string Name { get; set; } public int Count { get { return numberofitems; } set { numberofitems = value; } } public string ImageBase { get { return imgbase; } set { imgbase = value; SetImage(); } } public object BMP { get { return img; } } public override string ToString() { return (Name); } protected virtual void SetImage() { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Util; using Android.Content.Res; namespace Ricardo15.Droid.Adapters { class DealListAdapter : BaseAdapter { private Activity _activity; private Data _dat; public DealListAdapter(Activity activity, Data dat) { _activity = activity; _dat = dat; } public override int Count { get { return _dat._deals.Count; } } public override Java.Lang.Object GetItem(int position) { return position; } public override long GetItemId(int position) { return position; } public override View GetView(int position, View convertView, ViewGroup parent) { int n = position; var view = convertView ?? _activity.LayoutInflater.Inflate(Resource.Layout.DealListItem, parent, false); var item1 = view.FindViewById<ImageView>(Resource.Id.imageDealList); var item2 = view.FindViewById<TextView>(Resource.Id.titleDealList); if (n > -1) { DealObject z = _dat._deals[n]; item1.SetImageBitmap((Android.Graphics.Bitmap)z.BMP); item2.Text = z.Title; } return view; } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Reflection; namespace Ricardo15 { /// <summary> /// Class that handles data for both platforms /// </summary> public class Data { public List<Category> _categories = new List<Category>(); public List<DealObject> _alldeals = new List<DealObject>(); public List<DealObject> _deals = new List<DealObject>(); public int SelectedDeal = -1; private string errmess = ""; public Data() { LoadXMLData(); } public string LastErrorMessage { get { return errmess; } } /// <summary> /// Loads data from xml files /// </summary> private async void LoadXMLData() { #if __ANDROID__ string resPrefix = "Ricardo15.Droid."; #endif #if __IOS__ string resPrefix = "Ricardo15.iOS."; #endif try { var assembly = Assembly.GetExecutingAssembly(); Stream stream = assembly.GetManifestResourceStream(resPrefix + "CATEGORIES.xml"); //await Task.Factory.StartNew(delegate //for some reason does not work in iOS, hence omitted //{ XmlDocument doc = new XmlDocument(); doc.Load(stream); foreach (XmlNode s in doc.SelectSingleNode("DEALS").ChildNodes) { #if __ANDROID__ Category cat = new Ricardo15.Droid.CategoryD(); #endif #if __IOS__ Category cat = new Ricardo15.iOS.CategoryI(); #endif cat.ID = s.SelectSingleNode("ID").InnerText; cat.Name = s.SelectSingleNode("NAME").InnerText; cat.ImageBase = s.SelectSingleNode("IMAGE").InnerText; _categories.Add(cat); } //}); stream = assembly.GetManifestResourceStream(resPrefix + "DEALS.xml"); //await Task.Factory.StartNew(delegate //{ XmlDocument docD = new XmlDocument(); docD.Load(stream); foreach (XmlNode s in docD.SelectSingleNode("DEALS").ChildNodes) { #if __ANDROID__ DealObject d = new Ricardo15.Droid.DealD(); #endif #if __IOS__ DealObject d = new Ricardo15.iOS.DealI(); #endif d.ID = s.SelectSingleNode("ID").InnerText; d.CategoryID = s.SelectSingleNode("CATEGORYID").InnerText; int k = Convert.ToInt32(d.CategoryID); _categories[k - 1].Count++; d.Title = s.SelectSingleNode("TITLE").InnerText; d.Description = s.SelectSingleNode("DESCRIPTION").InnerText; d.ImageBase = s.SelectSingleNode("IMAGE").InnerText; _alldeals.Add(d); } //}); } catch (Exception exc) { errmess = exc.Message; } } /// <summary> /// Based on search word or chosen category, fills list _deals with appropriate ones /// </summary> public void FillDeals(string catID, string searchCriteria) { searchCriteria = searchCriteria.ToLower(); _deals = new List<DealObject>(); foreach (DealObject d in _alldeals) { if ((catID != "" && catID == d.CategoryID) || (searchCriteria != "" && (d.Title.ToLower().Contains(searchCriteria) || d.Description.ToLower().Contains(searchCriteria)))) _deals.Add(d); } } /// <summary> /// Returns selected deal /// </summary> public DealObject GetSelectedDeal() { if (SelectedDeal > -1 && SelectedDeal < _deals.Count) return _deals[SelectedDeal]; return new DealObject(); } } }
ef5b5d0aa056cb0869f1c48e529b936657cfdeb7
[ "Markdown", "C#" ]
17
C#
drpesic/RicardoCodeChallenge
ba2380770ba666136dcc965022360479edf6cd08
078bfe60cef6a61b75b51d4e3c65fae0820a7516
refs/heads/main
<file_sep>//DISPLAY window.onload = function(){ pantalla=document.getElementById('Display'); } //CONTROL DE PANTALLA let x=0; //Colocamos 0 en base al valor generico en pantalla, lo utlizamos como medio de sustitucin a la hora se insertar nuevos valores. let xi=1; //En esta variable se colcoca como asemejansa a un valor tipo booleano, estara en 1 cuando debamos escribir un nuevo numero en pantalla yestaran en 0 cuando al escribir en la pantalla estemos añaniendo cifras para completar un numero. let coma=0; //Esta variable nos permite controlar los numeros decimales. //FUNCIONES PARA VISUALIZAR LOS NUMEROS function numero(xx){ if(x=="0" || xi==1){ pantalla.innerHTML=xx; x==xx; }else{ pantalla.innerHTML+=xx; x+=xx; } xi=0 } function numero(xx){ if (x=="0" || xi==1) { pantalla.innerHTML=xx; x=xx; if (xx=="."){ pantalla.innerHTML="0."; x=xx; coma=1; } } else { if(xx=="." && coma==0) { pantalla.innerHTML+=xx; x+=xx; coma=1; }else if (xx=="." && coma==1) {} else{ pantalla.innerHTML+=xx; x+=xx } } xi=0 } //Operar function operar(s){ ni=x; op=s; xi=1; } //Igual function igualar(){ if(op=="no"){ pantalla.innerHTML=x; }else{ sl=ni+op+x; sol=eval(sl); pantalla.innerHTML=sol; x=sol; op="no"; xi=1; } } //FUNCION CLEAR PARCIAL function borradoParcial() { pantalla.innerHTML=0; x=0; coma=0; } //FUNCION CLEAR TOTAL function totalClear() { pantalla.innerHTML=0; x="0"; coma=0; ni=0; op="no" }
d7ad92eae7adbecec154bd580e7c4a2722c3c648
[ "JavaScript" ]
1
JavaScript
FranciscoMontenegro97/Calculadora
68e9cdcc76a468941163b7371105c8de3c53cddb
9d4804151d194d654bc61c25c2ec1efc0a1ea520
refs/heads/master
<file_sep>dogeweather =========== Such Weather http://dogeweather.com This fork is an Android Widget! Play store link: https://play.google.com/store/apps/details?id=com.tobbentm.dogeweather Also opens another awesome dogeweather app when clicked; https://github.com/VersoBit/WeatherDoge ![Screenshot](http://tobbentm.com/ul/dogeweather.png "Screenshot") License =========== dogeweather is licensed under the MIT license. (http://opensource.org/licenses/MIT) <file_sep>package com.tobbentm.dogeweather; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; /** * Created by Tobias on 28.01.14. */ public class suchprovider extends AppWidgetProvider { @Override public void onUpdate (Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){ ComponentName thisWidget = new ComponentName(context, suchprovider.class); int[] allWidgets = appWidgetManager.getAppWidgetIds(thisWidget); Intent intent = new Intent(context.getApplicationContext(), veryService.class); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgets); context.startService(intent); } } <file_sep>package com.tobbentm.dogeweather; import android.app.Activity; import android.app.AlertDialog; import android.appwidget.AppWidgetManager; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; /** * Created by Tobias on 04.03.14. */ public class muchConfig extends Activity { SharedPreferences sp; int wID; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.configlayout); sp = getSharedPreferences("so_conf", 0); Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null) { wID = extras.getInt( AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); } Intent resultValue = new Intent(); resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, wID); setResult(RESULT_CANCELED, resultValue); } private void configDone(){ Intent result = new Intent(); result.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, wID); setResult(RESULT_OK, result); //Ugly hack, please forgive me new suchprovider().onUpdate(this, AppWidgetManager.getInstance(this), new int[]{wID}); finish(); } public void btnAuto(View view) { String loc = "auto"; SharedPreferences.Editor editor = sp.edit(); editor.putString("loc", loc); editor.commit(); configDone(); } public void btnManual(View view) { String loc = ((EditText)findViewById(R.id.really_input)) .getText().toString().replaceAll(" ", "%20"); String url = "http://api.openweathermap.org/data/2.5/find?q="+loc+"&mode=json"; findViewById(R.id.plz_button).setEnabled(false); AsyncHttpClient cli = new AsyncHttpClient(); cli.get(url, new AsyncHttpResponseHandler(){ @Override public void onSuccess(String json){ Log.d("DOGE! - Search\t\t", json); JSONArray list = null; ArrayList<String> cityList = new ArrayList<String>(); try { JSONObject jsonObj = new JSONObject(json); list = jsonObj.getJSONArray("list"); for(int i = 0; i < list.length(); i++){ cityList.add(list.getJSONObject(i).getString("name") +", "+list.getJSONObject(i).getJSONObject("sys").getString("country")); } } catch (JSONException e) { e.printStackTrace(); } buildDialog(list, cityList.toArray(new String[cityList.size()])); } }); } private void buildDialog(final JSONArray list, String[] cityList){ AlertDialog.Builder dialog = new AlertDialog.Builder(this); dialog.setTitle(R.string.dialog_title); if(list != null && list.length() > 0){ if(list.length() == 1){ SharedPreferences.Editor editor = sp.edit(); try { editor.putString("loc", list.getJSONObject(0).getString("id")); } catch (JSONException e) { e.printStackTrace(); } editor.commit(); configDone(); }else{ dialog.setItems(cityList, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { SharedPreferences.Editor editor = sp.edit(); try { editor.putString("loc", list.getJSONObject(which).getString("id")); } catch (JSONException e) { e.printStackTrace(); } editor.commit(); configDone(); } }); } }else{ dialog.setMessage(R.string.dialog_error); findViewById(R.id.plz_button).setEnabled(true); } dialog.show(); } }
7d3329a6cd433139073f9b2e90002766c6f1bba1
[ "Markdown", "Java" ]
3
Markdown
TobbenTM/dogeweather
558ab080b1a6d9e146093163f93362035bdbea3f
8302cd4b80c4874a9f6e2a5778e96107b255d97a
refs/heads/master
<file_sep>package dynamicProgramming; import java.util.*; public class Huffman { private String input; private Node huffmanTree; //the huffman tree private Map<Character, String> mapping; //maps characters to binary strings /** * The Huffman constructor * */ public Huffman(String input) { this.input = input; mapping = new HashMap<>(); //first, we create a map from the letters in our string to their frequencies Map<Character, Integer> freqMap = getFreqs(input); //we'll be using a priority queue to store each node with its frequency, //as we need to continually find and merge the nodes with smallest frequency PriorityQueue<Node> huffman = new PriorityQueue<>(); /* * TODO: * 1) add all nodes to the priority queue * 2) continually merge the two lowest-frequency nodes until only one tree remains in the queue * 3) Use this tree to create a mapping from characters (the leaves) * to their binary strings (the path along the tree to that leaf) * * Remember to store the final tree as a global variable, as you will need it * to decode your encrypted string */ //add all nodes to the priority queue for (Map.Entry<Character, Integer> entry : freqMap.entrySet()) { huffman.add(new Node(entry.getKey(), entry.getValue(), null, null)); } //continually merge the two lowest-frequency nodes until only one tree remains in the queue while(huffman.size() > 1) { Node left = huffman.poll(); Node right = huffman.poll(); Node newNode = new Node(null, left.freq + right.freq, left, right); huffman.add(newNode); } //Remember to store the final tree as a global variable, as you will need it //to decode your encrypted string huffmanTree = huffman.poll(); if(huffmanTree.isLeaf()) { huffmanTree.freq = input.length(); } //Use this tree to create a mapping from characters (the leaves) //to their binary strings (the path along the tree to that leaf) constructBinary(huffmanTree, ""); } private void constructBinary(Node el, String bin) { if(el.isLeaf()) { mapping.put(el.letter, bin); } else { if(el.left != null) { constructBinary(el.left, bin + "0"); } if(el.right != null) { constructBinary(el.right, bin + "1"); } } } /** * Use the global mapping to convert your input string into a binary string */ public String encode() { String result = ""; for(int i = 0; i < input.length(); i++) { result += mapping.get(input.charAt(i)); } return result; } /** * Use the huffmanTree to decrypt the encoding back into the original input * * You should convert each prefix-free group of binary numbers in the * encoding to a character * * @param encoding - the encoded string that needs to be decrypted * @return the original string (should be the same as "input") */ public String decode(String encoding) { String result = ""; Node el = huffmanTree; if(!encoding.isEmpty()) { for(int i = 0; i < encoding.length(); i++) { if(el.isLeaf()) { result += el.letter.toString(); el = huffmanTree; i--; } else if(encoding.charAt(i) == '0') { el = el.left; } else if(encoding.charAt(i) == '1') { el = el.right; } } } else { for(int i = 1; i < huffmanTree.freq; i++) { result += huffmanTree.letter.toString(); } } return result + el.letter.toString(); } /** * This function tells us how well the compression algorithm worked * * note that a char is represented internal using 8 bits * * ex. if the string "aabc" maps to "0 0 10 11", we would have * a compression ratio of (6) / (8 * 4) = 0.1875 */ public static double compressionRatio(String input) { Huffman h = new Huffman(input); String encoding = h.encode(); int encodingLength = encoding.length(); int originalLength = 8 * input.length(); return encodingLength / (double) originalLength; } /** * We've given you this function, which helps you create * a frequency map from the input string */ private Map<Character, Integer> getFreqs(String input) { Map<Character, Integer> freqMap = new HashMap<>(); for (char c : input.toCharArray()) { if (freqMap.containsKey(c)) { freqMap.put(c, freqMap.get(c) + 1); } else { freqMap.put(c, 1); } } return freqMap; } /** * An inner Node class to build your huffman tree * * Each node has: * a frequency - the sum of the frequencies of all the node's leaves * a letter - the character that this node represents (only for leaves) * left and right children */ private class Node implements Comparable<Node> { private Character letter; //the letter of this node (only for leaves) private int freq; //frequency of this node private Node left; //add a 0 to you string private Node right; //add a 1 to your string public Node(Character letter, int freq, Node left, Node right) { this.letter = letter; this.freq = freq; this.left = left; this.right = right; } public boolean isLeaf() { return left == null && right == null; } @Override public int compareTo(Node o) { return this.freq - o.freq; } } } <file_sep># Dynamic-Programming-and-Greedy-Algorithms Contains programs for several greedy and dynamic programming algorithms. <b>Part 1: Understanding</b> There are two files (available on Codio) that you will be using: 1) GreedyDynamicAlgorithms 2) Huffman 1) GreedyDynamic Algorithms contains the first part of the homework. In it, you will find two problems: a) optimal intervals b) path through a grid Both of these questions are explained in more detail below. In one of them, a greedy approach can be used to solve the problem. In the other, you will have to use dynamic programming. Your first goal will be to figure out the algorithm that solves each problem! 2) Huffman is a class for encoding strings using the huffman algorithm. More hints for implementing the class are described later, but make sure to understand the algorithm first! An animated example of the algorithm can be found in the lecture slides. <b>Part 2: Greedy and Dynamic:</b> You have two problems to solve, using either greedy or dynamic programming algorithms. Your first job, before writing any code, is to figure out an algorithm that will solve the problem! General tips for a greedy problem: -What is a good top-level question to ask? -Brainstorm some possible greedy choices that the algorithm could make. Can you eliminate any of them with some counter-example inputs? -Can you answer the question right away, and be sure that this will lead to the optimal solution? Remember general tips for a dynamic programming problem: -What is a good top-level decision to make? -What are the base cases for the problem? -Can you come up with a recurrence relation? How can you solve larger problems using the solutions to subproblems? -Will you implement the algorithm iteratively or recursively? If you implement it iteratively, in what order must the subproblems be solved? -If you choose to implement your algorithm recursively, don't forget to memoize the solutions to subproblems. Question a: optimal intervals In this problem, you are given a list of intervals (similar to the activities problem from the lecture slides). Each interval can be defined by a pair of numbers (start, finish), where start is the start time of the interval, and finish is the finish time. However, there's a small twist. Each interval can also be either red or blue. The goal of this problem is to select the fewest number of RED intervals, such that all of the BLUE intervals are "intersected". In order for a blue interval to be "intersected", it must overlap with one of the red intervals that you selected. Note that with this problem, you will not have to output the actual optimal list of red intervals chosen. You only need to output the integer corresponding to the optimal number of red intervals. For example, suppose we're given a list of blue intervals: (0, 2) (5, 5) (7, 10) (11, 13) and a list of red intervals: (0, 4) (2, 5) (4, 8) (9, 10) (9, 11) (10, 12) (11, 12) You may want to draw these intervals out to get a better mental picture. We must choose the fewest number of red intervals such that all 4 blue intervals are intersected. In this case, the optimal answers is 2: we choose the intervals (2, 5) and (10, 12). With these two red intervals, all 4 blue intervals are intersected. Finally, in the case where no solution is possible (it is impossible to cover all of the blue intervals), your solution should return -1. Here are a few hints: 1) Should you use a greedy algorithm or a dynamic programming algorithm? Can you greedily choose a red interval based on some local decision without losing the optimal solution? 2) One idea that you might consider would be to greedily choose the longest red intervals, one at a time, until all blue intervals have been intersected. Surprisingly, this algorithm doesn't work. Can you come up with an example set of red and intervals that causes this algorithm to fail? 3) In the above example, we know that the blue interval (0, 2) must be intersected. The only two red intervals that intersect it are (0, 4) and (2, 5). The optimal solution here uses the interval (2, 5). What makes this interval a better one to use? 4) Pictures help! Try drawing out a few examples as you're coding to help with keeping track of any indices, etc. Finally, implement the optimalIntervals function found in GreedyDynamicAlgorithms.java! One thing to note: we've given you an Interval class with two methods that you may find useful: sortByStartTime() and sortByFinishTime() both take in a list of intervals, and sort them by start and finish time, respectively. Question b: optimal path through a grid In this problem, you are given an mxn grid (a 2d array) of integers, where each value in the grid contains a "cost". You start at position (0, 0) in the grid in the top left corner, and must travel to position (m-1, n-1) in the grid (the bottom right corner). Each time you move in the grid, you are only allowed to move either down or to the right. There is one twist: the value at each spot in the grid denotes the cost of entering that position. Your goal is to figure out an of the optimal path through this grid. For example, suppose we're given this grid: 5 1 1 2 4 7 2 4 5 5 6 3 The path of lowest cost, going from the top-left to the bottom-right portion of the grid, will be the sequence: DOWN DOWN RIGHT RIGHT DOWN. This optimal path has a cost of 5 + 2 + 2 + 4 + 5 + 3 = 21. Any other path through this grid will have a cost at least as large as 21 (note that there could be more than one path with the optimal cost, but in this example there isn't. In the case that there is more than one optimal path, you are free to output any one of these paths). NOTE: You will see that the output of this function is a List<Direction>. We've provided you with a Direction enum, which consists of two possible values: DOWN or RIGHT. For example, the actual list you would output in the example above would look something like: List<Direction> output = new LinkedList<>(); output.add(Direction.DOWN); output.add(Direction.DOWN); output.add(Direction.RIGHT); output.add(Direction.RIGHT); output.add(Direction.DOWN); A few hints for this problem: 1) Should you use a greedy algorithm or a dynamic programming algorithm? Can you greedily choose whether or not to go down or to the right at each spot in the grid without losing the optimal solution? 2) One idea might be to look at the spots immediately down and to the right of your current position in the grid, and move to the spot with a lower cost. This algorithm will fail. Can you come up with a simple grid where this algorithm won't produce the optimal path? <b>Part 3: Huffman Encoding</b> The second part of the homework is to implement the huffman algorithm that you saw in the lecture slides. As with the last homework, you want to familiarize yourself with the algorithm, as well as the animation in the lecture slides, before you jump into the code. Next, we'll walk through the Huffman class. This class takes in an input string in the constructor, and produces two pieces of data (which you should store as global field variables). The 3 field variables in this class that you must store (although you're free to add other field variables if you wish) are: input - the original string to be encoded huffmanTree - This will be your huffman binary tree, which you will create in the constructor. It is of type Node, which is a small class that we've given you (explained below). Remember, the way a huffman tree translates into an encoding is that the leaves of the tree represent characters. The encoding of each character can be expressed by the path taken from the root of the tree to that leaf: going left in the tree denotes adding a "0" to the encoding, while going right in the tree denotes a "1". mapping - A mapping from Characters to binary Strings. You will also create this mapping in the constructor, using your huffmanTree. We've given you two functions in the Huffman class: 1) getFreqs - No need to do anything here, we've used this function for your in the Huffman constructor. It will take in your input string, and convert it into a mapping from each character in the string to its frequency (the number of times that it appears) 2) compressionRatio - You won't be using this function either, but it tells you how well your huffman algorithm compressed the input string (note that we calculate this with the formula (encoded length) / (8 * original length). This is because ascii character require 8 bits to store, while 0s and 1s are only 1 bit each). It also contains 3 main functions for you to implement: 1) Huffman constructor - Takes in the string to be encoded, and creates the huffmanTree as well as the encoding mapping. Remember to refer back to the lecture slides for tips on the algorithm. Your constructor should do a few things: a) create nodes for each character in your string b) add all the nodes to the priority queue c) continue to merge the two nodes with lowest frequency until only one node remains in the priority queue (this will be the final huffman tree) d) use this huffman tree to create the encoding mapping (from characters to binary strings) 2) encode - encodes the "input" string using your encoding mapping, and returns the encoded string (i.e. a string of 1s and 0s) 3) decode - Takes in a binary string, and decodes it. You will need to use the huffmanTree to do this. One important thing to remember is that your huffmanTree is prefix-free. Because of this, each sequence of 1s and 0s in your binary string will correspond to exactly one character in the huffman tree. With all of these functions, here's an example of how you would use the Huffman class: Huffman h = new Huffman("aabc"); String encoding = h.encode; //With this string, we should have the mapping "a"->0, "b"->10, "c"->11. //Thus the encoded string should look like "001011". String decode = h.decode(encoding) //decode should be the same as the original string, "aabc" NOTE: We've given you some starting code in the constructor. First, we wrote a convenient function for you that creates a frequency mapping from a string. Next, we've instantiated a PriorityQueue for you. If you haven't seen this class before, it stores a list of elements (in this case, Nodes), and has two important functions that you will use: add(n) adds a node n to your priority queue. spoll() will extract the node with lowest frequency from your priority queue. These should be the only two functions that you need, but more information can be found by searching for PriorityQueue in the javadocs. NOTE 2: We've also given you a helpful Node class that you will use in your implementation (see at the bottom of the Huffman.java file). Every node contains 4 pieces of data: -the character corresponding to that node (only applies to leaves) -the frequency of that node (remember, when you combine two nodes, the new node outputted should have the sum of their frequencies) -the left and right subtrees of this node. One important thing to note is that only the leaves of your tree will have a character. If your node is not a leaf, its character should be Null. For example, to construct a leaf node you would write Node myLeaf = new Node("a", 5, null, null) //the character "a" shows up 5 times To construct a nonLeaf, you would write Node notLeaf = new Node(null, left.freq + right.freq, left, right) //not a leaf, so it's character should be null. You will also need to know whether or not a given node is a leaf when writing your program. To help with this, we've given you a small function, isLeaf(). As with the last homework, we won't be testing edge cases- the focus will be on implementing the algorithm correctly. Note that one other edge case that we won't test for is any encoding with a single repeated character (ex: "aaaa"). Can you think of why this presents an edge case in the implementation? Now that you've read through the Huffman class, you can implement the 3 functions!
a4752d3bc8fb9e0ddf027b35a40784f1724c78d6
[ "Markdown", "Java" ]
2
Java
sstamoulas/Dynamic-Programming-and-Greedy-Algorithms
85f840d1ed7637b7fe8f8833a100a6907c6c32c2
f25b2b6caaf635bf84c70e759c1a432e163c24dd
refs/heads/main
<file_sep>package gomvc import ( "io/ioutil" "strings" "github.com/getkin/kin-openapi/openapi2" "github.com/getkin/kin-openapi/openapi2conv" "github.com/getkin/kin-openapi/openapi3" yaml "github.com/ghodss/yaml" ) // LoadWithKin loads an OpenAPI spec into memory using the kin-openapi library func LoadWithKin(specPath string) *openapi3.Swagger { loader := openapi3.NewSwaggerLoader() loader.IsExternalRefsAllowed = true oa3, err := loader.LoadSwaggerFromFile(specPath) if err != nil { panic(err) } return oa3 } // LoadSwaggerV2AsV3 takes the file path of a v2 Swagger file and returns a // V3 representation func LoadSwaggerV2AsV3(specPath string) *openapi3.Swagger { swaggerSpec := openapi2.Swagger{} c, err := ioutil.ReadFile(specPath) if err != nil { panic(err) } err = yaml.Unmarshal(c, &swaggerSpec) if err != nil { panic(err) } oa3, err := openapi2conv.ToV3Swagger(&swaggerSpec) if err != nil { panic(err) } return oa3 } // assumes usage of OpenAPI 3.x spec in which component refs are formatted as // '#/componeents/<sub component type>/<user defined component name>' func getComponentName(ref string) string { parts := strings.Split(ref, "/") return parts[len(parts)-1] } <file_sep># GO-MVC ![](https://github.com/go-generation/go-mvc/workflows/test/badge.svg?branch=main) *** **Disclaimer** *** There are no guarantees of API stability until the first major version is released. Think of the current state as an alpha-phase product looking for validation from users about what features make sense and what the best UX is for those features. ## Installation - set up your GOPATH - make sure your regular PATH includes the go binary folder e.g. `/whereveryouinstalled/go/bin` - download dependencies ``` go get golang.org/x/tools/cmd/goimports ``` - download cli ``` go get -u github.com/go-generation/go-mvc/cmd/gomvc ``` ## Commands - `gomvc application` Generate application files - `gomvc help` Help about any command - `gomvc oa` Generate controllers from an OpenAPI yml file - `gomvc resource` Generate resource files - `gomvc seed` Generate seed files - `gomvc swagger` Generate controllers from a v2 Swagger yml file ## Usage Create an application: ``` $ mkdir yourapplication && cd yourapplication $ gomvc application yourapplication ``` Optionally create controllers from your OpenAPI or Swagger 2.0 yaml spec (json support is coming): ``` $ gomvc oa --spec path/to/openapi.yml ``` or ``` $ gomvc swagger --spec path/to/swagger.yml ``` Create more resources: ``` $ gomvc resource dogs ``` ## Swagger vs OpenAPI Disclaimer For ease of parsing, the `gomvc swagger` command currently converts the Swagger spec into an OpenAPI 3 spec. This is done by an underlying library gomvc uses which attempts to convert backwards compatible aspects of the spec. As such there may be some side effects or ignored properties. For example, a Swagger spec lists its reused parameters in a top level section called "parameters". In OA3, everything is nested under the "components" section. When resolving object/schema refs, you may find missing elements because it will try to look for parameters under "#/components/parameters" and not #/parameters". ## Generated Application Dependencies As of now, gomvc assumes you will want to use the following dependencies: - gin - postgres - zap - new relic agent - https://github.com/golang-migrate/migrate (will need to be installed by you) - https://github.com/volatiletech/sqlboiler ### Example steps: using sqlboiler 1. Generate application: `gomvc application petstore --dest ~/Code/petstore` 1. Design your SQL schema or at least one table 1. Create a migration per table: `migrate create -ext sql -dir migrations -seq create_users_table` 1. Fill the migration file with your SQL commands e.g. `CREATE USERS (etc...)` 1. Migrate your local database: `migrate -database YOUR_DATBASE_URL -path PATH_TO_YOUR_MIGRATIONS up` 1. Install sqlboiler by running `make dev-dependencies` 1. Create a sqlboiler configuration per https://github.com/volatiletech/sqlboiler#getting-started (will be automatically done for you in future GO-MVC release) 1. Start your application so that you have postgres running: `docker-compose up` 1. Run sqlboiler: `sqlboiler psql` 1. Run `gomvc resource {{tableName}}` for each of the tables you want to create an endpoint for. 1. Verify naming conventions align with what sqlboiler generated. You might need to edit the generated controllers. 1. Generate seeder to fill DB with test data (assumes models dir exists in your app directory): `gomvc seed`. 1. Continue dev-ing as you would normally If you're managing your schema independently, you can completely remove the migrate dependency from both your workflow and the app but you can still use sqlboiler regardless. <file_sep>FROM golang:1.16-alpine WORKDIR /app ADD go.sum . ADD go.mod . RUN go mod vendor ADD . /app CMD go run main.go <file_sep>package gomvc import ( "log" "github.com/spf13/cobra" ) var swagger = &cobra.Command{ Use: "swagger", Short: "Generate controllers from a v2 Swagger yml file", Run: func(cmd *cobra.Command, args []string) { configDir, err := cmd.LocalFlags().GetString("config") if err != nil { log.Println(err.Error()) return } // TODO: read spec location from config specPath, err := cmd.LocalFlags().GetString("spec") if err != nil { log.Println(err.Error()) return } // read intended destination for generation output destDir, err := cmd.LocalFlags().GetString("dest") if err != nil { log.Println(err.Error()) return } templateDir, err := cmd.LocalFlags().GetString("templates") if err != nil { log.Println(err.Error()) return } oa3 := LoadSwaggerV2AsV3(specPath) GenerateFromOA(oa3, destDir, templateDir, configDir) }, } // Swagger is the cli command that creates a router and controller functions // from a swagger file func Swagger() *cobra.Command { return swagger } <file_sep>package gomvc import ( "fmt" "log" "strings" "github.com/getkin/kin-openapi/openapi3" "github.com/iancoleman/strcase" "github.com/spf13/cobra" ) var model = &cobra.Command{ Use: "models", Short: "Generate model files", // Args: func(cmd *cobra.Command, args []string) error { // if len(args) < 1 { // return errors.New("requires a name for your new model") // } // return nil // }, Run: func(cmd *cobra.Command, args []string) { spec, _ := cmd.LocalFlags().GetString("spec") if spec == "" { panic("you must provide a path to your spec e.g. ./openapi.yml") } v2, _ := cmd.LocalFlags().GetBool("swagger-v2") v3, _ := cmd.LocalFlags().GetBool("openapi-v3") var oa3 *openapi3.Swagger if v2 && v3 { panic("you can only specify one version at a time") } if v2 { oa3 = LoadSwaggerV2AsV3(spec) } else { // this is defaulted if no version flag is provided oa3 = LoadWithKin(spec) } // TODO: support dest flag dir := "./models" createDirIfNotExists(dir) // create structs in the models dir for all component responses for name, r := range oa3.Components.Responses { o := LoadResponseObject(name, r.Value) str, err := CreateStructFromResponseObject(&o) if err != nil { panic(err) } structName := strings.ToLower(strcase.ToSnake(name)) filename := fmt.Sprintf("%s/%s.go", dir, structName) if err := CreateFileFromString(filename, str); err != nil { panic(err) } } // create structs in the models dir for all component schemas for name, schemaRef := range oa3.Components.Schemas { o := LoadSchemaObject(name, schemaRef) str, err := CreateStructFromSchemaObject(&o) if err != nil { panic(err) } structName := strings.ToLower(strcase.ToSnake(name)) if err := CreateFileFromString(fmt.Sprintf("%s/%s.go", dir, structName), str); err != nil { panic(err) } } // create structs in the models dir for all component schemas for name, parameterRef := range oa3.Components.Parameters { o := LoadParameterObject(name, parameterRef) str, err := CreateStructFromParameterObject(&o) if err != nil { panic(err) } structName := strings.ToLower(strcase.ToSnake(name)) if err := CreateFileFromString(fmt.Sprintf("%s/%s.go", dir, structName), str); err != nil { panic(err) } } log.Println("running gofmt and goimports on", dir) RunGoFmt(dir) RunGoImports(dir) }, } // Model is the cli command that creates new model func Model() *cobra.Command { return model } <file_sep>package gomvc import ( "errors" "log" "os" "path/filepath" "strings" "github.com/jinzhu/inflection" "github.com/spf13/cobra" ) var resource = &cobra.Command{ Use: "resource", Short: "Generate resource files", Args: func(cmd *cobra.Command, args []string) error { if len(args) < 1 { return errors.New("requires a name for your new resource") } return nil }, Run: func(cmd *cobra.Command, args []string) { dest, _ := cmd.LocalFlags().GetString("dest") // if no destination path is provided, assume that generation happens in // the current directory if dest == "" { dir, err := os.Getwd() if err != nil { panic(err) } dest = dir } name := args[0] log.Printf("preparing to create a new resource %s\n", name) orm, _ := cmd.LocalFlags().GetString("orm") path := filepath.Join("/", strings.ToLower(name)) controllerData := ControllerData{ Name: strings.Title(name), PluralName: inflection.Plural(name), Path: path, Actions: NewCRUDActions(name), ORM: orm, } if err := createControllerFromDefault(controllerData, dest); err != nil { panic(err) } }, } // Resource is the cli command that creates new resource func Resource() *cobra.Command { return resource } <file_sep>package gomvc import ( "math" "strings" "github.com/iancoleman/strcase" "github.com/jinzhu/inflection" ) func isIndex(method string, path string) bool { if strings.ToUpper(method) != "GET" { return false } // TODO: better way to determine? return !hasPathParameter(path) } func getControllerNameFromPath(path string) string { pathParts := strings.Split(path, "/") nonParams := []string{} for _, part := range pathParts { if !hasPathParameter(part) { nonParams = append(nonParams, part) } } // limit name to two nouns lastTwoIndex := len(nonParams) - 2 nameIndex := int(math.Max(0, float64(lastTwoIndex))) nonParams = nonParams[nameIndex:] name := strcase.ToCamel(strings.Join(nonParams, "_")) lastPathPart := pathParts[len(pathParts)-1] if hasPathParameter(lastPathPart) { return inflection.Singular(name) } return name } func hasPathParameter(s string) bool { // if it's a param it'll have the format `{paramName}` return strings.HasSuffix(s, "}") } var methodLookup = map[string]string{ "GET": "Show", "POST": "Create", "PUT": "Update", "DELETE": "Delete", } func getDefaultHandlerName(method, path string) string { var handler string // index is a special case because currently, all of the HTTP verbs have a 1 // to 1 relationship with an action except for Index and Show which both use // GET. if isIndex(method, path) { handler = "Index" } else { handler = methodLookup[method] } return handler } <file_sep>package gomvc import ( "io/ioutil" "log" yaml "github.com/ghodss/yaml" ) type GoMVCConfig struct { Denylist []string denyListMap map[string]bool } // NewGoMVCConfig is a constructor for a gomvc configuration read into memory func NewGoMVCConfig(configDir string) GoMVCConfig { var config GoMVCConfig if configDir == "" { // use defaults log.Println("no config provided, using defaults") return config } c, err := ioutil.ReadFile(configDir) if err != nil { log.Printf("error reading config: %v", err) return config } if err := yaml.Unmarshal(c, &config); err != nil { log.Printf("empty config: %+v", err) return config } config.mapDenylist() return config } func (c *GoMVCConfig) mapDenylist() { c.denyListMap = map[string]bool{} for _, item := range c.Denylist { c.denyListMap[item] = true } } func (c *GoMVCConfig) IsDenylisted(path string) bool { ok := c.denyListMap[path] return ok } <file_sep>package gomvc import ( "bufio" "fmt" "io" "io/ioutil" "log" "os" "github.com/pkg/errors" ) // CreateFileFromString takes a filepath as the destination of the file // to be created as well as the contents to be written to this file. func CreateFileFromString(filepath string, contents string) error { f, err := os.Create(filepath) if err != nil { return errors.Wrap(err, "CreateFileFromString: os.Create error") } w := bufio.NewWriter(f) _, err = w.WriteString(contents) w.Flush() if err != nil { return errors.Wrap(err, "CreateFileFromString: write string error") } return nil } func createStringFromFile(filePath string) string { content, err := ioutil.ReadFile(filePath) if err != nil { log.Fatal(err) } return string(content) } // Copy the src file to dst. Any existing file will be overwritten and will not // copy file attributes. // https://stackoverflow.com/questions/21060945/simple-way-to-copy-a-file-in-golang func Copy(src, dst string) error { in, err := os.Open(src) if err != nil { return err } defer in.Close() out, err := os.Create(dst) if err != nil { return err } defer out.Close() _, err = io.Copy(out, in) if err != nil { return err } return out.Close() } func createDirIfNotExists(dir string) { if !dirExists(dir) { if err := os.Mkdir(dir, os.ModePerm); err != nil { panic(err) } log.Printf("created %s\n", dir) } } func dirExists(path string) bool { i, err := os.Stat(path) if os.IsNotExist(err) { return false } return i.IsDir() } func fileExists(path string) bool { i, err := os.Stat(path) if os.IsNotExist(err) { return false } return !i.IsDir() } func addGoExt(s string) string { return fmt.Sprintf("%s.go", s) } <file_sep>#!/bin/bash echo "Waiting for servers to start..." attempts=1 while true; do docker exec -i {{Name}} curl -f http://localhost:8080/health > /dev/null 2> /dev/null if [ $? = 0 ]; then echo "Service started" break fi ((attempts++)) if [[ $attempts == 5 ]]; then echo "5 attempts to check health failed" break fi sleep 10 echo $attempts done<file_sep>package gomvc import ( "errors" "fmt" "go/parser" "go/token" "io/ioutil" "log" "os" "path/filepath" "strings" "github.com/aymerick/raymond" "github.com/spf13/cobra" ) var g = &cobra.Command{ Use: "g", Short: "Generate files from arbitrary templates", Args: func(cmd *cobra.Command, args []string) error { if len(args) < 2 { msg := "usage: gomvc g <your template name> <object name>" return errors.New(msg) } return nil }, Run: func(cmd *cobra.Command, args []string) { templateType := args[0] name := args[1] log.Printf("preparing to create %s file(s) for %s\n", templateType, name) if err := GenerateFromUserTemplate(name, templateType); err != nil { panic(err) } }, } func CreateFileFromLocalTemplate(data interface{}, templateDir, destPath string) { t, err := raymond.ParseFile(templateDir) if err != nil { panic(err) } r, err := t.Exec(data) if err != nil { panic(err) } if err := CreateFileFromString(destPath, r); err != nil { panic(err) } } func GenerateFromUserTemplate(name string, templateType string) error { baseTemplateDir := "./templates" src := fmt.Sprintf("%s/%s", baseTemplateDir, templateType) packageName := GetPackageName() data := map[string]string{ "Package": packageName, "Name": name, "TitleName": strings.Title(name), } if dirExists(src) { if err := handleDir(src, data); err != nil { return err } } else if fileExists(src + ".tpl") { templateDir := fmt.Sprintf("%s/%s.tpl", baseTemplateDir, templateType) destPath := fmt.Sprintf("%s/%s.go", ".", name) CreateFileFromLocalTemplate(data, templateDir, destPath) } else { log.Printf("'%s' is neither a template or directory of templates\n", src) } return nil } func handleDir(src string, data interface{}) error { // create a file from all templates in the directory recursively templates, err := ioutil.ReadDir(src) if err != nil { return err } for _, f := range templates { if f.IsDir() { if err := handleDir(filepath.Join(src, f.Name()), data); err != nil { return err } } templateDir := filepath.Join(src, f.Name()) parts := strings.Split(f.Name(), ".") nameWithoutExt := parts[len(parts)-2] destPath := fmt.Sprintf("%s/%s.go", ".", nameWithoutExt) CreateFileFromLocalTemplate(data, templateDir, destPath) } return nil } func GetPackageName() string { cwd, _ := os.Getwd() fset := token.NewFileSet() pkgs, err := parser.ParseDir(fset, cwd, nil, parser.ParseComments) if err != nil { log.Fatalf("parse dir error: %v\n ", err) } for _, pkg := range pkgs { return pkg.Name } return "" } // G is the cli command that creates new g func G() *cobra.Command { return g } <file_sep>package gomvc import ( "encoding/json" "strings" "github.com/aymerick/raymond" "github.com/getkin/kin-openapi/openapi3" "github.com/iancoleman/strcase" ) func CreateStructFromResponseObject(m *ResponseModel) (string, error) { tmplString := ` package models type {{Name}} struct { {{#if Parent}} {{Parent}}{{else}}{{#each Properties}} {{#if this.description}}// {{this.description}}{{/if}} {{camelize @key}} {{this.GoType}} {{/each}}{{/if}} } ` tmpl, err := raymond.Parse(tmplString) if err != nil { return "", err } tmpl.RegisterHelper("camelize", func(word string) string { return strcase.ToCamel(word) }) result := tmpl.MustExec(m) return result, nil } func LoadResponseObject(name string, r *openapi3.Response) ResponseModel { // hack b, _ := json.MarshalIndent(r, "", "\t") var o ResponseObject if err := json.Unmarshal(b, &o); err != nil { panic(err) } m := ResponseModel{} for contentType, content := range o.Content { m.Name = name m.ContentType = contentType // this will be brittel to bad refs refParts := strings.Split(content.Schema.Ref, "/") refName := refParts[len(refParts)-1] if m.Name != refName { m.Parent = refName } } return m } type ResponseObject struct { Content map[string]SchemaType `json:"content,omitempty"` Description string `json:"description,omitempty"` } type ResponseModel struct { ContentType string Parent string Name string Properties []Property } type SchemaType struct { Schema Schema `json:"schema,omitempty"` } type Schema struct { Ref string `json:"$ref,omitempty"` } <file_sep>module github.com/go-generation/go-mvc go 1.16 require ( github.com/Fanatics/toast v0.0.1 github.com/GeertJohan/go.rice v1.0.2 github.com/aymerick/raymond v2.0.2+incompatible github.com/daaku/go.zipexe v1.0.1 // indirect github.com/dave/dst v0.26.2 github.com/getkin/kin-openapi v0.61.0 github.com/ghodss/yaml v1.0.0 github.com/iancoleman/strcase v0.0.0-20191112232945-16388991a334 github.com/jinzhu/inflection v1.0.0 github.com/kr/text v0.2.0 // indirect github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect github.com/pkg/errors v0.9.1 github.com/spf13/cobra v1.1.3 github.com/spf13/pflag v1.0.5 github.com/stretchr/testify v1.6.1 // indirect golang.org/x/mod v0.4.1 golang.org/x/tools v0.0.0-20200724022722-7017fd6b1305 // indirect gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect ) <file_sep>FROM golang:1.13-alpine RUN go get -u github.com/smartystreets/goconvey ADD . /app WORKDIR /app RUN go install -v CMD goconvey -host 0.0.0.0 -port=9999 EXPOSE 9999 <file_sep>package gomvc import "github.com/spf13/cobra" var root = &cobra.Command{ Use: "gomvc", Short: "GoMVC is a CLI for generating and modifying golang MVC applications", Run: func(cmd *cobra.Command, args []string) { if err := cmd.Help(); err != nil { panic(err) } }, } // Root is the function called when running `gomvc` func Root() *cobra.Command { return root } <file_sep>package gomvc import ( "log" "path/filepath" "strings" "github.com/getkin/kin-openapi/openapi3" "github.com/spf13/cobra" ) var oa = &cobra.Command{ Use: "oa", Short: "Generate controllers from an OpenAPI yml file", Run: func(cmd *cobra.Command, args []string) { flags := cmd.LocalFlags() configDir, err := flags.GetString("config") if err != nil { log.Println(err.Error()) return } // TODO: read spec location from config specPath, err := flags.GetString("spec") if err != nil { log.Println(err.Error()) return } // read intended destination for generation output destDir, err := flags.GetString("dest") if err != nil { log.Println(err.Error()) return } templateDir, err := flags.GetString("templates") if err != nil { log.Println(err.Error()) return } oa3 := LoadWithKin(specPath) GenerateFromOA(oa3, destDir, templateDir, configDir) }, } // GenerateFromOA is the primary logic for the oa command, creating controllers func GenerateFromOA(oa3 *openapi3.Swagger, dest, templateDir, configDir string) { config := NewGoMVCConfig(configDir) createDirIfNotExists(dest) ctrlDest := filepath.Join(dest, "controllers") createDirIfNotExists(ctrlDest) CreateRouter(RouteData{}, "gin/router.tpl", ctrlDest) g := NewGenerator(oa3) for path, pathItem := range oa3.Paths { path = strings.Trim(path, " ") log.Printf("examining path, %s\n", path) if config.IsDenylisted(path) { continue } if err := g.CreateControllerFiles(path, pathItem, dest, templateDir); err != nil { log.Fatalf("%s: %s", path, err.Error()) } } } // OA is the cli command that creates a router and controller functions from an // OpenAPI file func OA() *cobra.Command { return oa } <file_sep>package gomvc import ( "bytes" "fmt" "go/token" "log" "os" "path/filepath" "sort" "strings" "github.com/dave/dst" "github.com/dave/dst/decorator" ) type RouteData struct { Controllers []ControllerData `json:"controllers,omitempty"` } // CreateRouter creates a router.go file to be used in the controllers directory func CreateRouter(data RouteData, relativeTemplatePath, destDir string) { sort.Slice(data.Controllers, func(i, j int) bool { return strings.Compare( data.Controllers[i].Name, data.Controllers[j].Name) < 1 }) outputPath := filepath.Join(destDir, "router.go") if err := createFileFromTemplates(relativeTemplatePath, data, outputPath); err != nil { log.Fatalf("error generating router file for %s %s\n", outputPath, err.Error()) } } func AddActionViaAST(data ControllerData, routerFilePath string, destDir string) { code := createStringFromFile(routerFilePath) f, err := decorator.Parse(code) if err != nil { panic(err) } fn, err := getFuncByName(f, "GetRouter") if err != nil { panic(err) } // current node is a function! numStatements := len(fn.Body.List) // the last statement is a return so we insert before the return which is why it's numStatements - 1 returnStatement := fn.Body.List[numStatements-1] // delete return statement fn.Body.List = fn.Body.List[:numStatements-1] // create the controller instantiation line controllerStmt := NewControllerStatement(data.Name) fn.Body.List = append(fn.Body.List, controllerStmt) // create the specific route registration line for each controller action for _, action := range data.Actions { routeStmt := NewRouteRegistrationStatement(action) fn.Body.List = append(fn.Body.List, routeStmt) } // add back the removed return to be at the end fn.Body.List = append(fn.Body.List, returnStatement) // i don't know why i can't just directly write to the file // instead of using the byte buffer intermediary w := &bytes.Buffer{} if err := decorator.Fprint(w, f); err != nil { panic(err) } updatedContents := w.String() newFile, _ := os.Create(routerFilePath) if _, err := newFile.WriteString(updatedContents); err != nil { panic(err) } } func NewRouteRegistrationStatement(action Action) *dst.ExprStmt { return &dst.ExprStmt{ X: &dst.CallExpr{ Fun: &dst.SelectorExpr{ Sel: &dst.Ident{Name: action.Method}, X: &dst.Ident{Name: "r"}, }, Args: []dst.Expr{ &dst.BasicLit{ Kind: token.STRING, Value: fmt.Sprintf("\"%s\"", action.Path), }, &dst.SelectorExpr{ Sel: &dst.Ident{Name: action.Name}, X: &dst.Ident{Name: fmt.Sprintf("%sCtrl", action.Resource)}, }, }, }, } } func NewControllerStatement(resource string) *dst.AssignStmt { name := fmt.Sprintf("%sCtrl", resource) return &dst.AssignStmt{ Tok: token.DEFINE, Lhs: []dst.Expr{ &dst.Ident{ Name: name, }, }, Rhs: []dst.Expr{ &dst.Ident{ Name: fmt.Sprintf("%sController{db: db, log: log}", strings.Title(resource)), }, }, } } // modified from https://github.com/laher/regopher/blob/master/parsing.go func getFuncByName(f *dst.File, funcName string) (*dst.FuncDecl, error) { for _, d := range f.Decls { switch fn := d.(type) { case *dst.FuncDecl: if fn.Name.Name == funcName { return fn, nil } } } return nil, fmt.Errorf("func not found") } <file_sep>package main import ( "errors" "fmt" "log" "os" "strings" "github.com/aymerick/raymond" gomvc "github.com/go-generation/go-mvc" "github.com/spf13/cobra" ) func main() { root := Root() root.AddCommand(Command()) if err := root.Execute(); err != nil { fmt.Println(err) os.Exit(1) } } var root = &cobra.Command{ Use: "dev", Short: "dev is the gomvc development helper", Run: func(cmd *cobra.Command, args []string) { if err := cmd.Help(); err != nil { panic(err) } }, } func Root() *cobra.Command { return root } var command = &cobra.Command{ Use: "command", Short: "Generate cli commands", Args: func(cmd *cobra.Command, args []string) error { if len(args) < 1 { return errors.New("requires a name for your new command") } return nil }, Run: func(cmd *cobra.Command, args []string) { name := strings.ToLower(args[0]) log.Println("preparing to create a new command:", name) data := map[string]string{ "Name": name, "TitleName": strings.Title(name), } t, err := raymond.ParseFile("./cmd/dev/command.tpl") if err != nil { panic(err) } r, err := t.Exec(data) if err != nil { panic(err) } destPath := fmt.Sprintf("%s/%s.go", ".", name) if err := gomvc.CreateFileFromString(destPath, r); err != nil { panic(err) } }, } // Command is the cli command that creates new cli commands func Command() *cobra.Command { return command } <file_sep>package gomvc import ( "fmt" "io/ioutil" "log" "path/filepath" "strings" "github.com/iancoleman/strcase" "golang.org/x/mod/modfile" ) type ControllerData struct { ModuleName string Name string PluralName string Path string Actions []Action TestPaths []TestPath ErrorResponses []Response ORM string } type TestPath struct { Path string Name string } func createControllerFromDefault(controllerData ControllerData, dest string) error { var name string gomodFile := filepath.Join(dest, "go.mod") data, err := ioutil.ReadFile(gomodFile) if err != nil { // we'll assume the file doesn't exist and guess that the directory is the module name name = GetLastPathPart(dest) } else { name = modfile.ModulePath(data) } controllerData.ModuleName = name dest = filepath.Join(dest, "controllers") lowerName := strings.ToLower(strcase.ToSnake(controllerData.Name)) controllerPath := filepath.Join(dest, addGoExt(lowerName)) helpers := []TemplateHelper{ { Name: "whichAction", Function: func(handler string) string { if handler == "" { log.Println("blank handler name provided") return "" } actionData := findActionByHandler(controllerData.Actions, handler) return methodPartial(actionData, handler, "gin") }, }, { Name: "whichActionTest", Function: func(handler string) string { actionData := findActionByHandler(controllerData.Actions, handler) return methodPartial(actionData, handler+"_test", "tests") }, }, } if err := createFileWithHelpers( "gin/controller.tmpl", controllerData, controllerPath, helpers); err != nil { return err } // generate controller http tests testControllerPath := fmt.Sprintf("%s/%s_test.go", dest, lowerName) if err := createFileWithHelpers( "tests/controller_test.tpl", controllerData, testControllerPath, helpers); err != nil { return err } // register the controller operations in the router routerFilePath := filepath.Join(dest, "router.go") AddActionViaAST(controllerData, routerFilePath, dest) return nil } // find specific action tied to the handler func findActionByHandler(actions []Action, handler string) Action { var current Action for _, a := range actions { if a.Handler == handler { current = a break } } return current } <file_sep>package gomvc import ( "errors" "fmt" "go/ast" "go/parser" "go/token" "log" "os" "path/filepath" "strings" "github.com/iancoleman/strcase" "github.com/spf13/cobra" "github.com/Fanatics/toast/collector" ) var seed = &cobra.Command{ Use: "seed", Short: "Generate seed files", Run: func(cmd *cobra.Command, args []string) { dest, _ := cmd.LocalFlags().GetString("dest") if dest == "" { path, err := os.Getwd() if err != nil { panic(err) } dest = path } cmdDir := filepath.Join(dest, "cmd") createDirIfNotExists(cmdDir) if err := CreateSeedCommand(dest); err != nil { panic(err) } }, } // Seed is the cli command that creates new seeders based on structs in your // application's "models" directory func Seed() *cobra.Command { return seed } // CreateSeedCommand creates a single cmd that inserts records for all models func CreateSeedCommand(dest string) error { modelDir := filepath.Join(dest, "models") data, err := collectFileData(modelDir) if err != nil { log.Println("filepath walk error", err) return err } var modelNames []string iterateModels(data, func(s collector.Struct) error { modelNames = append(modelNames, s.Name) return nil }) if len(modelNames) == 0 { return errors.New("No models found") } content := createContentsFromTemplate("sqlboiler/seeder.tmpl", struct { Models []string }{Models: modelNames}) commandDir := filepath.Join(dest, "cmd/seed") createDirIfNotExists(commandDir) fileName := filepath.Join(commandDir, "main.go") return CreateFileFromString(fileName, content) } // CreateSeederWithName creates a file with a single function. This function // connects to the DB and inserts records for each model using each the model // factories. func CreateSeederWithName(structName string, destDir string) error { // default to current dir if none given if destDir == "" { destDir = "./cmd/seed" } createDirIfNotExists(destDir) fileName := fmt.Sprintf("%s.go", strcase.ToSnake(structName)) dest := filepath.Join(destDir, fileName) name := strcase.ToCamel(structName) data := map[string]string{"Name": name} contents := createContentsFromTemplate("sqlboiler/seed.tmpl", data) return CreateFileFromString(dest, contents) } // CreateSeedersFromModels iterates through the given directory // finds models the creates seed files in the given destination func CreateSeedersFromModels(dir string, dest string) error { data, err := collectFileData(dir) if err != nil { log.Println("filepath walk error", err) return err } if len(data.Packages) == 0 { log.Println("No model data found. Exiting.") return nil } iterateModels(data, func(s collector.Struct) error { if err := CreateSeederWithName(s.Name, dest); err != nil { return err } return nil }) return nil } func iterateModels(data *collector.Data, lambda func(s collector.Struct) error) { for _, p := range data.Packages { for _, f := range p.Files { for _, s := range f.Structs { var hasAnyTags bool // hack for _, field := range s.Fields { if len(field.Tag) > 0 { hasAnyTags = true tag := strings.Trim(field.Tag, "`") parts := strings.Split(tag, " ") for _, p := range parts { tag := strings.Split(p, ":") name := tag[0] // some db tools use a 'db' struct tag to help with marshalling // so we use that convention here as a way to determine what the sql column is if name == "db" { values := strings.Trim(tag[1], "\"") valueParts := strings.Split(values, ",") log.Println(valueParts) } } } } if !hasAnyTags { continue } if err := lambda(s); err != nil { panic(err) } } } } } func collectFileData(dir string) (*collector.Data, error) { fset := token.NewFileSet() data := &collector.Data{} err := filepath.Walk(dir, func(path string, fi os.FileInfo, err error) error { if err != nil { log.Fatal("recursive walk error:", err) } // skip over files, only continue into directories for parser to enter if !fi.IsDir() { return nil } pkgs, err := parser.ParseDir(fset, path, nil, parser.ParseComments) if err != nil { log.Fatalf("parse dir error: %v\n", err) } for _, pkg := range pkgs { p := collector.Package{ Name: pkg.Name, } for _, file := range pkg.Files { c := &collector.FileCollector{} ast.Walk(c, file) f := collector.File{ Name: fset.Position(file.Pos()).Filename, Package: pkg.Name, Imports: c.Imports, BuildTags: c.BuildTags, Comments: c.Comments, MagicComments: c.MagicComments, GenerateComments: c.GenerateComments, Consts: c.Consts, Vars: c.Vars, Structs: c.Structs, TypeDefs: c.TypeDefs, Interfaces: c.Interfaces, Funcs: c.Funcs, } p.Files = append(p.Files, f) } data.Packages = append(data.Packages, p) } return nil }) return data, err } <file_sep>package gomvc import ( "encoding/json" "fmt" "strings" "github.com/aymerick/raymond" "github.com/getkin/kin-openapi/openapi3" "github.com/iancoleman/strcase" ) func CreateStructFromSchemaObject(o *SchemaObject) (string, error) { tmplString := ` package models {{#if GoType}} type {{Name}} {{GoType}} {{else}} type {{Name}} struct { {{#each Properties}} {{#if this.description}} // {{this.description}}{{/if}} {{camelize @key}} {{this.GoType}}{{/each}} } {{/if}} ` tmpl, err := raymond.Parse(tmplString) if err != nil { return "", err } tmpl.RegisterHelper("camelize", func(word string) string { return strcase.ToCamel(word) }) result := tmpl.MustExec(o) return result, nil } type Property struct { Name string `json:"name,omitempty"` Description string `json:"description,omitempty"` Type string `json:"type,omitempty"` Items Item `json:"items,omitempty"` Format string `json:"format,omitempty"` Required bool `json:"required,omitempty"` GoType string `json:"go_type,omitempty"` Ref string `json:"$ref,omitempty"` AdditionalProperties AdditionalProperties `json:"additionalProperties,omitempty"` } type AdditionalProperties struct { Type string OneOf []Type AnyOf []Type } type Type struct { Type string } type Item struct { Type string `json:"type,omitempty"` Format string `json:"format,omitempty"` } type SchemaObject struct { Name string Description string `json:"description,omitempty"` Properties map[string]Property `json:"properties,omitempty"` Required []string `json:"required,omitempty"` Type string `json:"type,omitempty"` Title string `json:"title,omitempty"` GoType string Items Item } // todo: collect enums func LoadSchemaObject(name string, r *openapi3.SchemaRef) SchemaObject { // hack b, _ := json.MarshalIndent(r, "", "\t") var o SchemaObject if err := json.Unmarshal(b, &o); err != nil { panic(err) } if o.Type == "array" { o.GoType = fmt.Sprintf("[]%s", o.Items.Type) } else if objectType(o.Type) { requiredMap := map[string]bool{} for _, propertyName := range o.Required { requiredMap[propertyName] = true } for name, property := range o.Properties { property.Required = requiredMap[name] // mutation goType := GetGoType(name, &property) property.GoType = goType o.Properties[name] = property } } else { o.GoType = GetGoPrimitiveType(o.Type) } o.Name = strcase.ToCamel(name) return o } func objectType(t string) bool { return t == "object" } func GetGoPrimitiveType(t string) string { switch t { case "boolean": return "bool" case "string": return "string" case "integer": return "int" default: panic(fmt.Sprintf("invalid primitive: %s", t)) } } // GetGoType mutates the property type to determine GoType func GetGoType(name string, p *Property) string { if p.Format == "" { switch p.Type { case "boolean": return "bool" case "string": return "string" case "integer": return "int" case "array": switch p.Items.Type { case "integer": return "[]int" case "number", "double": return "float" default: panic(fmt.Sprintf("unexpected format: %s", p.Format)) } case "object": if hasAdditionalProperties(p) { return "map[string]interface{}" } refObjectName := GetLastPathPart(p.Ref) return refObjectName case "number", "double": return "float64" case "": if p.Ref == "" { panic(fmt.Sprintf("while your spec may be valid, we require properties to have a type (e.g. integer, array) for %s %s", name, p.Ref)) } // is this enough? what if there's a ref and also properties refObjectName := GetLastPathPart(p.Ref) return refObjectName default: panic(fmt.Sprintf("unsupported type: %s for %s", p.Type, name)) } } else { switch p.Format { case "date-time": return "time.Time" case "number", "double": return "float64" default: return p.Format } } } func GetLastPathPart(path string) string { parts := strings.Split(path, "/") if len(parts) == 0 { return "" } return parts[len(parts)-1] } func hasAdditionalProperties(p *Property) bool { ap := &p.AdditionalProperties return ap.Type != "" && len(ap.AnyOf) == 0 && len(ap.OneOf) == 0 } <file_sep>package gomvc import ( "encoding/json" "fmt" "log" "net/http" "strconv" "strings" "github.com/getkin/kin-openapi/openapi3" "github.com/jinzhu/inflection" ) func NewCRUDActions(name string) []Action { actions := []Action{} title := strings.Title(name) singular := inflection.Singular(title) for _, action := range []Action{ {Resource: title, SingularResource: singular, Name: "Index", Method: http.MethodGet}, {Resource: title, SingularResource: singular, Name: "Create", Method: http.MethodPost}, } { if strings.HasPrefix(name, "/") { action.Path = strings.ToLower(name) } else { action.Path = "/" + strings.ToLower(name) } action.Handler = strings.Title(action.Name) actions = append(actions, action) } for _, detailAction := range []Action{ {Resource: title, SingularResource: singular, Name: "Show", Method: http.MethodGet}, {Resource: title, SingularResource: singular, Name: "Update", Method: http.MethodPut}, {Resource: title, SingularResource: singular, Name: "Delete", Method: http.MethodDelete}, } { detailAction.Path = fmt.Sprintf("/%s/:id", strings.ToLower(name)) detailAction.Handler = strings.Title(detailAction.Name) actions = append(actions, detailAction) } return actions } type Action struct { SingularResource string // Resource is loosely related with what the Controller is and has many actions Resource string // Name is the function name bound to the Controller Name string // Method is the HTTP verb Method string `json:"method,omitempty"` // Path is the associated url path Path string `json:"path,omitempty"` // Handler is the generic resource action name e.g. Index, Create Handler string `json:"handler,omitempty"` } type Response struct { Name string Code int Ref string } // NewResponses creates a list of responses from an OA3 response ref func NewResponses(specResponses map[string]*openapi3.ResponseRef) []Response { var responses []Response responseSet := map[string]bool{} for statusCode, resRef := range specResponses { r := NewResponse(statusCode, resRef) if _, ok := responseSet[r.Name]; !ok { responseSet[r.Name] = true responses = append(responses, r) } } return responses } // NewResponse is a constructor for the custom Response object func NewResponse(statusCode string, resRef *openapi3.ResponseRef) Response { code, _ := strconv.Atoi(statusCode) return Response{ Code: code, Ref: resRef.Ref, Name: resolveResponseName(resRef), } } func resolveResponseName(resRef *openapi3.ResponseRef) string { if resRef.Ref == "" { for _, obj := range resRef.Value.Content { name := resolveSchemaName(obj.Schema) // TODO: handle multiple return name } } return getComponentName(resRef.Ref) } func resolveSchemaName(schema *openapi3.SchemaRef) string { if schema.Ref == "" { return getComponentName(schema.Value.Items.Ref) } return getComponentName(schema.Ref) } func PrintJSON(v interface{}) { b, _ := json.MarshalIndent(v, "", "\t") log.Println(string(b)) } <file_sep>package main import ( "fmt" "os" gomvc "github.com/go-generation/go-mvc" "github.com/spf13/pflag" ) // shared flags var dest string var spec string var templateDir string // db flags var orm string func main() { root := gomvc.Root() app := gomvc.Application() root.AddCommand(app) setSharedFlags(app.Flags()) r := gomvc.Resource() root.AddCommand(r) setSharedFlags(r.Flags()) r.Flags().StringVarP(&orm, "orm", "o", "", "database access strategy") m := gomvc.Model() root.AddCommand(m) setSharedFlags(m.Flags()) m.Flags().BoolP("swagger-v2", "2", false, "Swagger v2 spec path") m.Flags().BoolP("openapi-v3", "3", false, "OpenAPI v3 spec path") m.Flags().StringVarP(&spec, "spec", "s", "./openapi.yml", "OpenAPI spec path") oa := gomvc.OA() root.AddCommand(oa) oaFlags := oa.Flags() setSharedFlags(oaFlags) oaFlags.StringVarP(&spec, "spec", "s", "./openapi.yml", "OpenAPI spec path") swagger := gomvc.Swagger() root.AddCommand(swagger) swaggerFlags := swagger.Flags() setSharedFlags(swaggerFlags) swaggerFlags.StringVarP(&spec, "spec", "s", "./swagger.yml", "Swagger spec path") seed := gomvc.Seed() root.AddCommand(seed) setSharedFlags(seed.Flags()) g := gomvc.G() root.AddCommand(g) if err := root.Execute(); err != nil { fmt.Println(err) os.Exit(1) } } func setSharedFlags(flags *pflag.FlagSet) { cwd, _ := os.Getwd() flags.StringVarP(&dest, "dest", "d", cwd, "output of generated files") flags.StringVarP(&templateDir, "templates", "t", "", "Custom template path") } <file_sep>.PHONY: models # Go parameters GOBUILD=go build GOCLEAN=go clean GOTEST=go test GOGET=go get all: test build dev-dependencies: go get -u -t github.com/volatiletech/sqlboiler go get github.com/volatiletech/sqlboiler/drivers/sqlboiler-psql build: $(GOBUILD) -tags=jsoniter . test: $(GOTEST) -v ./... start: make build go run main.go # usage: make migration N=tableName migration: migrate create -ext sql -dir ./migrations -seq $(N) migratedb: migrate up dropdb: migrate drop models: sqlboiler psql --no-tests --no-hooks --no-context <file_sep>package gomvc import ( "encoding/json" "github.com/aymerick/raymond" "github.com/getkin/kin-openapi/openapi3" "github.com/iancoleman/strcase" ) func LoadParameterObject(name string, r *openapi3.ParameterRef) ParameterObject { // hack b, _ := json.MarshalIndent(r, "", "\t") var o ParameterObject if err := json.Unmarshal(b, &o); err != nil { panic(err) } goType := GetGoType(name, &o.Schema) o.Schema.GoType = goType return o } func pathParamTmpl() string { return ` package models type {{camelize Name}} {{Schema.GoType}} ` } func queryParamTmpl() string { return ` package models type {{camelize Name}} struct { {{Name}} {{GoType}} } ` } func CreateStructFromParameterObject(o *ParameterObject) (string, error) { var tmplString string if o.In == "path" { tmplString = pathParamTmpl() } else if o.In == "query" { tmplString = queryParamTmpl() } else { // body panic(o.In) } tmpl, err := raymond.Parse(tmplString) if err != nil { return "", err } tmpl.RegisterHelper("camelize", func(word string) string { return strcase.ToCamel(word) }) result := tmpl.MustExec(o) return result, nil } type ParameterObject struct { Description string `json:"description,omitempty"` In string `json:"in,omitempty"` Name string `json:"name,omitempty"` Required bool `json:"required,omitempty"` Schema Property `json:"schema,omitempty"` } type ParameterSchema struct { Format string Type string GoType string } <file_sep>package gomvc import ( "log" "strings" "github.com/getkin/kin-openapi/openapi3" "github.com/iancoleman/strcase" "github.com/jinzhu/inflection" ) // Generator wraps functionality for reading and manipulating a single OpenAPI spec type Generator struct { oa3 *openapi3.Swagger } // NewGenerator is a constructor for Generator func NewGenerator(oa3 *openapi3.Swagger) Generator { return Generator{ oa3: oa3, } } // CreateControllerFiles creates a controller for operations found in // an OpenAPI file func (oag *Generator) CreateControllerFiles(path string, pathItem *openapi3.PathItem, dest string, templateDir string) error { name := strcase.ToSnake(pathItem.Summary) name = strings.ToLower(name) if name == "" { log.Printf("No summary provided in API, defaulting to deriving name from path %s since we can't identify a name for the resource", path) name = getControllerNameFromPath(path) } log.Printf("Preparing to generate controller files for %s %s", name, path) data := ControllerData{ Name: name, PluralName: inflection.Plural(name), Path: path, Actions: []Action{}, } var responses []Response responseSet := map[string]bool{} // collect controller methods based on specified HTTP verbs/operations for method, op := range pathItem.Operations() { var handler = getDefaultHandlerName(method, path) var operationName string if op.OperationID == "" { log.Printf("Missing operation ID. Generating default name for handler/operation function in controller %s.\n", name) operationName = handler } else { operationName = strings.Title(op.OperationID) } // responses might not be unique across controller actions // so this ensures that any associated generation happens once // additionally, we only care about the error responses // to generate filter functions opResponses := NewResponses(op.Responses) for _, r := range opResponses { if r.Code < 400 { continue } if _, ok := responseSet[r.Name]; !ok { responseSet[r.Name] = true responses = append(responses, r) } } a := Action{ SingularResource: inflection.Singular(name), Resource: name, Method: method, Path: path, Handler: handler, Name: operationName, } data.Actions = append(data.Actions, a) } data.ErrorResponses = responses if err := createControllerFromDefault(data, dest); err != nil { return err } log.Printf("created controller actions for %s\n", path) return nil } <file_sep>package gomvc import ( "fmt" "log" "strings" rice "github.com/GeertJohan/go.rice" "github.com/aymerick/raymond" ) type TemplateHelper struct { Name string Function func(string) string } // TODO: consolidate this with createFileFromTemplates func createContentsFromTemplate(tmplPath string, data interface{}) string { tmpl, err := getTemplate(tmplPath) if err != nil { panic(err) } result := tmpl.MustExec(data) return result } // TODO there's some duplication here and in the helper registration in controller.go func createFileFromTemplates(template string, data interface{}, destPath string) error { content := createContentsFromTemplate(template, data) if err := CreateFileFromString(destPath, content); err != nil { log.Println("could not create file for", destPath) return err } return nil } // TODO: support custom templates func methodPartial(ctx interface{}, name string, subDir string) string { name = strings.ToLower(name) tmplPath := fmt.Sprintf("%s/partials/%s.tmpl", subDir, name) tmpl, err := getTemplate(tmplPath) if err != nil { panic(err) } return tmpl.MustExec(ctx) } func createFileWithHelpers(tmplPath string, data interface{}, destPath string, helpers []TemplateHelper) error { tmpl, err := getTemplate(tmplPath) if err != nil { return err } for _, helper := range helpers { tmpl.RegisterHelper(helper.Name, helper.Function) } interpolated := tmpl.MustExec(data) if err := CreateFileFromString(destPath, interpolated); err != nil { log.Println("could not create file for", destPath) return err } return nil } func getTemplate(tmplPath string) (*raymond.Template, error) { box := rice.MustFindBox("templates") tmplString := box.MustString(tmplPath) return raymond.Parse(tmplString) } <file_sep>package gomvc import ( "errors" "go/build" "io/ioutil" "log" "os" "os/exec" "path" "path/filepath" "strings" rice "github.com/GeertJohan/go.rice" "github.com/GeertJohan/go.rice/embedded" "github.com/spf13/cobra" ) var application = &cobra.Command{ Use: "application", Short: "Generate application files", Args: func(cmd *cobra.Command, args []string) error { if len(args) < 1 { return errors.New("requires a name for your new application: `gomvc application [name of your application]`") } return nil }, Run: func(cmd *cobra.Command, args []string) { appName := args[0] log.Printf("preparing to create a new application: %s\n", appName) destinationDir := getAppDir(cmd, appName) // setup basic directories createDirIfNotExists(destinationDir) createDirIfNotExists(path.Join(destinationDir, "controllers")) createDirIfNotExists(path.Join(destinationDir, "models")) createDirIfNotExists(path.Join(destinationDir, "migrations")) createDirIfNotExists(path.Join(destinationDir, ".circleci")) // copy over static go files (not templated) for filename := range embedded.EmbeddedBoxes["static"].Files { log.Println("copying static file", destinationDir, filename) copyStatic(destinationDir, filename) } log.Println("finished copying static files") // TODO: extract and allow configuration that would filter static files: e.g. not using sqlboiler // render files from generic gomvc templates for _, file := range []File{ {Template: "gin/main.tpl", Name: "main.go"}, {Template: "build/docker-compose.yml.tpl", Name: "docker-compose.yml"}, {Template: "build/env.tpl", Name: ".env"}, {Template: "build/wait-for-server-start.sh.tpl", Name: ".circleci/wait-for-server-start.sh"}, } { data := map[string]string{ "Name": appName, "TitleName": strings.Title(appName), } destPath := filepath.Join(destinationDir, file.Name) if err := createFileFromTemplates(file.Template, data, destPath); err != nil { log.Printf("error creating file for %s: %s\n", file.Name, err.Error()) continue } log.Println("created ", file.Name) } // render files from special gomvc templates with specific template data ctrlDir := filepath.Join(destinationDir, "controllers") CreateRouter(RouteData{}, "gin/router.tpl", ctrlDir) }, PostRun: func(cmd *cobra.Command, args []string) { // this doesn't work for some reason appName := args[0] appDir := getAppDir(cmd, appName) // gofmt log.Println("running gofmt on", appDir) RunGoFmt(appDir) // goimports log.Println("running goimports on", appDir) RunGoImports(appDir) // go module log.Println("creating go module", appName) createModule(appDir, appName) }, } // Application is the cli command that creates new application. func Application() *cobra.Command { return application } func getAppDir(cmd *cobra.Command, appName string) string { dest, err := cmd.LocalFlags().GetString("dest") if err != nil { panic(err) } if dest == "" { cwd, _ := os.Getwd() return path.Join(cwd, appName) } return dest } func RunGoFmt(appDir string) { command := exec.Command(goRooted("gofmt"), "-w", appDir) runCommand(command) log.Printf("Just ran gofmt subprocess %d, exiting\n", command.Process.Pid) } func RunGoImports(appDir string) { command := exec.Command(goPathed("goimports"), "-w", appDir) runCommand(command) log.Printf("Just ran goimports subprocess %d, exiting\n", command.Process.Pid) } func goPathed(name string) string { gopath := os.Getenv("GOPATH") if gopath == "" { gopath = build.Default.GOPATH } return filepath.Join(gopath, "bin", name) } func goRooted(name string) string { goroot := os.Getenv("GOROOT") if goroot == "" { goroot = build.Default.GOROOT } return filepath.Join(goroot, "bin", name) } // currently can only be used in app dir func createModule(appDir, appName string) { command := exec.Command("go", "mod", "init", appName) command.Dir = appDir runCommand(command) } func runCommand(command *exec.Cmd) { stderr, err := command.StderrPipe() if err != nil { log.Fatal(err) } if err := command.Start(); err != nil { log.Fatal(err) } slurp, err := ioutil.ReadAll(stderr) if err != nil { log.Fatal(err) } log.Printf("%s", slurp) if err := command.Wait(); err != nil { log.Fatal(err) } } // File is a GoMVC specific type to store rendering meta data with the filenames type File struct { Template string Name string } func copyStatic(destinationBasePath string, name string) { box := rice.MustFindBox("static") dest := filepath.Join(destinationBasePath, name) if err := CreateFileFromString(dest, box.MustString(name)); err != nil { panic(err) } }
a550e1816f76e58994ccc84c5de44528f9001033
[ "Markdown", "Makefile", "Go", "Go Module", "Dockerfile", "Shell" ]
28
Go
phamdt/go-mvc
03a02e4763b1213d4bc87c2d2f3a283d2f7b4dbb
5e8f8ad8fd3efff51176a7337839b12401084d92
refs/heads/master
<repo_name>mdxprograms/todoit<file_sep>/README.md # todoit A todo app using backbone + firebase + es6 <file_sep>/app/assets/javascripts/modules/appView.js let $ = require('jquery'); let TodoView = require('./TodoView'); let Template = require('../templates/todo.hbs'); Backbone.$ = $; module.exports = Backbone.View.extend({ el: $('#todoApp'), events: { "click #add-todo": "createTodo" }, initialize: function () { this.list = this.$('#todo-list'); this.title = this.$('#todo-title'); this.description = this.$('#todo-description'); this.completed = false; this.listenTo(this.collection, 'add', this.addOne); }, addOne: function (todo) { let view = new TodoView({model: todo}); this.list.append(view.render().el); }, createTodo: function (e) { if (!this.title.val()) { return; } this.collection.create({ title: this.title.val(), description: this.description.val() }); this.title.val(''); this.description.val(''); } }); <file_sep>/app/assets/javascripts/App.js let $ = require('jquery'); let userLoginTemplate = require('./templates/userLogin.hbs'); let todoAppView = require('./templates/todoApp.hbs'); class App { constructor () { let ref = new Firebase('https://todoit.firebaseio.com'); let user = ref.getAuth(); if (user) { $('#todo-container').html(todoAppView); $('#user-profile-image').attr('src', sessionStorage.getItem('profileImage')); let AppView = require('./modules/AppView'); let TodoCollection = require('./modules/TodoCollection'); let collection = new TodoCollection(); let appView = new AppView({collection: collection}); } else { $('#todo-container').html(userLoginTemplate()); $('#login-user').on('click', function () { let $this = $(this); ref.authWithPassword({ email: $('#user-email').val(), password: <PASSWORD>').val() }, function (error, authData) { if (error) { alert(error); return; } $('#todo-container').html(todoAppView); $('#user-profile-image').attr('src', authData.password.profileImageURL); sessionStorage.setItem('profileImage', authData.password.profileImageURL); let AppView = require('./modules/AppView'); let TodoCollection = require('./modules/TodoCollection'); let collection = new TodoCollection(); let appView = new AppView({collection: collection}); }, { remember: 'sessionOnly' }); }) } } loggedInView() { } } App new App <file_sep>/app/assets/javascripts/modules/todoCollection.js let $ = require('jquery'); let moment = require('moment'); let todoModel = require("./TodoModel"); Backbone.$ = $; module.exports = Backbone.Firebase.Collection.extend({ model: todoModel, url: "https://todoit.firebaseio.com" }); <file_sep>/app/assets/javascripts/modules/todoModel.js let Backbone = require('backbone'); let $ = require('jquery'); let moment = require('moment'); Backbone.$ = $; module.exports = Backbone.Model.extend({ defaults: { title: "", description: "", completed: false, dueDate: moment().format("MM-DD-YYYY") } });
678490e5d3c20868dc9aa38dd4e169d8adb26e95
[ "Markdown", "JavaScript" ]
5
Markdown
mdxprograms/todoit
47811b98c524290f8585a93bfc33b2b65e06dede
ed6ece131408cf24a3154e9a4bd5f03a10eea4bf
refs/heads/master
<repo_name>brac10/conan-hello<file_sep>/src/main.cpp #include "hello.h" int main (void){ int foo = 0; for (int i = 0; i < 10; i++) { foo++; } hello(); }<file_sep>/src/CMakeLists.txt PROJECT(conan-hello) cmake_minimum_required(VERSION 2.8) SET(EXPORTS ${CMAKE_CURRENT_SOURCE_DIR}/../exports) set(CMAKE_DEBUG_POSTFIX _d) SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${EXPORTS}/bin) SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE ${EXPORTS}/bin) SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG ${EXPORTS}/bin) SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${EXPORTS}/lib) SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_RELEASE ${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}) SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_DEBUG ${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}) ADD_LIBRARY(hello STATIC hello.cpp) ADD_EXECUTABLE(greet main.cpp) set_target_properties(greet PROPERTIES DEBUG_POSTFIX ${CMAKE_DEBUG_POSTFIX}) TARGET_LINK_LIBRARIES(greet hello) IF (WIN32 AND "${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") TARGET_LINK_LIBRARIES(greet stdc++) ENDIF()<file_sep>/README.md # conan-hello "Hello world" project for testing Conan build and package setups This is test package to see how simply I could set up Conan, CMake, and Visual Studio Code to build and debug ## One-time Setup Build dependencies: - Install Python (3.5 or later) - Install CMake - Install the build tool: - **Windows:** Visual C++ Build Tools (http://landinghub.visualstudio.com/visual-cpp-build-tools) *Note: If you already have Visual Studio installed, you can skip this step. Also, when installing Visual C++ Build Tools, you may need to include the optional Windows SDK. I needed it to build on Windows 10.* - `pip install conan` ## Build Default Configuration A single command builds it: ``` conan build ``` Outputs go into the `exports` folder. ## Details This repo is set up for editor debugging in Visual Studio Code: https://code.visualstudio.com/. - `ctrl+shift+B` builds the project - `F5` runs the Debug build with breakpoint debugging enabled More detailed official docs for C/C++ in VS Code is here: https://code.visualstudio.com/docs/languages/cpp ## TODO - [ ] Cross-platform, current config is for Windows only - [ ] Set up a trivial package test run by `conan test_package` - [ ] Set up a trivial unit tests that get run on `conan build` - [ ] Find an easy way to do configure a "clean" function <file_sep>/conanfile.py import os from pathlib import Path from conans import ConanFile, CMake class HelloConan(ConanFile): name = "conan-hello" description = '"Hello world" project for testing Conan build and package setups' version = "0.1" license = "MIT" url = "https://github.com/memsharded/conan-hello-embed.git" settings = "os", "compiler", "arch" exports = "CMakeLists.txt", "hello.*", "main.cpp", "LICENSE", "README.md" def build(self): builddir = Path.cwd() / "build" self.build_type("Debug", builddir) self.build_type("Release", builddir) def package(self): self.copy("*.h", dst="include") self.copy("*.lib", dst="lib", src="lib") self.copy("*.a", dst="lib", src="lib") def package_info(self): self.cpp_info.libs=["hello"] def build_type(self, build_type, build_dir): bdir = build_dir / build_type # Debug install build bdir.mkdir(parents=True, exist_ok=True) os.chdir(str(bdir)) self.run(str.format('conan install ../.. -s build_type={}', build_type)) cmake = CMake(self.settings) self.run(str.format('cmake {src} {args}', src="../../src", args=cmake.command_line)) self.run(str.format('cmake --build . --config {} {}', build_type, cmake.build_config))
00db82172f7a6e74bc538dc998e12eb2d15a7c49
[ "Markdown", "Python", "CMake", "C++" ]
4
C++
brac10/conan-hello
5564cf8400d3dbe89ab769a4a18b614add99e0cb
bc2f2a6a212baf3b1e7edfb29370abcd9c636eab
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import {CdkDragDrop, moveItemInArray} from '@angular/cdk/drag-drop'; @Component({ selector: 'app-base-component', templateUrl: './base-component.component.html', styleUrls: ['./base-component.component.scss'] }) export class BaseComponentComponent implements OnInit { mydate: any; constructor() { } ngOnInit() { setInterval(()=>{ this.mydate = Date.now(); },1000) } timePeriods = [ 'Bronze age', 'Iron age', 'Middle ages', 'Early modern period', 'Long nineteenth century' ]; drop(event: CdkDragDrop<string[]>) { moveItemInArray(this.timePeriods, event.previousIndex, event.currentIndex); } }
59e52aa78e9928892381b114f7cfe207907dbb73
[ "TypeScript" ]
1
TypeScript
suryansh54/webOS
2cb21666c5079e2c5a909c9d82d251812e4ad0d1
fa45d671016ae98767e7d35dd80eebc2a89f8045
refs/heads/master
<repo_name>nathans7/react-seed<file_sep>/src/pages/Home/Home.jsx import React from 'react'; import { Route } from 'react-router-dom'; import { withRouter } from 'react-router'; class Home extends React.Component { constructor(props) { super(props); } render() { return ( <div className="Home"> Welcome to your react seed </div> ); } }; export default withRouter(Home); <file_sep>/src/index.js import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter, Route, NavLink, } from 'react-router-dom'; import App from './components/App/App'; import registerServiceWorker from './registerServiceWorker'; import './index.css'; ReactDOM.render(<BrowserRouter><App/></BrowserRouter>, document.getElementById('reactseed-app')); registerServiceWorker(); <file_sep>/src/js/util.js // JS Utilities function ajaxRequest(url, requestType, callback) { var request = new XMLHttpRequest(); request.open(requestType, url, true); request.onload = function() { if (request.status >= 200 && request.status < 400) { callback(request.responseText); } else { // We reached our target server, but it returned an error } }; request.onerror = function() { // There was a connection error of some sort }; request.send(); } function getCookieValue(a) { var b = document.cookie.match('(^|;)\\s*' + a + '\\s*=\\s*([^;]+)'); return b ? b.pop() : ''; } function createCookie(name,value,days) { var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime() + (days*24*60*60*1000)); expires = "; expires=" + date.toUTCString(); } document.cookie = name + "=" + value + expires + "; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function eraseCookie(name) { createCookie(name,"",-1); }
876432d654158808b977a851794ebc25448983ff
[ "JavaScript" ]
3
JavaScript
nathans7/react-seed
7fd40d87fff95b8f11c98ec7ebafedb5a546248d
9979ad9b55b3df2f26b1d65a44f088e1ac830a8f
refs/heads/master
<repo_name>Jonderlan/TrabalhoAndroid<file_sep>/app/src/main/java/com/example/vendaapp/helper/ConfiguracaoFirebase.java package com.example.vendaapp.helper; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; public class ConfiguracaoFirebase { private static DatabaseReference refereciaFirebase; private static FirebaseAuth referenciaAutenducacao; private static StorageReference referenciaStorage; public static DatabaseReference getFirebase(){ if (refereciaFirebase == null){ refereciaFirebase = FirebaseDatabase.getInstance().getReference(); } return refereciaFirebase; } //retorna instancia do FirebaseAuth public static FirebaseAuth getFirebaseAutenticacao(){ if(referenciaAutenducacao == null){ referenciaAutenducacao = FirebaseAuth.getInstance(); } return referenciaAutenducacao; } public static StorageReference getFirebaseStorage(){ if(referenciaStorage == null){ referenciaStorage = FirebaseStorage.getInstance().getReference(); } return referenciaStorage; } } <file_sep>/settings.gradle include ':app' rootProject.name='Venda app'
6cd676b0dc5dbb7ea621e5e990e52c9229e7b57b
[ "Java", "Gradle" ]
2
Java
Jonderlan/TrabalhoAndroid
40860a48b933838a36804d74cfcf94180db1eb33
0cb83189f7ad4d92dd6e12176761a247116c3875
refs/heads/master
<repo_name>vikrantRajan/TaskApp<file_sep>/routes/index.js module.exports = { getHomePage: (req, res) => { let query = "SELECT * FROM `todo` ORDER BY id ASC"; db.query(query, (err, result) => { console.log("resullts ", result); if(err) { res.redirect('/'); } res.render('index.ejs', { title: 'Welcome To the Task App | View all taks', todo: result }); }); } };<file_sep>/routes/task.js const fs = require('fs'); module.exports = { addTaskPage: (req, res) => { res.render('add-task.ejs', { title: 'Welcome To The Task App | Add A New Task', message: '' }); }, addTask: (req, res) => { // used for images which arent part of this project // if (!req.files) { // return res.status(400).send("No files were uploaded") // } let message = ''; let description = req.body.description; let category = req.body.category; var d = new Date(); var n = d.getTime(); console.log("Discription ", description) console.log('request ', req); console.log('body ', req.body); console.log('res ', res); }, editTaskPage: () => {}, editTask: () => {}, deleteTask: () => {} }
4b21701c7aff78136ee606a8526e83aa537b8846
[ "JavaScript" ]
2
JavaScript
vikrantRajan/TaskApp
75159243c9267f610067ba1e7d62112ee1219dc8
23ff5110bc92e4d7860bf82ed6bd5ce412ddc608
refs/heads/master
<repo_name>mstenkilde/ING_YNAB<file_sep>/README.md # ING_YNAB python script to make ING bank downloads consumable for YNAB <file_sep>/YNAB.py import os import csv import datetime from datetime import date # YNAB states: date,payee, memo, outflow, inflow # # example from bank #Datum;Naam / Omschrijving;Rekening;Tegenrekening;Code;Af Bij;Bedrag (EUR);MutatieSoort;Mededelingen #20180206;ETOS 7812 AMSTERDAM NLD;NL33INGB0655063803;;BA;Af;-18.67;Betaalautomaat;Pasvolgnr:002 05-02-2018 15:20 Transactie:A721P4 Term:W725Q5 #this works - but not quite right #"Date","Payee","Memo","Amount" #"2018-02-06","ETOS 7812 AMSTERDAM NLD","Pasvolgnr:002 Transactie:A721P4 Term:W725Q5","-18.67" # all , in [6] needs to be replaced with . print(amount.repl ace(",", ".")) done # date to be formatted 20180206 -> 02/06/18 (done) # Row[5] determines the value of [6] - if it is 'Af" then [6] needs to be a negative amount (*-1) OR! # better yet create a new column called outflow # examples: #07/23/16,Payee 1,Memo,100.00, #07/24/16,Payee 2,Memo,,500.00 inputfile = r"C:\Users\martin\Downloads\ING_dump.csv" outputfile = open(r"C:\Users\martin\Downloads\ING_import.csv", 'w') debug = "true" header = ['date', 'payee', 'memo', 'outflow', 'inflow'] def int2date(argdate: int): year = int(argdate / 10000) month = int((argdate % 10000) / 100) day = int(argdate % 100) return date(year, month, day) with open(inputfile) as csvfile: readCSV = csv.reader(csvfile, delimiter=',') next(readCSV) #Ignoring header line in csv for row in readCSV: #formatting date field datestring = str(int2date(int(row[0]))) payee = row[1] memo = row[8] #determine if its a negative amount if row[5] == 'Af': outflow = row[6].replace(",", ".") inflow = '' elif row[5] == 'Bij': inflow = row[6].replace(",", ".") outflow = '' #build string row_out = {datestring, payee, memo, outflow, inflow} #debug output if debug == 'true': print("date:", datestring) print("payee:", payee) print("memo:", memo) print("inflow:", inflow) print("outflow:", outflow) print row_out print("----") with open(inputfile + today + + ".csv", 'w', newline='') as e: dict_writer = csv.DictWriter(e, fieldnames=header) dict_writer.writeheader() dict_writer.writerow(row_out) #date,payee, memo, outflow, inflow
a587609eb11819ce6e84fd202d7204068a411c19
[ "Markdown", "Python" ]
2
Markdown
mstenkilde/ING_YNAB
fc24f7878e2a1ea416352161ff1127f076b71d93
0c3efb741559bea10b3042e6712507bbd3f284d7
refs/heads/master
<file_sep># labs theme <file_sep>#!/bin/bash dmenu_run -nb "#36352e" -nf "#848163" -sb "#36352e" -sf "#feefbd" -l 4 -g mc -w 0.3
a89e8e68f103de23be685c25cd0747be1fd38e03
[ "Markdown", "Shell" ]
2
Markdown
GA-KO/labs-theme
076c9ad8af6f9fffaf576df71299f065e56ad316
52983da6f7f6c7ba1588d331ba40a07538046986
refs/heads/master
<file_sep>shinyUI(fluidPage( theme = shinytheme("cosmo"), titlePanel("Snow Depth 2012-2014"), sidebarLayout( sidebarPanel( br(), dateInput("day", label = "Pick a day:", min = "2011-09-01", max = "2014-12-31", value = "2014-11-01", startview = "year"), br(), p("Draw range to zoom in, double-click to zoom out again."), br(), br(), br(), HTML("Data by <a href='http://en.ilmatieteenlaitos.fi/open-data-licence'> Finnish Meteorological Institute</a>."), br(), HTML("<a href='http://www.github.com/rOpenGov/fmi'>rmi R package</a> <NAME> et al. (C) 2014."), br(), br(), br(), HTML("More on this graph, see <a href='http://tuijasonkkila.fi/blog/2015/01/snow-in-lapland/'>blog posting</a>.") ), mainPanel( tabsetPanel( tabPanel("Graph", dygraphOutput("dygraph") ), tabPanel("Map", leafletOutput("leaflet")) ) ) ) ))<file_sep>shinyServer(function(input, output, session) { output$leaflet <- renderLeaflet({ leaflet() %>% addTiles() %>% addPopups(20.79, 69.05, "Enontekio, Kilpisjarvi") %>% addPopups(27.41, 68.42, "Inari, Saariselka tourist centre") %>% addPopups(29.18, 67.16, "Salla, Naruska") %>% setView(18.5167, 67.9000, zoom = 6) %>% addGeoJSON(hiihto1213) %>% addGeoJSON(hiihto1214) %>% addGeoJSON(hiihto1215) %>% addGeoJSON(hiihto1216) }) dayPicked <- reactive({ input$day }) output$dygraph <- renderDygraph({ dygraph(snow) %>% dySeries("Snow", label = "Saariselka") %>% dySeries("Snow.1", label = "Kilpisjarvi") %>% dySeries("Snow.2", label = "Salla") %>% dyAxis("x", drawGrid = FALSE) %>% dyAxis("y", label = "cm") %>% dyOptions(colors = RColorBrewer::brewer.pal(3, "Set2")) %>% dyLegend(show = "onmouseover", width = 400, showZeroValues = FALSE, hideOnMouseOut = TRUE) %>% dyEvent(date = dayPicked(), label = as.character(dayPicked()), labelLoc = "bottom") }) })<file_sep># snow Snow in Lapland as a [Shiny web app] (https://ttso.shinyapps.io/snow), see [blog posting](http://tuijasonkkila.fi/blog/2015/01/snow-in-lapland/). <file_sep>################################################################### # # Data by Finnish Meteorological Institute # http://en.ilmatieteenlaitos.fi/open-data-licence # # rmi R package <NAME> et al. (C) 2014 # https://github.com/rOpenGov/fmi # # Blog post http://tuijasonkkila.fi/blog/2015/01/snow-in-lapland/ # #################################################################### library(shiny) library(xts) library(dygraphs) library(leaflet) library(shinythemes) # ogr2ogr -f "GeoJSON" hiihtonnnn.gpx hiihtonnnn.geojson tracks hiihto1213 <- RJSONIO::fromJSON("hiihto1213.geojson") hiihto1214 <- RJSONIO::fromJSON("hiihto1214.geojson") hiihto1215 <- RJSONIO::fromJSON("hiihto1215.geojson") hiihto1216 <- RJSONIO::fromJSON("hiihto1216.geojson") saariselka <- read.table(file = "snow.Saariselka", header = TRUE, sep = ";", colClasses = c("Date", "numeric"), stringsAsFactors = FALSE) kilpisjarvi <- read.table(file = "snow.Kilpisjarvi", header = TRUE, sep = ";", colClasses = c("Date", "numeric"), stringsAsFactors = FALSE) salla <- read.table(file = "snow.Salla", header = TRUE, sep = ";", colClasses = c("Date", "numeric"), stringsAsFactors = FALSE) # Assuming here that -1 = 0 saariselka$Snow[saariselka$Snow == -1] <- 0 kilpisjarvi$Snow[kilpisjarvi$Snow == -1] <- 0 salla$Snow[salla$Snow == -1] <- 0 saariselka.xts <- as.xts(as.matrix(saariselka), order.by=saariselka[,1]) kilpisjarvi.xts <- as.xts(as.matrix(kilpisjarvi), order.by=kilpisjarvi[,1]) salla.xts <- as.xts(as.matrix(salla), order.by=salla[,1]) s.k <- cbind(saariselka.xts, kilpisjarvi.xts) snow <- cbind(s.k, salla.xts)
6000bb1b47cd61502c2862e038d8196acf0e0a1b
[ "Markdown", "R" ]
4
R
tts/snow
21a4746d43040abc8d6a2382042c04f637e6264a
ac2ed55c19e5dd4541da1506e7860fa0db07fd4a
refs/heads/main
<file_sep>const myButton=document.getElementById('button_ID'); var USER_ROCK_SELECTOR='ROCK'; var USER_PAPER_SELECTOR='PAPER'; var USER_SCISSOR_SELECTOR='SCISSOR'; var COMPUTER_ROCK_SELECTOR='ROCK'; var COMPUTER_PAPER_SELECTOR='PAPER'; var COMPUTER_SCISSOR_SELECTOR='SCISSOR'; var COMPUTER_SELECTION; let EnterUser; const RESULT_DRAW = 'DRAW'; const RESULT_PLAYER_WINS = 'PLAYER_WINS'; const RESULT_COMPUTER_WINS = 'COMPUTER_WINS'; let playerFunc=function whenUserPlay() { const intialEnterUser=prompt("Please enter"); EnterUser= intialEnterUser.toUpperCase(); if(USER_PAPER_SELECTOR===EnterUser) { console.log(USER_PAPER_SELECTOR); return USER_PAPER_SELECTOR; } else if (USER_ROCK_SELECTOR===EnterUser) { console.log(USER_ROCK_SELECTOR); return USER_ROCK_SELECTOR; } else if (USER_SCISSOR_SELECTOR===EnterUser) { console.log(USER_SCISSOR_SELECTOR); return USER_SCISSOR_SELECTOR; } else { alert("You Entered Something Wrong"); return; } } let computerFnc=function ComputerPlays() { COMPUTER_SELECTION=Math.random(); if(COMPUTER_SELECTION<0.33) { console.log(COMPUTER_ROCK_SELECTOR, COMPUTER_SELECTION); alert("Computer Chooses "+ COMPUTER_ROCK_SELECTOR); return (COMPUTER_ROCK_SELECTOR); } else if (COMPUTER_SELECTION>0.33 && COMPUTER_SELECTION<0.67) { console.log(COMPUTER_PAPER_SELECTOR, COMPUTER_SELECTION); alert("Computer Chooses "+ COMPUTER_PAPER_SELECTOR); return(COMPUTER_PAPER_SELECTOR); } else { console.log(COMPUTER_SCISSOR_SELECTOR, COMPUTER_SELECTION); alert("Computer Chooses "+ COMPUTER_SCISSOR_SELECTOR); return( COMPUTER_SCISSOR_SELECTOR); } } function final_Battle() { winning(playerFunc(),computerFnc()); } function winning(pchoice, cchoice) { if(pchoice===cchoice) { console.log(pchoice); console.log(cchoice); return alert(RESULT_DRAW); } else if((pchoice===USER_PAPER_SELECTOR && cchoice===COMPUTER_ROCK_SELECTOR) || (pchoice===USER_SCISSOR_SELECTOR && cchoice===COMPUTER_PAPER_SELECTOR) || (pchoice===USER_ROCK_SELECTOR && cchoice===COMPUTER_SCISSOR_SELECTOR)) { console.log(pchoice); console.log(cchoice); return alert(RESULT_PLAYER_WINS); } else { console.log(pchoice); console.log(cchoice); return alert(RESULT_COMPUTER_WINS); } } myButton.addEventListener('click', final_Battle);
2ebfcdbf2efbf150d631cc40d41027b65b373e3b
[ "JavaScript" ]
1
JavaScript
CHINTAN14987/Rock-Paper-Scissor
0b0d70a6b68d8006fc3d10e851f2cb903794eaee
914b41811b86fe3b04b3bbb8f78f2c714fd1ca1f
refs/heads/master
<file_sep>inputsource: inputsource.m gcc -framework Foundation -framework Carbon -O2 inputsource.m -o inputsource <file_sep># IceHe's Mac Confs Here are macOS configurations in directory `~`. <file_sep>rule "MD001" # Header levels should only increment by one level at a time rule "MD002" # First header should be a top level header rule "MD003" # Header style # rule "MD004" # Unordered list style rule "MD005" # Inconsistent indentation for list items at the same level rule "MD006" # Consider starting bulleted lists at the beginning of the line rule "MD007" , :indent => 4 # Unordered list indentation rule "MD009" # Trailing spaces rule "MD010" # Hard tabs rule "MD011" # Reversed link syntax rule "MD012" # Multiple consecutive blank lines # rule "MD013" # Line length # rule "MD014" # Dollar signs used before commands without showing output rule "MD018" # No space after hash on atx style header rule "MD019" # Multiple spaces after hash on atx style header rule "MD020" # No space inside hashes on closed atx style header rule "MD021" # Multiple spaces inside hashes on closed atx style header rule "MD022" # Headers should be surrounded by blank lines rule "MD023" # Headers must start at the beginning of the line # rule "MD024" # Multiple headers with the same content # rule "MD025" # Multiple top level headers in the same document rule "MD026" # Trailing punctuation in header # rule "MD027" # Multiple spaces after blockquote symbol rule "MD028" # Blank line inside blockquote # rule "MD029" # Ordered list item prefix # rule "MD030" # Spaces after list markers # rule "MD031" # Fenced code blocks should be surrounded by blank lines rule "MD032" # Lists should be surrounded by blank lines # rule "MD033" # Inline HTML # rule "MD034" # Bare URL used rule "MD035" # Horizontal style rule "MD036" # Emphasis used instead of a header rule "MD037" # Spaces inside emphasis markers # rule "MD038" # Spaces inside code span elements rule "MD039" # Spaces inside link text # rule "MD046" # Code block style <file_sep>####### # Git # ####### alias gau='git add -u && gs' alias gcf='git config' alias gcfl='git config -l' alias gcfe='git config -e' alias gcm='git commit -m' alias g.='git commit -m "`date +%F\ %T\ %a`"' alias ga.='gaa && g.' alias gcom='git checkout master' alias gdc='git diff --cached' alias gdwc='git diff --word-diff --cached' alias gfap='git fetch -ap' alias ggr='git grep' alias gi='git init' alias glf='git ls-files' alias glm='git pull main' alias glmm='git pull main master' alias glom='git pull origin master' alias gls='git ls-files' #alias gmom='git merge origin/master' alias gmom='git pull --rebase origin master' alias gmv='git mv' function gnb { branch=`git rev-parse --abbrev-ref HEAD` echo git push --set-upstream origin $branch git push --set-upstream origin $branch } alias grm='git rm' alias gr='git reset' alias grh='git reset HEAD --hard' alias gs='git status -bs' alias gst='git stash' alias gsd='git stash drop' alias gsl='git stash list' alias gsp='git stash pop' ## Git Experimental function args { echo \$?=$? echo \$#=$# echo \$@=$@ echo \$*=$* echo \$0=$0 echo \$1=$1 echo \$2=$2 echo \$3=$3 echo \$4=$4 echo \$5=$5 } function gcmc { if [[ $1 == "" ]]; then echo && echo custom text for git 404! return fi export clipboard=`pbpaste` echo echo \$ git add $clipboard ga $clipboard gs echo echo \$ git commit -m \"$1\" gcm "$1" } # git commit message prefix function gcmp { if [[ $1 == "" ]]; then echo && echo verb prefix for git 404! return fi gcmc "$1 `pbpaste`" } alias gadd="gcmp Add" alias gupd="gcmp Update" alias gfix="gcmp Fix" alias gimp="gcmp Improve" alias gref="gcmp Refactor" alias grem="gcmp Remove" alias grvt="gcmp Revert" alias gsim="gcmp Simplify" alias gtt="gcmp Test" alias gdep="gcmp Deprecate" # git commit short message prefix function gcsmp { if [[ $1 == "" || $2 == "" ]]; then echo && echo verb & type prefix for git 404! return fi gs echo #desc=`git status -s | grep "$2 " | awk -F "[./]" '{print $(NF-1)}'` desc=`git status -s | grep "$2 " | awk -F "[/]" '{print $NF}'` cmd="git commit -m '$1 $desc'" echo \$ $cmd echo eval $cmd } alias gaddj="gcsmp Add A" alias gupdj="gcsmp Update M" alias gfixj="gcsmp Fix M" alias gimpj="gcsmp Improve M" alias gmovj="gcsmp Move R" alias grenj="gcsmp Rename R" alias grefj="gcsmp Refactor M" alias gremj="gcsmp Remove D" alias gsimj="gcsmp Simplify M" alias gttj="gcsmp Test M" alias gdepj="gcsmp Deprecate M" function gren { gs echo desc=`git status -s | grep "R " | awk -F "R " '{ print $2 }'` cmd="git commit -m 'Rename $desc'" echo \$ $cmd echo eval $cmd } function gmov { gs echo desc=`git status -s | grep "R " | awk -F "R " '{ print $2 }'` cmd="git commit -m 'Move $desc'" echo \$ $cmd echo eval $cmd } <file_sep># If you come from bash you might have to change your $PATH. # export PATH=$HOME/bin:/usr/local/bin:$PATH # Path to your oh-my-zsh installation. export ZSH="/Users/IceHe/.oh-my-zsh" # Set name of the theme to load --- if set to "random", it will # load a random theme each time oh-my-zsh is loaded, in which case, # to know which specific one was loaded, run: echo $RANDOM_THEME # See https://github.com/robbyrussell/oh-my-zsh/wiki/Themes ZSH_THEME="robbyrussell" # Set list of themes to pick from when loading at random # Setting this variable when ZSH_THEME=random will cause zsh to load # a theme from this variable instead of looking in ~/.oh-my-zsh/themes/ # If set to an empty array, this variable will have no effect. # ZSH_THEME_RANDOM_CANDIDATES=( "robbyrussell" "agnoster" ) # Uncomment the following line to use case-sensitive completion. # CASE_SENSITIVE="true" # Uncomment the following line to use hyphen-insensitive completion. # Case-sensitive completion must be off. _ and - will be interchangeable. # HYPHEN_INSENSITIVE="true" # Uncomment the following line to disable bi-weekly auto-update checks. # DISABLE_AUTO_UPDATE="true" # Uncomment the following line to automatically update without prompting. # DISABLE_UPDATE_PROMPT="true" # Uncomment the following line to change how often to auto-update (in days). export UPDATE_ZSH_DAYS=1 # Uncomment the following line if pasting URLs and other text is messed up. # DISABLE_MAGIC_FUNCTIONS=true # Uncomment the following line to disable colors in ls. # DISABLE_LS_COLORS="true" # Uncomment the following line to disable auto-setting terminal title. # DISABLE_AUTO_TITLE="true" # Uncomment the following line to enable command auto-correction. # ENABLE_CORRECTION="true" # Uncomment the following line to display red dots whilst waiting for completion. # COMPLETION_WAITING_DOTS="true" # Uncomment the following line if you want to disable marking untracked files # under VCS as dirty. This makes repository status check for large repositories # much, much faster. # DISABLE_UNTRACKED_FILES_DIRTY="true" # Uncomment the following line if you want to change the command execution time # stamp shown in the history command output. # You can set one of the optional three formats: # "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd" # or set a custom format using the strftime function format specifications, # see 'man strftime' for details. # HIST_STAMPS="yyyy-mm-dd" # Would you like to use another custom folder than $ZSH/custom? # ZSH_CUSTOM=/path/to/new-custom-folder # Which plugins would you like to load? # Standard plugins can be found in ~/.oh-my-zsh/plugins/* # Custom plugins may be added to ~/.oh-my-zsh/custom/plugins/ # Example format: plugins=(rails git textmate ruby lighthouse) # Add wisely, as too many plugins slow down shell startup. #plugins=(git) plugins=( bgnotify # test branch # test colored-man-pages # test colorize # test : need python 3.6 command-not-found # test # requirement : https://github.com/Homebrew/homebrew-command-not-found copydir copyfile cp # docker # docker-compose # dotenv # to test? git globalias osx sudo tmux vundle z zsh-autosuggestions ) source $ZSH/oh-my-zsh.sh # User configuration # export MANPATH="/usr/local/man:$MANPATH" # You may need to manually set your language environment # export LANG=en_US.UTF-8 # Preferred editor for local and remote sessions # if [[ -n $SSH_CONNECTION ]]; then # export EDITOR='vim' # else # export EDITOR='mvim' # fi # Compilation flags # export ARCHFLAGS="-arch x86_64" # Set personal aliases, overriding those provided by oh-my-zsh libs, # plugins, and themes. Aliases can be placed here, though oh-my-zsh # users are encouraged to define aliases within the ZSH_CUSTOM folder. # For a full list of active aliases, run `alias`. # # Example aliases # alias zshconfig="mate ~/.zshrc" # alias ohmyzsh="mate ~/.oh-my-zsh" ######### # IceHe # ######### # Notice: # The configs above section "IceHe" are generated # when in oh-my-zsh installation. # Try not to modify them above if unneccessary. # If I need, I will just overwrite it bewlow. ####### # ENV # ####### # Locale export LANG=en_US.UTF-8 # export LANG=zh_CN.UTF-8 ## - macOS 下命令行终端无法输入中文或中文显示 : https://blog.csdn.net/j754379117/article/details/53897115 ## - 解决 macOs SSH LC_CTYPE 警告问题 : http://data4q.com/2018/01/06/%E8%A7%A3%E5%86%B3mac-os-x-ssh-lc_ctype%E8%AD%A6%E5%91%8A%E9%97%AE%E9%A2%98/ # PATH # # Config files on macOS: # # - /etc/paths # - /etc/paths.d/* # - /etc/profile # - Auto Completion : eval `/usr/libexec/path_helper -s` # # e.g. /etc/paths # # - Dirs */local/* must be put above /bin, /usr/bin and etc. # so that commands within */local/* can be accessible at first. # # ```text # /opt/local/sbin # /opt/local/bin # /opt/sbin # /opt/bin # /usr/local/sbin # /usr/local/bin # /usr/sbin # /usr/bin # /sbin # /bin # ```` # Go export GOPATH=$HOME/go export GOROOT=/usr/local/opt/go/libexec export PATH=$PATH:$GOPATH/bin export PATH=$PATH:$GOROOT/bin ### GOBIN must be an absolute path export GOBIN=~/go/bin # Groovy SDK export GROOVY_HOME=/usr/local/opt/groovy/libexec # JDK export JAVA_HOME=`/usr/libexec/java_home -v 1.8` # MySQL 5.x # Current version is 8.0+ by default. (2019-05-01) export PATH="/usr/local/opt/[email protected]/bin:$PATH" # export PATH="/usr/local/opt/[email protected]/bin:$PATH" # NVM export NVM_DIR="~/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm # CLI Editor if [[ -n $SSH_CONNECTION ]]; then export EDITOR='vim' else export EDITOR='nvim' fi ######### # ALIAS # ######### # Shortest alias bu='brew update -vvv && brew upgrade -vvv' alias d='docker' alias e='exit' alias m='mvn' alias o='open' alias pb='pbcopy' alias pbn='tr -d "\n" | pbcopy' alias rm='safe-rm' alias rp='realpath' # Applications alias st='open -a /Applications/Sublime\ Text.app/' alias vc='open -a /Applications/Visual\ Studio\ Code.app' # CD ( change directory ) alias zd='cd ~/Desktop' alias zl='cd ~/Downloads' alias zo='cd ~/Documents' alias zi='cd ~/Documents/Lib' alias ze='cd /etc' alias zc='cd /usr/local/Cellar' alias z.='cd ~/.config' alias zh='cd ~/.config/zsh' alias zp='cd ~/.privacy' alias zz='cd ~/.oh-my-zsh' # Docker ( seldom ) # alias dps='docker ps' # alias dst='docker start' # alias dsp='docker stop' # alias de='docker exec -it' # alias drm='docker rm' # alias drmi='docker rmi' ## Hexo ( almost not ) # alias h='zb && hexo s' # alias ha='zb && hexo clean && hexo g && hexo s' # alias tg='zb && clear && hexo clean && hexo deploy && -' # MySQL alias ms="mysql.server" # Redis alias rs="redis-server /usr/local/etc/redis.conf" # Vim | NeoVim alias v='nvim' alias sv='sudo nvim' # alias vim='nvim' ## Modify Files alias vgi='v ./.gitignore' alias vh='v /etc/hosts' alias vv='v ~/.vimrc' alias vcv='v ~/.cvimrc' alias viv='v ~/.ideavimrc' alias vt='v ~/.tmux.conf' alias vz='v ~/.zshrc' alias vk='v ~/.config/karabiner/karabiner.json' alias stk='st ~/.config/karabiner/karabiner.json' alias vck='vc ~/.config/karabiner/karabiner.json' alias vvc='v ~/.config/vscode/settings.json' alias stvc='st ~/.config/vscode/settings.json' alias vcvc='vc ~/.config/vscode/settings.json' # X if [[ -f "/Users/IceHe/.privacy/zsh.zsh" ]]; then source /Users/IceHe/.privacy/zsh.zsh fi # Source source ~/.config/zsh/fzf.zsh source ~/.config/zsh/git.zsh source ~/.config/zsh/ip.zsh source ~/.config/zsh/ls.zsh source ~/.config/zsh/proxy.zsh source ~/.config/zsh/tmux.zsh # Reload ZSH Configs in .zshrc alias sz='source ~/.zshrc && echo \$ source ~/.zshrc' # Clipboard (testing) function jj() { tmp_json=~/Downloads/tmp-json/$(date +%F_%T_%a_$RANDOM).json pbpaste | sed -E 's/\\(.)/\1/g' | /usr/local/bin/jq | tee -a $tmp_json #open -a "/Applications/Google Chrome.app" $tmp_json open $tmp_json } ############ # BIND-KEY # ############ # Expand Alias # ( including global via plugin globalias ) # ( REF : ~/.oh-my-zsh/plugins/globalias/globalias.plugin.zsh ) bindkey -M emacs "^x " globalias bindkey -M viins "^x " globalias # Revert improper configs in plugin globalias bindkey -M isearch " " magic-space bindkey -M emacs " " magic-space bindkey -M viins " " magic-space bindkey -M emacs -r "^ " bindkey -M viins -r "^ " <file_sep># .tools - `inputsource` : https://github.com/hnakamur/inputsource - `pngquant` : https://pngquant.org/ - `qshell` : https://developer.qiniu.com/kodo/tools/1302/qshell ## Link to tools ### Make links ```bash cd /path/to/TOOL ln -s $(realpath TOOL) /usr/local/bin/TOOL # e.g. cd inputsource ln -s $(realpath inputsource) /usr/local/bin/inputsource ``` ### Check links ```bash # list paths/to/TOOL where TOOL # Show which to use which TOOL # Check link to TOOL ls -hl path/to/TOOL # e.g. $ where inputsource /usr/bin/inputsource /usr/local/bin/inputsource $ which inputsource /usr/local/bin/inputsource $ ls -l intputsource lrwxr-xr-x 1 icehe admin 43 Sep 9 12:50 /usr/local/bin/inputsource -> /Users/IceHe/.tools/inputsource/inputsource ```
1e2c016a2aeee6bc116651e86aa968712d861316
[ "Markdown", "Makefile", "Ruby", "Shell" ]
6
Makefile
IceHe/dotfiles
bf0e0b863084e632881f7e74fc598d09c7374ec9
5b5cd3b544a79d18ebb3d38a2e67933b98fa7e70
refs/heads/master
<file_sep><!DOCTYPE HTML> <html lang ="pt-br"> <?php include("default.php"); ?> <body> <div class ="container"> <?php include("menu.php"); ?> </div> </body> </html>
1717e311684557f6799f901356988a1abd0c22a3
[ "PHP" ]
1
PHP
cauantaguchi/prjagenda
4135af2c672ac3289b6047089fc14938a2203886
6a394cf8815018cd558d47c5b3548f4d30fa0962