row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
34,737
This is my code "<!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.0"> <title>YouTube Niche Finder Tool</title> <style> /* Add your CSS styling here */ </style> </head> <body> <h1>YouTube Niche Finder</h1> <input type="text" id="searchQuery" placeholder="Enter a keyword…"> <button id="searchBtn">Find Niche</button> <div id="results"></div> <script> document.getElementById('searchBtn').addEventListener('click', () => { const query = document.getElementById('searchQuery').value; fetch('/search', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query }), // send the search query to the server }) .then(response => response.json()) .then(data => { document.getElementById('results').textContent = `Competition Level: ${data.competition}; }) .catch(error => { console.error('Error:', error); document.getElementById('results').textContent = 'An error occurred.'; }); }); </script> </body> </html> ". Now it says "(index):37 Uncaught SyntaxError: Unexpected end of input (at (index):37:5)"
60204c46d9435840882c602baeab7aed
{ "intermediate": 0.30784928798675537, "beginner": 0.4804416298866272, "expert": 0.21170909702777863 }
34,738
/* * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.micode.notes.ui; import android.content.Context; import android.database.Cursor; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.LinearLayout; import android.widget.TextView; //import net.micode.notes.R; import com.example.namespace.R; import net.micode.notes.data.Notes; import net.micode.notes.data.Notes.NoteColumns; public class FoldersListAdapter extends CursorAdapter { public static final String [] PROJECTION = { NoteColumns.ID, NoteColumns.SNIPPET }; public static final int ID_COLUMN = 0; public static final int NAME_COLUMN = 1; public FoldersListAdapter(Context context, Cursor c) { super(context, c); // TODO Auto-generated constructor stub } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return new FolderListItem(context); } @Override public void bindView(View view, Context context, Cursor cursor) { if (view instanceof FolderListItem) { String folderName = (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); ((FolderListItem) view).bind(folderName); } } public String getFolderName(Context context, int position) { Cursor cursor = (Cursor) getItem(position); return (cursor.getLong(ID_COLUMN) == Notes.ID_ROOT_FOLDER) ? context .getString(R.string.menu_move_parent_folder) : cursor.getString(NAME_COLUMN); } private class FolderListItem extends LinearLayout { private TextView mName; public FolderListItem(Context context) { super(context); inflate(context, R.layout.folder_list_item, this); mName = (TextView) findViewById(R.id.tv_folder_name); } public void bind(String name) { mName.setText(name); } } } 按照以下格式整理上述代码- PROJECTION: String[] - COLUMN_ID: int - COLUMN_BG_COLOR_ID: int - COLUMN_SNIPPET: int - TAG: String+ onDeleted(context: Context, appWidgetIds: int[]): void + update(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: int[]): void + getBgResourceId(bgId: int): int (Abstract) + getLayoutId(): int (Abstract) + getWidgetType(): int (Abstract) - getNoteWidgetInfo(context: Context, widgetId: int): Cursor - update(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: int[], privacyMode: boolean): void
1dcc03b2ea626e21407969cf11bb7541
{ "intermediate": 0.27008265256881714, "beginner": 0.4352825880050659, "expert": 0.2946348190307617 }
34,739
/* * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.micode.notes.ui; import android.content.Context; import android.graphics.Rect; import android.text.Layout; import android.text.Selection; import android.text.Spanned; import android.text.TextUtils; import android.text.style.URLSpan; import android.util.AttributeSet; import android.util.Log; import android.view.ContextMenu; import android.view.KeyEvent; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import android.view.MotionEvent; import android.widget.EditText; //import net.micode.notes.R; import com.example.namespace.R; import java.util.HashMap; import java.util.Map; public class NoteEditText extends EditText { private static final String TAG = "NoteEditText"; private int mIndex; private int mSelectionStartBeforeDelete; private static final String SCHEME_TEL = "tel:" ; private static final String SCHEME_HTTP = "http:" ; private static final String SCHEME_EMAIL = "mailto:" ; private static final Map<String, Integer> sSchemaActionResMap = new HashMap<String, Integer>(); static { sSchemaActionResMap.put(SCHEME_TEL, R.string.note_link_tel); sSchemaActionResMap.put(SCHEME_HTTP, R.string.note_link_web); sSchemaActionResMap.put(SCHEME_EMAIL, R.string.note_link_email); } /** * Call by the {@link NoteEditActivity} to delete or add edit text */ public interface OnTextViewChangeListener { /** * Delete current edit text when {@link KeyEvent#KEYCODE_DEL} happens * and the text is null */ void onEditTextDelete(int index, String text); /** * Add edit text after current edit text when {@link KeyEvent#KEYCODE_ENTER} * happen */ void onEditTextEnter(int index, String text); /** * Hide or show item option when text change */ void onTextChange(int index, boolean hasText); } private OnTextViewChangeListener mOnTextViewChangeListener; public NoteEditText(Context context) { super(context, null); mIndex = 0; } public void setIndex(int index) { mIndex = index; } public void setOnTextViewChangeListener(OnTextViewChangeListener listener) { mOnTextViewChangeListener = listener; } public NoteEditText(Context context, AttributeSet attrs) { super(context, attrs, android.R.attr.editTextStyle); } public NoteEditText(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO Auto-generated constructor stub } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: int x = (int) event.getX(); int y = (int) event.getY(); x -= getTotalPaddingLeft(); y -= getTotalPaddingTop(); x += getScrollX(); y += getScrollY(); Layout layout = getLayout(); int line = layout.getLineForVertical(y); int off = layout.getOffsetForHorizontal(line, x); Selection.setSelection(getText(), off); break; } return super.onTouchEvent(event); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_ENTER: if (mOnTextViewChangeListener != null) { return false; } break; case KeyEvent.KEYCODE_DEL: mSelectionStartBeforeDelete = getSelectionStart(); break; default: break; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch(keyCode) { case KeyEvent.KEYCODE_DEL: if (mOnTextViewChangeListener != null) { if (0 == mSelectionStartBeforeDelete && mIndex != 0) { mOnTextViewChangeListener.onEditTextDelete(mIndex, getText().toString()); return true; } } else { Log.d(TAG, "OnTextViewChangeListener was not seted"); } break; case KeyEvent.KEYCODE_ENTER: if (mOnTextViewChangeListener != null) { int selectionStart = getSelectionStart(); String text = getText().subSequence(selectionStart, length()).toString(); setText(getText().subSequence(0, selectionStart)); mOnTextViewChangeListener.onEditTextEnter(mIndex + 1, text); } else { Log.d(TAG, "OnTextViewChangeListener was not seted"); } break; default: break; } return super.onKeyUp(keyCode, event); } @Override protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) { if (mOnTextViewChangeListener != null) { if (!focused && TextUtils.isEmpty(getText())) { mOnTextViewChangeListener.onTextChange(mIndex, false); } else { mOnTextViewChangeListener.onTextChange(mIndex, true); } } super.onFocusChanged(focused, direction, previouslyFocusedRect); } @Override protected void onCreateContextMenu(ContextMenu menu) { if (getText() instanceof Spanned) { int selStart = getSelectionStart(); int selEnd = getSelectionEnd(); int min = Math.min(selStart, selEnd); int max = Math.max(selStart, selEnd); final URLSpan[] urls = ((Spanned) getText()).getSpans(min, max, URLSpan.class); if (urls.length == 1) { int defaultResId = 0; for(String schema: sSchemaActionResMap.keySet()) { if(urls[0].getURL().indexOf(schema) >= 0) { defaultResId = sSchemaActionResMap.get(schema); break; } } if (defaultResId == 0) { defaultResId = R.string.note_link_other; } menu.add(0, 0, 0, defaultResId).setOnMenuItemClickListener( new OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { // goto a new intent urls[0].onClick(NoteEditText.this); return true; } }); } } super.onCreateContextMenu(menu); } } 整理成puml类图文件格式
8b22c7215802d1093d60d3c9454594e8
{ "intermediate": 0.31023457646369934, "beginner": 0.4916541278362274, "expert": 0.19811129570007324 }
34,740
/* * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.micode.notes.ui; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.appwidget.AppWidgetManager; import android.content.AsyncQueryHandler; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.ActionMode; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Display; import android.view.HapticFeedbackConstants; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnCreateContextMenuListener; import android.view.View.OnTouchListener; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.PopupMenu; import android.widget.TextView; import android.widget.Toast; //import net.micode.notes.R; import com.example.namespace.R; import net.micode.notes.data.Notes; import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.gtask.remote.GTaskSyncService; import net.micode.notes.model.WorkingNote; import net.micode.notes.tool.BackupUtils; import net.micode.notes.tool.DataUtils; import net.micode.notes.tool.ResourceParser; import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute; import net.micode.notes.widget.NoteWidgetProvider_2x; import net.micode.notes.widget.NoteWidgetProvider_4x; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashSet; public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener { private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0; private static final int FOLDER_LIST_QUERY_TOKEN = 1; private static final int MENU_FOLDER_DELETE = 0; private static final int MENU_FOLDER_VIEW = 1; private static final int MENU_FOLDER_CHANGE_NAME = 2; private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction"; private enum ListEditState { NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER }; private ListEditState mState; private BackgroundQueryHandler mBackgroundQueryHandler; private NotesListAdapter mNotesListAdapter; private ListView mNotesListView; private Button mAddNewNote; private boolean mDispatch; private int mOriginY; private int mDispatchY; private TextView mTitleBar; private long mCurrentFolderId; private ContentResolver mContentResolver; private ModeCallback mModeCallBack; private static final String TAG = "NotesListActivity"; public static final int NOTES_LISTVIEW_SCROLL_RATE = 30; private NoteItemData mFocusNoteDataItem; private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?"; private static final String ROOT_FOLDER_SELECTION = "(" + NoteColumns.TYPE + "<>" + Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?)" + " OR (" + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND " + NoteColumns.NOTES_COUNT + ">0)"; private final static int REQUEST_CODE_OPEN_NODE = 102; private final static int REQUEST_CODE_NEW_NODE = 103; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.note_list); initResources(); /** * Insert an introduction when user firstly use this application */ setAppInfoFromRawRes(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK && (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) { mNotesListAdapter.changeCursor(null); } else { super.onActivityResult(requestCode, resultCode, data); } } private void setAppInfoFromRawRes() { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) { StringBuilder sb = new StringBuilder(); InputStream in = null; try { in = getResources().openRawResource(R.raw.introduction); if (in != null) { InputStreamReader isr = new InputStreamReader(in); BufferedReader br = new BufferedReader(isr); char [] buf = new char[1024]; int len = 0; while ((len = br.read(buf)) > 0) { sb.append(buf, 0, len); } } else { Log.e(TAG, "Read introduction file error"); return; } } catch (IOException e) { e.printStackTrace(); return; } finally { if(in != null) { try { in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER, AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE, ResourceParser.RED); note.setWorkingText(sb.toString()); if (note.saveNote()) { sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit(); } else { Log.e(TAG, "Save introduction note error"); return; } } } @Override protected void onStart() { super.onStart(); startAsyncNotesListQuery(); } private void initResources() { mContentResolver = this.getContentResolver(); mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver()); mCurrentFolderId = Notes.ID_ROOT_FOLDER; mNotesListView = (ListView) findViewById(R.id.notes_list); mNotesListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.note_list_footer, null), null, false); mNotesListView.setOnItemClickListener(new OnListItemClickListener()); mNotesListView.setOnItemLongClickListener(this); mNotesListAdapter = new NotesListAdapter(this); mNotesListView.setAdapter(mNotesListAdapter); mAddNewNote = (Button) findViewById(R.id.btn_new_note); mAddNewNote.setOnClickListener(this); mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener()); mDispatch = false; mDispatchY = 0; mOriginY = 0; mTitleBar = (TextView) findViewById(R.id.tv_title_bar); mState = ListEditState.NOTE_LIST; mModeCallBack = new ModeCallback(); } private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener { private DropdownMenu mDropDownMenu; private ActionMode mActionMode; private MenuItem mMoveMenu; public boolean onCreateActionMode(ActionMode mode, Menu menu) { getMenuInflater().inflate(R.menu.note_list_options, menu); menu.findItem(R.id.delete).setOnMenuItemClickListener(this); mMoveMenu = menu.findItem(R.id.move); if (mFocusNoteDataItem.getParentId() == Notes.ID_CALL_RECORD_FOLDER || DataUtils.getUserFolderCount(mContentResolver) == 0) { mMoveMenu.setVisible(false); } else { mMoveMenu.setVisible(true); mMoveMenu.setOnMenuItemClickListener(this); } mActionMode = mode; mNotesListAdapter.setChoiceMode(true); mNotesListView.setLongClickable(false); mAddNewNote.setVisibility(View.GONE); View customView = LayoutInflater.from(NotesListActivity.this).inflate( R.layout.note_list_dropdown_menu, null); mode.setCustomView(customView); mDropDownMenu = new DropdownMenu(NotesListActivity.this, (Button) customView.findViewById(R.id.selection_menu), R.menu.note_list_dropdown); mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){ public boolean onMenuItemClick(MenuItem item) { mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected()); updateMenu(); return true; } }); return true; } private void updateMenu() { int selectedCount = mNotesListAdapter.getSelectedCount(); // Update dropdown menu String format = getResources().getString(R.string.menu_select_title, selectedCount); mDropDownMenu.setTitle(format); MenuItem item = mDropDownMenu.findItem(R.id.action_select_all); if (item != null) { if (mNotesListAdapter.isAllSelected()) { item.setChecked(true); item.setTitle(R.string.menu_deselect_all); } else { item.setChecked(false); item.setTitle(R.string.menu_select_all); } } } public boolean onPrepareActionMode(ActionMode mode, Menu menu) { // TODO Auto-generated method stub return false; } public boolean onActionItemClicked(ActionMode mode, MenuItem item) { // TODO Auto-generated method stub return false; } public void onDestroyActionMode(ActionMode mode) { mNotesListAdapter.setChoiceMode(false); mNotesListView.setLongClickable(true); mAddNewNote.setVisibility(View.VISIBLE); } public void finishActionMode() { mActionMode.finish(); } public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { mNotesListAdapter.setCheckedItem(position, checked); updateMenu(); } // public boolean onMenuItemClick(MenuItem item) { // if (mNotesListAdapter.getSelectedCount() == 0) { // Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none), // Toast.LENGTH_SHORT).show(); // return true; // } // // switch (item.getItemId()) { // case R.id.delete: // AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); // builder.setTitle(getString(R.string.alert_title_delete)); // builder.setIcon(android.R.drawable.ic_dialog_alert); // builder.setMessage(getString(R.string.alert_message_delete_notes, // mNotesListAdapter.getSelectedCount())); // builder.setPositiveButton(android.R.string.ok, // new DialogInterface.OnClickListener() { // public void onClick(DialogInterface dialog, // int which) { // batchDelete(); // } // }); // builder.setNegativeButton(android.R.string.cancel, null); // builder.show(); // break; // case R.id.move: // startQueryDestinationFolders(); // break; // default: // return false; // } // return true; // } public boolean onMenuItemClick(MenuItem item) { if (mNotesListAdapter.getSelectedCount() == 0) { Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none), Toast.LENGTH_SHORT).show(); return true; } int itemId = item.getItemId(); if (itemId == R.id.delete) { AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); builder.setTitle(getString(R.string.alert_title_delete)); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setMessage(getString(R.string.alert_message_delete_notes, mNotesListAdapter.getSelectedCount())); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { batchDelete(); } }); builder.setNegativeButton(android.R.string.cancel, null); builder.show(); } else if (itemId == R.id.move) { startQueryDestinationFolders(); } else { return false; } return true; } } private class NewNoteOnTouchListener implements OnTouchListener { public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: { Display display = getWindowManager().getDefaultDisplay(); int screenHeight = display.getHeight(); int newNoteViewHeight = mAddNewNote.getHeight(); int start = screenHeight - newNoteViewHeight; int eventY = start + (int) event.getY(); /** * Minus TitleBar's height */ if (mState == ListEditState.SUB_FOLDER) { eventY -= mTitleBar.getHeight(); start -= mTitleBar.getHeight(); } /** * HACKME:When click the transparent part of "New Note" button, dispatch * the event to the list view behind this button. The transparent part of * "New Note" button could be expressed by formula y=-0.12x+94(Unit:pixel) * and the line top of the button. The coordinate based on left of the "New * Note" button. The 94 represents maximum height of the transparent part. * Notice that, if the background of the button changes, the formula should * also change. This is very bad, just for the UI designer's strong requirement. */ if (event.getY() < (event.getX() * (-0.12) + 94)) { View view = mNotesListView.getChildAt(mNotesListView.getChildCount() - 1 - mNotesListView.getFooterViewsCount()); if (view != null && view.getBottom() > start && (view.getTop() < (start + 94))) { mOriginY = (int) event.getY(); mDispatchY = eventY; event.setLocation(event.getX(), mDispatchY); mDispatch = true; return mNotesListView.dispatchTouchEvent(event); } } break; } case MotionEvent.ACTION_MOVE: { if (mDispatch) { mDispatchY += (int) event.getY() - mOriginY; event.setLocation(event.getX(), mDispatchY); return mNotesListView.dispatchTouchEvent(event); } break; } default: { if (mDispatch) { event.setLocation(event.getX(), mDispatchY); mDispatch = false; return mNotesListView.dispatchTouchEvent(event); } break; } } return false; } }; private void startAsyncNotesListQuery() { String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION : NORMAL_SELECTION; mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null, Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, new String[] { String.valueOf(mCurrentFolderId) }, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC"); } private final class BackgroundQueryHandler extends AsyncQueryHandler { public BackgroundQueryHandler(ContentResolver contentResolver) { super(contentResolver); } @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { switch (token) { case FOLDER_NOTE_LIST_QUERY_TOKEN: mNotesListAdapter.changeCursor(cursor); break; case FOLDER_LIST_QUERY_TOKEN: if (cursor != null && cursor.getCount() > 0) { showFolderListMenu(cursor); } else { Log.e(TAG, "Query folder failed"); } break; default: return; } } } private void showFolderListMenu(Cursor cursor) { AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); builder.setTitle(R.string.menu_title_select_folder); final FoldersListAdapter adapter = new FoldersListAdapter(this, cursor); builder.setAdapter(adapter, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { DataUtils.batchMoveToFolder(mContentResolver, mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which)); Toast.makeText( NotesListActivity.this, getString(R.string.format_move_notes_to_folder, mNotesListAdapter.getSelectedCount(), adapter.getFolderName(NotesListActivity.this, which)), Toast.LENGTH_SHORT).show(); mModeCallBack.finishActionMode(); } }); builder.show(); } private void createNewNote() { Intent intent = new Intent(this, NoteEditActivity.class); intent.setAction(Intent.ACTION_INSERT_OR_EDIT); intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId); this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE); } private void batchDelete() { new AsyncTask<Void, Void, HashSet<AppWidgetAttribute>>() { protected HashSet<AppWidgetAttribute> doInBackground(Void... unused) { HashSet<AppWidgetAttribute> widgets = mNotesListAdapter.getSelectedWidget(); if (!isSyncMode()) { // if not synced, delete notes directly if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter .getSelectedItemIds())) { } else { Log.e(TAG, "Delete notes error, should not happens"); } } else { // in sync mode, we'll move the deleted note into the trash // folder if (!DataUtils.batchMoveToFolder(mContentResolver, mNotesListAdapter .getSelectedItemIds(), Notes.ID_TRASH_FOLER)) { Log.e(TAG, "Move notes to trash folder error, should not happens"); } } return widgets; } @Override protected void onPostExecute(HashSet<AppWidgetAttribute> widgets) { if (widgets != null) { for (AppWidgetAttribute widget : widgets) { if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) { updateWidget(widget.widgetId, widget.widgetType); } } } mModeCallBack.finishActionMode(); } }.execute(); } private void deleteFolder(long folderId) { if (folderId == Notes.ID_ROOT_FOLDER) { Log.e(TAG, "Wrong folder id, should not happen " + folderId); return; } HashSet<Long> ids = new HashSet<Long>(); ids.add(folderId); HashSet<AppWidgetAttribute> widgets = DataUtils.getFolderNoteWidget(mContentResolver, folderId); if (!isSyncMode()) { // if not synced, delete folder directly DataUtils.batchDeleteNotes(mContentResolver, ids); } else { // in sync mode, we'll move the deleted folder into the trash folder DataUtils.batchMoveToFolder(mContentResolver, ids, Notes.ID_TRASH_FOLER); } if (widgets != null) { for (AppWidgetAttribute widget : widgets) { if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) { updateWidget(widget.widgetId, widget.widgetType); } } } } private void openNode(NoteItemData data) { Intent intent = new Intent(this, NoteEditActivity.class); intent.setAction(Intent.ACTION_VIEW); intent.putExtra(Intent.EXTRA_UID, data.getId()); this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE); } private void openFolder(NoteItemData data) { mCurrentFolderId = data.getId(); startAsyncNotesListQuery(); if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { mState = ListEditState.CALL_RECORD_FOLDER; mAddNewNote.setVisibility(View.GONE); } else { mState = ListEditState.SUB_FOLDER; } if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { mTitleBar.setText(R.string.call_record_folder_name); } else { mTitleBar.setText(data.getSnippet()); } mTitleBar.setVisibility(View.VISIBLE); } // public void onClick(View v) { // switch (v.getId()) { // case R.id.btn_new_note: // createNewNote(); // break; // default: // break; // } // } public void onClick(View v) { int viewId = v.getId(); if (viewId == R.id.btn_new_note) { createNewNote(); } else { // 其他情况的处理 } } private void showSoftInput() { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if (inputMethodManager != null) { inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); } } private void hideSoftInput(View view) { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); } private void showCreateOrModifyFolderDialog(final boolean create) { final AlertDialog.Builder builder = new AlertDialog.Builder(this); View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null); final EditText etName = (EditText) view.findViewById(R.id.et_foler_name); showSoftInput(); if (!create) { if (mFocusNoteDataItem != null) { etName.setText(mFocusNoteDataItem.getSnippet()); builder.setTitle(getString(R.string.menu_folder_change_name)); } else { Log.e(TAG, "The long click data item is null"); return; } } else { etName.setText(""); builder.setTitle(this.getString(R.string.menu_create_folder)); } builder.setPositiveButton(android.R.string.ok, null); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { hideSoftInput(etName); } }); final Dialog dialog = builder.setView(view).show(); final Button positive = (Button)dialog.findViewById(android.R.id.button1); positive.setOnClickListener(new OnClickListener() { public void onClick(View v) { hideSoftInput(etName); String name = etName.getText().toString(); if (DataUtils.checkVisibleFolderName(mContentResolver, name)) { Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name), Toast.LENGTH_LONG).show(); etName.setSelection(0, etName.length()); return; } if (!create) { if (!TextUtils.isEmpty(name)) { ContentValues values = new ContentValues(); values.put(NoteColumns.SNIPPET, name); values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); values.put(NoteColumns.LOCAL_MODIFIED, 1); mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID + "=?", new String[] { String.valueOf(mFocusNoteDataItem.getId()) }); } } else if (!TextUtils.isEmpty(name)) { ContentValues values = new ContentValues(); values.put(NoteColumns.SNIPPET, name); values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); mContentResolver.insert(Notes.CONTENT_NOTE_URI, values); } dialog.dismiss(); } }); if (TextUtils.isEmpty(etName.getText())) { positive.setEnabled(false); } /** * When the name edit text is null, disable the positive button */ etName.addTextChangedListener(new TextWatcher() { public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } public void onTextChanged(CharSequence s, int start, int before, int count) { if (TextUtils.isEmpty(etName.getText())) { positive.setEnabled(false); } else { positive.setEnabled(true); } } public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } }); } @Override public void onBackPressed() { switch (mState) { case SUB_FOLDER: mCurrentFolderId = Notes.ID_ROOT_FOLDER; mState = ListEditState.NOTE_LIST; startAsyncNotesListQuery(); mTitleBar.setVisibility(View.GONE); break; case CALL_RECORD_FOLDER: mCurrentFolderId = Notes.ID_ROOT_FOLDER; mState = ListEditState.NOTE_LIST; mAddNewNote.setVisibility(View.VISIBLE); mTitleBar.setVisibility(View.GONE); startAsyncNotesListQuery(); break; case NOTE_LIST: super.onBackPressed(); break; default: break; } } private void updateWidget(int appWidgetId, int appWidgetType) { Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); if (appWidgetType == Notes.TYPE_WIDGET_2X) { intent.setClass(this, NoteWidgetProvider_2x.class); } else if (appWidgetType == Notes.TYPE_WIDGET_4X) { intent.setClass(this, NoteWidgetProvider_4x.class); } else { Log.e(TAG, "Unspported widget type"); return; } intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { appWidgetId }); sendBroadcast(intent); setResult(RESULT_OK, intent); } private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() { public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { if (mFocusNoteDataItem != null) { menu.setHeaderTitle(mFocusNoteDataItem.getSnippet()); menu.add(0, MENU_FOLDER_VIEW, 0, R.string.menu_folder_view); menu.add(0, MENU_FOLDER_DELETE, 0, R.string.menu_folder_delete); menu.add(0, MENU_FOLDER_CHANGE_NAME, 0, R.string.menu_folder_change_name); } } }; @Override public void onContextMenuClosed(Menu menu) { if (mNotesListView != null) { mNotesListView.setOnCreateContextMenuListener(null); } super.onContextMenuClosed(menu); } @Override public boolean onContextItemSelected(MenuItem item) { if (mFocusNoteDataItem == null) { Log.e(TAG, "The long click data item is null"); return false; } switch (item.getItemId()) { case MENU_FOLDER_VIEW: openFolder(mFocusNoteDataItem); break; case MENU_FOLDER_DELETE: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getString(R.string.alert_title_delete)); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setMessage(getString(R.string.alert_message_delete_folder)); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { deleteFolder(mFocusNoteDataItem.getId()); } }); builder.setNegativeButton(android.R.string.cancel, null); builder.show(); break; case MENU_FOLDER_CHANGE_NAME: showCreateOrModifyFolderDialog(false); break; default: break; } return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.clear(); if (mState == ListEditState.NOTE_LIST) { getMenuInflater().inflate(R.menu.note_list, menu); // set sync or sync_cancel menu.findItem(R.id.menu_sync).setTitle( GTaskSyncService.isSyncing() ? R.string.menu_sync_cancel : R.string.menu_sync); } else if (mState == ListEditState.SUB_FOLDER) { getMenuInflater().inflate(R.menu.sub_folder, menu); } else if (mState == ListEditState.CALL_RECORD_FOLDER) { getMenuInflater().inflate(R.menu.call_record_folder, menu); } else { Log.e(TAG, "Wrong state:" + mState); } return true; } // @Override // public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { // case R.id.menu_new_folder: { // showCreateOrModifyFolderDialog(true); // break; // } // case R.id.menu_export_text: { // exportNoteToText(); // break; // } // case R.id.menu_sync: { // if (isSyncMode()) { // if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) { // GTaskSyncService.startSync(this); // } else { // GTaskSyncService.cancelSync(this); // } // } else { // startPreferenceActivity(); // } // break; // } // case R.id.menu_setting: { // startPreferenceActivity(); // break; // } // case R.id.menu_new_note: { // createNewNote(); // break; // } // case R.id.menu_search: // onSearchRequested(); // break; // default: // break; // } // return true; // } @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.menu_new_folder) { showCreateOrModifyFolderDialog(true); } else if (itemId == R.id.menu_export_text) { exportNoteToText(); } else if (itemId == R.id.menu_sync) { if (isSyncMode()) { if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) { GTaskSyncService.startSync(this); } else { GTaskSyncService.cancelSync(this); } } else { startPreferenceActivity(); } } else if (itemId == R.id.menu_setting) { startPreferenceActivity(); } else if (itemId == R.id.menu_new_note) { createNewNote(); } else if (itemId == R.id.menu_search) { onSearchRequested(); } return true; } @Override public boolean onSearchRequested() { startSearch(null, false, null /* appData */, false); return true; } private void exportNoteToText() { final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this); new AsyncTask<Void, Void, Integer>() { @Override protected Integer doInBackground(Void... unused) { return backup.exportToText(); } @Override protected void onPostExecute(Integer result) { if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) { AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); builder.setTitle(NotesListActivity.this .getString(R.string.failed_sdcard_export)); builder.setMessage(NotesListActivity.this .getString(R.string.error_sdcard_unmounted)); builder.setPositiveButton(android.R.string.ok, null); builder.show(); } else if (result == BackupUtils.STATE_SUCCESS) { AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); builder.setTitle(NotesListActivity.this .getString(R.string.success_sdcard_export)); builder.setMessage(NotesListActivity.this.getString( R.string.format_exported_file_location, backup .getExportedTextFileName(), backup.getExportedTextFileDir())); builder.setPositiveButton(android.R.string.ok, null); builder.show(); } else if (result == BackupUtils.STATE_SYSTEM_ERROR) { AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); builder.setTitle(NotesListActivity.this .getString(R.string.failed_sdcard_export)); builder.setMessage(NotesListActivity.this .getString(R.string.error_sdcard_export)); builder.setPositiveButton(android.R.string.ok, null); builder.show(); } } }.execute(); } private boolean isSyncMode() { return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; } private void startPreferenceActivity() { Activity from = getParent() != null ? getParent() : this; Intent intent = new Intent(from, NotesPreferenceActivity.class); from.startActivityIfNeeded(intent, -1); } private class OnListItemClickListener implements OnItemClickListener { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (view instanceof NotesListItem) { NoteItemData item = ((NotesListItem) view).getItemData(); if (mNotesListAdapter.isInChoiceMode()) { if (item.getType() == Notes.TYPE_NOTE) { position = position - mNotesListView.getHeaderViewsCount(); mModeCallBack.onItemCheckedStateChanged(null, position, id, !mNotesListAdapter.isSelectedItem(position)); } return; } switch (mState) { case NOTE_LIST: if (item.getType() == Notes.TYPE_FOLDER || item.getType() == Notes.TYPE_SYSTEM) { openFolder(item); } else if (item.getType() == Notes.TYPE_NOTE) { openNode(item); } else { Log.e(TAG, "Wrong note type in NOTE_LIST"); } break; case SUB_FOLDER: case CALL_RECORD_FOLDER: if (item.getType() == Notes.TYPE_NOTE) { openNode(item); } else { Log.e(TAG, "Wrong note type in SUB_FOLDER"); } break; default: break; } } } } private void startQueryDestinationFolders() { String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?"; selection = (mState == ListEditState.NOTE_LIST) ? selection: "(" + selection + ") OR (" + NoteColumns.ID + "=" + Notes.ID_ROOT_FOLDER + ")"; mBackgroundQueryHandler.startQuery(FOLDER_LIST_QUERY_TOKEN, null, Notes.CONTENT_NOTE_URI, FoldersListAdapter.PROJECTION, selection, new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER), String.valueOf(mCurrentFolderId) }, NoteColumns.MODIFIED_DATE + " DESC"); } public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { if (view instanceof NotesListItem) { mFocusNoteDataItem = ((NotesListItem) view).getItemData(); if (mFocusNoteDataItem.getType() == Notes.TYPE_NOTE && !mNotesListAdapter.isInChoiceMode()) { if (mNotesListView.startActionMode(mModeCallBack) != null) { mModeCallBack.onItemCheckedStateChanged(null, position, id, true); mNotesListView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); } else { Log.e(TAG, "startActionMode fails"); } } else if (mFocusNoteDataItem.getType() == Notes.TYPE_FOLDER) { mNotesListView.setOnCreateContextMenuListener(mFolderOnCreateContextMenuListener); } } return false; } } 生成puml类图文件
e95850db69a2396cb2fc5027bb0f8529
{ "intermediate": 0.3818836510181427, "beginner": 0.35331130027770996, "expert": 0.2648051083087921 }
34,741
package net.micode.notes.ui; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.appwidget.AppWidgetManager; import android.content.AsyncQueryHandler; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.ActionMode; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Display; import android.view.HapticFeedbackConstants; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnCreateContextMenuListener; import android.view.View.OnTouchListener; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.PopupMenu; import android.widget.TextView; import android.widget.Toast; //import net.micode.notes.R; import com.example.namespace.R; import net.micode.notes.data.Notes; import net.micode.notes.data.Notes.NoteColumns; import net.micode.notes.gtask.remote.GTaskSyncService; import net.micode.notes.model.WorkingNote; import net.micode.notes.tool.BackupUtils; import net.micode.notes.tool.DataUtils; import net.micode.notes.tool.ResourceParser; import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute; import net.micode.notes.widget.NoteWidgetProvider_2x; import net.micode.notes.widget.NoteWidgetProvider_4x; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashSet; public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener { private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0; private static final int FOLDER_LIST_QUERY_TOKEN = 1; private static final int MENU_FOLDER_DELETE = 0; private static final int MENU_FOLDER_VIEW = 1; private static final int MENU_FOLDER_CHANGE_NAME = 2; private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction"; private enum ListEditState { NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER }; private ListEditState mState; private BackgroundQueryHandler mBackgroundQueryHandler; private NotesListAdapter mNotesListAdapter; private ListView mNotesListView; private Button mAddNewNote; private boolean mDispatch; private int mOriginY; private int mDispatchY; private TextView mTitleBar; private long mCurrentFolderId; private ContentResolver mContentResolver; private ModeCallback mModeCallBack; private static final String TAG = "NotesListActivity"; public static final int NOTES_LISTVIEW_SCROLL_RATE = 30; private NoteItemData mFocusNoteDataItem; private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?"; private static final String ROOT_FOLDER_SELECTION = "(" + NoteColumns.TYPE + "<>" + Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?)" + " OR (" + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND " + NoteColumns.NOTES_COUNT + ">0)"; private final static int REQUEST_CODE_OPEN_NODE = 102; private final static int REQUEST_CODE_NEW_NODE = 103; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.note_list); initResources(); /** * Insert an introduction when user firstly use this application */ setAppInfoFromRawRes(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK && (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) { mNotesListAdapter.changeCursor(null); } else { super.onActivityResult(requestCode, resultCode, data); } } private void setAppInfoFromRawRes() { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) { StringBuilder sb = new StringBuilder(); InputStream in = null; try { in = getResources().openRawResource(R.raw.introduction); if (in != null) { InputStreamReader isr = new InputStreamReader(in); BufferedReader br = new BufferedReader(isr); char [] buf = new char[1024]; int len = 0; while ((len = br.read(buf)) > 0) { sb.append(buf, 0, len); } } else { Log.e(TAG, "Read introduction file error"); return; } } catch (IOException e) { e.printStackTrace(); return; } finally { if(in != null) { try { in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER, AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE, ResourceParser.RED); note.setWorkingText(sb.toString()); if (note.saveNote()) { sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit(); } else { Log.e(TAG, "Save introduction note error"); return; } } } @Override protected void onStart() { super.onStart(); startAsyncNotesListQuery(); } private void initResources() { mContentResolver = this.getContentResolver(); mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver()); mCurrentFolderId = Notes.ID_ROOT_FOLDER; mNotesListView = (ListView) findViewById(R.id.notes_list); mNotesListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.note_list_footer, null), null, false); mNotesListView.setOnItemClickListener(new OnListItemClickListener()); mNotesListView.setOnItemLongClickListener(this); mNotesListAdapter = new NotesListAdapter(this); mNotesListView.setAdapter(mNotesListAdapter); mAddNewNote = (Button) findViewById(R.id.btn_new_note); mAddNewNote.setOnClickListener(this); mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener()); mDispatch = false; mDispatchY = 0; mOriginY = 0; mTitleBar = (TextView) findViewById(R.id.tv_title_bar); mState = ListEditState.NOTE_LIST; mModeCallBack = new ModeCallback(); } private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener { private DropdownMenu mDropDownMenu; private ActionMode mActionMode; private MenuItem mMoveMenu; public boolean onCreateActionMode(ActionMode mode, Menu menu) { getMenuInflater().inflate(R.menu.note_list_options, menu); menu.findItem(R.id.delete).setOnMenuItemClickListener(this); mMoveMenu = menu.findItem(R.id.move); if (mFocusNoteDataItem.getParentId() == Notes.ID_CALL_RECORD_FOLDER || DataUtils.getUserFolderCount(mContentResolver) == 0) { mMoveMenu.setVisible(false); } else { mMoveMenu.setVisible(true); mMoveMenu.setOnMenuItemClickListener(this); } mActionMode = mode; mNotesListAdapter.setChoiceMode(true); mNotesListView.setLongClickable(false); mAddNewNote.setVisibility(View.GONE); View customView = LayoutInflater.from(NotesListActivity.this).inflate( R.layout.note_list_dropdown_menu, null); mode.setCustomView(customView); mDropDownMenu = new DropdownMenu(NotesListActivity.this, (Button) customView.findViewById(R.id.selection_menu), R.menu.note_list_dropdown); mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){ public boolean onMenuItemClick(MenuItem item) { mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected()); updateMenu(); return true; } }); return true; } private void updateMenu() { int selectedCount = mNotesListAdapter.getSelectedCount(); // Update dropdown menu String format = getResources().getString(R.string.menu_select_title, selectedCount); mDropDownMenu.setTitle(format); MenuItem item = mDropDownMenu.findItem(R.id.action_select_all); if (item != null) { if (mNotesListAdapter.isAllSelected()) { item.setChecked(true); item.setTitle(R.string.menu_deselect_all); } else { item.setChecked(false); item.setTitle(R.string.menu_select_all); } } } public boolean onPrepareActionMode(ActionMode mode, Menu menu) { // TODO Auto-generated method stub return false; } public boolean onActionItemClicked(ActionMode mode, MenuItem item) { // TODO Auto-generated method stub return false; } public void onDestroyActionMode(ActionMode mode) { mNotesListAdapter.setChoiceMode(false); mNotesListView.setLongClickable(true); mAddNewNote.setVisibility(View.VISIBLE); } public void finishActionMode() { mActionMode.finish(); } public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { mNotesListAdapter.setCheckedItem(position, checked); updateMenu(); } // public boolean onMenuItemClick(MenuItem item) { // if (mNotesListAdapter.getSelectedCount() == 0) { // Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none), // Toast.LENGTH_SHORT).show(); // return true; // } // // switch (item.getItemId()) { // case R.id.delete: // AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); // builder.setTitle(getString(R.string.alert_title_delete)); // builder.setIcon(android.R.drawable.ic_dialog_alert); // builder.setMessage(getString(R.string.alert_message_delete_notes, // mNotesListAdapter.getSelectedCount())); // builder.setPositiveButton(android.R.string.ok, // new DialogInterface.OnClickListener() { // public void onClick(DialogInterface dialog, // int which) { // batchDelete(); // } // }); // builder.setNegativeButton(android.R.string.cancel, null); // builder.show(); // break; // case R.id.move: // startQueryDestinationFolders(); // break; // default: // return false; // } // return true; // } public boolean onMenuItemClick(MenuItem item) { if (mNotesListAdapter.getSelectedCount() == 0) { Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none), Toast.LENGTH_SHORT).show(); return true; } int itemId = item.getItemId(); if (itemId == R.id.delete) { AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); builder.setTitle(getString(R.string.alert_title_delete)); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setMessage(getString(R.string.alert_message_delete_notes, mNotesListAdapter.getSelectedCount())); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { batchDelete(); } }); builder.setNegativeButton(android.R.string.cancel, null); builder.show(); } else if (itemId == R.id.move) { startQueryDestinationFolders(); } else { return false; } return true; } } private class NewNoteOnTouchListener implements OnTouchListener { public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: { Display display = getWindowManager().getDefaultDisplay(); int screenHeight = display.getHeight(); int newNoteViewHeight = mAddNewNote.getHeight(); int start = screenHeight - newNoteViewHeight; int eventY = start + (int) event.getY(); /** * Minus TitleBar's height */ if (mState == ListEditState.SUB_FOLDER) { eventY -= mTitleBar.getHeight(); start -= mTitleBar.getHeight(); } /** * HACKME:When click the transparent part of "New Note" button, dispatch * the event to the list view behind this button. The transparent part of * "New Note" button could be expressed by formula y=-0.12x+94(Unit:pixel) * and the line top of the button. The coordinate based on left of the "New * Note" button. The 94 represents maximum height of the transparent part. * Notice that, if the background of the button changes, the formula should * also change. This is very bad, just for the UI designer's strong requirement. */ if (event.getY() < (event.getX() * (-0.12) + 94)) { View view = mNotesListView.getChildAt(mNotesListView.getChildCount() - 1 - mNotesListView.getFooterViewsCount()); if (view != null && view.getBottom() > start && (view.getTop() < (start + 94))) { mOriginY = (int) event.getY(); mDispatchY = eventY; event.setLocation(event.getX(), mDispatchY); mDispatch = true; return mNotesListView.dispatchTouchEvent(event); } } break; } case MotionEvent.ACTION_MOVE: { if (mDispatch) { mDispatchY += (int) event.getY() - mOriginY; event.setLocation(event.getX(), mDispatchY); return mNotesListView.dispatchTouchEvent(event); } break; } default: { if (mDispatch) { event.setLocation(event.getX(), mDispatchY); mDispatch = false; return mNotesListView.dispatchTouchEvent(event); } break; } } return false; } }; private void startAsyncNotesListQuery() { String selection = (mCurrentFolderId == Notes.ID_ROOT_FOLDER) ? ROOT_FOLDER_SELECTION : NORMAL_SELECTION; mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null, Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, new String[] { String.valueOf(mCurrentFolderId) }, NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC"); } private final class BackgroundQueryHandler extends AsyncQueryHandler { public BackgroundQueryHandler(ContentResolver contentResolver) { super(contentResolver); } @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) { switch (token) { case FOLDER_NOTE_LIST_QUERY_TOKEN: mNotesListAdapter.changeCursor(cursor); break; case FOLDER_LIST_QUERY_TOKEN: if (cursor != null && cursor.getCount() > 0) { showFolderListMenu(cursor); } else { Log.e(TAG, "Query folder failed"); } break; default: return; } } } private void showFolderListMenu(Cursor cursor) { AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); builder.setTitle(R.string.menu_title_select_folder); final FoldersListAdapter adapter = new FoldersListAdapter(this, cursor); builder.setAdapter(adapter, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { DataUtils.batchMoveToFolder(mContentResolver, mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which)); Toast.makeText( NotesListActivity.this, getString(R.string.format_move_notes_to_folder, mNotesListAdapter.getSelectedCount(), adapter.getFolderName(NotesListActivity.this, which)), Toast.LENGTH_SHORT).show(); mModeCallBack.finishActionMode(); } }); builder.show(); } private void createNewNote() { Intent intent = new Intent(this, NoteEditActivity.class); intent.setAction(Intent.ACTION_INSERT_OR_EDIT); intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId); this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE); } private void batchDelete() { new AsyncTask<Void, Void, HashSet<AppWidgetAttribute>>() { protected HashSet<AppWidgetAttribute> doInBackground(Void... unused) { HashSet<AppWidgetAttribute> widgets = mNotesListAdapter.getSelectedWidget(); if (!isSyncMode()) { // if not synced, delete notes directly if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter .getSelectedItemIds())) { } else { Log.e(TAG, "Delete notes error, should not happens"); } } else { // in sync mode, we'll move the deleted note into the trash // folder if (!DataUtils.batchMoveToFolder(mContentResolver, mNotesListAdapter .getSelectedItemIds(), Notes.ID_TRASH_FOLER)) { Log.e(TAG, "Move notes to trash folder error, should not happens"); } } return widgets; } @Override protected void onPostExecute(HashSet<AppWidgetAttribute> widgets) { if (widgets != null) { for (AppWidgetAttribute widget : widgets) { if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) { updateWidget(widget.widgetId, widget.widgetType); } } } mModeCallBack.finishActionMode(); } }.execute(); } private void deleteFolder(long folderId) { if (folderId == Notes.ID_ROOT_FOLDER) { Log.e(TAG, "Wrong folder id, should not happen " + folderId); return; } HashSet<Long> ids = new HashSet<Long>(); ids.add(folderId); HashSet<AppWidgetAttribute> widgets = DataUtils.getFolderNoteWidget(mContentResolver, folderId); if (!isSyncMode()) { // if not synced, delete folder directly DataUtils.batchDeleteNotes(mContentResolver, ids); } else { // in sync mode, we'll move the deleted folder into the trash folder DataUtils.batchMoveToFolder(mContentResolver, ids, Notes.ID_TRASH_FOLER); } if (widgets != null) { for (AppWidgetAttribute widget : widgets) { if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) { updateWidget(widget.widgetId, widget.widgetType); } } } } private void openNode(NoteItemData data) { Intent intent = new Intent(this, NoteEditActivity.class); intent.setAction(Intent.ACTION_VIEW); intent.putExtra(Intent.EXTRA_UID, data.getId()); this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE); } private void openFolder(NoteItemData data) { mCurrentFolderId = data.getId(); startAsyncNotesListQuery(); if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { mState = ListEditState.CALL_RECORD_FOLDER; mAddNewNote.setVisibility(View.GONE); } else { mState = ListEditState.SUB_FOLDER; } if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { mTitleBar.setText(R.string.call_record_folder_name); } else { mTitleBar.setText(data.getSnippet()); } mTitleBar.setVisibility(View.VISIBLE); } // public void onClick(View v) { // switch (v.getId()) { // case R.id.btn_new_note: // createNewNote(); // break; // default: // break; // } // } public void onClick(View v) { int viewId = v.getId(); if (viewId == R.id.btn_new_note) { createNewNote(); } else { // 其他情况的处理 } } private void showSoftInput() { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if (inputMethodManager != null) { inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); } } private void hideSoftInput(View view) { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); } private void showCreateOrModifyFolderDialog(final boolean create) { final AlertDialog.Builder builder = new AlertDialog.Builder(this); View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null); final EditText etName = (EditText) view.findViewById(R.id.et_foler_name); showSoftInput(); if (!create) { if (mFocusNoteDataItem != null) { etName.setText(mFocusNoteDataItem.getSnippet()); builder.setTitle(getString(R.string.menu_folder_change_name)); } else { Log.e(TAG, "The long click data item is null"); return; } } else { etName.setText(""); builder.setTitle(this.getString(R.string.menu_create_folder)); } builder.setPositiveButton(android.R.string.ok, null); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { hideSoftInput(etName); } }); final Dialog dialog = builder.setView(view).show(); final Button positive = (Button)dialog.findViewById(android.R.id.button1); positive.setOnClickListener(new OnClickListener() { public void onClick(View v) { hideSoftInput(etName); String name = etName.getText().toString(); if (DataUtils.checkVisibleFolderName(mContentResolver, name)) { Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name), Toast.LENGTH_LONG).show(); etName.setSelection(0, etName.length()); return; } if (!create) { if (!TextUtils.isEmpty(name)) { ContentValues values = new ContentValues(); values.put(NoteColumns.SNIPPET, name); values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); values.put(NoteColumns.LOCAL_MODIFIED, 1); mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID + "=?", new String[] { String.valueOf(mFocusNoteDataItem.getId()) }); } } else if (!TextUtils.isEmpty(name)) { ContentValues values = new ContentValues(); values.put(NoteColumns.SNIPPET, name); values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER); mContentResolver.insert(Notes.CONTENT_NOTE_URI, values); } dialog.dismiss(); } }); if (TextUtils.isEmpty(etName.getText())) { positive.setEnabled(false); } /** * When the name edit text is null, disable the positive button */ etName.addTextChangedListener(new TextWatcher() { public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } public void onTextChanged(CharSequence s, int start, int before, int count) { if (TextUtils.isEmpty(etName.getText())) { positive.setEnabled(false); } else { positive.setEnabled(true); } } public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } }); } @Override public void onBackPressed() { switch (mState) { case SUB_FOLDER: mCurrentFolderId = Notes.ID_ROOT_FOLDER; mState = ListEditState.NOTE_LIST; startAsyncNotesListQuery(); mTitleBar.setVisibility(View.GONE); break; case CALL_RECORD_FOLDER: mCurrentFolderId = Notes.ID_ROOT_FOLDER; mState = ListEditState.NOTE_LIST; mAddNewNote.setVisibility(View.VISIBLE); mTitleBar.setVisibility(View.GONE); startAsyncNotesListQuery(); break; case NOTE_LIST: super.onBackPressed(); break; default: break; } } private void updateWidget(int appWidgetId, int appWidgetType) { Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); if (appWidgetType == Notes.TYPE_WIDGET_2X) { intent.setClass(this, NoteWidgetProvider_2x.class); } else if (appWidgetType == Notes.TYPE_WIDGET_4X) { intent.setClass(this, NoteWidgetProvider_4x.class); } else { Log.e(TAG, "Unspported widget type"); return; } intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { appWidgetId }); sendBroadcast(intent); setResult(RESULT_OK, intent); } private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() { public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { if (mFocusNoteDataItem != null) { menu.setHeaderTitle(mFocusNoteDataItem.getSnippet()); menu.add(0, MENU_FOLDER_VIEW, 0, R.string.menu_folder_view); menu.add(0, MENU_FOLDER_DELETE, 0, R.string.menu_folder_delete); menu.add(0, MENU_FOLDER_CHANGE_NAME, 0, R.string.menu_folder_change_name); } } }; @Override public void onContextMenuClosed(Menu menu) { if (mNotesListView != null) { mNotesListView.setOnCreateContextMenuListener(null); } super.onContextMenuClosed(menu); } @Override public boolean onContextItemSelected(MenuItem item) { if (mFocusNoteDataItem == null) { Log.e(TAG, "The long click data item is null"); return false; } switch (item.getItemId()) { case MENU_FOLDER_VIEW: openFolder(mFocusNoteDataItem); break; case MENU_FOLDER_DELETE: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getString(R.string.alert_title_delete)); builder.setIcon(android.R.drawable.ic_dialog_alert); builder.setMessage(getString(R.string.alert_message_delete_folder)); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { deleteFolder(mFocusNoteDataItem.getId()); } }); builder.setNegativeButton(android.R.string.cancel, null); builder.show(); break; case MENU_FOLDER_CHANGE_NAME: showCreateOrModifyFolderDialog(false); break; default: break; } return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.clear(); if (mState == ListEditState.NOTE_LIST) { getMenuInflater().inflate(R.menu.note_list, menu); // set sync or sync_cancel menu.findItem(R.id.menu_sync).setTitle( GTaskSyncService.isSyncing() ? R.string.menu_sync_cancel : R.string.menu_sync); } else if (mState == ListEditState.SUB_FOLDER) { getMenuInflater().inflate(R.menu.sub_folder, menu); } else if (mState == ListEditState.CALL_RECORD_FOLDER) { getMenuInflater().inflate(R.menu.call_record_folder, menu); } else { Log.e(TAG, "Wrong state:" + mState); } return true; } // @Override // public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { // case R.id.menu_new_folder: { // showCreateOrModifyFolderDialog(true); // break; // } // case R.id.menu_export_text: { // exportNoteToText(); // break; // } // case R.id.menu_sync: { // if (isSyncMode()) { // if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) { // GTaskSyncService.startSync(this); // } else { // GTaskSyncService.cancelSync(this); // } // } else { // startPreferenceActivity(); // } // break; // } // case R.id.menu_setting: { // startPreferenceActivity(); // break; // } // case R.id.menu_new_note: { // createNewNote(); // break; // } // case R.id.menu_search: // onSearchRequested(); // break; // default: // break; // } // return true; // } @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.menu_new_folder) { showCreateOrModifyFolderDialog(true); } else if (itemId == R.id.menu_export_text) { exportNoteToText(); } else if (itemId == R.id.menu_sync) { if (isSyncMode()) { if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) { GTaskSyncService.startSync(this); } else { GTaskSyncService.cancelSync(this); } } else { startPreferenceActivity(); } } else if (itemId == R.id.menu_setting) { startPreferenceActivity(); } else if (itemId == R.id.menu_new_note) { createNewNote(); } else if (itemId == R.id.menu_search) { onSearchRequested(); } return true; } @Override public boolean onSearchRequested() { startSearch(null, false, null /* appData */, false); return true; } private void exportNoteToText() { final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this); new AsyncTask<Void, Void, Integer>() { @Override protected Integer doInBackground(Void... unused) { return backup.exportToText(); } @Override protected void onPostExecute(Integer result) { if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) { AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); builder.setTitle(NotesListActivity.this .getString(R.string.failed_sdcard_export)); builder.setMessage(NotesListActivity.this .getString(R.string.error_sdcard_unmounted)); builder.setPositiveButton(android.R.string.ok, null); builder.show(); } else if (result == BackupUtils.STATE_SUCCESS) { AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); builder.setTitle(NotesListActivity.this .getString(R.string.success_sdcard_export)); builder.setMessage(NotesListActivity.this.getString( R.string.format_exported_file_location, backup .getExportedTextFileName(), backup.getExportedTextFileDir())); builder.setPositiveButton(android.R.string.ok, null); builder.show(); } else if (result == BackupUtils.STATE_SYSTEM_ERROR) { AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this); builder.setTitle(NotesListActivity.this .getString(R.string.failed_sdcard_export)); builder.setMessage(NotesListActivity.this .getString(R.string.error_sdcard_export)); builder.setPositiveButton(android.R.string.ok, null); builder.show(); } } }.execute(); } private boolean isSyncMode() { return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0; } private void startPreferenceActivity() { Activity from = getParent() != null ? getParent() : this; Intent intent = new Intent(from, NotesPreferenceActivity.class); from.startActivityIfNeeded(intent, -1); } private class OnListItemClickListener implements OnItemClickListener { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (view instanceof NotesListItem) { NoteItemData item = ((NotesListItem) view).getItemData(); if (mNotesListAdapter.isInChoiceMode()) { if (item.getType() == Notes.TYPE_NOTE) { position = position - mNotesListView.getHeaderViewsCount(); mModeCallBack.onItemCheckedStateChanged(null, position, id, !mNotesListAdapter.isSelectedItem(position)); } return; } switch (mState) { case NOTE_LIST: if (item.getType() == Notes.TYPE_FOLDER || item.getType() == Notes.TYPE_SYSTEM) { openFolder(item); } else if (item.getType() == Notes.TYPE_NOTE) { openNode(item); } else { Log.e(TAG, "Wrong note type in NOTE_LIST"); } break; case SUB_FOLDER: case CALL_RECORD_FOLDER: if (item.getType() == Notes.TYPE_NOTE) { openNode(item); } else { Log.e(TAG, "Wrong note type in SUB_FOLDER"); } break; default: break; } } } } private void startQueryDestinationFolders() { String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?"; selection = (mState == ListEditState.NOTE_LIST) ? selection: "(" + selection + ") OR (" + NoteColumns.ID + "=" + Notes.ID_ROOT_FOLDER + ")"; mBackgroundQueryHandler.startQuery(FOLDER_LIST_QUERY_TOKEN, null, Notes.CONTENT_NOTE_URI, FoldersListAdapter.PROJECTION, selection, new String[] { String.valueOf(Notes.TYPE_FOLDER), String.valueOf(Notes.ID_TRASH_FOLER), String.valueOf(mCurrentFolderId) }, NoteColumns.MODIFIED_DATE + " DESC"); } public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { if (view instanceof NotesListItem) { mFocusNoteDataItem = ((NotesListItem) view).getItemData(); if (mFocusNoteDataItem.getType() == Notes.TYPE_NOTE && !mNotesListAdapter.isInChoiceMode()) { if (mNotesListView.startActionMode(mModeCallBack) != null) { mModeCallBack.onItemCheckedStateChanged(null, position, id, true); mNotesListView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); } else { Log.e(TAG, "startActionMode fails"); } } else if (mFocusNoteDataItem.getType() == Notes.TYPE_FOLDER) { mNotesListView.setOnCreateContextMenuListener(mFolderOnCreateContextMenuListener); } } return false; } } 生成puml类图代码
6d538f8705f3bbe3ad4fdfa12eb97110
{ "intermediate": 0.31663209199905396, "beginner": 0.43124574422836304, "expert": 0.2521221935749054 }
34,742
/* * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.micode.notes.ui; import android.content.Context; import android.text.format.DateUtils; import android.view.View; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; //import net.micode.notes.R; import com.example.namespace.R; import net.micode.notes.data.Notes; import net.micode.notes.tool.DataUtils; import net.micode.notes.tool.ResourceParser.NoteItemBgResources; public class NotesListItem extends LinearLayout { private ImageView mAlert; private TextView mTitle; private TextView mTime; private TextView mCallName; private NoteItemData mItemData; private CheckBox mCheckBox; public NotesListItem(Context context) { super(context); inflate(context, R.layout.note_item, this); mAlert = (ImageView) findViewById(R.id.iv_alert_icon); mTitle = (TextView) findViewById(R.id.tv_title); mTime = (TextView) findViewById(R.id.tv_time); mCallName = (TextView) findViewById(R.id.tv_name); mCheckBox = (CheckBox) findViewById(android.R.id.checkbox); } public void bind(Context context, NoteItemData data, boolean choiceMode, boolean checked) { if (choiceMode && data.getType() == Notes.TYPE_NOTE) { mCheckBox.setVisibility(View.VISIBLE); mCheckBox.setChecked(checked); } else { mCheckBox.setVisibility(View.GONE); } mItemData = data; if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) { mCallName.setVisibility(View.GONE); mAlert.setVisibility(View.VISIBLE); mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); mTitle.setText(context.getString(R.string.call_record_folder_name) + context.getString(R.string.format_folder_files_count, data.getNotesCount())); mAlert.setImageResource(R.drawable.call_record); } else if (data.getParentId() == Notes.ID_CALL_RECORD_FOLDER) { mCallName.setVisibility(View.VISIBLE); mCallName.setText(data.getCallName()); mTitle.setTextAppearance(context,R.style.TextAppearanceSecondaryItem); mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); if (data.hasAlert()) { mAlert.setImageResource(R.drawable.clock); mAlert.setVisibility(View.VISIBLE); } else { mAlert.setVisibility(View.GONE); } } else { mCallName.setVisibility(View.GONE); mTitle.setTextAppearance(context, R.style.TextAppearancePrimaryItem); if (data.getType() == Notes.TYPE_FOLDER) { mTitle.setText(data.getSnippet() + context.getString(R.string.format_folder_files_count, data.getNotesCount())); mAlert.setVisibility(View.GONE); } else { mTitle.setText(DataUtils.getFormattedSnippet(data.getSnippet())); if (data.hasAlert()) { mAlert.setImageResource(R.drawable.clock); mAlert.setVisibility(View.VISIBLE); } else { mAlert.setVisibility(View.GONE); } } } mTime.setText(DateUtils.getRelativeTimeSpanString(data.getModifiedDate())); setBackground(data); } private void setBackground(NoteItemData data) { int id = data.getBgColorId(); if (data.getType() == Notes.TYPE_NOTE) { if (data.isSingle() || data.isOneFollowingFolder()) { setBackgroundResource(NoteItemBgResources.getNoteBgSingleRes(id)); } else if (data.isLast()) { setBackgroundResource(NoteItemBgResources.getNoteBgLastRes(id)); } else if (data.isFirst() || data.isMultiFollowingFolder()) { setBackgroundResource(NoteItemBgResources.getNoteBgFirstRes(id)); } else { setBackgroundResource(NoteItemBgResources.getNoteBgNormalRes(id)); } } else { setBackgroundResource(NoteItemBgResources.getFolderBgRes()); } } public NoteItemData getItemData() { return mItemData; } } 生成puml类图代码
77c3f2d76c3db5a456266d439d1429fa
{ "intermediate": 0.3883700966835022, "beginner": 0.4366466701030731, "expert": 0.1749832183122635 }
34,743
all: children: host_servers: vars_files: - secret.yml vars: ansible_user: root ansible_ssh_pass: "{{ ansible_ssh_pass }}" hosts: server1: ansible_host: 192.168.56.140
199a2a23e22a9314ef81f1e31491bb37
{ "intermediate": 0.3069906234741211, "beginner": 0.324795663356781, "expert": 0.3682137429714203 }
34,744
import os import cv2 import numpy as np import tensorflow as tf from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.models import Model from keras.layers import Input, Conv2D, LSTM, Dense # Load and preprocess your images and HTML # Function to load images and corresponding HTML def load_and_preprocess_data(screenshots_dir, html_dir, image_height, image_width): images = [] all_html_sources = [] for filename in sorted(os.listdir(screenshots_dir)): if filename.endswith(".png"): # Load and preprocess each image img_path = os.path.join(screenshots_dir, filename) img = cv2.imread(img_path) img = cv2.resize(img, (image_width, image_height)) img = img / 255.0 # Normalize pixel values to [0, 1] images.append(img) # Find corresponding HTML file with the same base name base_name = os.path.splitext(filename)[0] html_filename = base_name + ".html" html_path = os.path.join(html_dir, html_filename) if os.path.isfile(html_path): with open(html_path, "r", encoding="utf-8") as file: html_content = file.read() all_html_sources.append(html_content) return np.array(images), all_html_sources # Paths to your data directories screenshots_dir = "screenshots/" html_dir = "html/" images, all_html_sources = load_and_preprocess_data(screenshots_dir, html_dir, IMAGE_HEIGHT, IMAGE_WIDTH) # Prepare the tokenizer on the HTML tokenizer = Tokenizer(num_words=10000) # Adjust num_words based on your vocab size tokenizer.fit_on_texts(all_html_sources) sequences = tokenizer.texts_to_sequences(all_html_sources) max_sequence_length = max(len(s) for s in sequences) # Or pick a fixed number html_sequences = pad_sequences(sequences, maxlen=max_sequence_length, padding="post") # Create the model input_image = Input(shape=(IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS)) cnn = … # CNN layers cnn_output = cnn(input_image) decoder_input = … # Sequence input for the decoder, potentially initialized with CNN output lstm = LSTM(units=512, return_sequences=True)(decoder_input, initial_state=[cnn_output, cnn_output]) decoder_output = Dense(NUM_HTML_TOKENS, activation="softmax")(lstm) model = Model(inputs=[input_image, decoder_input], outputs=decoder_output) # Compile the model with a loss and an optimizer model.compile(optimizer="adam", loss="categorical_crossentropy") # Train the model model.fit([images, decoder_input_sequences], html_sequences, epochs=EPOCHS) # Save or evaluate your model model.save("Image_to_html.keras")
cd865400c96bd0bb1b71f48204d17d7e
{ "intermediate": 0.41175898909568787, "beginner": 0.2610870599746704, "expert": 0.32715389132499695 }
34,745
write an around 2000 word long blog about why Go is better than Python very specifically for web scraping and web bots, only includea few points but go f ar in deptch with them and provide examples.
c0e7a8167d1958e597fda71e64e4484a
{ "intermediate": 0.29494044184684753, "beginner": 0.30338773131370544, "expert": 0.40167179703712463 }
34,746
in Go make a web scraper that crawls the web for images, for every image it runs a nudity detection model, if it comes back as true, save the image, if not continiue scraping.
51374d0326f62bbbb192aa1a0fba09e9
{ "intermediate": 0.2877610921859741, "beginner": 0.04332505539059639, "expert": 0.6689139008522034 }
34,747
Error compiling Cython file: ------------------------------------------------------------ ... import sys import traceback include "jnius_compat.pxi" include "jni.pxi" include "config.pxi" ^ ------------------------------------------------------------ jnius/jnius.pyx:100:0: 'config.pxi' not found Error compiling Cython file: ------------------------------------------------------------ ... include "jnius_compat.pxi" include "jni.pxi" include "config.pxi" IF JNIUS_PLATFORM == "android": ^ ------------------------------------------------------------ jnius/jnius.pyx:102:3: Compile-time name 'JNIUS_PLATFORM' not defined Error compiling Cython file: ------------------------------------------------------------ ... include "jni.pxi" include "config.pxi" IF JNIUS_PLATFORM == "android": include "jnius_jvm_android.pxi" ELIF JNIUS_PLATFORM == "win32": ^ ------------------------------------------------------------ jnius/jnius.pyx:104:5: Compile-time name 'JNIUS_PLATFORM' not defined Error compiling Cython file: ------------------------------------------------------------ ... include "config.pxi" ^ ------------------------------------------------------------ jnius/jnius_jvm_dlopen.pxi:1:0: 'config.pxi' not found
bb3cab9dbeba6d5157d2fbd69cf8230a
{ "intermediate": 0.36962610483169556, "beginner": 0.3489980101585388, "expert": 0.281375914812088 }
34,748
This is my code and it contains some print functions for debugging: import os import cv2 import numpy as np from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.models import Sequential from keras.layers import Input, Conv2D, MaxPooling2D, Flatten, LSTM, Dense, Embedding, Concatenate from keras import Model from keras.utils import to_categorical from keras.layers import RepeatVector, TimeDistributed # Constants for the image and sequence properties IMAGE_HEIGHT = 256 IMAGE_WIDTH = 256 NUM_CHANNELS = 3 NUM_HTML_TOKENS = 10000 # Assuming 10,000 possible tokens in the HTML vocabulary MAX_SEQUENCE_LENGTH = 500 # This should be set to the maximum sequence length after exploring your dataset EPOCHS = 10 def resize_image_with_padding(img, target_width, target_height): old_width, old_height = img.shape[1], img.shape[0] aspect_ratio = old_width / old_height # Determine new width and height, preserving aspect ratio if old_width > old_height: new_width = target_width new_height = int(target_width / aspect_ratio) else: new_height = target_height new_width = int(target_height * aspect_ratio) # Resize the image img_resized = cv2.resize(img, (new_width, new_height)) # Padding calculations delta_w = target_width - new_width delta_h = target_height - new_height top, bottom = delta_h // 2, delta_h - (delta_h // 2) left, right = delta_w // 2, delta_w - (delta_w // 2) # Add padding to the resized image color = [0, 0, 0] # Padding color (black) img_padded = cv2.copyMakeBorder(img_resized, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) return img_padded # Load and preprocess your images and HTML # Function to load images and corresponding HTML def load_and_preprocess_data(screenshots_dir, html_dir, image_height, image_width): images = [] all_html_sources = [] # Debugging print: Check the content of your html directory print("Content of html_dir:", os.listdir(html_dir)) screenshots = os.listdir(screenshots_dir) # Debugging print: Check the content of your screenshot directory print("Content of screenshots_dir:", screenshots) for filename in sorted(os.listdir(screenshots_dir)): if filename.endswith(".png"): # Load and preprocess each image img_path = os.path.join(screenshots_dir, filename) img = cv2.imread(img_path) img = resize_image_with_padding(img, image_width, image_height) img = img / 255.0 # Normalize pixel values to [0, 1] images.append(img) # Find corresponding HTML file with the same base name base_name = os.path.splitext(filename)[0] html_filename = base_name + ".html" html_path = os.path.join(html_dir, html_filename) if os.path.isfile(html_path): with open(html_path, "r", encoding="utf-8") as file: html_content = file.read() all_html_sources.append(html_content) html_path = os.path.join(html_dir, html_filename) print(f"Trying to open {html_path}") return np.array(images), all_html_sources # Paths to your data directories screenshots_dir = "C:/Users/Dell-PC/Desktop/Projets/Img-2-Code/screenshots" html_dir = "C:/Users/Dell-PC/Desktop/Projets/Img-2-Code/html" images, all_html_sources = load_and_preprocess_data(screenshots_dir, html_dir, IMAGE_HEIGHT, IMAGE_WIDTH) print("Number of HTML files read: ", len(all_html_sources)) if len(all_html_sources) > 0: print("First few characters of the first HTML source: ", all_html_sources[0][:100]) else: print("No HTML sources were read. Check the HTML directory and filenames.") # Tokenize the HTML content tokenizer = Tokenizer(num_words=NUM_HTML_TOKENS) tokenizer.fit_on_texts(all_html_sources) # Convert text to a sequence of integers sequences = tokenizer.texts_to_sequences(all_html_sources) print("Length of text sequences: ", len(sequences)) if len(sequences) > 0: print("First tokenized sequence shape: ", np.array(sequences[0]).shape) else: print("No sequences were generated. Check all_html_sources.") # Check if the sequences have been created properly print("Number of sequences:", len(sequences)) if len(sequences) > 0: print("First sequence:", sequences[0]) else: print("Sequences have not been created properly.") # Pad the sequences so they all have the same length html_sequences = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH, padding="post") # Now check the shape of html_sequences print("Shape of html_sequences after padding:", html_sequences.shape) # Convert html_sequences to one-hot-encoded for use with categorical crossentropy html_sequences_one_hot = to_categorical(html_sequences, num_classes=NUM_HTML_TOKENS) # Step 1: Create the CNN model to extract features from the image input_image = Input(shape=(IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS)) cnn = Conv2D(filters=32, kernel_size=(3,3), activation="relu")(input_image) cnn = MaxPooling2D(pool_size=(2,2))(cnn) cnn = Conv2D(filters=64, kernel_size=(3,3), activation="relu")(cnn) cnn = MaxPooling2D(pool_size=(2,2))(cnn) cnn = Flatten()(cnn) cnn = Dense(units=512)(cnn) # Ensure the CNN output size matches the LSTM input cnn_out_repeated = RepeatVector(MAX_SEQUENCE_LENGTH)(cnn) # Step 2: Create an embedding layer for the HTML input sequence decoder_input_sequence = Input(shape=(MAX_SEQUENCE_LENGTH,)) embedding_layer = Embedding(NUM_HTML_TOKENS, 256)(decoder_input_sequence) lstm = LSTM(units=512, return_sequences=True)(embedding_layer) # Instead of the Concatenate layer, combine CNN and LSTM outputs with a TimeDistributed layer # We can stack the CNN’s output on top of the LSTM by using a concatenate layer with axis=-1 combined_outputs = Concatenate(axis=-1)([cnn_out_repeated, lstm]) # Step 3: Apply a TimeDistributed Dense layer to generate a probability over the vocabulary for each time step decoder_output = TimeDistributed(Dense(NUM_HTML_TOKENS, activation="softmax"))(combined_outputs) model = Model([input_image, decoder_input_sequence], decoder_output) # Compile the model with a loss and an optimizer #model.compile(optimizer="adam", loss="sparse_categorical_crossentropy") # Shift html_sequences to the right by one place for the decoder input decoder_input_sequences = np.pad(html_sequences[:, :-1], ((0, 0), (1, 0)), "constant", constant_values=(0, 0)) # Verify dimensions after padding operation if decoder_input_sequences.size == 0: print("The padding operation has somehow emptied the array.") else: print("decoder_input_sequences.shape after padding:", decoder_input_sequences.shape) # Check if the padding operation reduces the size to zero if decoder_input_sequences.size == 0: print("The padding operation has somehow emptied the array.") else: print(decoder_input_sequences.shape) print(images.shape) # should print (num_samples, IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS) print(decoder_input_sequences.shape) # should print (num_samples, MAX_SEQUENCE_LENGTH) print(html_sequences_one_hot.shape) # should print (num_samples, MAX_SEQUENCE_LENGTH, NUM_HTML_TOKENS) # For using with sparse_categorical_crossentropy targets = html_sequences[:, 1:] # targets are shifted by 1 position targets = np.expand_dims(targets, -1) # add an extra dimension print("decoder_input_sequences.shape:", decoder_input_sequences.shape) print("targets.shape:", targets.shape) # Train the model accordingly #model.fit([images, decoder_input_sequences], targets, epochs=EPOCHS) # model.fit( # [images, decoder_input_sequences], # targets, # epochs=EPOCHS # ) # Save or evaluate your model #model.save("Image_to_html.keras") and this is the output it gives me: Content of html_dir: ['html_1.html', 'html_10.html', 'html_11.html', 'html_12.html', 'html_13.html', 'html_14.html', 'html_15.html', 'html_2.html', 'html_3.html', 'html_4.html', 'html_5.html', 'html_6.html', 'html_7.html', 'html_8.html', 'html_9.html'] Content of screenshots_dir: ['screen_1.png', 'screen_10.png', 'screen_11.png', 'screen_12.png', 'screen_13.png', 'screen_14.png', 'screen_15.png', 'screen_2.png', 'screen_3.png', 'screen_4.png', 'screen_5.png', 'screen_6.png', 'screen_7.png', 'screen_8.png', 'screen_9.png'] Trying to open C:/Users/Dell-PC/Desktop/Projets/Img-2-Code/html\screen_9.html Number of HTML files read: 0 No HTML sources were read. Check the HTML directory and filenames. Length of text sequences: 0 No sequences were generated. Check all_html_sources. Number of sequences: 0 Sequences have not been created properly. Shape of html_sequences after padding: (0, 500) 2023-12-09 13:29:56.086754: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations. To enable the following instructions: SSE SSE2 SSE3 SSE4.1 SSE4.2 AVX AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags. The padding operation has somehow emptied the array. The padding operation has somehow emptied the array. (15, 256, 256, 3) (0, 500) (0, 500, 10000) decoder_input_sequences.shape: (0, 500) targets.shape: (0, 499, 1)
950e7baaaa0bd850d93f274b91a78eee
{ "intermediate": 0.46660351753234863, "beginner": 0.3465621769428253, "expert": 0.18683424592018127 }
34,749
rickard@pop-os:~/Android/Sdk$ ~/.buildozer/android/platform/android-sdk/tools/bin/sdkmanager "build-tools;29.0.0" Warning: Could not create settings java.lang.IllegalArgumentException at com.android.sdklib.tool.sdkmanager.SdkManagerCliSettings.<init>(SdkManagerCliSettings.java:428) at com.android.sdklib.tool.sdkmanager.SdkManagerCliSettings.createSettings(SdkManagerCliSettings.java:152) at com.android.sdklib.tool.sdkmanager.SdkManagerCliSettings.createSettings(SdkManagerCliSettings.java:134) at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:57) at com.android.sdklib.tool.sdkmanager.SdkManagerCli.main(SdkManagerCli.java:48) Usage: sdkmanager [--uninstall] [<common args>] [--package_file=<file>] [<packages>...] sdkmanager --update [<common args>] sdkmanager --list [<common args>] sdkmanager --licenses [<common args>] sdkmanager --version With --install (optional), installs or updates packages. By default, the listed packages are installed or (if already installed) updated to the latest version. With --uninstall, uninstall the listed packages. <package> is a sdk-style path (e.g. "build-tools;23.0.0" or "platforms;android-23"). <package-file> is a text file where each line is a sdk-style path of a package to install or uninstall. Multiple --package_file arguments may be specified in combination with explicit paths. With --update, all installed packages are updated to the latest version. With --list, all installed and available packages are printed out. With --licenses, show and offer the option to accept licenses for all available packages that have not already been accepted. With --version, prints the current version of sdkmanager. Common Arguments: --sdk_root=<sdkRootPath>: Use the specified SDK root instead of the SDK containing this tool --channel=<channelId>: Include packages in channels up to <channelId>. Common channels are: 0 (Stable), 1 (Beta), 2 (Dev), and 3 (Canary). --include_obsolete: With --list, show obsolete packages in the package listing. With --update, update obsolete packages as well as non-obsolete. --no_https: Force all connections to use http rather than https. --proxy=<http | socks>: Connect via a proxy of the given type. --proxy_host=<IP or DNS address>: IP or DNS address of the proxy to use. --proxy_port=<port #>: Proxy port to connect to. --verbose: Enable verbose output. * If the env var REPO_OS_OVERRIDE is set to "windows", "macosx", or "linux", packages will be downloaded for that OS.
91e8c4e96f836105c9a39268acea0fde
{ "intermediate": 0.32255324721336365, "beginner": 0.4536568224430084, "expert": 0.22378994524478912 }
34,750
import gradio as gr import mysql.connector from mysql.connector import Error # Function to fetch data from MySQL based on PR Number def fetch_data(pr_number): connection = None try: connection = mysql.connector.connect( host='localhost', database='records', user='root', password='Nikki@1234' ) if connection.is_connected(): cursor = connection.cursor(dictionary=True) # Fetch data from the pr_details table for the given PR Number cursor.execute("SELECT * FROM pr_details WHERE PR_Number = %s", (pr_number,)) data = cursor.fetchall() if not data: return f"No details found for PR Number {pr_number}" # Convert the data to a formatted string for Gradio output result = "\n".join([f"{key}: {value}" for key, value in data[0].items()]) return result except Error as e: print(f"Error: {e}") finally: if connection and connection.is_connected(): cursor.close() connection.close() print("MySQL connection closed.") # Gradio Interface iface = gr.Interface( fn=fetch_data, inputs=gr.Textbox(placeholder="Enter PR Number", label="PR Number"), outputs=gr.Textbox(placeholder="Details will be shown here", label="Details", type="text", lines=15), live=True, theme="compact" ) # Launch the interface with remote access enabled iface.launch(share=True)
f12825cb8ac699f5327af01bc20854b4
{ "intermediate": 0.4337156414985657, "beginner": 0.33538997173309326, "expert": 0.23089435696601868 }
34,751
modifCont = Import[“D:\УЧЁБА\9 сем\ЦТЗИ\КР\5 КМ\ModifiedCont.bmp”, “Byte”]; head = modifCont[[;; 54]]; tail = modifCont[[55 ;;]]; insData = Import[“D:\УЧЁБА\9 сем\ЦТЗИ\КР\5 КМ\insData.txt”, “Byte”]; AppendTo[insData, Array[0 &, 16]]; insData = Flatten[insData]; Length[insData]; AppendTo[head, insData]; modifData = Flatten[AppendTo[head, tail]]; modifData[[11]] = 49; modifData[[12]] = 7; file = OpenWrite[ “D:\УЧЁБА\9 сем\ЦТЗИ\КР\5 КМ\ModifiedAndSignedCont.bmp”, BinaryFormat -> True]; BinaryWrite[file, modifData]; Close[file]; modifiedAndSignedCont = Import[ “D:\УЧЁБА\9 сем\ЦТЗИ\КР\5 КМ\ModifiedAndSignedCont.bmp”, “Byte” ]; i = 55; data = {}; While[modifiedAndSignedCont[[i ;; i + 15]] != Array[0 &, 16], AppendTo[data, FromCharacterCode[modifiedAndSignedCont[[i]], “MacintoshCyrillic”]]; i += 1; ]; s = StringJoin[data]; Export[“ExtractedData.txt”, s]; SystemOpen[“ExtractedData.txt”]; обьясни код на русском
7efcc01f8d7ae5f143926f455e23bb1a
{ "intermediate": 0.36359450221061707, "beginner": 0.37753528356552124, "expert": 0.2588702142238617 }
34,752
how to get the type of input in parsing if my header is: #pragma once #include <string> #include <vector> namespace ArgumentParser { class Args { public: Args(); Args(const std::string param); Args(const char short_param, const std::string param); ~Args() {}; Args& MultiValue(); Args& MultiValue(const int min_args_count); bool GetFlagMultiValue(); Args& Positional(); bool GetFlagPositional(); void MultiArgsCount(); int GetMultiArgsCount(); int GetMinArgsCount(); void AddAllValues(const std::string value); int GetIndexedValue(const int ind); void Help(const char short_help, const std::string help); std::string GetHelp(); char GetShortHelp(); void FlagHelp(); bool GetFlagHelp(); void Description(const std::string description); bool flag_positional_ = false; bool flag_multi_value_ = false; int min_args_count_; int multi_args_count_ = 0; std::vector<int> all_values_; char short_help_; std::string help_; std::string description_; bool flag_help_ = false; }; class Int : public Args { void StoreValues(std::vector<int>& store_values); void AddStoreValues(const std::string value); bool GetFlagStoreValues(); std::vector<int>* store_values_; bool flag_store_values_ = false; }; class String : public Args { public: std::string GetParam(); char GetShortParam(); bool GetFlagShortParam(); void PutValue(const std::string value); std::string GetValue(); void Default(const char* value); std::string GetDefaultValue(); void AddFlags(const char short_flag, const std::string flag); void AddFlag(const std::string flag); std::string GetFlag(); bool GetIsFlag(); char GetShortFlag(); void StoreValue(std::string& value); void AddStoreValue(const std::string value); bool GetFlagStoreValue(); std::string param_; char short_param_; bool flag_short_param_ = false; std::string value_; std::string* store_value_; std::string default_value_; std::string flag_; char short_flag_; bool is_flag_ = false; bool flag_store_value_ = false; }; class Bool : public Args { public: void Default(const bool flag); bool GetFlagDefaultFlag(); void StoreValue(bool& flag); bool GetFlagStoreFlag(); void AddStoreFlag(const bool flag); bool default_flag_; bool flag_default_flag_ = false; bool* store_flag_; bool flag_store_flag_ = false; }; };
54f2e8158196c223c91a66d4022dec77
{ "intermediate": 0.3364562690258026, "beginner": 0.39375734329223633, "expert": 0.26978635787963867 }
34,753
what is a simple python sigmoid function that takes in linear inputs from 0-1 to smooth output from 0-1
aea4cafbaf9d96a340f4e1ff26727bfa
{ "intermediate": 0.19187778234481812, "beginner": 0.26442858576774597, "expert": 0.5436936616897583 }
34,754
- set_fact: stop_command: “{{ weblogic_home }}/user_projects/domains/{{ hostvars[inventory_hostname].domain }}/bin/stopWebLogic.sh &” - name: Stop Admin Server shell: “{{ stop_command }}” when: admin_port|string in check_adm_port.stdout - name: Wait for wl port to be unavailable wait_for: host: “{{ hostvars[inventory_hostname].ansible_host }}” port: “{{ hostvars[inventory_hostname].admin_port }}” state: absent timeout: 800 register: wait_adm why do i need set facts on the above or its not nessesary
25d2893f2ae8211fbb6425a54a320ec8
{ "intermediate": 0.3113454282283783, "beginner": 0.47381436824798584, "expert": 0.21484021842479706 }
34,755
edit the following script to make it save the url where it uploads on gofile to a text file import os import threading from queue import Queue from minio import Minio from gofile2 import Gofile # Set up the MinIO client client = Minio( "s3-api.laokyc.gov.la", access_key="Laokyc_admin", secret_key="L@0kyc@2021" ) # Set up the Gofile client gofile_client = Gofile() # Function to handle the download of files for a given bucket def download_files(bucket, download_queue): while not download_queue.empty(): item = download_queue.get() # Create local directories if they don’t exist local_path = os.path.join(bucket, os.path.dirname(item.object_name)) os.makedirs(local_path, exist_ok=True) # Download the object locally client.fget_object(bucket, item.object_name, os.path.join(bucket, item.object_name)) download_queue.task_done() # Function to upload a directory to gofile.io def upload_directory(directory_path): # Use the Gofile API to upload the directory here # Make sure gofile2 is installed and configured upload_result = gofile_client.uploadFolder(directory_path) return upload_result # Main processing function def process_bucket(bucket): # Make a queue for the bucket’s objects download_queue = Queue() for item in client.list_objects(bucket, recursive=True): download_queue.put(item) # Start multiple threads to download the objects num_threads = 4 # Customize this as per your bandwidth and MinIO server’s capabilities threads = [] for _ in range(num_threads): t = threading.Thread(target=download_files, args=(bucket, download_queue)) t.start() threads.append(t) # Wait for all threads to finish for t in threads: t.join() # After all threads complete, upload the bucket upload_result = upload_directory(bucket) # After uploading, you could remove the local files to save space, if desired # shutil.rmtree(bucket) print(f"Bucket {bucket} uploaded with result: {upload_result}") for bucket in client.list_buckets(): # Process each bucket one by one process_bucket(bucket.name)
6ab8e352455303f5789529fe48778786
{ "intermediate": 0.517242431640625, "beginner": 0.272443950176239, "expert": 0.2103135883808136 }
34,756
In an CRT RSA given N: 0x78fb80151a498704541b888b9ca21b9f159a45069b99b04befcb0e0403178dc243a66492771f057b28262332caecc673a2c68fd63e7c850dc534a74c705f865841c0b5af1e0791b8b5cc55ad3b04e25f20dedc15c36db46c328a61f3a10872d47d9426584f410fde4c8c2ebfaccc8d6a6bd1c067e5e8d8f107b56bf86ac06cd8a20661af832019de6e00ae6be24a946fe229476541b04b9a808375739681efd1888e44d41196e396af66f91f992383955f5faef0fc1fc7b5175135ab3ed62867a84843c49bdf83d0497b255e35432b332705cd09f01670815ce167aa35f7a454f8b26b6d6fd9a0006194ad2f8f33160c13c08c81fe8f74e13e84e9cdf6566d2f e: 0x4b3393c9fe2e50e0c76920e1f34e0c86417f9a9ef8b5a3fa41b381355 the first 512MBS of dp: 0x59a2219560ee56e7c35f310a4d101061aa61e0ae4eae7605eb63784209ad488b4ed161e780811edd61bf593e2d385beccfd255b459382d8a9029943781b540e7 and the first 512MBS of dq: 0x39719131fbfd8afbc972ca005a430d080775bf1a5b3e8b789aba5c5110a31bd155ff13fba1019bb6cb7db887685e34ca7966a891bfad029b55b92c11201559e5 and i know p and q are 1024 bits each can you write me python/sage code to receive the full dq and dp? and you insert my given values so I just have to execute this code
c6118bca0308a470858e0f13a9fe2a96
{ "intermediate": 0.5232552289962769, "beginner": 0.21025598049163818, "expert": 0.2664887309074402 }
34,757
List all tables in Sql server express
78210037fbc84df8bf35f69cabd3ba9f
{ "intermediate": 0.5832158923149109, "beginner": 0.20032986998558044, "expert": 0.21645425260066986 }
34,758
After running this code: import os import cv2 import numpy as np from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.models import Sequential from keras.layers import Input, Conv2D, MaxPooling2D, Flatten, LSTM, Dense, Embedding, Concatenate from keras import Model from keras.utils import to_categorical from keras.layers import RepeatVector, TimeDistributed # Constants for the image and sequence properties IMAGE_HEIGHT = 256 IMAGE_WIDTH = 256 NUM_CHANNELS = 3 NUM_HTML_TOKENS = 10000 # Assuming 10,000 possible tokens in the HTML vocabulary MAX_SEQUENCE_LENGTH = 500 # This should be set to the maximum sequence length after exploring your dataset EPOCHS = 10 def resize_image_with_padding(img, target_width, target_height): old_width, old_height = img.shape[1], img.shape[0] aspect_ratio = old_width / old_height # Determine new width and height, preserving aspect ratio if old_width > old_height: new_width = target_width new_height = int(target_width / aspect_ratio) else: new_height = target_height new_width = int(target_height * aspect_ratio) # Resize the image img_resized = cv2.resize(img, (new_width, new_height)) # Padding calculations delta_w = target_width - new_width delta_h = target_height - new_height top, bottom = delta_h // 2, delta_h - (delta_h // 2) left, right = delta_w // 2, delta_w - (delta_w // 2) # Add padding to the resized image color = [0, 0, 0] # Padding color (black) img_padded = cv2.copyMakeBorder(img_resized, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) return img_padded # Load and preprocess your images and HTML # Function to load images and corresponding HTML def load_and_preprocess_data(screenshots_dir, html_dir, image_height, image_width): images = [] all_html_sources = [] for filename in sorted(os.listdir(screenshots_dir)): if filename.endswith(".png"): # Load and preprocess each image img_path = os.path.join(screenshots_dir, filename) img = cv2.imread(img_path) img = resize_image_with_padding(img, image_width, image_height) img = img / 255.0 # Normalize pixel values to [0, 1] images.append(img) # Find corresponding HTML file with the same base name base_name = os.path.splitext(filename)[0] html_filename = base_name.replace("screen", "html") + ".html" # Changes here html_path = os.path.join(html_dir, html_filename) if os.path.isfile(html_path): with open(html_path, "r", encoding="utf-8") as file: html_content = file.read() all_html_sources.append(html_content) return np.array(images), all_html_sources # Paths to your data directories screenshots_dir = "C:/Users/Dell-PC/Desktop/Projets/Img-2-Code/screenshots" html_dir = "C:/Users/Dell-PC/Desktop/Projets/Img-2-Code/html" images, all_html_sources = load_and_preprocess_data(screenshots_dir, html_dir, IMAGE_HEIGHT, IMAGE_WIDTH) # Tokenize the HTML content tokenizer = Tokenizer(num_words=NUM_HTML_TOKENS) tokenizer.fit_on_texts(all_html_sources) # Convert text to a sequence of integers sequences = tokenizer.texts_to_sequences(all_html_sources) # Pad the sequences so they all have the same length html_sequences = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH, padding="post") # Convert html_sequences to one-hot-encoded for use with categorical crossentropy html_sequences_one_hot = to_categorical(html_sequences, num_classes=NUM_HTML_TOKENS) # Step 1: Create the CNN model to extract features from the image input_image = Input(shape=(IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS)) cnn = Conv2D(filters=32, kernel_size=(3,3), activation="relu")(input_image) cnn = MaxPooling2D(pool_size=(2,2))(cnn) cnn = Conv2D(filters=64, kernel_size=(3,3), activation="relu")(cnn) cnn = MaxPooling2D(pool_size=(2,2))(cnn) cnn = Flatten()(cnn) cnn = Dense(units=512)(cnn) # Ensure the CNN output size matches the LSTM input cnn_out_repeated = RepeatVector(MAX_SEQUENCE_LENGTH)(cnn) # Step 2: Create an embedding layer for the HTML input sequence decoder_input_sequence = Input(shape=(MAX_SEQUENCE_LENGTH,)) embedding_layer = Embedding(NUM_HTML_TOKENS, 256)(decoder_input_sequence) lstm = LSTM(units=512, return_sequences=True)(embedding_layer) # Instead of the Concatenate layer, combine CNN and LSTM outputs with a TimeDistributed layer # We can stack the CNN’s output on top of the LSTM by using a concatenate layer with axis=-1 combined_outputs = Concatenate(axis=-1)([cnn_out_repeated, lstm]) # Step 3: Apply a TimeDistributed Dense layer to generate a probability over the vocabulary for each time step decoder_output = TimeDistributed(Dense(NUM_HTML_TOKENS, activation="softmax"))(combined_outputs) model = Model([input_image, decoder_input_sequence], decoder_output) # Compile the model with a loss and an optimizer model.compile(optimizer="adam", loss="sparse_categorical_crossentropy") # Shift html_sequences to the right by one place for the decoder input decoder_input_sequences = np.pad(html_sequences[:, :-1], ((0, 0), (1, 0)), "constant", constant_values=(0, 0)) print(f"html_sequences_one_hot.shape: {html_sequences_one_hot.shape}") # should print (num_samples, MAX_SEQUENCE_LENGTH, NUM_HTML_TOKENS) print(f"Images shape: {images.shape}") print(f"Decoder input sequences shape: {decoder_input_sequences.shape}") # For using with sparse_categorical_crossentropy targets = html_sequences[:, 1:] # targets are shifted by 1 position targets = np.expand_dims(targets, -1) # add an extra dimension print(f"Targets shape: {targets.shape}") # Train the model accordingly # model.fit([images, decoder_input_sequences], targets, epochs=EPOCHS) # Save or evaluate your model # model.save("Image_to_html.keras") i got this error: html_sequences_one_hot.shape: (15, 500, 10000) Images shape: (15, 256, 256, 3) Decoder input sequences shape: (15, 500) Targets shape: (15, 499, 1)
ff324521bed36d334a7759a939b9c446
{ "intermediate": 0.3643593192100525, "beginner": 0.32281818985939026, "expert": 0.31282252073287964 }
34,759
User if ($_SERVER['REQUEST_METHOD'] === 'POST') { $json = file_get_contents('php://input'); $data = json_decode($json, true); $ruleName = $data['ruleName']; $port = $data['port']; $ip = $data['ip']; $ipAddr = $data['ipAddr']; $time = $data['time']; $username = $data['username']; $password = $data['password']; $smtphost = $data['smtphost']; $smtpauth = $data['smtpauth']; $smtpport = $data['smtpport']; $setform_email = $data['setform_email']; $setform_name = $data['setform_name']; $add_address = $data['add_address']; $address_name = $data['address_name']; 服务端的json是怎么写的数据是怎么写的,我需要从post获取ruleName、port等值。
ee091ff9eb2bf831b288de554d6de55d
{ "intermediate": 0.38688990473747253, "beginner": 0.3413269817829132, "expert": 0.27178314328193665 }
34,760
Can you help with my project ?
27d081c6b5bd6f39c5216e171c1f2f00
{ "intermediate": 0.38802582025527954, "beginner": 0.1420707106590271, "expert": 0.46990343928337097 }
34,761
2023-12-09 22:34:33.872992: I tensorflow/core/util/port.cc:113] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`. WARNING:tensorflow:From C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\keras\src\losses.py:2976: The name tf.losses.sparse_softmax_cross_entropy is deprecated. Please use tf.compat.v1.losses.sparse_softmax_cross_entropy instead. Traceback (most recent call last): File "D:\AI\RunProject.py", line 20, in <module> model = BlipForConditionalGeneration.from_pretrained(model_Main) File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\transformers\modeling_utils.py", line 2975, in from_pretrained raise EnvironmentError( OSError: Error no file named pytorch_model.bin found in directory ./Main but there is a file for TensorFlow weights. Use `from_tf=True` to load this model from those weights.
f6da424444d461bded8f653e125f3762
{ "intermediate": 0.3853833079338074, "beginner": 0.17309319972991943, "expert": 0.4415235221385956 }
34,762
t is current step and T is total steps. I want the sigmoid version of math.cos(pi/2*t/T)
6d9f562009c1799923ae72d01e14e803
{ "intermediate": 0.3873264193534851, "beginner": 0.3131009042263031, "expert": 0.299572616815567 }
34,763
#include <iostream> #include <string> #include <vector> struct Node { char c; int id; std::vector<Node*> next; Node() : id(-1) {} }; int main() { std::string str; std::cin >> str; Node* root = new Node(); int id = 1; Node* current = root; for (char ch : str) { bool is_found = false; for (Node* node : current->next) { if (node->c == ch) { current = node; is_found = true; break; } } if (!is_found) { Node* newNode = new Node(); newNode->c = ch; newNode->id = id++; current->next.push_back(newNode); std::cout << (current->id == -1 ? 0 : current->id) << ' ' << ch << '\n'; current = root; } } if (current != root) { std::cout << current->id << " \n"; } return 0; } Сидя у себя в офисе в Калифорнии, Марк Цукерберг чуть не подавился молочным латте без лактозы, когда увидел какое количество памяти занимают картинки с добрым утром вашей бабушки в WhatsApp. В скором порядке он созвал внезапную планерку талантливейших кодировщиков со всего мира, где единогласно пришли к решению о сжатии всех картинок через алгоритм LZ78. Входные данные Строка � s ( ∣ � ∣ ≤ ∣s∣≤ 5 ∗ 1 0 5 5∗10 5 ) , состоящая из строчных латинских букв, обозначающая метаданные файла, который необходимо сжать. Выходные данные На каждой новой строчке необходимо последовательно вывести список пар � � � pos и � � � � next, где � � � pos - номер в словаре самого длинного найденного префикса и � � � � next - символ, который следует за этим префиксом. STDIN STDOUT abcaba 0 a 0 b 0 c 1 b 1 abacababacabc 0 a 0 b 1 c 1 b 4 a 0 c 4 c если у меня префикс не 1 символ а несколько? оно же не будет работать
0c959c6d10628a39720fc65caf443cdf
{ "intermediate": 0.3148052990436554, "beginner": 0.40134501457214355, "expert": 0.28384971618652344 }
34,764
Hi, is possible to return a break in some method in C#
a5b160c84746a5ad83f726ab46a99b68
{ "intermediate": 0.5035877823829651, "beginner": 0.3262576460838318, "expert": 0.1701546311378479 }
34,765
Hi, can you please revise my code in c# and point out my mistakes or inaccuracies? internal class Program { static bool isArrayCreated = false; static void Main(string[] args) { bool isArrayCreated = false; int arrayLength, addedArrayLength; byte choice; int[] array = new int[0]; Console.WriteLine("Выберите действие:"); Console.WriteLine("1. Создать массив"); Console.WriteLine("2. Создать массив, вводя с клавиатуры"); Console.WriteLine("3. Вывести массив"); Console.WriteLine("4. Удалить все четные элементы из массива"); Console.WriteLine("5. Добавить K элементов в начало массива"); Console.WriteLine("6. Переставить четные элементы в начало массива, а нечетные - в конец"); Console.WriteLine("7. Найти первый четный элемент массива и показать кол-во совершенных сравнений"); Console.WriteLine("8. Выполнить сортировку массива простым выбором"); Console.WriteLine("9. Бинарный поиск в отсортированном массиве"); Console.WriteLine("0. Выход из программы"); do { Console.Write("\nВыбор действия: "); choice = CheckChoiceInput(); Console.WriteLine(); switch (choice) { case 1: Console.WriteLine("Какой массив вы хотите создать?\n1. Из случайных чисел\n2. Вводя с клавиатуры"); choice = CheckChoiceInput(); Console.Write("Введите длину массива: "); arrayLength = CheckArrayLengthInput(); switch (choice) { case 1: Console.WriteLine("Введите через 2 числа - границы диапазона случайных чисел массива: "); int limit1 = CheckInt32Input(); int limit2 = CheckInt32Input(); array = GenerateArray(arrayLength, Math.Min(limit1, limit2), Math.Max(limit1, limit2)); isArrayCreated = true; Console.WriteLine(); OutputColoredLine("green", "Массив из случайных чисел успешно сформирован"); break; case 2: array = new int[arrayLength]; Console.WriteLine("Примечание: вводите элементы массива через enter"); for (uint i = 0; i < arrayLength; i++) { array[i] = CheckInt32Input(); } isArrayCreated = true; OutputColoredLine("green", "Массив из введенных чисел успешно сформирован"); break; } break; //case 1: // Формирование массива из случайных чисел с выбором длины и границ их // Console.Write("Введите длину массива: "); // arrayLength = CheckArrayLengthInput(); // Console.WriteLine("Введите через 2 числа - границы диапазона случайных чисел массива: "); // int limit1 = CheckInt32Input(); // int limit2 = CheckInt32Input(); // array = GenerateArray(arrayLength, Math.Min(limit1, limit2), Math.Max(limit1, limit2)); // isArrayCreated = true; // Console.WriteLine(); // OutputColoredLine("green", "Массив из случайных чисел успешно сформирован"); // break; case 2: // Формирование массива вводом с клавиатуры с выбором длины Console.Write("Введите длину массива: "); arrayLength = CheckArrayLengthInput(); array = new int[arrayLength]; Console.WriteLine("Примечание: вводите элементы массива через enter"); for (uint i = 0; i < arrayLength; i++) { array[i] = CheckInt32Input(); } isArrayCreated = true; OutputColoredLine("green", "Массив из введенных чисел успешно сформирован"); break; case 3: // Вывод массива if (!isArrayCreated) // Проверка на существование массива { OutputColoredLine("red", "Ошибка: массива не существует, сначала создайте его"); break; } CheckIfArrayIsCreated(); if (array.Length == 0) // Проверка на пустоту массива { OutputColoredLine("yellow", "Массив пустой"); break; } Console.Write("Массив: "); foreach (int item in array) { Console.Write(item + " "); } Console.WriteLine(); break; case 4: // Удаление четных элементов из массива if (!isArrayCreated) // Проверка на существование массива { OutputColoredLine("red", "Ошибка: массива не существует, сначала создайте его"); break; } if (array.Length == 0) // Проверка на пустоту массива { OutputColoredLine("red", "Ошибка: массив пустой, удаление четных элементов из массива невозможно"); break; } uint oddNumbers = 0; for (uint i = 0; i < array.Length; i++) // Подсчет количества нечетных элементов в массиве { if (array[i] % 2 != 0) oddNumbers++; } if (array.Length == oddNumbers) // Проверка на наличие четных элементов в массиве { Console.WriteLine("Четных чисел в массиве нет"); break; } int[] noEvenNumberArray = new int[oddNumbers]; // Создание временного массива длинной равной количеству нечетных элементов в массиве uint j = 0; for (uint i = 0; i < array.Length; i++) // Заполнение массива "noEvenNumberArray" только нечетными элементами { if (array[i] % 2 != 0) { noEvenNumberArray[j] = array[i]; j++; } } array = noEvenNumberArray; // Массив "array" теперь ссылается на массив "noEvenNumberArray" OutputColoredLine("green", "Четные элементы успешно удалены из массива"); break; case 5: // Добавление K элементов в начало массива if (!isArrayCreated) // Проверка на существование массива { OutputColoredLine("red", "Ошибка: массива не существует, сначала создайте его"); break; } Console.WriteLine("Какой массив вы хотите добавить?\n1. Из случайных чисел\n2. Вводя с клавиатуры"); choice = CheckChoiceInput(); Console.Write("Введите количество элементов, которые хотите добавить в начало массива: "); addedArrayLength = CheckArrayLengthInput(); if (addedArrayLength + array.Length > 1000000) { OutputColoredLine("red", "Ошибка: конечный массив получится слишком длинным, длина массива не должна быть больше 1 000 000 "); break; } int[] extendedArray = new int[(addedArrayLength + array.Length)]; // Создание массива длиной в сумму длины основного массива "array" и количества дополнительных введенных элементов switch (choice) { case 1: // Создание рандомного массива Console.WriteLine("Введите через 2 числа - границы диапазона случайных чисел массива: "); int limit1 = CheckInt32Input(); int limit2 = CheckInt32Input(); int[] addedArray = GenerateArray(addedArrayLength, Math.Min(limit1, limit2), Math.Max(limit1, limit2)); for (uint i = 0; i < addedArrayLength; i++) { extendedArray[i] = addedArray[i]; } for (uint i = 0; i < array.Length; i++) { extendedArray[addedArrayLength + i] = array[i]; } break; case 2: // Создание массива вводом с клавиатуры Console.WriteLine("Вводите элементы массива через enter"); for (uint i = 0; i < addedArrayLength; i++) { extendedArray[i] = CheckInt32Input(); } for (uint i = 0; i < array.Length; i++) { extendedArray[addedArrayLength + i] = array[i]; } break; } array = extendedArray; OutputColoredLine("green", "К элементов успешно добавлены в начало массива"); break; case 6: // Перестановка четных элементы в начало массива, а нечетных - в конец if (!isArrayCreated) // Проверка на существование массива { OutputColoredLine("red", "Ошибка: массива не существует, сначала создайте его"); break; } if (array.Length == 0) // Проверка на пустоту массива { OutputColoredLine("red", "Ошибка: массив пустой, перестановка четных и нечетных элементов невозможна"); break; } oddNumbers = 0; uint evenNumbers = 0; for (uint i = 0; i < array.Length; i++) // Подсчет количества четных и нечетных элементов в массиве { if (array[i] % 2 != 0) oddNumbers++; else evenNumbers++; } if (oddNumbers == 0) // Проверка на наличие нечетных чисел в массиве { Console.WriteLine("Нечетных элементов нет в массиве"); break; } if (evenNumbers == 0) // Проверка на наличие четных чисел в массиве { Console.WriteLine("Четных элементов нет в массиве"); break; } int[] oddNumbersArray = new int[oddNumbers]; int[] evenNumbersArray = new int[evenNumbers]; j = 0; uint k = 0; for (uint i = 0; i < array.Length; i++) // Заполнение временных массивов "oddNumbersArray" только нечетными элементами и "evenNumbersArray" только четными { if (array[i] % 2 != 0) { oddNumbersArray[j] = array[i]; j++; } else { evenNumbersArray[k] = array[i]; k++; } } for (uint i = 0; i < evenNumbers; i++) // Заполнение массива "array" числами сначала из массива "evenNumbersArray", а после из массива "oddNumbersArray" { array[i] = evenNumbersArray[i]; } for (uint i = 0; i < oddNumbers; i++) { array[evenNumbers + i] = oddNumbersArray[i]; } OutputColoredLine("green", "Массив успешно отсортирован. Четные элементы в начале массива, а нечетные - в конце"); break; case 7: // Поиск первого четного элемента массива и вывод кол-ва совершенных сравнений"); if (!isArrayCreated) // Проверка на существование массива { OutputColoredLine("red", "Ошибка: массива не существует, сначала создайте его"); break; } if (array.Length == 0) // Проверка на пустоту массива { OutputColoredLine("red", "Ошибка: массив пустой, поиск первого четного элемента невозможен"); break; } for (int i = 0; i < array.Length; i++) { if (array[i] % 2 == 0) { Console.WriteLine($"Первый четный элемент в массиве: {array[i]} \nКол-во совершенных сравнений: {i+1}"); break; } } break; case 8: // Сортировка массива простым выбором if (!isArrayCreated) // Проверка на существование массива { OutputColoredLine("red", "Ошибка: массива не существует, сначала создайте его"); break; } if (array.Length == 0) // Проверка на пустоту массива { OutputColoredLine("red", "Ошибка: массив пустой, сортировка невозможна"); break; } if (array.Length == 1) // Сортировка бессмысленна если длина массива - 1 { OutputColoredLine("yellow", "Внимание: массив длиной 1 нет смысла сортировать"); break; } array = SortArr(array); OutputColoredLine("green", "Массив успешно отсортирован по возрастанию методом простого выбора"); break; case 9: // Бинарный поиск элемента в остортированном массиве if (!isArrayCreated) // Проверка на существование массива { OutputColoredLine("red", "Ошибка: массива не существует, сначала создайте его"); break; } if (array.Length == 0) // Проверка на пустоту массива { OutputColoredLine("red", "Ошибка: массив пустой, поиск элементов невозможен"); break; } Console.Write("Введите число для поиска: "); int numToFind = CheckInt32Input(); bool isReadyToSearchNum = true; for (int i = 0; i < array.Length; i++) { int[] temp = new int[array.Length]; temp = SortArr(temp); if (array[i] != SortArr(array)[i]) { OutputColoredLine("yellow", "Внимание: для бинарного поиска нужен остортированный массив, сначала остортируйте его"); isReadyToSearchNum = false; break; } if (array.Length == 1) { if (numToFind == array[0]) Console.WriteLine($"Элемент {array[0]} в массиве находится под номером 1"); else Console.WriteLine($"Элемент {numToFind} не найден"); break; } } if (!isReadyToSearchNum) break; int left = 0; int right = array.Length - 1; int avrg; do { avrg = (left + right) / 2; if (array[avrg] < numToFind) left = avrg + 1; else right = avrg; } while (left != right); if (array[left] == numToFind) Console.WriteLine($"Элемент {numToFind} в массиве находится под номером {left + 1}"); else Console.WriteLine($"Элемент {numToFind} не найден"); break; } } while (choice != 0); Console.WriteLine("Программа завершила свою работу"); } static void CheckIfArrayIsCreated() { if (!isArrayCreated) // Проверка на существование массива { OutputColoredLine("red", "Ошибка: массива не существует, сначала создайте его"); break; } } static int[] SortArr(int[] array) { int min, n_min, j; for (int i = 0; i < array.Length - 1; i++) { min = array[i]; n_min = i; for (j = i + 1; j < array.Length; j++) { if (array[j] < min) { min = array[j]; n_min = j; } } array[n_min] = array[i]; array[i] = min; } return array; } static int[] GenerateArray(int arrayLength, int min, int max) // Создание массива из случайных чисел (длина - arrayLength, минимальное число - min, максимальное число - max) { Random number = new(); int[] array = new int[arrayLength]; for (uint i = 0; i < arrayLength; ++i) { array[i] = number.Next(min, max); } return array; } static void OutputColoredLine(string color, string line) { switch (color) { case "green": Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(line); Console.ResetColor(); break; case "red": Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(line); Console.ResetColor(); break; case "yellow": Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(line); Console.ResetColor(); break; } } static byte CheckChoiceInput() { while (true) { try { byte choice = Convert.ToByte(Console.ReadLine()); if (choice >= 0 && choice <= 9) return choice; OutputColoredLine("red", "Ошибка: введите номер действия только от 0 до 9"); } catch (FormatException) { OutputColoredLine("red", "Ошибка: введите номер действия!"); } catch (OverflowException) { OutputColoredLine("red", "Ошибка: введите номер действия только от 0 до 9"); } } } static int CheckInt32Input() { while (true) { try { int number = Convert.ToInt32(Console.ReadLine()); return number; } catch (FormatException) { OutputColoredLine("red", "Ошибка: введите число!"); } catch (OverflowException) { OutputColoredLine("red", "Ошибка: можно вводить только числа в диапазоне Int32 (от -2 147 483 648 до 2 147 483 647)"); } } } static int CheckArrayLengthInput() { while (true) { try { int number = Convert.ToInt32(Console.ReadLine()); if (number > 0 && number <= 1000000) return number; else OutputColoredLine("red", "Ошибка: длина может быть только в диапазоне от 1 до 1 000 000"); } catch (FormatException) { OutputColoredLine("red", "Ошибка: введите число!"); } catch (OverflowException) { OutputColoredLine("red", "Ошибка: длина может быть только в диапазоне от 1 до 1 000 000"); } } } }
8c299bc690e09337b5ea0a65bed18f21
{ "intermediate": 0.2028595209121704, "beginner": 0.6092811822891235, "expert": 0.18785922229290009 }
34,766
hi'
b55b62c8df0ee2af158bdf6a14ba794b
{ "intermediate": 0.33072131872177124, "beginner": 0.25938719511032104, "expert": 0.4098914563655853 }
34,767
hi
dd25df2c7f4ca83c80e91bd1182dd0c3
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
34,768
In Beautiful Soup, from this "<td><i class="fa fa-calendar"></i> 2023-12-07 <i class="fa fa-clock-o"></i> 00:00</td>" How can I get the date "2023-12-07" and the time "00:00" in ISO format?
615de94565b5afb55d0b178bd7d70d1c
{ "intermediate": 0.44799721240997314, "beginner": 0.26588040590286255, "expert": 0.2861224412918091 }
34,769
#pragma once #include "Arguments.h" #include <string> #include <vector> namespace ArgumentParser { class ArgParser { public: ArgParser(const std::string& name) : parser_name_(name) {} ~ArgParser() {}; bool Parse(std::vector<std::string> args); ArgParser& AddStringArgument(const std::string param); ArgParser& AddStringArgument(const char short_param, const std::string param); ArgParser& AddStringArgument(const char short_param, const std::string param, const std::string description); std::string GetStringValue(const std::string param); Args& AddIntArgument(const std::string number); Args& AddIntArgument(const std::string numer, const std::string description); int GetIntValue(const std::string param); Args& AddIntArgument(const char short_param, const std::string param); int GetIntValue(const std::string param, const int ind); Args& AddFlag(const char short_flag, const std::string flag); Args& AddFlag(const char short_flag, const std::string flag, const std::string description); Args& AddFlag(const std::string flag, const std::string description); bool GetFlag(const std::string flag); Args& AddHelp(const char short_help, const std::string help, const std::string description); bool Help(); std::string HelpDescription(); private: std::string parser_name_; std::vector<Args*> all_; }; } #include "ArgParser.h" #include "Arguments.h" #include <string> #include <vector> #include <iostream> namespace ArgumentParser { bool ArgParser::Parse(std::vector<std::string> args) { if (all_.empty() && args.size() == 1) { return true; } int count = 0; for (int i = 0; i < args.size(); ++i) { std::string origin_param = "--" + all_[j]->GetParam() + "="; std::string origin_short_param = "-"; origin_short_param.push_back(all_[j]->GetShortParam()); origin_short_param += "="; if (args.size() == 1 && !all_[j]->GetDefaultValue().empty()) { all_[j]->PutValue(all_[j]->GetDefaultValue()); ++count; } else if (!all_[j]->GetParam().empty() && args[i].substr(0, origin_param.length()) == origin_param && !all_[j]->GetFlagMultiValue()) { all_[j]->PutValue(args[i].substr(origin_param.length(), args[i].length())); if (all_[j]->GetFlagStoreValue()) { all_[j]->AddStoreValue(all_[j]->GetValue()); } ++count; } else if (all_[j]->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param && !all_[j]->GetFlagMultiValue()) { all_[j]->PutValue(args[i].substr(origin_short_param.length(), args[i].length())); if (all_[j]->GetFlagStoreValue()) { all_[j]->AddStoreValue(all_[j]->GetValue()); } ++count; } else if (all_[j]->GetFlagMultiValue()) { if (args[i].substr(0, origin_param.length()) == origin_param) { all_[j]->PutValue(args[i].substr(origin_param.length(), args[i].length())); all_[j]->MultiArgsCount(); } else if (all_[j]->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param) { all_[j]->PutValue(args[i].substr(origin_short_param.length(), args[i].length())); all_[j]->MultiArgsCount(); } if (args[i][0] == '-' && all_[j]->GetFlagStoreValues()) { all_[j]->AddStoreValues(all_[j]->GetValue()); all_[j]->AddAllValues(all_[j]->GetValue()); } } std::string origin_flag = "--" + all_[j]->GetFlag(); std::string origin_help = "--" + all_[j]->GetHelp(); std::string origin_short_help = "-"; origin_short_help.push_back(all_[j]->GetShortHelp()); if (all_[j]->GetIsFlag()) { if (args[i].substr(0, origin_flag.length()) == origin_flag) { if (all_[j]->GetFlagStoreFlag()) { all_[j]->AddStoreFlag(true); } ++count; } else if (args[i][0] == '-' && args[i][1] != '-' && args[i].length() > 2) { for (int z = 1; z < args[i].length(); ++z) { if (args[i][z] == all_[j]->GetShortFlag()) { if (all_[j]->GetFlagStoreFlag()) { all_[j]->AddStoreFlag(true); } ++count; } } } } else if (all_[j]->GetFlagPositional()) { int count_len = 0; for (int k = 0; k < args[i].length(); ++k) { if (!std::isdigit(args[i][k])){ break; } else { ++count_len; } } if (count_len == args[i].length()) { all_[j]->PutValue(args[i]); all_[j]->MultiArgsCount(); if (all_[j]->GetFlagStoreValues()) { all_[j]->AddStoreValues(all_[j]->GetValue()); all_[j]->AddAllValues(all_[j]->GetValue()); } } } else if (args[i].substr(0, origin_help.length()) == origin_help || args[i].substr(0, origin_short_help.length()) == origin_short_help) { all_[j]->FlagHelp(); ++count; } } for (int i = 0; i < all_.size(); ++i) { if (all_[i]->GetMultiArgsCount() > 0) { ++count; } if (all_[i]->GetFlagDefaultFlag()) { ++count; } if (all_[i]->GetMultiArgsCount() > 0 && all_[i]->GetMinArgsCount() > all_[i]->GetMultiArgsCount()) { return false; } } if (count == all_.size()) { return true; } else { for (int i = 0; i < all_.size(); ++i) { if (all_[i]->GetFlagHelp()) { return true; } } return false; } } ArgParser& ArgParser::AddStringArgument(const std::string param) { String* str = new String(); str->param_ = param; all_->push_back(*str); return *this; } ArgParser& ArgParser::AddStringArgument(const char short_param, const std::string param) { String* str = new String(); str->short_param_ = short_param; str->param_ = param; all_->push_back(*str); return *this; } ArgParser& ArgParser::AddStringArgument(const char short_param, const std::string param, const std::string description) { String* str = new String(); str->param_ = param; all_->push_back(*str); str->Description(description); return *this; } std::string ArgParser::GetStringValue(const std::string param) { for (int i = 0; i < (all_).size(); ++i) { if (static_cast<String*>(all_[i])->param_ == param) { return static_cast<String*>(all_[i])->GetValue(); } } } Args& ArgParser::AddIntArgument(const std::string number) { Args* int_val = new Args(number); all_.push_back(int_val); return *int_val; } Args& ArgParser::AddIntArgument(const std::string numer, const std::string description) { Args* int_val = new Args(numer); all_.push_back(int_val); int_val->Description(description); return *int_val; } int ArgParser::GetIntValue(const std::string param) { for (int i = 0; i < all_.size(); ++i) { if (all_[i]->GetParam() == param) { int value = std::stoi(all_[i]->GetValue()); return value; } } } Args& ArgParser::AddIntArgument(const char short_param, const std::string param) { Args* int_val = new Args(short_param, param); all_.push_back(int_val); return *int_val; } int ArgParser::GetIntValue(const std::string param, const int ind) { if (all_[ind]->GetParam() == param) { return all_[ind]->GetIndexedValue(ind); } } Args& ArgParser::AddFlag(const char short_flag, const std::string flag) { Args* new_flag = new Args(); new_flag->AddFlags(short_flag, flag); all_.push_back(new_flag); return *new_flag; } Args& ArgParser::AddFlag(const char short_flag, const std::string flag, const std::string description) { Args* new_flag = new Args(); new_flag->AddFlags(short_flag, flag); all_.push_back(new_flag); new_flag->Description(description); return *new_flag; } Args& ArgParser::AddFlag(const std::string flag, const std::string description) { Args* new_flag = new Args(); new_flag->AddFlag(flag); all_.push_back(new_flag); new_flag->Description(description); return *new_flag; } bool ArgParser::GetFlag(const std::string flag) { for (int i = 0; i < all_.size(); ++i) { if (all_[i]->GetFlag() == flag) { return true; } } return false; } bool ArgParser::Help() { return true; } Args& ArgParser::AddHelp(const char short_help, const std::string help, const std::string description) { Args* new_help = new Args(); new_help->Help(short_help, help); new_help->Description(description); all_.push_back(new_help); return *new_help; } std::string ArgParser::HelpDescription() { std::cout << "My Parser\n"; std::cout << "Some Description about program\n\n"; std::cout << "-i, --input=<string>, File path for input file [repeated, min args = 1]\n"; std::cout << "-s, --flag1, Use some logic [default = true]\n"; std::cout << "-p, --flag2, Use some logic\n"; std::cout << " --number=<int>, Some Number\n\n"; std::cout << "-h, --help Display this help and exit\n"; } }#pragma once #include <string> #include <vector> namespace ArgumentParser { class Args { public: Args(); Args(const std::string param); Args(const char short_param, const std::string param); ~Args() {}; Args& MultiValue(); Args& MultiValue(const int min_args_count); bool GetFlagMultiValue(); Args& Positional(); bool GetFlagPositional(); void MultiArgsCount(); int GetMultiArgsCount(); int GetMinArgsCount(); void AddAllValues(const std::string value); int GetIndexedValue(const int ind); void Help(const char short_help, const std::string help); std::string GetHelp(); char GetShortHelp(); void FlagHelp(); bool GetFlagHelp(); void Description(const std::string description); bool flag_positional_ = false; bool flag_multi_value_ = false; int min_args_count_; int multi_args_count_ = 0; std::vector<int> all_values_; char short_help_; std::string help_; std::string description_; bool flag_help_ = false; }; class Int : public Args { void StoreValues(std::vector<int>& store_values); void AddStoreValues(const std::string value); bool GetFlagStoreValues(); std::vector<int>* store_values_; bool flag_store_values_ = false; }; class String : public Args { public: std::string GetParam(); char GetShortParam(); bool GetFlagShortParam(); void PutValue(const std::string value); std::string GetValue(); void Default(const char* value); std::string GetDefaultValue(); void AddFlags(const char short_flag, const std::string flag); void AddFlag(const std::string flag); std::string GetFlag(); bool GetIsFlag(); char GetShortFlag(); void StoreValue(std::string& value); void AddStoreValue(const std::string value); bool GetFlagStoreValue(); std::string param_; char short_param_; bool flag_short_param_ = false; std::string value_; std::string* store_value_; std::string default_value_; std::string flag_; char short_flag_; bool is_flag_ = false; bool flag_store_value_ = false; }; class Bool : public Args { public: void Default(const bool flag); bool GetFlagDefaultFlag(); void StoreValue(bool& flag); bool GetFlagStoreFlag(); void AddStoreFlag(const bool flag); bool default_flag_; bool flag_default_flag_ = false; bool* store_flag_; bool flag_store_flag_ = false; }; };#include "Arguments.h" #include <string> #include <vector> namespace ArgumentParser { Args::Args() {} Args::Args(const std::string param) { static_cast<String*>(this)->param_ = param; } Args::Args(const char short_param, const std::string param) { static_cast<String*>(this)->param_ = param; static_cast<String*>(this)->short_param_ = short_param; static_cast<String*>(this)->flag_short_param_ = true; } std::string String::GetParam() { return param_; } std::string String::GetValue() { return value_; } char Args::GetShortParam() { return short_param_; } bool Args::GetFlagShortParam() { return flag_short_param_; } void Args::PutValue(const std::string value) { value_ = value; } void Args::Default(const char* value) { default_value_ = value; } void Args::Default(const bool flag) { default_flag_ = flag; flag_default_flag_ = true; } std::string Args::GetDefaultValue() { return default_value_; } bool Args::GetFlagDefaultFlag() { return flag_default_flag_; } void Args::StoreValue(std::string& value) { store_value_ = &value; flag_store_value_ = true; } void Args::StoreValues(std::vector<int>& store_values) { store_values_ = &store_values; flag_store_values_ = true; } void Args::StoreValue(bool& flag) { store_flag_ = &flag; flag_store_flag_ = true; } bool Args::GetFlagStoreValue() { return flag_store_value_; } void Args::AddStoreValue(const std::string value) { *store_value_ = value; } void Args::AddStoreValues(const std::string value) { (*store_values_).push_back(std::stoi(value)); } bool Args::GetFlagStoreValues() { return flag_store_values_; } bool Args::GetFlagStoreFlag() { return flag_store_flag_; } void Args::AddStoreFlag(const bool flag) { *store_flag_ = flag; } Args& Args::MultiValue() { flag_multi_value_ = true; return *this; } Args& Args::MultiValue(const int min_args_count) { flag_multi_value_ = true; min_args_count_ = min_args_count; return *this; } bool Args::GetFlagMultiValue() { return flag_multi_value_; } void Args::MultiArgsCount() { ++multi_args_count_; } int Args::GetMultiArgsCount() { return multi_args_count_; } int Args::GetMinArgsCount() { return min_args_count_; } void Args::AddAllValues(const std::string value) { all_values_.push_back(std::stoi(value)); } int Args::GetIndexedValue(const int ind) { return all_values_[ind]; } void Args::AddFlags(const char short_flag, const std::string flag) { short_flag_ = short_flag; flag_ = flag; is_flag_ = true; } void Args::AddFlag(const std::string flag) { flag_ = flag; is_flag_ = true; } std::string Args::GetFlag() { return flag_; } bool Args::GetIsFlag() { return is_flag_; } char Args::GetShortFlag() { return short_flag_; } Args& Args::Positional() { flag_positional_ = true; return *this; } bool Args::GetFlagPositional() { return flag_positional_; } void Args::Help(const char short_help, const std::string help) { short_help_ = short_help; help_ = help; } std::string Args::GetHelp() { return help_; } char Args::GetShortHelp() { return short_help_; } void Args::FlagHelp() { flag_help_ = true; } bool Args::GetFlagHelp() { return flag_help_; } void Args::Description(const std::string description) { description_ = description; } }get type in parsing and switch
98cd54977ee64f1a07e3c0a6fa7d9bb2
{ "intermediate": 0.3705430030822754, "beginner": 0.5171922445297241, "expert": 0.1122647374868393 }
34,770
be very careful about the non-ascii character. and rewrite the python code so the user-input is instead being calculated, so the if-condition for "good flag" is met. show new python code.
21128c2b1dc29d9641a118d19c5bddaf
{ "intermediate": 0.32689180970191956, "beginner": 0.29609590768814087, "expert": 0.3770122528076172 }
34,771
goal:met "good flag" condition. code:
bee79058c71fdeaaea16e7b5f3f06fb3
{ "intermediate": 0.30660173296928406, "beginner": 0.38659313321113586, "expert": 0.3068051040172577 }
34,772
Write Python code that puts a sine wave into an array and saves the data to WAV file. Start by setting the bits per sample to 32, the maximum values to 2^32-1, the sample rate to 44100 samples per second, the frequency to 880 Hz, the amplitude to 1.00 times the maximum, the duration to 1.00 seconds, and the name of the output file to "output.wav".
738429dc727a9af71bf552d6d27ffe84
{ "intermediate": 0.5054545998573303, "beginner": 0.1277959644794464, "expert": 0.36674943566322327 }
34,773
why code no worky? import requests import random import time headers = { 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_8 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6 Mobile/15E148 Safari/604.1', 'Accept': '*/*', 'Accept-Language': 'en-US,en;q=0.5', # 'Accept-Encoding': 'gzip, deflate', 'Content-Type': 'application/json', 'Origin': 'http://svmzii-28628.portmap.host:28628', 'Connection': 'keep-alive', 'Referer': 'http://svmzii-28628.portmap.host:28628/', } while True: fp = random.randint(-19000000, -19999999) json_data = { 'hash': fp } response = requests.post('http://svmzii-28628.portmap.host:28628/receive_hash', headers=headers, json=json_data) print('sent:', fp) time.sleep(1) /usr/bin/python3.10 /home/brrt/Documents/folder/fraud/main.py Traceback (most recent call last): File "/home/brrt/Documents/folder/fraud/main.py", line 16, in <module> fp = random.randint(-19000000, -19999999) File "/usr/lib/python3.10/random.py", line 370, in randint return self.randrange(a, b+1) File "/usr/lib/python3.10/random.py", line 353, in randrange raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width)) ValueError: empty range for randrange() (-19000000, -19999998, -999998)
aa46bcca415e7c0e17caa7b354b17b69
{ "intermediate": 0.6135203838348389, "beginner": 0.2817481756210327, "expert": 0.10473139584064484 }
34,774
goal: met the condition "good flag". code:
67359728707ca8ad5e99495f9583a504
{ "intermediate": 0.2309093326330185, "beginner": 0.33829742670059204, "expert": 0.43079322576522827 }
34,775
how add vite to react projects ?
990a81e595f6467076c6be30f28f7849
{ "intermediate": 0.41916120052337646, "beginner": 0.16199946403503418, "expert": 0.41883933544158936 }
34,776
do you know the libtom github repository?
3006ea124d36a51da2b1f6707c072cac
{ "intermediate": 0.5455290079116821, "beginner": 0.15118467807769775, "expert": 0.3032863736152649 }
34,777
✘ [ERROR] The JSX syntax extension is not currently enabled vite with react
3f38daeaaaf51191e1bafaa73815ec5d
{ "intermediate": 0.2613255977630615, "beginner": 0.5058231353759766, "expert": 0.23285122215747833 }
34,778
make this code faster and more efficient: def parse_genome(): reference_sequences = [] with open(GENOME, "r") as file: origin_reached = False for line in file: if line.startswith("ORIGIN"): origin_reached=True if origin_reached: items = line.split() if items[0].isdigit(): reference_sequences.extend(items[1:]) reference_sequence = "".join(reference_sequences).upper() return reference_sequence
cb9f7bc842d9e023814725957684c5d5
{ "intermediate": 0.4417651295661926, "beginner": 0.3257793188095093, "expert": 0.2324555218219757 }
34,779
code baby face from jojo's bizarre adventure in to roblox
20e9b497ad6803d11438868695e9fb02
{ "intermediate": 0.3243923485279083, "beginner": 0.351639062166214, "expert": 0.3239685595035553 }
34,780
write me requirement specifications for fp_mod() function created for libtom. do some requirement traceability over the source code
18a07b5a2d025c018facc39344229d8d
{ "intermediate": 0.5794195532798767, "beginner": 0.21963973343372345, "expert": 0.20094065368175507 }
34,781
what is the PIPE format when dealing with credit cards? its some sort of way to store credit card details where they are seperated by vertical bars
621cb81006b6d6c5d52acff9b2a43053
{ "intermediate": 0.40433505177497864, "beginner": 0.31111443042755127, "expert": 0.2845505475997925 }
34,782
it doesn't pick up the bluetooth buttons: import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:path_provider/path_provider.dart'; import 'package:camera/camera.dart'; import 'package:flutter/material.dart'; import 'package:just_audio/just_audio.dart'; import 'package:volume_watcher/volume_watcher.dart'; import 'package:flutter/services.dart'; import 'package:http/http.dart' as http; Future<void> main() async { // Ensure that plugin services are initialized so that `availableCameras()` // can be called before `runApp()` WidgetsFlutterBinding.ensureInitialized(); // Obtain a list of the available cameras on the device. final cameras = await availableCameras(); // Get a specific camera from the list of available cameras. final firstCamera = cameras.first; runApp( MaterialApp( theme: ThemeData.dark(), home: TakePictureScreen( // Pass the appropriate camera to the TakePictureScreen widget. camera: firstCamera, ), ), ); } // A screen that allows users to take a picture using a given camera. class TakePictureScreen extends StatefulWidget { const TakePictureScreen({ super.key, required this.camera, }); final CameraDescription camera; @override TakePictureScreenState createState() => TakePictureScreenState(); } class TakePictureScreenState extends State<TakePictureScreen> { late CameraController _controller; late Future<void> _initializeControllerFuture; @override void initState() { super.initState(); // To display the current output from the Camera, // create a CameraController. _controller = CameraController( // Get a specific camera from the list of available cameras. widget.camera, // Define the resolution to use. ResolutionPreset.medium, ); // Next, initialize the controller. This returns a Future. _initializeControllerFuture = _controller.initialize(); } Future<void> captureAndSendImage() async { // Your existing code here... try { await _initializeControllerFuture; final image = await _controller.takePicture(); if (!mounted) return; // Send the image to the server var request = http.MultipartRequest( 'POST', Uri.parse('http://localhost:8000/api/phone/camera')); request.files.add(await http.MultipartFile.fromPath('file', image.path)); request.fields['direction'] = "In"; var res = await request.send(); var response = await http.Response.fromStream(res); if (response.statusCode == 200) { // If the server returns a 200 OK response, then proceed var responseData = jsonDecode(response.body); var audioBase64 = responseData[1]['audio']; // Decode the Base64 string to bytes var audioBytes = base64Decode(audioBase64); // Save the audio to a temporary file var directory = await getApplicationDocumentsDirectory(); var audioPath = '${directory.path}/temp.mp3'; var audioFile = File(audioPath); await audioFile.writeAsBytes(audioBytes); // Load the audio file var player = AudioPlayer(); await player.setUrl(audioPath); // Play the audio file player.play(); } else { // If the server returns an error response, // then print the status code. print('Failed to upload image. Status code: ${response.statusCode}.'); } } catch (e) { print(e); } } @override void dispose() { // Dispose of the controller when the widget is disposed. _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return KeyboardListener( focusNode: FocusNode(), autofocus: true, onKeyEvent: (KeyEvent event) { if (event is KeyDownEvent) { print(event.logicalKey.keyLabel); if (event.logicalKey.keyLabel == 'Audio Volume Up') { captureAndSendImage(); } if (event.logicalKey.keyLabel == 'Audio Volume Down') { captureAndSendImage(); } } }, child: Scaffold( appBar: AppBar(title: const Text('Take a picture')), body: FutureBuilder<void>( future: _initializeControllerFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { return CameraPreview(_controller); } else { return const Center(child: CircularProgressIndicator()); } }, ), floatingActionButton: FloatingActionButton( onPressed: captureAndSendImage, child: const Icon(Icons.camera_alt), ), ), ); } }
d5451d2ebe289950fb8dc32545c85244
{ "intermediate": 0.4889356791973114, "beginner": 0.37164103984832764, "expert": 0.13942328095436096 }
34,783
#pragma once #include <string> #include <vector> namespace ArgumentParser { enum class Type { INT, STRING, BOOL, HELP, }; class Args { public: Args(); Args(const std::string param); Args(const char short_param, const std::string param); ~Args() {}; virtual Type GetType() const = 0; Args& MultiValue(); Args& MultiValue(const int min_args_count); bool GetFlagMultiValue(); Args& Positional(); bool GetFlagPositional(); void MultiArgsCount(); int GetMultiArgsCount(); int GetMinArgsCount(); void AddAllValues(const std::string value); int GetIndexedValue(const int ind); void Description(const std::string description); bool flag_positional_ = false; bool flag_multi_value_ = false; int min_args_count_; int multi_args_count_ = 0; std::vector<int> all_values_; std::string description_; }; class Int : public Args { public: Type GetType() const override { return Type::INT; } void StoreValues(std::vector<int>& store_values); void AddStoreValues(const std::string value); bool GetFlagStoreValues(); std::string GetParam(); char GetShortParam(); bool GetFlagShortParam(); void PutValue(const std::string value); std::string GetValue(); std::vector<int>* store_values_; std::string param_; char short_param_; bool flag_short_param_ = false; bool flag_store_values_ = false; std::string value_; }; class String : public Args { public: Type GetType() const override { return Type::STRING; } std::string GetParam(); char GetShortParam(); bool GetFlagShortParam(); String& Default(const char* value); std::string GetDefaultValue(); void StoreValue(std::string& value); void AddStoreValue(const std::string value); bool GetFlagStoreValue(); std::string param_; char short_param_; bool flag_short_param_ = false; std::string* store_value_; std::string default_value_; bool flag_store_value_ = false; }; class Bool : public Args { public: Type GetType() const override { return Type::BOOL; } Bool& Default(const bool flag); bool GetFlagDefaultFlag(); void StoreValue(bool& flag); bool GetFlagStoreFlag(); void AddStoreFlag(const bool flag); void AddFlags(const char short_flag, const std::string flag); void AddFlag(const std::string flag); std::string GetFlag(); bool GetIsFlag(); char GetShortFlag(); std::string flag_; char short_flag_; bool is_flag_ = false; bool default_flag_; bool flag_default_flag_ = false; bool* store_flag_; bool flag_store_flag_ = false; }; class Help : public Args { public: Type GetType() const override { return Type::HELP; } std::string GetHelp(); char GetShortHelp(); void FlagHelp(); bool GetFlagHelp(); void Description(const std::string description); char short_help_; std::string help_; std::string description_; bool flag_help_ = false; }; };Help& ArgParser::AddHelp(const char short_help, const std::string help, const std::string description) { Help* new_help = new Help(); all_.push_back(new_help); return *new_help; } требуется спецификатор типаC/C++(79)
3d5823f8a83bd72f4f3e742d4dd1318b
{ "intermediate": 0.3328872621059418, "beginner": 0.34212443232536316, "expert": 0.32498839497566223 }
34,784
#pragma once #include "Arguments.h" #include <string> #include <vector> namespace ArgumentParser { class ArgParser { public: ArgParser(const std::string& name) : parser_name_(name) {} ~ArgParser() {}; bool Parse(std::vector<std::string> args); String& AddStringArgument(const std::string param); String& AddStringArgument(const char short_param, const std::string param); String& AddStringArgument(const char short_param, const std::string param, const std::string description); std::string GetStringValue(const std::string param); Int& AddIntArgument(const std::string number); Int& AddIntArgument(const std::string numer, const std::string description); int GetIntValue(const std::string param); Int& AddIntArgument(const char short_param, const std::string param); int GetIntValue(const std::string param, const int ind); Bool& AddFlag(const char short_flag, const std::string flag); Bool& AddFlag(const char short_flag, const std::string flag, const std::string description); Bool& AddFlag(const std::string flag, const std::string description); bool GetFlag(const std::string flag); Args& AddHelp(const char short_help, const std::string help, const std::string description); bool Help(); std::string HelpDescription(); private: std::string parser_name_; std::vector<Args*> all_; }; } #include "ArgParser.h" #include "Arguments.h" #include <string> #include <vector> #include <iostream> namespace ArgumentParser { bool ArgParser::Parse(std::vector<std::string> args) { if (all_.empty() && args.size() == 1) { return true; } int count = 0; for (int i = 0; i < args.size(); ++i) { for (int j = 0; j < all_.size(); ++j) { TypeFlag type = all_[j]->GetTypeFlag(); switch (type) { case TypeFlag::INT: { Int* arg = static_cast<Int*>(all_[j]); std::string origin_param = "--" + arg->GetParam() + "="; std::string origin_short_param = "-"; origin_short_param.push_back(arg->GetShortParam()); origin_short_param += "="; if (!arg->GetParam().empty() && args[i].substr(0, origin_param.length()) == origin_param && !all_[j]->GetFlagMultiValue()) { arg->PutValue(args[i].substr(origin_param.length(), args[i].length())); ++count; } else if (arg->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param && !all_[j]->GetFlagMultiValue()) { arg->PutValue(args[i].substr(origin_short_param.length(), args[i].length())); ++count; } else if (all_[j]->GetFlagMultiValue()) { if (args[i].substr(0, origin_param.length()) == origin_param) { arg->PutValue(args[i].substr(origin_param.length(), args[i].length())); all_[j]->MultiArgsCount(); } else if (arg->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param) { arg->PutValue(args[i].substr(origin_short_param.length(), args[i].length())); all_[j]->MultiArgsCount(); } } if (all_[j]->GetFlagPositional()) { int count_len = 0; for (int k = 0; k < args[i].length(); ++k) { if (!std::isdigit(args[i][k])){ break; } else { ++count_len; } } if (count_len == args[i].length()) { arg->PutValue(args[i]); arg->MultiArgsCount(); if (arg->GetFlagStoreValues()) { arg->AddStoreValues(arg->GetValue()); all_[j]->AddAllValues(arg->GetValue()); } } } } break; case TypeFlag::STRING: { String* arg = static_cast<String*>(all_[j]); std::string origin_param = "--" + arg->GetParam() + "="; std::string origin_short_param = "-"; origin_short_param.push_back(arg->GetShortParam()); origin_short_param += "="; if (args.size() == 1 && !arg->GetDefaultValue().empty()) { arg->PutValue(arg->GetDefaultValue()); ++count; } else if (!arg->GetParam().empty() && args[i].substr(0, origin_param.length()) == origin_param && !all_[j]->GetFlagMultiValue()) { arg->PutValue(args[i].substr(origin_param.length(), args[i].length())); if (arg->GetFlagStoreValue()) { arg->AddStoreValue(arg->GetValue()); } ++count; } else if (arg->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param && !all_[j]->GetFlagMultiValue()) { arg->PutValue(args[i].substr(origin_short_param.length(), args[i].length())); if (arg->GetFlagStoreValue()) { arg->AddStoreValue(arg->GetValue()); } ++count; } else if (arg->GetFlagMultiValue()) { if (args[i].substr(0, origin_param.length()) == origin_param) { arg->PutValue(args[i].substr(origin_param.length(), args[i].length())); arg->MultiArgsCount(); } else if (arg->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param) { arg->PutValue(args[i].substr(origin_short_param.length(), args[i].length())); arg->MultiArgsCount(); } } } break; case TypeFlag::BOOL: { Bool* arg = static_cast<Bool*>(all_[j]); std::string origin_flag = "--" + arg->GetFlag(); if (arg->GetIsFlag()) { if (args[i].substr(0, origin_flag.length()) == origin_flag) { if (arg->GetFlagStoreFlag()) { arg->AddStoreFlag(true); } ++count; } else if (args[i][0] == '-' && args[i][1] != '-' && args[i].length() > 2) { for (int z = 1; z < args[i].length(); ++z) { if (args[i][z] == arg->GetShortFlag()) { if (arg->GetFlagStoreFlag()) { arg->AddStoreFlag(true); } ++count; } } } } } break; case TypeFlag::UNKNOWN: { Args* arg = static_cast<Args*>(all_[j]); std::string origin_help = "--" + all_[j]->GetHelp(); std::string origin_short_help = "-"; origin_short_help.push_back(all_[j]->GetShortHelp()); if (args[i].substr(0, origin_help.length()) == origin_help || args[i].substr(0, origin_short_help.length()) == origin_short_help) { all_[j]->FlagHelp(); ++count; } } break; } } } for (int i = 0; i < all_.size(); ++i) { if (all_[i]->GetMultiArgsCount() > 0) { ++count; } if (static_cast<Bool*>(all_[i])->GetFlagDefaultFlag()) { ++count; } if (all_[i]->GetMultiArgsCount() > 0 && all_[i]->GetMinArgsCount() > all_[i]->GetMultiArgsCount()) { return false; } } if (count == all_.size()) { return true; } else { for (int i = 0; i < all_.size(); ++i) { if (all_[i]->GetFlagHelp()) { return true; } } return false; } } String& ArgParser::AddStringArgument(const std::string param) { String* str = new String(); str->param_ = param; all_.push_back(str); return *str; } String& ArgParser::AddStringArgument(const char short_param, const std::string param) { String* str = new String(); str->short_param_ = short_param; str->param_ = param; str->flag_short_param_ = true; all_.push_back(str); return *str; } String& ArgParser::AddStringArgument(const char short_param, const std::string param, const std::string description) { String* str = new String(); str->short_param_ = short_param; str->param_ = param; str->flag_short_param_ = true; all_.push_back(str); str->Description(description); return *str; } std::string ArgParser::GetStringValue(const std::string param) { for (int i = 0; i < (all_).size(); ++i) { if (static_cast<String*>(all_[i])->param_ == param) { return static_cast<String*>(all_[i])->GetValue(); } } } Int& ArgParser::AddIntArgument(const std::string number) { Int* int_val = new Int(); int_val->param_ = number; all_.push_back(int_val); return *int_val; } Int& ArgParser::AddIntArgument(const std::string number, const std::string description) { Int* int_val = new Int(); int_val->param_ = number; all_.push_back(int_val); int_val->Description(description); return *int_val; } int ArgParser::GetIntValue(const std::string param) { for (int i = 0; i < all_.size(); ++i) { if (static_cast<Int*>(all_[i])->GetParam() == param) { int value = std::stoi(static_cast<Int*>(all_[i])->GetValue()); return value; } } } Int& ArgParser::AddIntArgument(const char short_param, const std::string param) { Int* int_val = new Int(); int_val->short_param_ = short_param; all_.push_back(int_val); return *int_val; } int ArgParser::GetIntValue(const std::string param, const int ind) { if (static_cast<Int*>(all_[ind])->GetParam() == param) { return static_cast<Int*>(all_[ind])->GetIndexedValue(ind); } } Bool& ArgParser::AddFlag(const char short_flag, const std::string flag) { Bool* new_flag = new Bool(); new_flag->AddFlags(short_flag, flag); all_.push_back(new_flag); return *new_flag; } Bool& ArgParser::AddFlag(const char short_flag, const std::string flag, const std::string description) { Bool* new_flag = new Bool(); new_flag->AddFlags(short_flag, flag); all_.push_back(new_flag); new_flag->Description(description); return *new_flag; } Bool& ArgParser::AddFlag(const std::string flag, const std::string description) { Bool* new_flag = new Bool(); new_flag->AddFlag(flag); all_.push_back(new_flag); new_flag->Description(description); return *new_flag; } bool ArgParser::GetFlag(const std::string flag) { for (int i = 0; i < all_.size(); ++i) { if (static_cast<Bool*>(all_[i])->GetFlag() == flag) { return true; } } return false; } bool ArgParser::Help() { return true; } Args& ArgParser::AddHelp(const char short_help, const std::string help, const std::string description) { Args* new_help = new Args(); new_help->Help(short_help, help); new_help->Description(description); all_.push_back(new_help); return *new_help; } std::string ArgParser::HelpDescription() { std::cout << "My Parser\n"; std::cout << "Some Description about program\n\n"; std::cout << "-i, --input=<string>, File path for input file [repeated, min args = 1]\n"; std::cout << "-s, --flag1, Use some logic [default = true]\n"; std::cout << "-p, --flag2, Use some logic\n"; std::cout << " --number=<int>, Some Number\n\n"; std::cout << "-h, --help Display this help and exit\n"; } } #pragma once #include <string> #include <vector> namespace ArgumentParser { enum class TypeFlag { INT, STRING, BOOL, UNKNOWN // In case no flag is set or Args is a base type that should not be instantiated }; class Args { public: Args(); Args(const std::string param); Args(const char short_param, const std::string param); ~Args() {}; virtual TypeFlag GetTypeFlag() const { return TypeFlag::UNKNOWN; } Args& MultiValue(); Args& MultiValue(const int min_args_count); bool GetFlagMultiValue(); Args& Positional(); bool GetFlagPositional(); void MultiArgsCount(); int GetMultiArgsCount(); int GetMinArgsCount(); void AddAllValues(const std::string value); void Help(const char short_help, const std::string help); std::string GetHelp(); char GetShortHelp(); void FlagHelp(); bool GetFlagHelp(); void Description(const std::string description); void StoreValues(std::vector<int>& store_values); bool GetFlagStoreValues(); bool flag_store_values_ = false; bool flag_positional_ = false; bool flag_multi_value_ = false; int min_args_count_; int multi_args_count_ = 0; std::vector<int> all_values_; char short_help_; std::string help_; std::string description_; bool flag_help_ = false; std::vector<int>* store_values_; }; class Int : public Args { public: TypeFlag GetTypeFlag() const override { return TypeFlag::INT; } void AddStoreValues(const std::string value); std::string GetParam(); char GetShortParam(); bool GetFlagShortParam(); void PutValue(const std::string value); std::string GetValue(); int GetIndexedValue(const int ind); std::string param_; char short_param_; bool flag_short_param_ = false; bool flag_store_values_ = false; std::string value_; }; class String : public Args { public: TypeFlag GetTypeFlag() const override { return TypeFlag::STRING; } std::string GetParam(); char GetShortParam(); bool GetFlagShortParam(); String& Default(const char* value); std::string GetDefaultValue(); void PutValue(const std::string value); std::string GetValue(); void StoreValue(std::string& value); void AddStoreValue(const std::string value); bool GetFlagStoreValue(); std::string param_; char short_param_; bool flag_short_param_ = false; std::string* store_value_; std::string default_value_; std::string value_; bool flag_store_value_ = false; }; class Bool : public Args { public: TypeFlag GetTypeFlag() const override { return TypeFlag::BOOL; } Bool& Default(const bool flag); bool GetFlagDefaultFlag(); void StoreValue(bool& flag); bool GetFlagStoreFlag(); void AddStoreFlag(const bool flag); void AddFlags(const char short_flag, const std::string flag); void AddFlag(const std::string flag); std::string GetFlag(); bool GetIsFlag(); char GetShortFlag(); std::string flag_; char short_flag_; bool is_flag_ = false; bool default_flag_; bool flag_default_flag_ = false; bool* store_flag_; bool flag_store_flag_ = false; }; }; #include "Arguments.h" #include <string> #include <vector> namespace ArgumentParser { Args::Args() {} Args::Args(const std::string param) { static_cast<String*>(this)->param_ = param; } Args::Args(const char short_param, const std::string param) { static_cast<String*>(this)->param_ = param; static_cast<String*>(this)->short_param_ = short_param; static_cast<String*>(this)->flag_short_param_ = true; } std::string String::GetParam() { return param_; } char String::GetShortParam() { return short_param_; } bool String::GetFlagShortParam() { return flag_short_param_; } std::string Int::GetParam() { return param_; } char Int::GetShortParam() { return short_param_; } bool Int::GetFlagShortParam() { return flag_short_param_; } void Int::PutValue(const std::string value) { value_ = value; } std::string Int::GetValue() { return value_; } void String::PutValue(const std::string value) { value_ = value; } std::string String::GetValue() { return value_; } String& String::Default(const char* value) { default_value_ = value; return *this; } Bool& Bool::Default(const bool flag) { default_flag_ = flag; flag_default_flag_ = true; return *this; } std::string String::GetDefaultValue() { return default_value_; } bool Bool::GetFlagDefaultFlag() { return flag_default_flag_; } void String::StoreValue(std::string& value) { store_value_ = &value; flag_store_value_ = true; } void Args::StoreValues(std::vector<int>& store_values) { store_values_ = &store_values; flag_store_values_ = true; } void Bool::StoreValue(bool& flag) { store_flag_ = &flag; flag_store_flag_ = true; } bool String::GetFlagStoreValue() { return flag_store_value_; } void String::AddStoreValue(const std::string value) { *store_value_ = value; } void Int::AddStoreValues(const std::string value) { (*store_values_).push_back(std::stoi(value)); } bool Args::GetFlagStoreValues() { return flag_store_values_; } bool Bool::GetFlagStoreFlag() { return flag_store_flag_; } void Bool::AddStoreFlag(const bool flag) { *store_flag_ = flag; } Args& Args::MultiValue() { flag_multi_value_ = true; return *this; } Args& Args::MultiValue(const int min_args_count) { flag_multi_value_ = true; min_args_count_ = min_args_count; return *this; } bool Args::GetFlagMultiValue() { return flag_multi_value_; } void Args::MultiArgsCount() { ++multi_args_count_; } int Args::GetMultiArgsCount() { return multi_args_count_; } int Args::GetMinArgsCount() { return min_args_count_; } void Args::AddAllValues(const std::string value) { all_values_.push_back(std::stoi(value)); } int Int::GetIndexedValue(const int ind) { return all_values_[ind]; } void Bool::AddFlags(const char short_flag, const std::string flag) { short_flag_ = short_flag; flag_ = flag; is_flag_ = true; } void Bool::AddFlag(const std::string flag) { flag_ = flag; is_flag_ = true; } std::string Bool::GetFlag() { return flag_; } bool Bool::GetIsFlag() { return is_flag_; } char Bool::GetShortFlag() { return short_flag_; } Args& Args::Positional() { flag_positional_ = true; return *this; } bool Args::GetFlagPositional() { return flag_positional_; } void Args::Help(const char short_help, const std::string help) { short_help_ = short_help; help_ = help; } std::string Args::GetHelp() { return help_; } char Args::GetShortHelp() { return short_help_; } void Args::FlagHelp() { flag_help_ = true; } bool Args::GetFlagHelp() { return flag_help_; } void Args::Description(const std::string description) { description_ = description; } } TEST(ArgParserTestSuite, MultiValueTest) { ArgParser parser("My Parser"); std::vector<int> int_values; parser.AddIntArgument('p', "param1").MultiValue().StoreValues(int_values); ASSERT_TRUE(parser.Parse(SplitString("app --param1=1"))); ASSERT_EQ(parser.GetIntValue("param1", 0), 1); ASSERT_EQ(int_values[1], 2); ASSERT_EQ(int_values[2], 3); }9: Test command: /Users/alishashelby/Desktop/labwork4-alishashelby/build/tests/argparser_tests "--gtest_filter=ArgParserTestSuite.MultiValueTest" "--gtest_also_run_disabled_tests" 9: Working Directory: /Users/alishashelby/Desktop/labwork4-alishashelby/build/tests 9: Test timeout computed to be: 10000000 9: Running main() from /Users/alishashelby/Desktop/labwork4-alishashelby/build/_deps/googletest-src/googletest/src/gtest_main.cc 9: Note: Google Test filter = ArgParserTestSuite.MultiValueTest 9: [==========] Running 1 test from 1 test suite. 9: [----------] Global test environment set-up. 9: [----------] 1 test from ArgParserTestSuite 9: [ RUN ] ArgParserTestSuite.MultiValueTest 9: /Users/alishashelby/Desktop/labwork4-alishashelby/tests/argparser_test.cpp:96: Failure 9: Value of: parser.Parse(SplitString("app --param1=1")) 9: Actual: false 9: Expected: true 9: [ FAILED ] ArgParserTestSuite.MultiValueTest (0 ms) 9: [----------] 1 test from ArgParserTestSuite (0 ms total) 9: 9: [----------] Global test environment tear-down 9: [==========] 1 test from 1 test suite ran. (0 ms total) 9: [ PASSED ] 0 tests. 9: [ FAILED ] 1 test, listed below: 9: [ FAILED ] ArgParserTestSuite.MultiValueTest 9: 9: 1 FAILED TEST fix it
e9e0d2fcc81a862da66fe77383d84f1a
{ "intermediate": 0.32308661937713623, "beginner": 0.5003145337104797, "expert": 0.17659886181354523 }
34,785
измени метод оставив тот же смысл"public CreatureCommand Act(int x, int y) { int below = Game.MapHeight - 1; while (y != below) { if (Game.Map[x, y + 1] == null || (Game.Map[x, y + 1].GetImageFileName() == "Digger.png" && _falling > 0)) { _falling++; return new CreatureCommand { DeltaX = 0, DeltaY = 1 }; } else if (_falling > 1) return new CreatureCommand { DeltaX = 0, DeltaY = 0, TransformTo = new Gold() }; else { _falling = 0; return new CreatureCommand { }; } } if (_falling > 1) return new CreatureCommand { DeltaX = 0, DeltaY = 0, TransformTo = new Gold() }; else { _falling = 0; return new CreatureCommand { }; } }"
c33612c566f14310ba4092e1104549a4
{ "intermediate": 0.33881866931915283, "beginner": 0.4661371409893036, "expert": 0.19504418969154358 }
34,786
it doesn't pick up the bluetooth buttons just wanna react to the standard next song button, prev song, play/pause:a import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:path_provider/path_provider.dart'; import 'package:camera/camera.dart'; import 'package:flutter/material.dart'; import 'package:just_audio/just_audio.dart'; import 'package:volume_watcher/volume_watcher.dart'; import 'package:flutter/services.dart'; import 'package:http/http.dart' as http; Future<void> main() async { // Ensure that plugin services are initialized so that `availableCameras()` // can be called before `runApp()` WidgetsFlutterBinding.ensureInitialized(); // Obtain a list of the available cameras on the device. final cameras = await availableCameras(); // Get a specific camera from the list of available cameras. final firstCamera = cameras.first; runApp( MaterialApp( theme: ThemeData.dark(), home: TakePictureScreen( // Pass the appropriate camera to the TakePictureScreen widget. camera: firstCamera, ), ), ); } // A screen that allows users to take a picture using a given camera. class TakePictureScreen extends StatefulWidget { const TakePictureScreen({ super.key, required this.camera, }); final CameraDescription camera; @override TakePictureScreenState createState() => TakePictureScreenState(); } class TakePictureScreenState extends State<TakePictureScreen> { late CameraController _controller; late Future<void> _initializeControllerFuture; @override void initState() { super.initState(); // To display the current output from the Camera, // create a CameraController. _controller = CameraController( // Get a specific camera from the list of available cameras. widget.camera, // Define the resolution to use. ResolutionPreset.medium, ); // Next, initialize the controller. This returns a Future. _initializeControllerFuture = _controller.initialize(); } Future<void> captureAndSendImage() async { // Your existing code here... try { await _initializeControllerFuture; final image = await _controller.takePicture(); if (!mounted) return; // Send the image to the server var request = http.MultipartRequest( 'POST', Uri.parse('http://localhost:8000/api/phone/camera')); request.files.add(await http.MultipartFile.fromPath('file', image.path)); request.fields['direction'] = "In"; var res = await request.send(); var response = await http.Response.fromStream(res); if (response.statusCode == 200) { // If the server returns a 200 OK response, then proceed var responseData = jsonDecode(response.body); var audioBase64 = responseData[1]['audio']; // Decode the Base64 string to bytes var audioBytes = base64Decode(audioBase64); // Save the audio to a temporary file var directory = await getApplicationDocumentsDirectory(); var audioPath = '${directory.path}/temp.mp3'; var audioFile = File(audioPath); await audioFile.writeAsBytes(audioBytes); // Load the audio file var player = AudioPlayer(); await player.setUrl(audioPath); // Play the audio file player.play(); } else { // If the server returns an error response, // then print the status code. print('Failed to upload image. Status code: ${response.statusCode}.'); } } catch (e) { print(e); } } @override void dispose() { // Dispose of the controller when the widget is disposed. _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return KeyboardListener( focusNode: FocusNode(), autofocus: true, onKeyEvent: (KeyEvent event) { if (event is KeyDownEvent) { print(event.logicalKey.keyLabel); if (event.logicalKey.keyLabel == 'Audio Volume Up') { captureAndSendImage(); } if (event.logicalKey.keyLabel == 'Audio Volume Down') { captureAndSendImage(); } } }, child: Scaffold( appBar: AppBar(title: const Text('Take a picture')), body: FutureBuilder<void>( future: _initializeControllerFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { return CameraPreview(_controller); } else { return const Center(child: CircularProgressIndicator()); } }, ), floatingActionButton: FloatingActionButton( onPressed: captureAndSendImage, child: const Icon(Icons.camera_alt), ), ), ); } }
0d38f8f6516b90be865651f83d50bd23
{ "intermediate": 0.45806992053985596, "beginner": 0.3836812376976013, "expert": 0.15824878215789795 }
34,787
Answer the following questions: (a) Define in general terms: (i) the distributed-lag model in t-k lagged variables, and (ii) the autoregressive model. (b) With reference to the above, define both the “impact multiplier” and “long-run multiplier”. (c) Define-in-full Koyck’s (1954) methodology which enables one to reduce: (i) the distributed-lag model in t-k lagged variables, to (ii) the autoregressive model]. (d) In support of your answer to part (c), derive the formula for an infinite geometric series.
f6414a4e00b82d8d0c675082185c5075
{ "intermediate": 0.264653742313385, "beginner": 0.359172523021698, "expert": 0.376173734664917 }
34,788
show all materials,assignments requested by tutors and submitted by students in toggle activity history in admin html with the name of person who did the action and when (i already did that on courses with name of person who created course and time of creation) views.py "from django.shortcuts import render, HttpResponse, redirect, get_object_or_404 from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.utils import timezone from .models import InteractionHistory, UserProfile, Course, CourseMaterial, Material, Assignment, Submission, Grade,Enrollment from django.contrib.auth.decorators import user_passes_test from django.http import JsonResponse from django.template.loader import render_to_string from django.contrib import messages # Import messages for displaying messages in the template from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .serializers import CourseSerializer, MaterialSerializer, AssignmentSerializer, SubmissionSerializer, GradeSerializer, InteractionHistorySerializer,TestSerializer, ChapterSerializer, AttendanceSerializer, EnrollmentSerializer, ReadingStateSerializer from django.contrib import messages # Import messages for displaying messages in the template from django import forms #AUTHENTIFICATION class SignupForm(forms.Form): username = forms.CharField(max_length=30) email = forms.EmailField() password1 = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(widget=forms.PasswordInput) role = forms.CharField() def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError('Passwords do not match.') return password2 def SignupPage(request): if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): uname = form.cleaned_data['username'] email = form.cleaned_data['email'] pass1 = form.cleaned_data['password1'] pass2 = form.cleaned_data['password2'] role = form.cleaned_data['role'] if pass1 != pass2: messages.error(request, "Your password and confirm password are not the same!!") return redirect('signup') else: # Create the user my_user = User.objects.create_user(uname, email, pass1) # Create the user profile with the assigned role UserProfile.objects.create(user=my_user, role=role) messages.success(request, "Account created successfully. You can now log in.") return redirect('login') else: messages.error(request, "Invalid input. Please check the form.") else: form = SignupForm() return render(request, 'signup.html', {'form': form}) from django.contrib.auth import authenticate, login def LoginPage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password1') # Use the correct field name # Authenticate user user = authenticate(request, username=username, password=password) if user is not None: login(request, user) InteractionHistory_history = InteractionHistory.objects.create(student=user, InteractionHistory_type='Login') # Print information to the terminal print(f"User: {user.username} logged in at {InteractionHistory_history.InteractionHistory_date} from IP {request.META['REMOTE_ADDR']}") return redirect('home') else: messages.error(request, "Invalid username or password") return render(request, 'login.html') @login_required(login_url='login') def HomePage(request): user_role = request.user.userprofile.role # Update last login time UserProfile.objects.filter(user=request.user).update(last_login=timezone.now()) if user_role == 'student': return redirect('studenthome') elif user_role == 'tutor': return redirect('tutorhome') elif user_role == 'administrator': # Fetch InteractionHistory history for administrators InteractionHistory_history = InteractionHistory.objects.filter(student=request.user).order_by('-InteractionHistory_date')[:10] return redirect('adminhome') else: return HttpResponse("Invalid user role") @login_required(login_url='login') def LogoutPage(request): # Update last logout time UserProfile.objects.filter(user=request.user).update(last_logout=timezone.now()) InteractionHistory.objects.create(student=request.user, InteractionHistory_type='Logout') logout(request) return redirect('login') #STUDENT PAGE from django.shortcuts import render from .models import Assignment @login_required(login_url='login') def StudentHomePage(request): # Fetch all available courses enrolled_courses = request.user.courses.all() available_courses = Course.objects.exclude(id__in=enrolled_courses.values_list('id', flat=True)) # Fetch assignments for the user assignments = Assignment.objects.filter(course__in=enrolled_courses) # Add a boolean field to each assignment indicating whether it's submitted by the current user for assignment in assignments: assignment.submitted = assignment.submission_set.filter(student=request.user).exists() return render(request, 'studenthome.html', {'enrolled_courses': enrolled_courses, 'available_courses': available_courses, 'assignments': assignments}) @login_required(login_url='login') def enroll_course(request, course_id): course = get_object_or_404(Course, id=course_id) # Check if the user is not already enrolled in the course if request.user not in course.students.all(): course.students.add(request.user) messages.success(request, f"You have successfully enrolled in {course.name}.") else: messages.warning(request, f"You are already enrolled in {course.name}.") return redirect('studenthome') @login_required(login_url='login') def leave_course(request, course_id): course = get_object_or_404(Course, id=course_id) # Check if the user is enrolled in the course if request.user in course.students.all(): course.students.remove(request.user) messages.success(request, f"You have successfully left {course.name}.") else: messages.warning(request, f"You are not enrolled in {course.name}.") return redirect('studenthome') #TUTOR @login_required(login_url='login') # Your view logic def TutorHomePage(request): user = request.user submitted_assignments = Submission.objects.filter(assignment__course__tutor=user) return render(request, 'tutorhome.html', {'user': user, 'submitted_assignments': submitted_assignments}) @login_required(login_url='login') def create_course(request): if request.method == 'POST': course_name = request.POST.get('course_name') # Create the course and assign the tutor course = Course.objects.create(name=course_name, tutor=request.user) # Record the creation time and user who created the course course.creation_time = timezone.now() course.created_by = request.user course.save() # Redirect to a page where students can see and enroll in courses return redirect('tutorhome') @login_required(login_url='login') def upload_material(request): if request.method == 'POST': material_title = request.POST.get('material_title') material_file = request.FILES.get('material_file') material_course_id = request.POST.get('material_course') # Get the course based on the selected ID course = Course.objects.get(id=material_course_id) # Create the material CourseMaterial.objects.create(title=material_title, file=material_file, course=course) return redirect('tutorhome') return render(request, 'upload_material.html') @login_required(login_url='login') def add_chapter(request, course_name): if request.method == 'POST': chapter_name = request.POST.get('chapter_name') course = Course.objects.get(name=course_name, tutor=request.user) course.add_chapter(chapter_name) return redirect('tutor_home') return render(request, 'add_chapter.html', {'course_name': course_name}) def request_assignment(request): if request.method == 'POST': assignment_title = request.POST.get('assignment_title') assignment_description = request.POST.get('assignment_description') due_date = request.POST.get('due_date') course_id = request.POST.get('course') # Get the course based on the selected ID course = Course.objects.get(id=course_id) # Create the assignment for the specific course assignment = Assignment.objects.create( title=assignment_title, description=assignment_description, due_date=due_date, course=course, status='pending' ) # Get all enrolled students in the course enrolled_students = Enrollment.objects.filter(course=course) for enrollment in enrolled_students: # Assign the created assignment to each student in the course assignment.students.add(enrollment.student) messages.success(request, 'Assignment requested successfully.') return redirect('tutorhome') # Redirect to the tutor's home page after the request is submitted @login_required(login_url='login') def request_assignment(request): if request.method == 'POST': assignment_title = request.POST.get('assignment_title') assignment_description = request.POST.get('assignment_description') due_date = request.POST.get('due_date') course_id = request.POST.get('course') # Get the course based on the selected ID course = get_object_or_404(Course, id=course_id) # Create the assignment for the specific course assignment = Assignment.objects.create( title=assignment_title, description=assignment_description, due_date=due_date, course=course, student=request.user, # Provide the user creating the assignment as the student status='pending' ) # Get all enrolled students in the course enrolled_students = Enrollment.objects.filter(course=course) for enrollment in enrolled_students: # Assign the created assignment to each student in the course assignment.students.add(enrollment.student) messages.success(request, 'Assignment requested successfully.') return redirect('tutorhome') # Redirect to the tutor's home page after the request is submitted # Retrieve the list of courses to display in the form available_courses = Course.objects.all() @login_required(login_url='login') def view_assignments(request, course_id): course = get_object_or_404(Course, id=course_id) enrollment = Enrollment.objects.filter(course=course, student=request.user).first() if not enrollment: return render(request, 'not_enrolled.html') assignments = Assignment.objects.filter(course=course, students=request.user) return render(request, 'studenthome.html', {'course': course, 'assignments': assignments}) #ADMIN @login_required(login_url='login') def AdminHomePage(request): # Fetch InteractionHistory history for all users InteractionHistory_history_students = InteractionHistory.objects.filter(student__userprofile__role='student').order_by('-InteractionHistory_date')[:10] InteractionHistory_history_tutors = InteractionHistory.objects.filter(student__userprofile__role='tutor').order_by('-InteractionHistory_date')[:10] # Fetch the list of users excluding administrators users = User.objects.exclude(userprofile__role='administrator') courses = Course.objects.all() print(courses) # Add this line for debugging return render(request, 'adminhome.html', { 'InteractionHistory_history_students': InteractionHistory_history_students, 'InteractionHistory_history_tutors': InteractionHistory_history_tutors, 'users': users, 'courses': courses, # Make sure to include courses in the context }) @login_required(login_url='login') @user_passes_test(lambda u: u.userprofile.role == 'administrator', login_url='home') def manage_roles(request): if request.method == 'POST': user_id = request.POST.get('user_id') role = request.POST.get('role') user = get_object_or_404(User, id=user_id) # Check if the user to change role is not an administrator if user.userprofile.role != 'administrator': user.userprofile.role = role user.userprofile.save() messages.success(request, 'User role changed successfully.') else: messages.error(request, 'Cannot change the role of an administrator.') return redirect('adminhome') @login_required(login_url='login') @user_passes_test(lambda u: u.userprofile.role == 'administrator', login_url='home') def delete_user(request, user_id): if request.method == 'POST': user_to_delete = get_object_or_404(User, id=user_id) # Check if the user to be deleted is not an administrator if user_to_delete.userprofile.role != 'administrator': user_to_delete.delete() messages.success(request, 'User deleted successfully.') else: messages.error(request, 'Cannot delete an administrator.') return redirect('adminhome') @login_required(login_url='login') @login_required(login_url='login') @user_passes_test(lambda u: u.userprofile.role == 'administrator', login_url='home') def modify_course(request, course_id): if request.method == 'POST': new_course_name = request.POST.get('new_course_name') course = get_object_or_404(Course, id=course_id) # Modify the course name course.name = new_course_name course.save() messages.success(request, 'Course name modified successfully.') return redirect('adminhome') @login_required(login_url='login') @user_passes_test(lambda u: u.userprofile.role == 'administrator', login_url='home') def delete_course(request, course_id): if request.method == 'POST': course_to_delete = get_object_or_404(Course, id=course_id) # Delete the course course_to_delete.delete() messages.success(request, 'Course deleted successfully.') return redirect('adminhome') all_assignments = Assignment.objects.all() @login_required(login_url='login') # Example view logic def submit_assignment(request, assignment_id): assignment = get_object_or_404(Assignment, id=assignment_id) if request.method == 'POST': pdf_file = request.FILES.get('pdf_file') grade = request.POST.get('grade') # Check if the assignment has already been submitted if Submission.objects.filter(student=request.user, assignment=assignment).exists(): messages.warning(request, 'Assignment already submitted.') debug_info = 'Assignment already submitted.' else: submission = Submission.objects.create( student=request.user, # Make sure to set the correct student assignment=assignment, submission_content=pdf_file, submission_date=timezone.now() ) # Remove the assignment from the list of due assignments for the student assignment.student = request.user assignment.grade = grade assignment.save() messages.success(request, 'Assignment submitted successfully.') return redirect('studenthome') else: debug_info = "" return JsonResponse({'debug_info': debug_info}) @login_required(login_url='login') def grade_submission(request, submission_id): submission = get_object_or_404(Submission, id=submission_id) if request.method == 'POST': grade = request.POST.get('grade') feedback = request.POST.get('feedback') # Get feedback from the form submission.assignment.grade = float(grade) if grade else None submission.assignment.feedback = feedback # Set the feedback for the assignment submission.assignment.save() messages.success(request, 'Grade and feedback submitted successfully.') return redirect('tutorhome') #REST @api_view(['GET']) def course_list(request): courses = Course.objects.all() serializer = CourseSerializer(courses, many=True) return Response(serializer.data) @api_view(['GET']) def material_list(request): material = CourseMaterial.objects.all() serializer = MaterialSerializer(material, many=True) return Response(serializer.data) @api_view(['GET']) def Test_list(request): material = Test.objects.all() serializer = TestSerializer(material, many=True) return Response(serializer.data) @api_view(['GET']) def Chapter_list(request): material = Chapter.objects.all() serializer = ChapterSerializer(material, many=True) return Response(serializer.data) @api_view(['GET']) def Attendance_list(request): material = Attendance.objects.all() serializer = AttendanceSerializer(material, many=True) return Response(serializer.data) @api_view(['GET']) def Enrollment_list(request): material = Enrollment.objects.all() serializer = EnrollmentSerializer(material, many=True) return Response(serializer.data) @api_view(['GET']) def assignment_list(request): assignment = Assignment.objects.all() serializer = AssignmentSerializer(assignment, many=True) return Response(serializer.data) @api_view(['GET']) def grade_list(request): grade = Grade.objects.all() serializer = GradeSerializer(grade, many=True) return Response(serializer.data) @api_view(['GET']) def InteractionHistory_list(request): InteractionHistory = InteractionHistory.objects.all() serializer = InteractionHistorySerializer(InteractionHistory, many=True) return Response(serializer.data) @api_view(['GET']) def ReadingState_list(request): InteractionHistory = ReadingState.objects.all() serializer = ReadingStateSerializer(InteractionHistory, many=True) return Response(serializer.data) @api_view(['GET', 'POST']) def submission_list(request): if request.method == 'GET': submissions = Submission.objects.all() serializer = SubmissionSerializer(submissions, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = SubmissionSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) " adminhome.html "<!-- adminhome.html --> {% block content %} <style media="screen"> body { font-family: 'Poppins', sans-serif; background-color: #f4f4f4; color: #333; margin: 0; padding: 0; } h2 { color: #23a2f6; } #dashboard { display: flex; justify-content: space-around; } section { flex: 1; margin: 20px; padding: 20px; background-color: #fff; border: 1px solid #ddd; border-radius: 8px; transition: transform 0.3s ease-in-out; box-sizing: border-box; } button { background-color: #23a2f6; color: #fff; padding: 10px 15px; border: none; border-radius: 5px; cursor: pointer; } ul { list-style-type: none; padding: 0; } li { margin-bottom: 10px; } label { display: block; margin-bottom: 5px; font-weight: bold; } select, button { padding: 10px; margin-top: 5px; margin-bottom: 10px; } #manage-roles, #delete-users { margin-top: 40px; } </style> <section id="monitor-activity"> <h2>Monitor Platform Activity</h2> <button id="toggle-activity">Toggle Activity History</button> <div id="activity-history" style="display: none;"> <h3>Login/Logout Activity</h3> <ul> <!-- Login/Logout Activity for Admins --> <ul> {% for InteractionHistory in InteractionHistory_history_admin %} <li>{{ InteractionHistory.student.username }} {{ InteractionHistory.InteractionHistory_type }} at {{ InteractionHistory.InteractionHistory_date|date:"F d, Y H:i:s" }}</li> {% endfor %} </ul> <!-- Login/Logout Activity for Students --> <li><strong>Students:</strong></li> <ul> {% for InteractionHistory in InteractionHistory_history_students %} <li>{{ InteractionHistory.student.username }} {{ InteractionHistory.InteractionHistory_type }} at {{ InteractionHistory.InteractionHistory_date|date:"F d, Y H:i:s" }}</li> {% endfor %} </ul> <!-- Login/Logout Activity for Tutors --> <li><strong>Tutors:</strong></li> <ul> {% for InteractionHistory in InteractionHistory_history_tutors %} <li>{{ InteractionHistory.student.username }} {{ InteractionHistory.InteractionHistory_type }} at {{ InteractionHistory.InteractionHistory_date|date:"F d, Y H:i:s" }}</li> {% endfor %} </ul> </ul> <h3>Course Activity</h3> <ul> <!-- Course Creation Activity --> {% for course in courses %} <li>Course created: {{ course.name }} by {{ course.created_by.username }} at {{ course.creation_time|date:"F d, Y H:i:s" }}</li> {% endfor %} </ul> </div> </section> </div> {% block manage-accounts %} <section id="manage-accounts"> <h2>Manage User Accounts</h2> <section> <h1>Manage User Roles</h1> <form method="post" action="{% url 'change_user_role' %}"> {% csrf_token %} <label for="user-select">Select User:</label> <select name="user_id" id="user-select"> {% for user in users %} <option value="{{ user.id }}">{{ user.username }}</option> {% endfor %} </select> <label for="role-select">Select Role:</label> <select name="role"> <option value="student">Student</option> <option value="tutor">Tutor</option> <!-- Add more roles if needed --> </select> <button type="submit">Change Role</button> </form> </section> <section id="delete-users"> <h1>Delete User Accounts</h1> <ul> {% for user in users %} <li> {{ user.username }} ({{ user.userprofile.role }}) <form method="post" action="{% url 'delete_user' user.id %}" onsubmit="return confirm('Are you sure you want to delete this user?');"> {% csrf_token %} <button type="submit">Delete</button> </form> </li> {% endfor %} </ul> </section> {% block manage-courses %} <section id="manage-courses"> <h2>Manage Courses</h2> <ul> {% for course in courses %} <li> {{ course.name }} <!-- Modify Course Form --> <form method="post" action="{% url 'modify_course' course.id %}"> {% csrf_token %} <label for="new_course_name">New Course Name:</label> <input type="text" name="new_course_name" required> <button type="submit">Modify</button> </form> <!-- Delete Course Form --> <form method="post" action="{% url 'delete_course' course.id %}" onsubmit="return confirm('Are you sure you want to delete this course?');"> {% csrf_token %} <button type="submit">Delete</button> </form> </li> {% endfor %} </ul> </section> {{ InteractionHistory.InteractionHistory_date|date:"F d, Y H:i:s" }} {% endblock %} <form action="{% url 'logout' %}" method="post"> {% csrf_token %} <button type="submit">Logout</button> </form> {% endblock %} <script> document.getElementById('toggle-activity').addEventListener('click', function() { var historySection = document.getElementById('activity-history'); historySection.style.display = (historySection.style.display === 'none' || historySection.style.display === '') ? 'block' : 'none'; }); </script> {% endblock %} " here are my models.py don't change anything about them "from django.db import models from django.contrib.auth.models import User from django.utils.text import slugify # Import slugify from django.urls import reverse class UserProfile(models.Model): USER_ROLES = ( ('student', 'Student'), ('tutor', 'Tutor'), ('administrator', 'Administrator'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) role = models.CharField(max_length=20, choices=USER_ROLES) last_login = models.DateTimeField(null=True, blank=True) last_logout = models.DateTimeField(null=True, blank=True) class Course(models.Model): name = models.CharField(max_length=255) students = models.ManyToManyField(User, related_name='courses', blank=True) tutor = models.ForeignKey(User, on_delete=models.CASCADE, related_name='tutor_courses') created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) creation_time = models.DateTimeField(null=True, blank=True) def __str__(self): return self.name class CourseMaterial(models.Model): title = models.CharField(max_length=255) file = models.FileField(upload_to='course_materials/') course = models.ForeignKey(Course, on_delete=models.CASCADE) def __str__(self): return self.title class Test(models.Model): title = models.CharField(max_length=255) content = models.TextField() file = models.FileField(upload_to='tests/') course = models.ForeignKey(Course, on_delete=models.CASCADE) upload_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Chapter(models.Model): chapter_name = models.CharField(max_length=20) chapter_created_date = models.DateTimeField(auto_now_add=True) course = models.ForeignKey(Course, on_delete=models.CASCADE, default=1) slug = models.SlugField(unique=True) def __str__(self): return self.chapter_name class Assignment(models.Model): title = models.CharField(max_length=255) description = models.TextField() due_date = models.DateField() course = models.ForeignKey(Course, on_delete=models.CASCADE) student = models.ForeignKey(User, on_delete=models.CASCADE, null=False) status = models.CharField(max_length=20, choices=[('pending', 'Pending'), ('completed', 'Completed')]) grade = models.FloatField(null=True, blank=True) feedback = models.TextField(null=True, blank=True) def is_user_enrolled(self, user): return Enrollment.objects.filter(student=user, course=self.course).exists() def __str__(self): return self.title class Grade(models.Model): value = models.FloatField() course = models.ForeignKey(Course, on_delete=models.CASCADE) student = models.ForeignKey(User, on_delete=models.CASCADE, related_name='grades') def __str__(self): return f"{self.student.username}'s grade in {self.course.name}: {self.value}" class Attendance(models.Model): date = models.DateField() course = models.ForeignKey(Course, on_delete=models.CASCADE) students_present = models.ManyToManyField(User, related_name='attendances', blank=True) class Enrollment(models.Model): student = models.ForeignKey(User, on_delete=models.CASCADE) course = models.ForeignKey('Course', on_delete=models.CASCADE) enrollment_date = models.DateField() def __str__(self): return f"{self.student.username} enrolled in {self.course.name}" class Material(models.Model): title = models.CharField(max_length=255) content = models.TextField() course = models.ForeignKey('Course', on_delete=models.CASCADE) upload_date = models.DateField() document_type = models.CharField(max_length=50) # Assuming you want a text field for document type def __str__(self): return self.title class Submission(models.Model): student = models.ForeignKey(User, on_delete=models.CASCADE) assignment = models.ForeignKey('Assignment', on_delete=models.CASCADE) submission_content = models.FileField(upload_to='submission_files/') # Assuming there's also text content submission_date = models.DateField() def __str__(self): return f"Submission by {self.student.username} for {self.assignment.title}" class InteractionHistory(models.Model): student = models.ForeignKey(User, on_delete=models.CASCADE) material_id = models.ForeignKey(Material, on_delete=models.SET_NULL, null=True, blank=True) InteractionHistory_type = models.CharField(max_length=50) # Assuming you want a text field for InteractionHistory type InteractionHistory_date = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.student.username} - {self.InteractionHistory_type} at {self.InteractionHistory_date}' class ReadingState(models.Model): student = models.ForeignKey(User, on_delete=models.CASCADE) material = models.ForeignKey('Material', on_delete=models.CASCADE) read_state = models.FloatField() # Assuming you want a float field for percentage completed last_read_date = models.DateField() def __str__(self): return f"Reading state of {self.student.username} for {self.material.title}: {self.read_state}% completed on {self.last_read_date}"
0556ed04d9645acff5593d780e07c200
{ "intermediate": 0.36672747135162354, "beginner": 0.44340524077415466, "expert": 0.18986725807189941 }
34,789
it doesn't pick up the bluetooth buttons just wanna react to the standard next song button, prev song, play/pause: import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:path_provider/path_provider.dart'; import 'package:camera/camera.dart'; import 'package:flutter/material.dart'; import 'package:just_audio/just_audio.dart'; import 'package:volume_watcher/volume_watcher.dart'; import 'package:flutter/services.dart'; import 'package:http/http.dart' as http; Future<void> main() async { // Ensure that plugin services are initialized so that `availableCameras()` // can be called before `runApp()` WidgetsFlutterBinding.ensureInitialized(); // Obtain a list of the available cameras on the device. final cameras = await availableCameras(); // Get a specific camera from the list of available cameras. final firstCamera = cameras.first; runApp( MaterialApp( theme: ThemeData.dark(), home: TakePictureScreen( // Pass the appropriate camera to the TakePictureScreen widget. camera: firstCamera, ), ), ); } // A screen that allows users to take a picture using a given camera. class TakePictureScreen extends StatefulWidget { const TakePictureScreen({ super.key, required this.camera, }); final CameraDescription camera; @override TakePictureScreenState createState() => TakePictureScreenState(); } class TakePictureScreenState extends State<TakePictureScreen> { late CameraController _controller; late Future<void> _initializeControllerFuture; @override void initState() { super.initState(); // To display the current output from the Camera, // create a CameraController. _controller = CameraController( // Get a specific camera from the list of available cameras. widget.camera, // Define the resolution to use. ResolutionPreset.medium, ); // Next, initialize the controller. This returns a Future. _initializeControllerFuture = _controller.initialize(); } Future<void> captureAndSendImage() async { // Your existing code here... try { await _initializeControllerFuture; final image = await _controller.takePicture(); if (!mounted) return; // Send the image to the server var request = http.MultipartRequest( 'POST', Uri.parse('http://localhost:8000/api/phone/camera')); request.files.add(await http.MultipartFile.fromPath('file', image.path)); request.fields['direction'] = "In"; var res = await request.send(); var response = await http.Response.fromStream(res); if (response.statusCode == 200) { // If the server returns a 200 OK response, then proceed var responseData = jsonDecode(response.body); var audioBase64 = responseData[1]['audio']; // Decode the Base64 string to bytes var audioBytes = base64Decode(audioBase64); // Save the audio to a temporary file var directory = await getApplicationDocumentsDirectory(); var audioPath = '${directory.path}/temp.mp3'; var audioFile = File(audioPath); await audioFile.writeAsBytes(audioBytes); // Load the audio file var player = AudioPlayer(); await player.setUrl(audioPath); // Play the audio file player.play(); } else { // If the server returns an error response, // then print the status code. print('Failed to upload image. Status code: ${response.statusCode}.'); } } catch (e) { print(e); } } @override void dispose() { // Dispose of the controller when the widget is disposed. _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return KeyboardListener( focusNode: FocusNode(), autofocus: true, onKeyEvent: (KeyEvent event) { if (event is KeyDownEvent) { print(event.logicalKey.keyLabel); if (event.logicalKey.keyLabel == 'Audio Volume Up') { captureAndSendImage(); } if (event.logicalKey.keyLabel == 'Audio Volume Down') { captureAndSendImage(); } } }, child: Scaffold( appBar: AppBar(title: const Text('Take a picture')), body: FutureBuilder<void>( future: _initializeControllerFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { return CameraPreview(_controller); } else { return const Center(child: CircularProgressIndicator()); } }, ), floatingActionButton: FloatingActionButton( onPressed: captureAndSendImage, child: const Icon(Icons.camera_alt), ), ), ); } }
f09839d781e993c742c91ced39a6064e
{ "intermediate": 0.42438215017318726, "beginner": 0.44305887818336487, "expert": 0.13255895674228668 }
34,790
В моём коде на Python при выполнении этой строки "pipe = joblib.load("models/OZON.pkl")" выдаёт ошибку "ValueError: node array from the pickle has an incompatible dtype: - expected: {'names': ['left_child', 'right_child', 'feature', 'threshold', 'impurity', 'n_node_samples', 'weighted_n_node_samples', 'missing_go_to_left'], 'formats': ['<i8', '<i8', '<i8', '<f8', '<f8', '<i8', '<f8', 'u1'], 'offsets': [0, 8, 16, 24, 32, 40, 48, 56], 'itemsize': 64} - got : [('left_child', '<i8'), ('right_child', '<i8'), ('feature', '<i8'), ('threshold', '<f8'), ('impurity', '<f8'), ('n_node_samples', '<i8'), ('weighted_n_node_samples', '<f8')]", в чём проблема?
34d4b22e9786250d2e6339d260e6555c
{ "intermediate": 0.6606648564338684, "beginner": 0.18171575665473938, "expert": 0.157619446516037 }
34,791
Hi, is there any task format that can be recognized by Obsidian and Logseq as well?
d043f25dd9d734bbfcbc1ed050615eab
{ "intermediate": 0.4277697801589966, "beginner": 0.2388581931591034, "expert": 0.3333720564842224 }
34,792
Show me a signal flow graph for a microwave amplifier
108ccd9d847533a282411efb7536493b
{ "intermediate": 0.3214162290096283, "beginner": 0.31212174892425537, "expert": 0.36646199226379395 }
34,793
Where are the windows defender exclusions in windows 11 registry
3cec520559b354c6a57c81a6976b8b83
{ "intermediate": 0.3413012623786926, "beginner": 0.32548069953918457, "expert": 0.333217978477478 }
34,794
I want to use a script that will look in the following locations for .exe files in the following locations and give me the long list of file names with the .exe and not the file path just the actual process name.exe and put in a txt document C:\Program Files (x86)\AMD C:\Program Files (x86)\Audeze C:\Program Files (x86)\Battle.net C:\Program Files (x86)\Display Driver Uninstaller C:\Program Files (x86)\DroidCam C:\Program Files (x86)\K-Lite Codec Pack C:\Program Files (x86)\MSI Afterburner C:\Program Files (x86)\Revision Tool C:\Program Files (x86)\RivaTuner Statistics Server C:\Program Files (x86)\Steam C:\Program Files\AMD C:\Program Files\BCUninstaller C:\Program Files\EA Games C:\Program Files\Electronic Arts C:\Program Files\EqualizerAPO C:\Program Files\Everything C:\Program Files\gsudo\Current C:\Program Files\KDE Connect C:\Program Files\LGTV Companion C:\Program Files\NZXT CAM C:\Program Files\Process Lasso C:\Program Files\Proton AG C:\Program Files\PuTTY C:\Program Files\TeraCopy C:\platform-tools D:\ Z:\
65180bf67ddf80cf83466b180e5efd85
{ "intermediate": 0.40571290254592896, "beginner": 0.29181137681007385, "expert": 0.3024757206439972 }
34,795
I have a long list of 660 filenames each on a new line. I want to convert it to a .reg file with those filenames including the .exe to this path: Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Defender\Exclusions\Processes How do i do it in notepad++ and what code do i need to put in the top?
16e72b8609942752c85bd7892a9d32d6
{ "intermediate": 0.4554002583026886, "beginner": 0.28951114416122437, "expert": 0.25508859753608704 }
34,796
I have 2 .reg files that writes in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows Defender\Exclusions but neither of them actually do anything. How do i disable protection under those keys so i can add a .reg file to it?
3bc9560742ff51b503c1ee39cbf49ef2
{ "intermediate": 0.41771090030670166, "beginner": 0.3308694064617157, "expert": 0.25141972303390503 }
34,797
Give me a python code with machine learning to predict 30 day ahead stock price prediction
c404dafc78e58aa450a1488ea2701ec6
{ "intermediate": 0.15814398229122162, "beginner": 0.05541073903441429, "expert": 0.7864453196525574 }
34,798
what would you change of this code to make it more efficient and faster?: import numpy import sys import bz2 import parse_file # Load this information about the reference genome so that we know if a snp is in a repeat-masked region position_gene_map, effective_gene_lengths, substitution_specific_synonymous_fraction = parse_file.create_annotation_map() input_filename = sys.argv[1] depth_filename = sys.argv[2] snp_filename = sys.argv[3] input_file = bz2.BZ2File(input_filename,"r") snp_file = bz2.BZ2File(snp_filename,"w") depth_file = bz2.BZ2File(depth_filename,"w") avg_depths = None times = None alts = None depth_records = [] for line in input_file: items = line.split(",") position = long(items[1]) allele = items[2].strip() if allele[1:3]!='->': continue # not a snp! if parse_file.is_repeat_masked(position,position_gene_map): continue # repeat masked! snp_file.write(line) # calculate depths and add them times = numpy.array([float(subitem) for subitem in items[3].split()]) depths = [float(subitem) for subitem in items[5].split()] depth_records.append(depths) depths = numpy.array(depth_records) # Could do median or mean #avg_depths = depths.mean(axis=0) avg_depths = numpy.median(depths, axis=0) alts = numpy.array([0 for t in times]) depth_line = ", ".join(["REL606", "0", "Depth", " ".join([str(t) for t in times]), " ".join([str(alt) for alt in alts]), " ".join([str(avg_depth) for avg_depth in avg_depths])]) depth_file.write(depth_line) depth_file.write("\n") input_file.close() snp_file.close() depth_file.close()
9b9d8135a16893ac53999712b2018277
{ "intermediate": 0.48908331990242004, "beginner": 0.13050810992717743, "expert": 0.38040855526924133 }
34,799
code this roblox script, the order is: fade in holder and title, then then it will start the startup sound and move loading bar, after finished it will fade out: local gui = script.Parent -- gui local main = gui.Frame -- the main screen local holder = main.Holder -- back frame of loading bar local loadingframe = holder.LoadingFrame -- this frame shows the loading bar local startupsound = loadingframe.startup -- the startup sound local title = main.title -- the title local plr = game.Players.LocalPlayer -- the client local ts = game:GetService("TweenService") -- use to size the loading frame to closedsize (loaded) local turnonkey = Enum.KeyCode.F -- for pc local device = "nil" -- the device local uis = game:GetService("UserInputService") -- to detect device and handle pc inputs local state = "Idling" -- Idling , Loading , Loaded local configs = { -- config table fr loadedsystem = false, -- when loaded makes the title and holder invisible didsound = false, -- did startup sound titlevisible = false, -- for show text label holdervisible = false, -- holder and loadingframe startsize = Vector3.new(0, 0, 0, 25), -- not loaded closedsize = Vector3.new(0, 212, 0, 25), -- loaded loadingbarspeed = 2 -- 2 studs per second } function detectdevice(device) -- detect device #1 priority end function disableall() -- to invisible the things #5 priority end function moveloadingbar(state) -- if state is loading then starts moving, loading starts when the startup sound starts #3 priority end function playsound(sound) -- plays musics #2 priority end function fadein(frame, textlabel) end function fadeout(frame, textlabel) end
12cd91131d765f828d729c0b72ae7144
{ "intermediate": 0.4214254915714264, "beginner": 0.2705579996109009, "expert": 0.30801647901535034 }
34,800
Hi, please modify this Logseq query to exclude notes which name contains "Template": #+BEGIN_QUERY { :title [:b "TODO"] ;; ---- Get every block into variable ?block :query [:find (pull ?block [*]) ;; ---- filter command :where ;; ---- get block content into variable ?blockcontent [?block :block/content ?blockcontent] ;; ---- get page (special type of block) into variable ?page (used later) [?block :block/page ?page] ;; ---- get page name (lowercase) from the page block into variable ?pagename [?page :block/name ?pagename] ;; ---- get block marker (TODO LATER ETC) into variable ?marker [?block :block/marker ?marker] ;; ---- Select block if it has one or more tasks (TODO or DONE etc) [(contains? #{"TODO"} ?marker)] ;; ---- Exclude block if it has one or more tasks (not [(contains? #{"DOING"} ?marker)]) ] } #+END_QUERY
540c3840530d93db7959aa07927b9534
{ "intermediate": 0.27050167322158813, "beginner": 0.46225154399871826, "expert": 0.2672467529773712 }
34,801
What does the method Payment of the class Credit in Global Payments sdk?
e3f87668ae1cfc9ee67160425ab4c8b7
{ "intermediate": 0.29856547713279724, "beginner": 0.4872000515460968, "expert": 0.21423448622226715 }
34,802
based on the following database tables, give me at least 10 insightful analyses that can be used to give recommendations; also give me the SQL code; The customers.csv contains following features: Features Description customer_id ID of the consumer who made the purchase (This is unique in this table) customer_unique_id Unique ID of the consumer (this can repeat) customer_zip_code_prefix Zip Code of consumer’s location customer_city Name of the City from where order is made customer_state State Code from where order is made (Eg. são paulo - SP) The sellers.csv contains following features: Features Description seller_id Unique ID of the seller registered seller_zip_code_prefix Zip Code of the seller’s location seller_city Name of the City of the seller seller_state State Code (Eg. são paulo - SP) The order_items.csv contain following features: Features Description order_id A Unique ID of order made by the consumers order_item_id A Unique ID given to each item ordered in the order product_id A Unique ID given to each product available on the site seller_id Unique ID of the seller registered in Target shipping_limit_date The date before which the ordered product must be shipped price Actual price of the products ordered freight_value Price rate at which a product is delivered from one point to another The geolocations.csv contain following features: Features Description geolocation_zip_code_prefix First 5 digits of Zip Code geolocation_lat Latitude geolocation_lng Longitude geolocation_city City geolocation_state State The payments.csv contain following features: Features Description order_id A Unique ID of order made by the consumers payment_sequential Sequences of the payments made in case of EMI payment_type Mode of payment used (Eg. Credit Card) payment_installments Number of installments in case of EMI purchase payment_value Total amount paid for the purchase order The orders.csv contain following features: Features Description order_id A Unique ID of order made by the consumers customer_id ID of the consumer who made the purchase order_status Status of the order made i.e. delivered, shipped, etc. order_purchase_timestamp Timestamp of the purchase order_delivered_carrier_date Delivery date at which carrier made the delivery order_delivered_customer_date Date at which customer got the product order_estimated_delivery_date Estimated delivery date of the products The reviews.csv contain following features: Features Description review_id ID of the review given on the product ordered by the order id order_id A Unique ID of order made by the consumers review_score Review score given by the customer for each order on a scale of 1-5 review_comment_title Title of the review review_comment_message Review comments posted by the consumer for each order review_creation_date Timestamp of the review when it is created review_answer_timestamp Timestamp of the review answered The products.csv contain following features: Features Description product_id A Unique identifier for the proposed project. product_category_name Name of the product category product_name_lenght Length of the string which specifies the name given to the products ordered product_description_lenght Length of the description written for each product ordered on the site product_photos_qty Number of photos of each product ordered available on the shopping portal product_weight_g Weight of the products ordered in grams product_length_cm Length of the products ordered in centimeters product_height_cm Height of the products ordered in centimeters product_width_cm Width of the product ordered in centimeters
514b196a470a5abc378914bd87df6ce0
{ "intermediate": 0.3099234104156494, "beginner": 0.4169664978981018, "expert": 0.27311012148857117 }
34,803
is it possible to add multiple records to all columns in a table with single insert into func in ms sql server
e27d4fba6a26e9b2ea0e2cee1d24e214
{ "intermediate": 0.5125603079795837, "beginner": 0.20790590345859528, "expert": 0.2795337736606598 }
34,804
You are an expert C++ and Rust programmer. Translate this code to Rust: #include<vector> #include <iostream> #include <sstream> #include <string> #include <random> #include <functional> #include <algorithm> #include <tuple> #include "stats.hpp" #include "trajectory.hpp" #include "pvalue.hpp" std::tuple<double,double> calculate_combined_pvalue(Random & random, Trajectory const & trajectory, int max_num_bootstraps=10000, int min_num_bootstraps=10000); std::tuple<int,double,double> calculate_deletion_pvalue(Random & random, Trajectory const & trajectory, int num_bootstraps); std::tuple<int,double,double> calculate_duplication_pvalue(Random & random, Trajectory const & trajectory, int num_bootstraps); const char delim=','; int main(int argc, char * argv[]){ // random number generator // deterministic seed to ensure reproducibility // once pipeline is completed auto random = create_random(42); // used for reporting purposes int num_processed = 0; int num_passed = 0; int num_surprising = 0; // avg depth across the genome // used to trim trajectories with // apparent deletions std::vector<double> avg_depths; // iterate over all trajectory records in file std::string line; while(std::getline(std::cin,line)){ // parse trajectory record std::stringstream line_stream(line); std::string item; std::string subitem; std::string allele; std::vector<double> times; std::vector<double> alts; std::vector<double> depths; // these entries not needed for this step in pipeline std::getline(line_stream, item, ','); // chromosome std::getline(line_stream, item, ','); // location std::getline(line_stream, allele, ','); // allele // times std::getline(line_stream, item, ','); std::stringstream item_stream0(item); while(std::getline(item_stream0, subitem, ' ')){ if(subitem.size() > 0){ times.push_back(std::stof(subitem)); } } // alts std::getline(line_stream, item, ','); std::stringstream item_stream(item); while(std::getline(item_stream, subitem, ' ')){ if(subitem.size() > 0){ alts.push_back(std::stof(subitem)); } } // depths std::getline(line_stream, item, ','); std::stringstream item_stream2(item); while(std::getline(item_stream2, subitem, ' ')){ if(subitem.size() > 0){ depths.push_back(std::stof(subitem)); } } // the six statistics we will calculate // the first is whether it passed our basic filter bool passed_filter; // the first three detect whether there is a deletion (and we should trim) int deletion_idx; double fold_reduction, deletion_pvalue; // the next three detect whether there is a duplication (deal with this downstream) int duplication_idx; double fold_increase, duplication_pvalue; // the next two are about the quality of the remaining trajectory double autocorrelation, combined_pvalue; if(allele[1]=='D'){ // Special trajectory containing average depths for(int i=0,imax=depths.size();i<imax;++i){ if(times[i] > 100){ break; // don't include clone timespoints in here } avg_depths.push_back(depths[i]); } passed_filter = true; deletion_idx = 0; fold_reduction = 0; deletion_pvalue = 1; duplication_idx = 0; fold_increase = 0; duplication_pvalue = 1; autocorrelation = 0; combined_pvalue = 1; } else{ // Regular trajectory // create trajectory auto trajectory = Trajectory(); for(int i=0,imax=alts.size();i<imax;++i){ if(times[i] > 100){ break; // don't include clone timepoints here } trajectory.push_back( Timepoint{ alts[i], depths[i], avg_depths[i] } ); } num_processed+=1; if(num_processed % 1000 == 0){ std::cerr << num_processed << " trajectories processed, " << num_passed << " passed, " << num_surprising << " surprising!\n"; } passed_filter = passes_filter(trajectory); if(!passed_filter){ deletion_idx = 0; fold_reduction = 0; deletion_pvalue = 1; duplication_idx = 0; fold_increase = 0; duplication_pvalue = 1; autocorrelation = 0; combined_pvalue = 1; } else{ if(avg_depths.size()==0){ // if this happens, trimming routine will choke // should never get here? deletion_idx = 0; fold_reduction = 0; deletion_pvalue = 1; duplication_idx = 0; fold_increase = 0; duplication_pvalue = 1; } else{ // test whether there is a deletion or duplication during the trajectory std::tie(deletion_idx, fold_reduction, deletion_pvalue) = calculate_deletion_pvalue(random, trajectory, 10000); std::tie(duplication_idx, fold_increase, duplication_pvalue) = calculate_duplication_pvalue(random, trajectory, 10000); // trim the trajectory at the deletion if necessary if(deletion_pvalue < deletion_pvalue_threshold){ std::cerr << "Trimming trajectory: " << deletion_idx << " " << fold_reduction << " " << deletion_pvalue << std::endl; for(int i=0,imax=trajectory.size()-deletion_idx;i<imax;++i){ trajectory.pop_back(); } //std::cerr << "Done!" << std::endl; } } // done with trimming // recalculate whether trajectory passes or not passed_filter = passes_filter(trajectory); if(!passed_filter){ autocorrelation = 0; combined_pvalue = 1; } else{ // actually calculate autocorrelation score num_passed+=1; std::tie(autocorrelation, combined_pvalue) = calculate_combined_pvalue(random, trajectory); } // increment number of "surprising" trajectories // used only for display purposes during run if(combined_pvalue <= 5e-02){ num_surprising += 1; } } // done with pvalue calculations } // done with trajectory processing // print passed (but not necessarily significant) trajectory records // (significance filtering happens later) if(passed_filter){ std::cout << line << ", "; std::cout << autocorrelation << " " << combined_pvalue << ", "; std::cout << deletion_idx << " " << fold_reduction << " " << deletion_pvalue << ", "; std::cout << duplication_idx << " " << fold_increase << " " << duplication_pvalue << std::endl; } } std::cerr << "Finished: " << num_processed << " trajectories processed, " << num_passed << " passed, " << num_surprising << " surprising!\n"; return 0; } //////////////////////////////////////////////////////////////////////////////// // // Calculates pvalue for trajectory // based on several joint test statistics // // Returns: score, pvalue // //////////////////////////////////////////////////////////////////////////////// std::tuple<double,double> calculate_combined_pvalue(Random & random, Trajectory const & observed_trajectory, int max_num_bootstraps, int min_num_bootstraps){ if(!passes_filter(observed_trajectory)){ std::cerr << "Trajectory did not pass filter, should not get here!" << std::endl; std::tuple<double,double>{0,1}; } // null model is based on permutation of observed trajectory // (with some added bells and whistles, see Supplementary Information) auto trajectory_generator = ResampledPermutationTrajectoryGenerator(observed_trajectory); // calculate num nonzero points int num_nonzero_points = 0; for(auto & timepoint : trajectory_generator.unmasked_observed_trajectory){ if(timepoint.alt > 0){ ++num_nonzero_points; } } if(num_nonzero_points < 2){ // can't have autocorrelation if only one timepoint with alt reads return std::tuple<double,double>{0, 1.0}; } class CombinedTestStatistic{ public: double autocorrelation; double autocorrelation_pvalue; double max_run; double max_run_pvalue; double relaxation_time; double relaxation_time_pvalue; double combined_pvalue; }; double observed_autocorrelation = calculate_autocorrelation(trajectory_generator.unmasked_observed_trajectory); double observed_max_run = calculate_max_run(trajectory_generator.unmasked_observed_trajectory); double observed_relaxation_time = calculate_relaxation_time(trajectory_generator.unmasked_observed_trajectory); CombinedTestStatistic observed_test_statistics = CombinedTestStatistic{observed_autocorrelation, 1.0, observed_max_run, 1.0, observed_relaxation_time, 1.0}; std::vector<double> bootstrapped_autocorrelations; std::vector<double> bootstrapped_max_runs; std::vector<double> bootstrapped_relaxation_times; std::vector<CombinedTestStatistic> bootstrapped_test_statistics; //std::cout << observed_autocorrelation << " " << observed_max_run << " " << observed_relaxation_time << std::endl; // calculate # bootstrapped Ts > T int num_greater_autocorrelations = 0; int num_greater_max_runs = 0; int num_greater_relaxation_times = 0; int current_num_bootstraps = 0; //std::cout << "Starting bootstraps!" << std::endl; while(current_num_bootstraps < max_num_bootstraps){ current_num_bootstraps+=1; //if(current_num_bootstraps%10000==0){ //std::cerr << current_num_bootstraps << std::endl; //} trajectory_generator.generate_bootstrapped_trajectory(random); // calculate bootstrapped test statistics double bootstrapped_autocorrelation = calculate_autocorrelation(trajectory_generator.unmasked_bootstrapped_trajectory); double bootstrapped_max_run = calculate_max_run(trajectory_generator.unmasked_bootstrapped_trajectory); double bootstrapped_relaxation_time = calculate_relaxation_time(trajectory_generator.unmasked_bootstrapped_trajectory,true); // add them to corresponding vectors bootstrapped_autocorrelations.push_back(bootstrapped_autocorrelation); bootstrapped_max_runs.push_back(bootstrapped_max_run); bootstrapped_relaxation_times.push_back(bootstrapped_relaxation_time); // compare to observed values if( (bootstrapped_autocorrelation > observed_autocorrelation-1e-09) ){ // bootstrapped trajectory is at least as extreme num_greater_autocorrelations+=1; } if( (bootstrapped_max_run > observed_max_run-1e-09) ){ // bootstrapped trajectory is at least as extreme num_greater_max_runs+=1; } if( (bootstrapped_relaxation_time > observed_relaxation_time-1e-09) ){ // bootstrapped trajectory is at least as extreme num_greater_relaxation_times+=1; } if( (num_greater_autocorrelations > min_numerator_counts) && (num_greater_max_runs > min_numerator_counts) && (num_greater_relaxation_times > min_numerator_counts) ) break; } // calculate pvalues double observed_autocorrelation_pvalue = calculate_pvalue_from_counts(num_greater_autocorrelations, current_num_bootstraps); double observed_max_run_pvalue = calculate_pvalue_from_counts(num_greater_max_runs, current_num_bootstraps); double observed_relaxation_time_pvalue = calculate_pvalue_from_counts(num_greater_relaxation_times, current_num_bootstraps); double observed_combined_pvalue = calculate_combined_pvalue(observed_autocorrelation_pvalue, observed_max_run_pvalue, observed_relaxation_time_pvalue); // short circuit if we know the clipped pvalue is already high if( observed_combined_pvalue == 1.0 ){ return std::tuple<double, double>{observed_autocorrelation, 1.0}; } //std::cerr << "Passed initial screen: " << observed_autocorrelation_pvalue << " " << observed_max_run_pvalue << " " << observed_relaxation_time_pvalue << " " << observed_combined_pvalue << std::endl; //std::cerr << "Generating auxilliary trajectories..." << std::endl; // otherwise, prepare to calculate bootstrapped combine pvalues // first populate at least ~ min num bootstrapped trajectories for(int i=0;i<min_num_bootstraps;++i){ trajectory_generator.generate_bootstrapped_trajectory(random); // calculate bootstrapped test statistics double bootstrapped_autocorrelation = calculate_autocorrelation(trajectory_generator.unmasked_bootstrapped_trajectory); double bootstrapped_max_run = calculate_max_run(trajectory_generator.unmasked_bootstrapped_trajectory); double bootstrapped_relaxation_time = calculate_relaxation_time(trajectory_generator.unmasked_bootstrapped_trajectory,true); // add them to corresponding vectors bootstrapped_autocorrelations.push_back(bootstrapped_autocorrelation); bootstrapped_max_runs.push_back(bootstrapped_max_run); bootstrapped_relaxation_times.push_back(bootstrapped_relaxation_time); } // then sort test statistic lists std::sort(bootstrapped_autocorrelations.begin(), bootstrapped_autocorrelations.end()); std::sort(bootstrapped_max_runs.begin(), bootstrapped_max_runs.end()); std::sort(bootstrapped_relaxation_times.begin(), bootstrapped_relaxation_times.end()); // use these sorted lists to re-adjust observed pvalues // observed_autocorrelation_pvalue = calculate_pvalue_from_sorted_list(bootstrapped_autocorrelations, observed_autocorrelation); // observed_max_run_pvalue = calculate_pvalue_from_sorted_list(bootstrapped_max_runs, observed_max_run); // observed_relaxation_time_pvalue = calculate_pvalue_from_sorted_list(bootstrapped_relaxation_times, observed_relaxation_time); // observed_combined_pvalue = calculate_combined_pvalue(observed_autocorrelation_pvalue, observed_max_run_pvalue, observed_relaxation_time_pvalue); // //std::cerr << "Recalculated versions: " << observed_autocorrelation_pvalue << " " << observed_max_run_pvalue << " " << observed_relaxation_time_pvalue << " " << observed_combined_pvalue << std::endl; // now calculate a pvalue using the "combined pvalue" as a test statistic int num_greater = 0; current_num_bootstraps = 0; while(current_num_bootstraps < max_num_bootstraps){ current_num_bootstraps+=1; trajectory_generator.generate_bootstrapped_trajectory(random); // calculate bootstrapped test statistics double bootstrapped_autocorrelation = calculate_autocorrelation(trajectory_generator.unmasked_bootstrapped_trajectory); // double bootstrapped_max_run = calculate_max_run(trajectory_generator.unmasked_bootstrapped_trajectory); // double bootstrapped_relaxation_time = calculate_relaxation_time(trajectory_generator.unmasked_bootstrapped_trajectory,true); // // calculate pvalues for those test statistics double bootstrapped_autocorrelation_pvalue = calculate_pvalue_from_sorted_list(bootstrapped_autocorrelations, bootstrapped_autocorrelation); // double bootstrapped_max_run_pvalue = calculate_pvalue_from_sorted_list(bootstrapped_max_runs, bootstrapped_max_run); // double bootstrapped_relaxation_time_pvalue = calculate_pvalue_from_sorted_list(bootstrapped_relaxation_times, bootstrapped_relaxation_time); // double bootstrapped_combined_pvalue = calculate_combined_pvalue(bootstrapped_autocorrelation_pvalue, bootstrapped_max_run_pvalue, bootstrapped_relaxation_time_pvalue); // //std::cerr << bootstrapped_autocorrelation_pvalue << " " << bootstrapped_max_run_pvalue << " " << bootstrapped_relaxation_time_pvalue << " " << bootstrapped_combined_pvalue << std::endl; if(bootstrapped_combined_pvalue <= observed_combined_pvalue){ num_greater += 1; } if(num_greater > min_numerator_counts){ break; } } // calculate final pvalue double pvalue = calculate_pvalue_from_counts(num_greater, current_num_bootstraps); // decrease uncertainty for things near the boundary if(pvalue>0.01 && pvalue<0.05){ // run it again // now calculate a pvalue using the "combined pvalue" as a test statistic while(current_num_bootstraps < 1000000){ current_num_bootstraps+=1; trajectory_generator.generate_bootstrapped_trajectory(random); // calculate bootstrapped test statistics double bootstrapped_autocorrelation = calculate_autocorrelation(trajectory_generator.unmasked_bootstrapped_trajectory); // double bootstrapped_max_run = calculate_max_run(trajectory_generator.unmasked_bootstrapped_trajectory); // double bootstrapped_relaxation_time = calculate_relaxation_time(trajectory_generator.unmasked_bootstrapped_trajectory,true); // // calculate pvalues for those test statistics double bootstrapped_autocorrelation_pvalue = calculate_pvalue_from_sorted_list(bootstrapped_autocorrelations, bootstrapped_autocorrelation); // double bootstrapped_max_run_pvalue = calculate_pvalue_from_sorted_list(bootstrapped_max_runs, bootstrapped_max_run); // double bootstrapped_relaxation_time_pvalue = calculate_pvalue_from_sorted_list(bootstrapped_relaxation_times, bootstrapped_relaxation_time); // double bootstrapped_combined_pvalue = calculate_combined_pvalue(bootstrapped_autocorrelation_pvalue, bootstrapped_max_run_pvalue, bootstrapped_relaxation_time_pvalue); // if(bootstrapped_combined_pvalue <= observed_combined_pvalue){ num_greater += 1; } } // calculate final pvalue pvalue = calculate_pvalue_from_counts(num_greater, current_num_bootstraps); } //std::cerr << "Final pvalue: " << pvalue << std::endl; return std::tuple<double,double>{observed_autocorrelation, pvalue}; } //////////////////////////////////////////////////////////////////////////////// // // Calculates pvalue and location for trimming trajectory // if it looks like a deletion has occured // // Returns: index, fold_change, pvalue // //////////////////////////////////////////////////////////////////////////////// std::tuple<int,double,double> calculate_deletion_pvalue(Random & random, Trajectory const & trajectory, int num_bootstraps){ std::vector<double> depth_trajectory; std::vector<int> ks; // construct depth trajectory for(int k=0,kmax=trajectory.size();k<kmax;++k){ if(trajectory[k].median_depth < min_depth){ // do nothing! } else{ depth_trajectory.push_back(trajectory[k].depth/trajectory[k].median_depth); ks.push_back(k); } } int L = depth_trajectory.size(); if(L < 1){ return std::tuple<int,double,double>{-1,0,1}; } int observed_k; double observed_fold_change, observed_loglikelihood; int dummy_observed_k; double dummy_observed_fold_change; std::tie(observed_k, observed_fold_change, observed_loglikelihood) = calculate_depth_change(depth_trajectory); if(observed_fold_change > deletion_fold_reduction_threshold){ std::tie(observed_k, observed_fold_change, observed_loglikelihood) = calculate_depth_change(depth_trajectory, deletion_fold_reduction_threshold); } int cutoff_idx = ks[L-observed_k]; if(cutoff_idx > trajectory.size()){ std::cerr << "Panic! " << observed_k << " " << cutoff_idx << " " << trajectory.size() << std::endl; } int num_greater = 0; int current_num_bootstraps = 0; for(;current_num_bootstraps < num_bootstraps; ++current_num_bootstraps){ if(num_greater > 10){ break; } std::shuffle(depth_trajectory.begin(), depth_trajectory.end(), random); int bootstrapped_k; double bootstrapped_fold_change, bootstrapped_loglikelihood; int dummy_bootstrapped_k; double dummy_bootstrapped_fold_change; std::tie(bootstrapped_k, bootstrapped_fold_change, bootstrapped_loglikelihood) = calculate_depth_change(depth_trajectory); if(bootstrapped_fold_change > deletion_fold_reduction_threshold){ std::tie(bootstrapped_k, dummy_bootstrapped_fold_change, bootstrapped_loglikelihood) = calculate_depth_change(depth_trajectory, deletion_fold_reduction_threshold); } if(bootstrapped_loglikelihood >= observed_loglikelihood){ num_greater += 1; } } double pvalue = (num_greater+1)*1.0/(current_num_bootstraps+1); return std::tuple<int,double,double>{cutoff_idx, observed_fold_change, pvalue}; } //////////////////////////////////////////////////////////////////////////////// // // Calculates pvalue and location for trimming trajectory // if it looks like a duplication has occured // // Returns: index, fold_change, pvalue // //////////////////////////////////////////////////////////////////////////////// std::tuple<int,double,double> calculate_duplication_pvalue(Random & random, Trajectory const & trajectory, int num_bootstraps){ std::vector<double> depth_trajectory; std::vector<int> ks; // construct depth trajectory for(int k=0,kmax=trajectory.size();k<kmax;++k){ if(trajectory[k].median_depth < min_depth){ // do nothing! } else{ depth_trajectory.push_back(trajectory[k].depth/trajectory[k].median_depth); ks.push_back(k); } } int L = depth_trajectory.size(); if(L < 1){ return std::tuple<int,double,double>{-1,0,1}; } int observed_k; double observed_fold_change, observed_loglikelihood; int dummy_observed_k; double dummy_observed_fold_change; std::tie(observed_k, observed_fold_change, observed_loglikelihood) = calculate_depth_change(depth_trajectory); if(observed_fold_change < duplication_fold_increase_threshold){ std::tie(observed_k, observed_fold_change, observed_loglikelihood) = calculate_depth_change(depth_trajectory, duplication_fold_increase_threshold); } int cutoff_idx = ks[L-observed_k]; if(cutoff_idx > trajectory.size()){ std::cerr << "Panic! " << observed_k << " " << cutoff_idx << " " << trajectory.size() << std::endl; } int num_greater = 0; int current_num_bootstraps = 0; for(;current_num_bootstraps < num_bootstraps; ++current_num_bootstraps){ if(num_greater > 10){ break; } std::shuffle(depth_trajectory.begin(), depth_trajectory.end(), random); int bootstrapped_k; double bootstrapped_fold_change, bootstrapped_loglikelihood; int dummy_bootstrapped_k; double dummy_bootstrapped_fold_change; std::tie(bootstrapped_k, bootstrapped_fold_change, bootstrapped_loglikelihood) = calculate_depth_change(depth_trajectory); if(bootstrapped_fold_change < duplication_fold_increase_threshold){ std::tie(bootstrapped_k, bootstrapped_fold_change, bootstrapped_loglikelihood) = calculate_depth_change(depth_trajectory, duplication_fold_increase_threshold); } if(bootstrapped_loglikelihood >= observed_loglikelihood){ num_greater += 1; } } double pvalue = (num_greater+1)*1.0/(current_num_bootstraps+1); return std::tuple<int,double,double>{cutoff_idx, observed_fold_change, pvalue}; }
aa5b578bba5657b16d8129cc56c9c957
{ "intermediate": 0.415621817111969, "beginner": 0.3318447172641754, "expert": 0.252533495426178 }
34,805
измени методы оставив тот же смысл для начинающего на C# "public CreatureCommand Act(int x, int y) { int xTo = 0; int yTo = 0; if (FindPlayer()) { if (Player.xPos == x) { if (Player.yPos < y) yTo = -1; else if (Player.yPos > y) yTo = 1; } else if (Player.yPos == y) { if (Player.xPos < x) xTo = -1; else if (Player.xPos > x) xTo = 1; } else { if (Player.xPos < x) xTo = -1; else if (Player.xPos > x) xTo = 1; } } else return new CreatureCommand() { DeltaX = 0, DeltaY = 0 }; if (!(x + xTo >= 0 && x + xTo < Game.MapWidth && y + yTo >= 0 && y + yTo < Game.MapHeight)) return new CreatureCommand() { DeltaX = 0, DeltaY = 0 }; var map = Game.Map[x + xTo, y + yTo]; if (map != null && (map.ToString() == "Digger.Terrain" || map.ToString() == "Digger.Sack" || map.ToString() == "Digger.Monster")) return new CreatureCommand() { DeltaX = 0, DeltaY = 0 }; return new CreatureCommand() { DeltaX = xTo, DeltaY = yTo }; } static private bool FindPlayer() { for (int i = 0; i < Game.MapWidth; i++) { for (int j = 0; j < Game.MapHeight; j++) { if (Game.Map[i, j] != null && Game.Map[i, j].GetImageFileName() == "Digger.png") { Player.xPos = i; Player.yPos = j; return true; } } } return false; }"
917cce1a23e14500cdc5f34f9046c0f5
{ "intermediate": 0.3053678870201111, "beginner": 0.46966058015823364, "expert": 0.22497154772281647 }
34,806
try: #Establish connection connection = mysql.connector.connect(host = 'localhost', user = 'root', password = '123456', database = 'world') if connection.is_connected(): cursor = connection.cursor() cursor.execute('select * from city') record = cursor.fetchall() column_names = [desc[0] for desc in cursor.description] # print(cursor.description) df_source = pd.DataFrame(record,columns = column_names) # Detecting the encoding type with open('D:/VS Code programs/Data validator/city.csv','rb') as file: encoding_type = cd.detect(file.read()) df_target = pd.read_csv('D:/VS Code programs/Data validator/city.csv',delimiter = ',',encoding=encoding_type['encoding']) # print('sou') # print(df_source) # print('tar') # print(df_target) # Compare data comparison_result = pd.merge(df_source, df_target, how='outer', indicator=True)#.loc[lambda x: x['_merge'] != 'both'] # Write the comparison result to an Excel file comparison_result.to_excel('D:/VS Code programs/Data validator/comparision.xlsx', index=False) print("Comparison completed. Results saved to",'D:\VS Code programs\Data validator') except Error as e: print('while connecting to sql:',e) finally: # Close the connection if connection.is_connected(): cursor.close() connection.close() print('MySQL connection is closed') What is cursor in
086dac54f82a6b9c419834d10059881e
{ "intermediate": 0.4289202392101288, "beginner": 0.4024888277053833, "expert": 0.1685909479856491 }
34,807
how to hide any folder
bc82c83d952e2b61138b48fde8e86355
{ "intermediate": 0.27900683879852295, "beginner": 0.33647534251213074, "expert": 0.3845178186893463 }
34,808
it doesn't detect the keypresses: import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:path_provider/path_provider.dart'; import 'package:camera/camera.dart'; import 'package:flutter/material.dart'; import 'package:just_audio/just_audio.dart'; import 'package:flutter/services.dart'; import 'package:http/http.dart' as http; Future<void> main() async { // Ensure that plugin services are initialized so that `availableCameras()` // can be called before `runApp()` WidgetsFlutterBinding.ensureInitialized(); // Obtain a list of the available cameras on the device. final cameras = await availableCameras(); // Get a specific camera from the list of available cameras. final firstCamera = cameras.first; runApp( MaterialApp( theme: ThemeData.dark(), home: TakePictureScreen( // Pass the appropriate camera to the TakePictureScreen widget. camera: firstCamera, ), ), ); } // A screen that allows users to take a picture using a given camera. class TakePictureScreen extends StatefulWidget { const TakePictureScreen({ super.key, required this.camera, }); final CameraDescription camera; @override TakePictureScreenState createState() => TakePictureScreenState(); } class TakePictureScreenState extends State<TakePictureScreen> { late CameraController _controller; late Future<void> _initializeControllerFuture; @override void initState() { super.initState(); // To display the current output from the Camera, // create a CameraController. _controller = CameraController( // Get a specific camera from the list of available cameras. widget.camera, // Define the resolution to use. ResolutionPreset.medium, ); // Next, initialize the controller. This returns a Future. _initializeControllerFuture = _controller.initialize(); } Future<void> captureAndSendImage() async { // Your existing code here... try { await _initializeControllerFuture; final image = await _controller.takePicture(); if (!mounted) return; // Send the image to the server var request = http.MultipartRequest( 'POST', Uri.parse('http://localhost:8000/api/phone/camera')); request.files.add(await http.MultipartFile.fromPath('file', image.path)); request.fields['direction'] = "In"; var res = await request.send(); var response = await http.Response.fromStream(res); if (response.statusCode == 200) { // If the server returns a 200 OK response, then proceed var responseData = jsonDecode(response.body); var audioBase64 = responseData[1]['audio']; // Decode the Base64 string to bytes var audioBytes = base64Decode(audioBase64); // Save the audio to a temporary file var directory = await getApplicationDocumentsDirectory(); var audioPath = '${directory.path}/temp.mp3'; var audioFile = File(audioPath); await audioFile.writeAsBytes(audioBytes); // Load the audio file var player = AudioPlayer(); await player.setUrl(audioPath); // Play the audio file player.play(); } else { // If the server returns an error response, // then print the status code. print('Failed to upload image. Status code: ${response.statusCode}.'); } } catch (e) { print(e); } } @override void dispose() { // Dispose of the controller when the widget is disposed. _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return KeyboardListener( focusNode: FocusNode(), autofocus: true, onKeyEvent: (KeyEvent event) { if (event is KeyDownEvent) { print(event.logicalKey.keyLabel); if (event.logicalKey.keyLabel == 'Audio Volume Up') { captureAndSendImage(); } if (event.logicalKey.keyLabel == 'Audio Volume Down') { captureAndSendImage(); } } }, child: Scaffold( appBar: AppBar(title: const Text('Take a picture')), body: FutureBuilder<void>( future: _initializeControllerFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.done) { return CameraPreview(_controller); } else { return const Center(child: CircularProgressIndicator()); } }, ), floatingActionButton: FloatingActionButton( onPressed: captureAndSendImage, child: const Icon(Icons.camera_alt), ), ), ); } }
1e8c6e87d850b1ee51f4f79fc68f3512
{ "intermediate": 0.40793082118034363, "beginner": 0.389412522315979, "expert": 0.2026566118001938 }
34,809
#pragma once #include "Arguments.h" #include <string> #include <vector> namespace ArgumentParser { class ArgParser { public: ArgParser(const std::string& name) : parser_name_(name) {} ~ArgParser() {}; bool Parse(std::vector<std::string> args); String& AddStringArgument(const std::string param); String& AddStringArgument(const char short_param, const std::string param); String& AddStringArgument(const char short_param, const std::string param, const std::string description); std::string GetStringValue(const std::string param); Int& AddIntArgument(const std::string number); Int& AddIntArgument(const std::string numer, const std::string description); int GetIntValue(const std::string param); Int& AddIntArgument(const char short_param, const std::string param); int GetIntValue(const std::string param, const int ind); Bool& AddFlag(const char short_flag, const std::string flag); Bool& AddFlag(const char short_flag, const std::string flag, const std::string description); Bool& AddFlag(const std::string flag, const std::string description); bool GetFlag(const std::string flag); Args& AddHelp(const char short_help, const std::string help, const std::string description); bool Help(); std::string HelpDescription(); private: std::string parser_name_; std::vector<Args*> all_; }; } #include "ArgParser.h" #include "Arguments.h" #include <string> #include <vector> #include <iostream> namespace ArgumentParser { bool ArgParser::Parse(std::vector<std::string> args) { if (all_.empty() && args.size() == 1) { return true; } int count = 0; for (int i = 0; i < args.size(); ++i) { for (int j = 0; j < all_.size(); ++j) { TypeFlag type = all_[j]->GetTypeFlag(); switch (type) { case TypeFlag::INT: { Int* arg = static_cast<Int*>(all_[j]); std::string origin_param = "--" + arg->GetParam() + "="; std::string origin_short_param = "-"; origin_short_param.push_back(arg->GetShortParam()); origin_short_param += "="; if (!arg->GetParam().empty() && args[i].substr(0, origin_param.length()) == origin_param && !all_[j]->GetFlagMultiValue()) { arg->PutValue(args[i].substr(origin_param.length(), args[i].length())); ++count; } else if (arg->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param && !all_[j]->GetFlagMultiValue()) { arg->PutValue(args[i].substr(origin_short_param.length(), args[i].length())); ++count; } else if (all_[j]->GetFlagMultiValue()) { if (args[i].substr(0, origin_param.length()) == origin_param) { arg->PutValue(args[i].substr(origin_param.length(), args[i].length())); all_[j]->MultiArgsCount(); } else if (arg->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param) { arg->PutValue(args[i].substr(origin_short_param.length(), args[i].length())); all_[j]->MultiArgsCount(); } } if (all_[j]->GetFlagPositional()) { int count_len = 0; for (int k = 0; k < args[i].length(); ++k) { if (!std::isdigit(args[i][k])){ break; } else { ++count_len; } } if (count_len == args[i].length()) { arg->PutValue(args[i]); arg->MultiArgsCount(); if (arg->GetFlagStoreValues()) { arg->AddStoreValues(arg->GetValue()); all_[j]->AddAllValues(arg->GetValue()); } } } } break; case TypeFlag::STRING: { String* arg = static_cast<String*>(all_[j]); std::string origin_param = "--" + arg->GetParam() + "="; std::string origin_short_param = "-"; origin_short_param.push_back(arg->GetShortParam()); origin_short_param += "="; if (args.size() == 1 && !arg->GetDefaultValue().empty()) { arg->PutValue(arg->GetDefaultValue()); ++count; } else if (!arg->GetParam().empty() && args[i].substr(0, origin_param.length()) == origin_param && !all_[j]->GetFlagMultiValue()) { arg->PutValue(args[i].substr(origin_param.length(), args[i].length())); if (arg->GetFlagStoreValue()) { arg->AddStoreValue(arg->GetValue()); } ++count; } else if (arg->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param && !all_[j]->GetFlagMultiValue()) { arg->PutValue(args[i].substr(origin_short_param.length(), args[i].length())); if (arg->GetFlagStoreValue()) { arg->AddStoreValue(arg->GetValue()); } ++count; } else if (arg->GetFlagMultiValue()) { if (args[i].substr(0, origin_param.length()) == origin_param) { arg->PutValue(args[i].substr(origin_param.length(), args[i].length())); arg->MultiArgsCount(); } else if (arg->GetFlagShortParam() && args[i].substr(0, origin_short_param.length()) == origin_short_param) { arg->PutValue(args[i].substr(origin_short_param.length(), args[i].length())); arg->MultiArgsCount(); } } } break; case TypeFlag::BOOL: { Bool* arg = static_cast<Bool*>(all_[j]); std::string origin_flag = "--" + arg->GetFlag(); if (arg->GetIsFlag()) { if (args[i].substr(0, origin_flag.length()) == origin_flag) { if (arg->GetFlagStoreFlag()) { arg->AddStoreFlag(true); } ++count; } else if (args[i][0] == '-' && args[i][1] != '-' && args[i].length() > 2) { for (int z = 1; z < args[i].length(); ++z) { if (args[i][z] == arg->GetShortFlag()) { if (arg->GetFlagStoreFlag()) { arg->AddStoreFlag(true); } ++count; } } } } } break; case TypeFlag::UNKNOWN: { Args* arg = static_cast<Args*>(all_[j]); std::string origin_help = "--" + all_[j]->GetHelp(); std::string origin_short_help = "-"; origin_short_help.push_back(all_[j]->GetShortHelp()); if (args[i].substr(0, origin_help.length()) == origin_help || args[i].substr(0, origin_short_help.length()) == origin_short_help) { all_[j]->FlagHelp(); ++count; } } break; } } } for (int i = 0; i < all_.size(); ++i) { if (all_[i]->GetMultiArgsCount() > 0) { ++count; } if (static_cast<Bool*>(all_[i])->GetFlagDefaultFlag()) { ++count; } if (all_[i]->GetMultiArgsCount() > 0 && all_[i]->GetMinArgsCount() > all_[i]->GetMultiArgsCount()) { return false; } } if (count == all_.size()) { return true; } else { for (int i = 0; i < all_.size(); ++i) { if (all_[i]->GetFlagHelp()) { return true; } } return false; } } String& ArgParser::AddStringArgument(const std::string param) { String* str = new String(); str->param_ = param; all_.push_back(str); return *str; } String& ArgParser::AddStringArgument(const char short_param, const std::string param) { String* str = new String(); str->short_param_ = short_param; str->param_ = param; str->flag_short_param_ = true; all_.push_back(str); return *str; } String& ArgParser::AddStringArgument(const char short_param, const std::string param, const std::string description) { String* str = new String(); str->short_param_ = short_param; str->param_ = param; str->flag_short_param_ = true; all_.push_back(str); str->Description(description); return *str; } std::string ArgParser::GetStringValue(const std::string param) { for (int i = 0; i < (all_).size(); ++i) { if (static_cast<String*>(all_[i])->param_ == param) { return static_cast<String*>(all_[i])->GetValue(); } } } Int& ArgParser::AddIntArgument(const std::string number) { Int* int_val = new Int(); int_val->param_ = number; all_.push_back(int_val); return *int_val; } Int& ArgParser::AddIntArgument(const std::string number, const std::string description) { Int* int_val = new Int(); int_val->param_ = number; all_.push_back(int_val); int_val->Description(description); return *int_val; } int ArgParser::GetIntValue(const std::string param) { for (int i = 0; i < all_.size(); ++i) { if (static_cast<Int*>(all_[i])->GetParam() == param) { int value = std::stoi(static_cast<Int*>(all_[i])->GetValue()); return value; } } } Int& ArgParser::AddIntArgument(const char short_param, const std::string param) { Int* int_val = new Int(); int_val->short_param_ = short_param; all_.push_back(int_val); return *int_val; } int ArgParser::GetIntValue(const std::string param, const int ind) { if (static_cast<Int*>(all_[ind])->GetParam() == param) { return static_cast<Int*>(all_[ind])->GetIndexedValue(ind); } } Bool& ArgParser::AddFlag(const char short_flag, const std::string flag) { Bool* new_flag = new Bool(); new_flag->AddFlags(short_flag, flag); all_.push_back(new_flag); return *new_flag; } Bool& ArgParser::AddFlag(const char short_flag, const std::string flag, const std::string description) { Bool* new_flag = new Bool(); new_flag->AddFlags(short_flag, flag); all_.push_back(new_flag); new_flag->Description(description); return *new_flag; } Bool& ArgParser::AddFlag(const std::string flag, const std::string description) { Bool* new_flag = new Bool(); new_flag->AddFlag(flag); all_.push_back(new_flag); new_flag->Description(description); return *new_flag; } bool ArgParser::GetFlag(const std::string flag) { for (int i = 0; i < all_.size(); ++i) { if (static_cast<Bool*>(all_[i])->GetFlag() == flag) { return true; } } return false; } bool ArgParser::Help() { return true; } Args& ArgParser::AddHelp(const char short_help, const std::string help, const std::string description) { Args* new_help = new Args(); new_help->Help(short_help, help); new_help->Description(description); all_.push_back(new_help); return *new_help; } std::string ArgParser::HelpDescription() { std::cout << "My Parser\n"; std::cout << "Some Description about program\n\n"; std::cout << "-i, --input=<string>, File path for input file [repeated, min args = 1]\n"; std::cout << "-s, --flag1, Use some logic [default = true]\n"; std::cout << "-p, --flag2, Use some logic\n"; std::cout << " --number=<int>, Some Number\n\n"; std::cout << "-h, --help Display this help and exit\n"; } } #pragma once #include <string> #include <vector> namespace ArgumentParser { enum class TypeFlag { INT, STRING, BOOL, UNKNOWN // In case no flag is set or Args is a base type that should not be instantiated }; class Args { public: Args(); Args(const std::string param); Args(const char short_param, const std::string param); ~Args() {}; virtual TypeFlag GetTypeFlag() const { return TypeFlag::UNKNOWN; } Args& MultiValue(); Args& MultiValue(const int min_args_count); bool GetFlagMultiValue(); Args& Positional(); bool GetFlagPositional(); void MultiArgsCount(); int GetMultiArgsCount(); int GetMinArgsCount(); void AddAllValues(const std::string value); void Help(const char short_help, const std::string help); std::string GetHelp(); char GetShortHelp(); void FlagHelp(); bool GetFlagHelp(); void Description(const std::string description); void StoreValues(std::vector<int>& store_values); bool GetFlagStoreValues(); bool flag_store_values_ = false; bool flag_positional_ = false; bool flag_multi_value_ = false; int min_args_count_; int multi_args_count_ = 0; std::vector<int> all_values_; char short_help_; std::string help_; std::string description_; bool flag_help_ = false; std::vector<int>* store_values_; }; class Int : public Args { public: TypeFlag GetTypeFlag() const override { return TypeFlag::INT; } void AddStoreValues(const std::string value); std::string GetParam(); char GetShortParam(); bool GetFlagShortParam(); void PutValue(const std::string value); std::string GetValue(); int GetIndexedValue(const int ind); std::string param_; char short_param_; bool flag_short_param_ = false; bool flag_store_values_ = false; std::string value_; }; class String : public Args { public: TypeFlag GetTypeFlag() const override { return TypeFlag::STRING; } std::string GetParam(); char GetShortParam(); bool GetFlagShortParam(); String& Default(const char* value); std::string GetDefaultValue(); void PutValue(const std::string value); std::string GetValue(); void StoreValue(std::string& value); void AddStoreValue(const std::string value); bool GetFlagStoreValue(); std::string param_; char short_param_; bool flag_short_param_ = false; std::string* store_value_; std::string default_value_; std::string value_; bool flag_store_value_ = false; }; class Bool : public Args { public: TypeFlag GetTypeFlag() const override { return TypeFlag::BOOL; } Bool& Default(const bool flag); bool GetFlagDefaultFlag(); void StoreValue(bool& flag); bool GetFlagStoreFlag(); void AddStoreFlag(const bool flag); void AddFlags(const char short_flag, const std::string flag); void AddFlag(const std::string flag); std::string GetFlag(); bool GetIsFlag(); char GetShortFlag(); std::string flag_; char short_flag_; bool is_flag_ = false; bool default_flag_; bool flag_default_flag_ = false; bool* store_flag_; bool flag_store_flag_ = false; }; }; #include "Arguments.h" #include <string> #include <vector> namespace ArgumentParser { Args::Args() {} Args::Args(const std::string param) { static_cast<String*>(this)->param_ = param; } Args::Args(const char short_param, const std::string param) { static_cast<String*>(this)->param_ = param; static_cast<String*>(this)->short_param_ = short_param; static_cast<String*>(this)->flag_short_param_ = true; } std::string String::GetParam() { return param_; } char String::GetShortParam() { return short_param_; } bool String::GetFlagShortParam() { return flag_short_param_; } std::string Int::GetParam() { return param_; } char Int::GetShortParam() { return short_param_; } bool Int::GetFlagShortParam() { return flag_short_param_; } void Int::PutValue(const std::string value) { value_ = value; } std::string Int::GetValue() { return value_; } void String::PutValue(const std::string value) { value_ = value; } std::string String::GetValue() { return value_; } String& String::Default(const char* value) { default_value_ = value; return *this; } Bool& Bool::Default(const bool flag) { default_flag_ = flag; flag_default_flag_ = true; return *this; } std::string String::GetDefaultValue() { return default_value_; } bool Bool::GetFlagDefaultFlag() { return flag_default_flag_; } void String::StoreValue(std::string& value) { store_value_ = &value; flag_store_value_ = true; } void Args::StoreValues(std::vector<int>& store_values) { store_values_ = &store_values; flag_store_values_ = true; } void Bool::StoreValue(bool& flag) { store_flag_ = &flag; flag_store_flag_ = true; } bool String::GetFlagStoreValue() { return flag_store_value_; } void String::AddStoreValue(const std::string value) { *store_value_ = value; } void Int::AddStoreValues(const std::string value) { (*store_values_).push_back(std::stoi(value)); } bool Args::GetFlagStoreValues() { return flag_store_values_; } bool Bool::GetFlagStoreFlag() { return flag_store_flag_; } void Bool::AddStoreFlag(const bool flag) { *store_flag_ = flag; } Args& Args::MultiValue() { flag_multi_value_ = true; return *this; } Args& Args::MultiValue(const int min_args_count) { flag_multi_value_ = true; min_args_count_ = min_args_count; return *this; } bool Args::GetFlagMultiValue() { return flag_multi_value_; } void Args::MultiArgsCount() { ++multi_args_count_; } int Args::GetMultiArgsCount() { return multi_args_count_; } int Args::GetMinArgsCount() { return min_args_count_; } void Args::AddAllValues(const std::string value) { all_values_.push_back(std::stoi(value)); } int Int::GetIndexedValue(const int ind) { return all_values_[ind]; } void Bool::AddFlags(const char short_flag, const std::string flag) { short_flag_ = short_flag; flag_ = flag; is_flag_ = true; } void Bool::AddFlag(const std::string flag) { flag_ = flag; is_flag_ = true; } std::string Bool::GetFlag() { return flag_; } bool Bool::GetIsFlag() { return is_flag_; } char Bool::GetShortFlag() { return short_flag_; } Args& Args::Positional() { flag_positional_ = true; return *this; } bool Args::GetFlagPositional() { return flag_positional_; } void Args::Help(const char short_help, const std::string help) { short_help_ = short_help; help_ = help; } std::string Args::GetHelp() { return help_; } char Args::GetShortHelp() { return short_help_; } void Args::FlagHelp() { flag_help_ = true; } bool Args::GetFlagHelp() { return flag_help_; } void Args::Description(const std::string description) { description_ = description; } } #include <lib/ArgParser.h> #include <gtest/gtest.h> #include <sstream> using namespace ArgumentParser; /* Функция принимает в качество аргумента строку, разделяет ее по "пробелу" и возвращает вектор полученных слов */ std::vector<std::string> SplitString(const std::string& str) { std::istringstream iss(str); return {std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>()}; } TEST(ArgParserTestSuite, EmptyTest) { ArgParser parser("My Empty Parser"); ASSERT_TRUE(parser.Parse(SplitString("app"))); } TEST(ArgParserTestSuite, StringTest) { ArgParser parser("My Parser"); parser.AddStringArgument("param1"); ASSERT_TRUE(parser.Parse(SplitString("app --param1=value1"))); ASSERT_EQ(parser.GetStringValue("param1"), "value1"); } TEST(ArgParserTestSuite, ShortNameTest) { ArgParser parser("My Parser"); parser.AddStringArgument('p', "param1"); ASSERT_TRUE(parser.Parse(SplitString("app -p=value1"))); ASSERT_EQ(parser.GetStringValue("param1"), "value1"); } TEST(ArgParserTestSuite, DefaultTest) { ArgParser parser("My Parser"); parser.AddStringArgument("param1").Default("value1"); ASSERT_TRUE(parser.Parse(SplitString("app"))); ASSERT_EQ(parser.GetStringValue("param1"), "value1"); } TEST(ArgParserTestSuite, NoDefaultTest) { ArgParser parser("My Parser"); parser.AddStringArgument("param1"); ASSERT_FALSE(parser.Parse(SplitString("app"))); } TEST(ArgParserTestSuite, StoreValueTest) { ArgParser parser("My Parser"); std::string value; parser.AddStringArgument("param1").StoreValue(value); ASSERT_TRUE(parser.Parse(SplitString("app --param1=value1"))); ASSERT_EQ(value, "value1"); } TEST(ArgParserTestSuite, MultiStringTest) { ArgParser parser("My Parser"); std::string value; parser.AddStringArgument("param1").StoreValue(value); parser.AddStringArgument('a', "param2"); ASSERT_TRUE(parser.Parse(SplitString("app --param1=value1 --param2=value2"))); ASSERT_EQ(parser.GetStringValue("param2"), "value2"); } TEST(ArgParserTestSuite, IntTest) { ArgParser parser("My Parser"); parser.AddIntArgument("param1"); ASSERT_TRUE(parser.Parse(SplitString("app --param1=100500"))); ASSERT_EQ(parser.GetIntValue("param1"), 100500); } TEST(ArgParserTestSuite, MultiValueTest) { ArgParser parser("My Parser"); std::vector<int> int_values; parser.AddIntArgument('p', "param1").MultiValue().StoreValues(int_values); ASSERT_TRUE(parser.Parse(SplitString("app --param1=1 --param1=2 --param1=3"))); ASSERT_EQ(parser.GetIntValue("param1", 0), 1); ASSERT_EQ(int_values[1], 2); ASSERT_EQ(int_values[2], 3); } TEST(ArgParserTestSuite, MinCountMultiValueTest) { ArgParser parser("My Parser"); std::vector<int> int_values; size_t MinArgsCount = 10; parser.AddIntArgument('p', "param1").MultiValue(MinArgsCount).StoreValues(int_values); ASSERT_FALSE(parser.Parse(SplitString("app --param1=1 --param1=2 --param1=3"))); } TEST(ArgParserTestSuite, FlagTest) { ArgParser parser("My Parser"); parser.AddFlag('f', "flag1"); ASSERT_TRUE(parser.Parse(SplitString("app --flag1"))); ASSERT_TRUE(parser.GetFlag("flag1")); } TEST(ArgParserTestSuite, FlagsTest) { ArgParser parser("My Parser"); bool flag3 ; parser.AddFlag('a', "flag1"); parser.AddFlag('b', "flag2").Default(true); parser.AddFlag('c', "flag3").StoreValue(flag3); ASSERT_TRUE(parser.Parse(SplitString("app -ac"))); ASSERT_TRUE(parser.GetFlag("flag1")); ASSERT_TRUE(parser.GetFlag("flag2")); ASSERT_TRUE(flag3); } TEST(ArgParserTestSuite, PositionalArgTest) { ArgParser parser("My Parser"); std::vector<int> values; parser.AddIntArgument("Param1").MultiValue(1).Positional().StoreValues(values); ASSERT_TRUE(parser.Parse(SplitString("app 1 2 3 4 5"))); ASSERT_EQ(values[0], 1); ASSERT_EQ(values[2], 3); ASSERT_EQ(values.size(), 5); } TEST(ArgParserTestSuite, HelpTest) { ArgParser parser("My Parser"); parser.AddHelp('h', "help", "Some Description about program"); ASSERT_TRUE(parser.Parse(SplitString("app --help"))); ASSERT_TRUE(parser.Help()); } TEST(ArgParserTestSuite, HelpStringTest) { ArgParser parser("My Parser"); parser.AddHelp('h', "help", "Some Description about program"); parser.AddStringArgument('i', "input", "File path for input file").MultiValue(1); parser.AddFlag('s', "flag1", "Use some logic").Default(true); parser.AddFlag('p', "flag2", "Use some logic"); parser.AddIntArgument("numer", "Some Number"); ASSERT_TRUE(parser.Parse(SplitString("app --help"))); // Проверка закоментирована намеренно. Ождиается, что результат вызова функции будет приблизительно такой же, // но не с точностью до символа /*ASSERT_EQ( parser.HelpDescription(), "My Parser\n" "Some Description about program\n" "\n" "-i, --input=<string>, File path for input file [repeated, min args = 1]\n" "-s, --flag1, Use some logic [default = true]\n" "-p, --flag2, Use some logic\n" " --number=<int>, Some Number\n" "\n" "-h, --help Display this help and exit\n" );*/ } 9: Value of: parser.Parse(SplitString("app --param1=1 --param1=2 --param1=3")) 9: Actual: false 9: Expected: true 9: [ FAILED ] ArgParserTestSuite.MultiValueTest (0 ms) 9: [----------] 1 test from ArgParserTestSuite (0 ms total) 9: 9: [----------] Global test environment tear-down 9: [==========] 1 test from 1 test suite ran. (0 ms total) 9: [ PASSED ] 0 tests. 9: [ FAILED ] 1 test, listed below: 9: [ FAILED ] ArgParserTestSuite.MultiValueTest 9: 9: 1 FAILED TEST why failed, fix it
b2ebf55308237ef207cc3b9c6fe0658e
{ "intermediate": 0.32308661937713623, "beginner": 0.5003145337104797, "expert": 0.17659886181354523 }
34,810
#include <iostream> #include <vector> struct ArrNode { int data; int left; int right; ArrNode() : data(0), left(-1), right(-1) {} ArrNode(int data, int left, int right) : data(data), left(left), right(right) {} }; class AVL { public: struct Node { int value; Node* left; Node* right; int height; Node() : left(nullptr), right(nullptr) {} Node(int value) : value(value), left(nullptr), right(nullptr), height(1) {} }; int GetHeight(Node* node) { if (node == nullptr) return 0; return node->height; } void UpdateHeight(Node* node) { if (node->left == 0 && node->right == 0) { node->height = 0; } else { node->height = 1 + std::max(GetHeight(node->left), GetHeight(node->right)); } } Node* Insert(Node* node, ArrNode value) { if (node->value == 0 || node == nullptr) { return new Node(value.data); } if (value.data < node->value) { node->left = Insert(node->left, value); } else if (value.data > node->value) { node->right = Insert(node->right, value); } else { return node; } node->height = 1 + std::max(GetHeight(node->left), GetHeight(node->right)); return node; } Node* LeftRotation(Node* x) { Node *y = x->right; Node *T2 = y->left; y->left = x; x->right = T2; x->height = std::max(GetHeight(x->left), GetHeight(x->right)) + 1; y->height = std::max(GetHeight(y->left), GetHeight(y->right)) + 1; return y; } Node* RightRotation(Node* y) { Node *x = y->left; Node *T2 = x->right; x->right = y; y->left = T2; y->height = std::max(GetHeight(y->left), GetHeight(y->right)) + 1; x->height = std::max(GetHeight(x->left), GetHeight(x->right)) + 1; return x; } bool Search(Node* node, int value) { if (node->value == 0) { return false; } if (value == node->value) { return true; } if (value < node->value) { return Search(node->left, value); } else { return Search(node->right, value); } } void Insert(ArrNode value) { root = Insert(root, value); } bool Search(int value) { return Search(root, value); } void Balance() { if (GetHeight(root->right->left) > GetHeight(root->right->right)) { root->right = RightRotation(root->right); } root = LeftRotation(root); } void PrintCurrentLevel(Node* root, int level, int& counter_childs, int& index, ArrNode arr[]) { if (root == nullptr) return; if (level == 1) { arr[index].data = root->value; if (root->left != nullptr) { arr[index].left = ++counter_childs; } else { arr[index].left = 0; } if (root->right != nullptr) { arr[index].right = ++counter_childs; } else { arr[index].right = 0; } ++index; } else if (level > 1) { PrintCurrentLevel(root->left, level - 1, counter_childs, index, arr); PrintCurrentLevel(root->right, level - 1, counter_childs, index, arr); } } void PrintLevelOrder(ArrNode arr[]) { int h = GetHeight(root); int counter_childs = 1; int index = 0; for (int i = 1; i <= h; i++) { PrintCurrentLevel(root, i, counter_childs, index, arr); } } private: Node* root; }; int main() { int size; std::cin >> size; ArrNode arr[size]; AVL avl; for (int i = 0; i < size; ++i) { int value, left_child, right_child; std::cin >> value >> left_child >> right_child; arr[i].data = value; arr[i].left = left_child; arr[i].right = right_child; } for (int i = 0; i < size; ++i) { avl.Insert(arr[i]); } // avl.Balance(); // avl.PrintLevelOrder(arr); // for (int i = 0; i < size; ++i) { // std::cout << arr[i].data << ' '; // std::cout << arr[i].left << ' '; // std::cout << arr[i].right << '\n'; // } } ❯ ./main2 7 -2 7 2 8 4 3 9 0 0 3 5 6 0 0 0 6 0 0 -7 0 0 [1] 32306 segmentation fault ./main2 почему? НЕ НАДО ДЕЛАТЬ БАЛАНСИРОВКИ!!!!
071cc547dfd601f30b4612c8dde98116
{ "intermediate": 0.34491658210754395, "beginner": 0.4611652195453644, "expert": 0.1939181536436081 }
34,811
I created an new repository in my github account, I want to add my local project to this repository
02e734a14a6c908760917521e67dee70
{ "intermediate": 0.3214725852012634, "beginner": 0.2669132649898529, "expert": 0.41161417961120605 }
34,812
can you solve a bayesian optimization problem?
27ab7f88eedb8c33a7d7b1e3833755b4
{ "intermediate": 0.09747087955474854, "beginner": 0.0914117693901062, "expert": 0.8111173510551453 }
34,813
how to setup clipboard on sway
eb30d60599a3c2da6c8066f6df3ffe71
{ "intermediate": 0.3544892966747284, "beginner": 0.29656127095222473, "expert": 0.3489494323730469 }
34,814
image preview for ranger sway
859bab9a771f5bc3b283f0b4c6b4ddfd
{ "intermediate": 0.35801824927330017, "beginner": 0.29194289445877075, "expert": 0.35003891587257385 }
34,815
ranger image preview for sway and alacritty
9063c3303590e086c05425de1a30aafb
{ "intermediate": 0.3414272367954254, "beginner": 0.2893849015235901, "expert": 0.3691878616809845 }
34,816
hi
4b0859c998d33975d66d9ca960649c69
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
34,817
this is a PWN ctf challenge, where I identified a Format String Attack. But I'm at the very first step of understanding what's happening. Explain the values you see there (info for you, and explain this behavouir: the very first address never changes, second and third do change, fourth and the following does not change!). explain the addresses step by step for a visual thinker, use 2D graphics (like -- and _ characters for example) to explain how to stack works as well. and then explain what the very next step is in this challenge, I believe finding the offset, but I could be wrong. so evaluate it. explain everything in German language
37cdb611de943b5a1bd73e3228ad38ff
{ "intermediate": 0.40338441729545593, "beginner": 0.3518597185611725, "expert": 0.2447558045387268 }
34,818
clipboard for sway
132a211fb901146c484b63e7f397bcfd
{ "intermediate": 0.31863659620285034, "beginner": 0.3195834457874298, "expert": 0.36177992820739746 }
34,819
how to bind wl-copy and wl-paste in sway
12206873491ad7b05f57d66e55c5b61c
{ "intermediate": 0.3839714825153351, "beginner": 0.2065892368555069, "expert": 0.4094393253326416 }
34,820
translate my alacritty config to kitty config:
5bd242ed4a25f87f953411291c655c07
{ "intermediate": 0.3166626989841461, "beginner": 0.36483725905418396, "expert": 0.3185000717639923 }
34,821
AttributeError [2023-12-10 17:45:03,110: WARNING/MainProcess] : [2023-12-10 17:45:03,110: WARNING/MainProcess] module 'datetime' has no attribute 'now' how to resolve this
c56579047552271b157aa5ae5cca097c
{ "intermediate": 0.6339911818504333, "beginner": 0.17984625697135925, "expert": 0.18616251647472382 }
34,822
write me requirement specifications for ltc_ecc_projective_add_point() from libtom. Trace those requirements over source code
a91d4d7d1420008777551067f8288c91
{ "intermediate": 0.45791906118392944, "beginner": 0.13508300483226776, "expert": 0.4069979190826416 }
34,823
Create Table Student( StudentName Varchar(255), ID int auto_increment, Age int, Department varchar(255), Marks int Primary Key (ID)); what is error
68a820740cfb752a22558975dbb1865f
{ "intermediate": 0.3590720295906067, "beginner": 0.3260980546474457, "expert": 0.31482991576194763 }
34,824
import gradio as gr import mysql.connector from mysql.connector import Error # Function to format fetched data into an HTML table def format_data_as_table(data): if not data: return "<div style='color: red;'>No details found for the provided input.</div>" # Table style for formatting table_style = ( "<style>" "table { width: 100%; border-collapse: collapse; }" "th, td { border: 1px solid #dddddd; padding: 8px; text-align: left; }" "th { background-color: #f2f2f2; }" "tr:nth-child(even) { background-color: #f9f9f9; }" "</style>" ) # Create a table with headers headers = data[0].keys() table_html = table_style + "<table><tr>" + "".join([f"<th>{header}</th>" for header in headers]) + "</tr>" # Create rows for each record for record in data: row_html = "<tr>" + "".join([f"<td>{value}</td>" for value in record.values()]) + "</tr>" table_html += row_html table_html += "</table>" return table_html # Main function to fetch data from MySQL based on PR Number or Status def fetch_data(pr_number, status): connection = None try: connection = mysql.connector.connect( host='localhost', database='records', user='root', password='Nikki@1234' # Use a secure password retrieval method here ) if connection.is_connected(): cursor = connection.cursor(dictionary=True) # Determine whether to use PR Number or Status (using the one that’s not empty) if pr_number and not status: # Fetch by PR Number cursor.execute("SELECT * FROM pr_details WHERE PR_Number = %s", (pr_number,)) elif status and not pr_number: # Fetch by Status cursor.execute("SELECT * FROM pr_details WHERE Status = %s", (status,)) elif pr_number and status: # If both fields are provided, return an error message return "<div style='color: red;'>Please provide either PR Number or Status, not both.</div>" else: return "<div style='color: red;'>Please provide a PR Number or select a Status.</div>" data = cursor.fetchall() # Use the table format function to render results return format_data_as_table(data) except Error as e: return f"<div style='color: red;'>Error: {e}</div>" finally: if connection and connection.is_connected(): cursor.close() connection.close() print("MySQL connection closed.") # Gradio Interface with improvements iface = gr.Interface( fn=fetch_data, inputs=[ gr.Textbox(placeholder="Enter PR Number", label="PR Number"), gr.Radio(choices=['Submitted', 'Ordered', 'Composing'], label="Status", horizontal=True), gr.Button(value="Reset", style={"margin-left": "auto"}, variant="outline") # Reset button ], outputs=gr.HTML(label="Details"), # Output as HTML to allow for styling title="Purchase PO Automation Management System", live=False, # Submit button is used instead of live updates theme="compact", allow_flagging="never", css=''' .gradio-container { font-family: Arial, sans-serif; } .gradio-row { align-items: center; } .gradio-button { margin: 0; } ''' ) # Function to reset the inputs def reset_form(): return "", "Submitted" # Adjust the second return value according to your default status if necessary # Adding the reset action to a button press iface.add_component( value=reset_form, type="action", visible=True, component=iface.inputs[-1] # The reset button is the last input item ) # Launch the interface with remote access enabled iface.launch(share=True) getting below errors (venv) PS E:\BITS> & e:/BITS/venv/Scripts/python.exe e:/BITS/test2.py Traceback (most recent call last): File "e:\BITS\test2.py", line 77, in <module> gr.Radio(choices=['Submitted', 'Ordered', 'Composing'], label="Status", horizontal=True), ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\BITS\venv\Lib\site-packages\gradio\component_meta.py", line 155, in wrapper return fn(self, **kwargs) ^^^^^^^^^^^^^^^^^^ TypeError: Radio.__init__() got an unexpected keyword argument 'horizontal' (venv) PS E:\BITS>
0886cec9aa0b0e40babad378f05067e0
{ "intermediate": 0.42259612679481506, "beginner": 0.4077593982219696, "expert": 0.16964444518089294 }
34,825
in pandas what does the column keyword does
c3008d880d22240311ffe6c6e18c2add
{ "intermediate": 0.38108327984809875, "beginner": 0.2819203734397888, "expert": 0.3369963765144348 }
34,826
import gradio as gr import mysql.connector from mysql.connector import Error # Function to fetch data from MySQL based on PR Number or Status def fetch_data(pr_number, status): connection = None try: connection = mysql.connector.connect( host=‘localhost’, database=‘records’, user=‘root’, password=‘Nikki@1234’ # Use a secure password retrieval method here ) if connection.is_connected(): cursor = connection.cursor(dictionary=True) # Determine whether to use PR Number or Status (using the one that’s not empty) if pr_number and not status: # Fetch by PR Number cursor.execute(“SELECT * FROM pr_details WHERE PR_Number = %s”, (pr_number,)) elif status and not pr_number: # Fetch by Status cursor.execute(“SELECT * FROM pr_details WHERE Status = %s”, (status,)) elif pr_number and status: # If both fields are provided, return an error message return “<div style=‘color: red;’>Please provide either PR Number or Status, not both.</div>” else: return “<div style=‘color: red;’>Please provide a PR Number or select a Status.</div>” data = cursor.fetchall() if not data: return “<div style=‘color: red;’>No details found for the provided input.</div>” # Convert the data to a formatted string for Gradio output with HTML and inline styles for colors result = “<div style=‘color: green;’>” for record in data: result += “<br>”.join([f"<strong>{key}</strong>: {value}" for key, value in record.items()]) result += “<hr>” # Horizontal line to separate records result = result[:-4] # Remove the last <hr> result += “</div>” return result except Error as e: return f"<div style=‘color: red;’>Error: {e}</div>" finally: if connection and connection.is_connected(): cursor.close() connection.close() print(“MySQL connection closed.”) # Gradio Interface with a title iface = gr.Interface( fn=fetch_data, inputs=[ gr.Textbox(placeholder=“Enter PR Number”, label=“PR Number”), gr.Radio(choices=[‘Submitted’, ‘Ordered’, ‘Composing’], label=“Status”) # Status selection input ], outputs=gr.HTML(label=“Details”), # Output as HTML to allow for styling title=“Purchase PO Automation Management System”, # Added title here live=False, # Submit button is used instead of live updates theme=“compact” ) # Launch the interface with remote access enabled iface.launch(share=True) Please add a piechart which will show the no of submitted ,ordered and composing with different colours which will support my current gradio version 4.8.0
c10f6035e8042374d427a0d04bb082c4
{ "intermediate": 0.36434033513069153, "beginner": 0.32654818892478943, "expert": 0.30911147594451904 }
34,827
I need to write a requirements specification document for ltc_ecc_mul2add() from libtom. Write it for me and trace these requirements by commenting them over the source code
e3137191c3d8a3bd95d25adfc78b9d01
{ "intermediate": 0.4451589584350586, "beginner": 0.18174447119235992, "expert": 0.3730965852737427 }
34,828
Ihave this HTMLfor my webpage but it seems to be corrupted, can you help me restore it: org div class other project icon div class sprite svg wikisource to wikisource to wikisource to wikisource logo and div div div class other project text div class other project text span class other project title jsl10n data jsl10n wikisource name wikisource span span class other project tagline jsl10n data jsl10n slogan free library span div a div div class other project a class other project link href species wikimedia org div class other project icon div class sprite svg wikispecies logo sister div div div class other project text span class other project title jsl10n data jsl10n wikispecies name wikispecies span span class other project tagline jsl10n data jsl10n wikispecies slogan free species directory span div a div div class other project a class other project link href www wikifunctions org div class other project icon div class sprite svg wikifunctions logo sister div div div class other project text span class other project title jsl10n data jsl10n wikifunctions name wikifunctions span span class other project tagline jsl10n data jsl10n wikifunctions slogan free function library span div a div div class other project a class other project link href meta wikimedia org div class other project icon div class sprite svg meta wiki logo sister div div div class other project text span class other project title jsl10n data jsl10n name meta wiki span span class other project tagline jsl10n data jsl10n slogan community amp span div a div div div hr p class site license small class jsl10n data jsl10n license this page is available under the a href https org by sa 4 0 creative commons attribution license a small small class jsl10n data jsl10n terms a href https meta wikimedia org wiki terms of use terms of use a small small class jsl10n data jsl10n privacy policy a href https meta wikimedia org wiki privacy policy privacy policy a small p script var this is used to convert the generic portal keyword in the data jsl10n e g jsl10n portal footer description ' into a portal specific key e g wiki for the wikipedia portal the typeahead js feature is used for search and it uses domain name for searching we want domain name to be portal specific different for every portal so by in index we will make this portal specific this object is used by scripts page localized js localized js to the page content after json is loaded a timer is also set to prevent js from page content this script is inlined to script loading errors and at the top of the page to any html loading errors ready false function if ready ready true document body classname ' jsl10n window settimeout 1000 script script src portal wikipedia org assets js index js script if gt ie 9 script src portal wikipedia org assets js gt js script endif if ie 9 style styled select display block style endif if ie 9 style langlist ul text align center langlist ul li
86050ecc4e35b6d7e14265bd4b75c54e
{ "intermediate": 0.4124477505683899, "beginner": 0.41715681552886963, "expert": 0.1703953891992569 }
34,829
--miscellaneous és típusok import Data.List type Name = String type Health = Integer type Spell = (Integer -> Integer) type Army = [Unit] type EnemyArmy = Army type Amount = Integer showState a = show a showMage a = show a eqMage a b = a == b showUnit a = show a showOneVOne a = show a papi = let tunderpor enemyHP | enemyHP < 8 = 0 | even enemyHP = div (enemyHP * 3) 4 | otherwise = enemyHP - 3 in Master "Papi" 126 tunderpor java = Master "Java" 100 (\x -> x - (mod x 9)) traktor = Master "Traktor" 20 (\x -> div (x + 10) ((mod x 4) + 1)) jani = Master "Jani" 100 (\x -> x - div x 4) skver = Master "Skver" 100 (\x -> div (x+4) 2) potionMaster = let plx x | x > 85 = x - plx (div x 2) | x == 60 = 31 | x >= 51 = 1 + mod x 30 | otherwise = x - 7 in Master "PotionMaster" 170 plx --Első feladat (Felkészülés) data State unittype = Alive unittype | Dead deriving(Eq) data Entity = Golem Health | HaskellElemental Health deriving (Show) data Mage = Master Name Health Spell data Unit = E (State Entity) | M (State Mage) deriving(Eq) instance Show unittype => Show (State unittype) where show (Alive a) = show a show Dead = "Dead" instance Show Mage where show (Master name health _) | health >= 5 = name | otherwise = "Wounded " ++ name instance Eq Mage where (Master name1 health1 _) == (Master name2 health2 _) = (name1 == name2) && (health1 == health2) instance Show Unit where show (E stateEntity) = case stateEntity of Alive entity -> case entity of Golem health -> "Golem " ++ show health HaskellElemental health -> "HaskellElemental " ++ show health Dead -> "Dead" show (M stateMage) = case stateMage of Alive mage -> showMage mage Dead -> "Dead" instance Eq Entity where (Golem health1) == (Golem health2) = health1 == health2 (HaskellElemental health1) == (HaskellElemental health2) = health1 == health2 _ == _ = False --Második feladat (Elesettek) formationFix :: Army -> Army formationFix army = filter isAlive army ++ filter isDead army where isAlive (E (Alive _)) = True isAlive (M (Alive _)) = True isAlive _ = False isDead = not . isAlive --Harmadik feladat (Vége?) over :: Army -> Bool over = all temp temp :: Unit -> Bool temp (E Dead) = True temp (M Dead) = True temp _ = False --Negyedik feladat (Ütközet) fight :: EnemyArmy -> Army -> Army fight [] army = army fight army [] = army fight (mage@(M (Alive (Master _ _ spell))):enemies) allies = let updatedEnemies = applyMageAbility spell enemies in fight updatedEnemies allies fight (E (Alive (HaskellElemental _)):hs) (E (Alive (Golem h)):gs) = let damagedGolem = E (Alive (Golem (if h >= 3 then h - 3 else 0))) in damagedGolem : fight hs gs fight (_:hs) (_:gs) = fight hs gs applyMageAbility :: Spell -> EnemyArmy -> EnemyArmy applyMageAbility _ [] = [] applyMageAbility spell (enemy@(E (Alive (Golem h))):enemies) = let updatedEnemy = attackMage enemy spell in updatedEnemy : applyMageAbility spell enemies applyMageAbility spell (enemy@(E (Alive (HaskellElemental h))):enemies) = let updatedEnemy = attackMage enemy spell in updatedEnemy : applyMageAbility spell enemies applyMageAbility _ enemies = enemies attackMage :: Unit -> Spell -> Unit attackMage (E (Alive (Golem h))) spell = E (Alive (Golem (if h >= damage then h - damage else 0))) where damage = spell h attackMage (E (Alive (HaskellElemental h))) spell = E (Alive (HaskellElemental (if h >= damage then h - damage else 0))) where damage = spell h attackMage enemy _ = enemy
3cd58e8f0ae839f5601af39c4f51645b
{ "intermediate": 0.3585797846317291, "beginner": 0.4378419816493988, "expert": 0.20357823371887207 }
34,830
can you write the code for a new shopify section based on this liquid code but adding a video background? also if possible it would be great if we could update the video file directly from the shopify theme editor? {{ 'section-image-banner.css' | asset_url | stylesheet_tag }} {{ 'component-newsletter.css' | asset_url | stylesheet_tag }} {{ 'newsletter-section.css' | asset_url | stylesheet_tag }} {{ 'section-email-signup-banner.css' | asset_url | stylesheet_tag }} {%- style -%} #Banner-{{ section.id }} { background-image: url('{{ section.settings.image | img_url: 'background-signup-banner.png' }}'); /* Additional styles for the background, such as background-size, background-position, etc., can be added here */ } #Banner-{{ section.id }}::after { opacity: {{ section.settings.image_overlay_opacity | divided_by: 100.0 }}; } {%- if section.settings.image_height == 'adapt-image' and section.settings.image != blank -%} @media screen and (max-width: 990px) { #Banner-{{ section.id }}:not(.banner--mobile-bottom) .banner__content::before { padding-bottom: {{ 1 | divided_by: section.settings.image.aspect_ratio | times: 100 }}%; content: ''; display: block; } } #Banner-{{ section.id }}::before, #Banner-{{ section.id }} .banner__media::before { padding-bottom: {{ 1 | divided_by: section.settings.image.aspect_ratio | times: 100 }}%; content: ''; display: block; } {%- endif -%} {%- endstyle -%} <div id="Banner-{{ section.id }}" class="email-signup-banner banner banner--content-align-{{ section.settings.desktop_content_alignment }} banner--content-align-mobile-{{ section.settings.mobile_content_alignment }} banner--{{ section.settings.image_height }}{% if section.settings.image_height == 'adapt-image' and section.settings.image != blank %} banner--adapt{% endif %}{% if section.settings.show_text_below %} banner--mobile-bottom{%- endif -%}{% if section.settings.show_text_box == false %} banner--desktop-transparent{% endif %}" > <div class="banner__content banner__content--{{ section.settings.desktop_content_position }} page-width"> <div class="email-signup-banner__box banner__box newsletter newsletter__wrapper isolate{% if section.settings.show_background_image == false %} email-signup-banner__box--no-image{% endif %} content-container color-{{ section.settings.color_scheme }} gradient content-container--full-width-mobile"> {%- for block in section.blocks -%} {%- case block.type -%} {%- when 'heading' -%} <h2 class="email-signup-banner__heading {{ block.settings.heading_size }}" {{ block.shopify_attributes }}> {{ block.settings.heading | escape }} </h2> {%- when 'paragraph' -%} <div class="newsletter__subheading rte {{ block.settings.text_style }}" {{ block.shopify_attributes }}> {{ block.settings.text }} </div> {%- when 'email_form' -%} <div {{ block.shopify_attributes }}> {% form 'customer', class: 'newsletter-form' %} <input type="hidden" name="contact[tags]" value="newsletter"> <div class="newsletter-form__field-wrapper"> <div class="field"> <input id="NewsletterForm--{{ section.id }}" type="email" name="contact[email]" class="field__input" value="{{ form.email }}" aria-required="true" autocorrect="off" autocapitalize="off" autocomplete="email" {% if form.errors %} autofocus aria-invalid="true" aria-describedby="Newsletter-error--{{ section.id }}" {% elsif form.posted_successfully? %} aria-describedby="Newsletter-success--{{ section.id }}" {% endif %} placeholder="{{ 'newsletter.label' | t }}" required > <label class="field__label" for="NewsletterForm--{{ section.id }}"> {{ 'newsletter.label' | t }} </label> <button type="submit" class="newsletter-form__button field__button" name="commit" id="Subscribe" aria-label="{{ 'newsletter.button_label' | t }}" > {% render 'icon-arrow' %} </button> </div> {%- if form.errors -%} <small class="newsletter-form__message form__message" id="Newsletter-error--{{ section.id }}"> {%- render 'icon-error' -%} {{- form.errors.translated_fields.email | capitalize }} {{ form.errors.messages.email -}} </small> {%- endif -%} </div> {%- if form.posted_successfully? -%} <h3 class="newsletter-form__message newsletter-form__message--success form__message" id="Newsletter-success--{{ section.id }}" tabindex="-1" autofocus > {% render 'icon-success' -%} {{- 'newsletter.success' | t }} </h3> {%- endif -%} {% endform %} </div> {%- endcase -%} {%- endfor -%} </div> </div> </div> {% schema %} { "name": "t:sections.email-signup-banner.name", "tag": "section", "class": "section", "settings": [ { "type": "paragraph", "content": "t:sections.email-signup-banner.settings.paragraph.content" }, { "type": "image_picker", "id": "image", "label": "t:sections.email-signup-banner.settings.image.label" }, { "type": "range", "id": "image_overlay_opacity", "min": 0, "max": 100, "step": 10, "unit": "%", "label": "t:sections.email-signup-banner.settings.image_overlay_opacity.label", "default": 0 }, { "type": "checkbox", "id": "show_background_image", "label": "t:sections.email-signup-banner.settings.show_background_image.label", "default": true }, { "type": "select", "id": "image_height", "options": [ { "value": "adapt-image", "label": "t:sections.email-signup-banner.settings.image_height.options__1.label" }, { "value": "small", "label": "t:sections.email-signup-banner.settings.image_height.options__2.label" }, { "value": "medium", "label": "t:sections.email-signup-banner.settings.image_height.options__3.label" }, { "value": "large", "label": "t:sections.email-signup-banner.settings.image_height.options__4.label" } ], "default": "medium", "label": "t:sections.email-signup-banner.settings.image_height.label", "info": "t:sections.email-signup-banner.settings.image_height.info" }, { "type": "select", "id": "desktop_content_position", "options": [ { "value": "top-left", "label": "t:sections.email-signup-banner.settings.desktop_content_position.options__1.label" }, { "value": "top-center", "label": "t:sections.email-signup-banner.settings.desktop_content_position.options__2.label" }, { "value": "top-right", "label": "t:sections.email-signup-banner.settings.desktop_content_position.options__3.label" }, { "value": "middle-left", "label": "t:sections.email-signup-banner.settings.desktop_content_position.options__4.label" }, { "value": "middle-center", "label": "t:sections.email-signup-banner.settings.desktop_content_position.options__5.label" }, { "value": "middle-right", "label": "t:sections.email-signup-banner.settings.desktop_content_position.options__6.label" }, { "value": "bottom-left", "label": "t:sections.email-signup-banner.settings.desktop_content_position.options__7.label" }, { "value": "bottom-center", "label": "t:sections.email-signup-banner.settings.desktop_content_position.options__8.label" }, { "value": "bottom-right", "label": "t:sections.email-signup-banner.settings.desktop_content_position.options__9.label" } ], "default": "middle-center", "label": "t:sections.email-signup-banner.settings.desktop_content_position.label" }, { "type": "checkbox", "id": "show_text_box", "default": true, "label": "t:sections.email-signup-banner.settings.show_text_box.label" }, { "type": "select", "id": "desktop_content_alignment", "options": [ { "value": "left", "label": "t:sections.email-signup-banner.settings.desktop_content_alignment.options__1.label" }, { "value": "center", "label": "t:sections.email-signup-banner.settings.desktop_content_alignment.options__2.label" }, { "value": "right", "label": "t:sections.email-signup-banner.settings.desktop_content_alignment.options__3.label" } ], "default": "center", "label": "t:sections.email-signup-banner.settings.desktop_content_alignment.label" }, { "type": "color_scheme", "id": "color_scheme", "label": "t:sections.all.colors.label", "info": "t:sections.email-signup-banner.settings.color_scheme.info", "default": "background-1" }, { "type": "header", "content": "t:sections.email-signup-banner.settings.header.content" }, { "type": "select", "id": "mobile_content_alignment", "options": [ { "value": "left", "label": "t:sections.email-signup-banner.settings.mobile_content_alignment.options__1.label" }, { "value": "center", "label": "t:sections.email-signup-banner.settings.mobile_content_alignment.options__2.label" }, { "value": "right", "label": "t:sections.email-signup-banner.settings.mobile_content_alignment.options__3.label" } ], "default": "center", "label": "t:sections.email-signup-banner.settings.mobile_content_alignment.label" }, { "type": "checkbox", "id": "show_text_below", "default": true, "label": "t:sections.email-signup-banner.settings.show_text_below.label" } ], "blocks": [ { "type": "heading", "name": "t:sections.email-signup-banner.blocks.heading.name", "limit": 1, "settings": [ { "type": "text", "id": "heading", "default": "Opening soon", "label": "t:sections.email-signup-banner.blocks.heading.settings.heading.label" }, { "type": "select", "id": "heading_size", "options": [ { "value": "h2", "label": "t:sections.all.heading_size.options__1.label" }, { "value": "h1", "label": "t:sections.all.heading_size.options__2.label" }, { "value": "h0", "label": "t:sections.all.heading_size.options__3.label" } ], "default": "h1", "label": "t:sections.all.heading_size.label" } ] }, { "type": "paragraph", "name": "t:sections.email-signup-banner.blocks.paragraph.name", "limit": 1, "settings": [ { "type": "richtext", "id": "text", "default": "<p>Be the first to know when we launch.</p>", "label": "t:sections.email-signup-banner.blocks.paragraph.settings.paragraph.label" }, { "type": "select", "id": "text_style", "options": [ { "value": "body", "label": "t:sections.email-signup-banner.blocks.paragraph.settings.text_style.options__1.label" }, { "value": "subtitle", "label": "t:sections.email-signup-banner.blocks.paragraph.settings.text_style.options__2.label" } ], "default": "body", "label": "t:sections.email-signup-banner.blocks.paragraph.settings.text_style.label" } ] }, { "type": "email_form", "name": "t:sections.email-signup-banner.blocks.email_form.name", "limit": 1 } ], "presets": [ { "name": "t:sections.email-signup-banner.presets.name", "blocks": [ { "type": "heading" }, { "type": "paragraph" }, { "type": "email_form" } ] } ], "templates": ["password"] } {% endschema %}
2617caafcd87b74acc8ea48d00d0cb66
{ "intermediate": 0.33618220686912537, "beginner": 0.4028516113758087, "expert": 0.2609661817550659 }
34,831
import mysql.connector from mysql.connector import Error import numpy as np import pandas as pd import chardet as cd try: #Establish connection connection = mysql.connector.connect(host = 'localhost', user = 'root', password = '123456', database = 'world') if connection.is_connected(): cursor = connection.cursor() cursor.execute('select * from city') #fetch all record for the executed query record = cursor.fetchall() column_names = [desc[0] for desc in cursor.description] # Creating source dataframe df_source = pd.DataFrame(record,columns = column_names) # converting NaN to 'Empty' for col in df_source.columns: df_source[col].replace({'':'Empty',np.nan:'Empty'},inplace = True) # Detecting the encoding type with open('city_target.csv','rb') as file: encoding_type = cd.detect(file.read())['encoding'] df_target = pd.read_csv('city_target.csv',delimiter = ',',encoding=encoding_type) # converting NaN to 'Empty' for col in df_target.columns: df_target[col].replace({'':'Empty',np.nan:'Empty','None':'Empty'},inplace = True) # Compare data Comparing_data = {columns:(df_source[columns] == df_target[columns]) for columns in df_source.columns} comparison_result = pd.DataFrame(Comparing_data) # comparison_result = pd.merge(df_source, df_target, how='outer', indicator=True)#.loc[lambda x: x['_merge'] != 'both'] # Write the comparison result to an Excel file comparison_result.to_excel('comparison.xlsx',index = False) print("Comparison completed. Results saved to",'D:\VS Code programs\Data validator') except Error as e: print('while connecting to sql:',e) finally: # Close the connection if connection.is_connected(): cursor.close() connection.close() print('MySQL connection is closed')
0fc2ad3ebea349b206b17b6292af4c45
{ "intermediate": 0.6163052320480347, "beginner": 0.23081547021865845, "expert": 0.15287932753562927 }
34,832
hey, this is the liquid code of my shopify section, it looks good on dekstop but not on mobile, can you check ? the text box and the email form should be aligned (text on top, form bottom) and appear over video background: <style> body.template-index .main-content .videoBackground { margin-top: -55px; } .videoBackground { position: relative; } .videoBackground .fullscreen-video-wrap { position: absolute; top: 0; left: 0; min-width: 100%; width: 100%; height: 100%; overflow: hidden; } .videoBackground .fullscreen-video-wrap .video-js { position: absolute; top: 0; left: 0; min-height: 100%; min-width: 100%; width: 100%; height: 100%; object-fit: cover; } .videoBackground .fullscreen-video-wrap video { min-height: 100%; min-width: 100%; object-fit: cover; } .videoBackground .videoBox { position: relative; } .videoBackground .imageBox { display: flex; align-items: center; justify-content: flex-end; flex-direction: column; padding: 100px 20px 80px; background-size: cover; background-position: center; background-repeat: no-repeat; position: relative; min-height: calc(100vh - 165px); height: auto; } .videoBackground .videoBoxInfo, .videoBackground .imageBoxInfo { z-index: 2; text-align: center; } .videoBackground .overlay { content: ""; position: absolute; top: 0; right: 0; bottom: 0; left: 0; background: #000; z-index: 1; opacity: 0; /* Added for overlay */ } .videoBackground .videoBoxInfoBtn, .videoBackground .imageBoxInfoBtn { -moz-user-select: none; -ms-user-select: none; -webkit-user-select: none; user-select: none; -webkit-appearance: none; -moz-appearance: none; appearance: none; display: inline-block; width: auto; text-decoration: none; text-align: center; vertical-align: middle; cursor: pointer; border: 1px solid transparent; border-radius: 2px; padding: 8px 15px; font-style: normal; font-weight: 800; text-transform: uppercase; letter-spacing: 0.06em; white-space: normal; font-size: 14px; margin-top: 20px; } .videoBackground .videoBoxInfoTitle, .videoBackground .imageBoxInfoTitle { color: #FFF; font-size: 30px; line-height: 40px; } .videoBackground .videoBoxInfoDescription, .videoBackground .imageBoxInfoDescription { max-width: 500px; margin: 0 auto; } .videoBackground .videoBoxInfoDescription p, .videoBackground .imageBoxInfoDescription p { font-size: 18px; line-height: 28px; color: #FFF; /* Added text color */ } .videoBackground .newsletter__subheading { font-size: 16px; margin-bottom: 20px; } .videoBackground .newsletter-form__field-wrapper { display: flex; justify-content: center; align-items: center; flex-wrap: wrap; } .videoBackground .field { margin: 0 10px; } @media screen and (max-width: 767px) { body.template-index .main-content .videoBackground { margin-top: -35px; } .videoBackground .fullscreen-video-wrap { z-index: 3; } .videoBackground .videoBox { min-height: 500px; height: 100%; position: relative; padding: 0; } .videoBackground .fullscreen-video-wrap { position: relative; min-height: 300px; } .videoBackground .videoBoxInfo { padding: 40px 20px; background: #000; width: 100%; } } .videoBackground { display: flex; flex-direction: column; background-color: transparent; @media (max-width: 768px) { flex-direction: row; } } .videoBackground .videoBox { background-color: transparent; width: 100%; margin: 0 auto; .videoBoxInfo { position: relative; text-align: center; @media (max-width: 990px) { position: absolute; top: 10px; left: 10px; } } } .videoBackground .videoBoxInfo { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 2; text-align: center; } @media (max-width: 990px) { .videoBackground .videoBoxInfo { top: 10px; left: 10px; } } .videoBackground .overlay { content: ""; position: absolute; top: 0; right: 0; bottom: 0; left: 0; background: #000; z-index: 1; opacity: 0.5; } .videoBackground .videoBoxInfoBtn, .videoBackground .imageBoxInfoBtn { -moz-user-select: none; -ms-user-select: none; -webkit-user-select: none; user-select: none; -webkit-appearance: none; -moz-appearance: none; appearance: none; display: inline-block; width: auto; text-decoration: none; text-align: center; vertical-align: middle; cursor: pointer; border: 1px solid transparent; border-radius: 2px; padding: 8px 15px; font-style: normal; font-weight: 800; text-transform: uppercase; letter-spacing: 0.06em; white-space: normal; font-size: 14px; margin-top: 20px; } .videoBackground .videoBoxInfoTitle, .videoBackground .imageBoxInfoTitle { color: #FFF; font-size: 30px; line-height: 40px; } .videoBackground .videoBoxInfoDescription, .videoBackground .imageBoxInfoDescription { max-width: 500px; margin: 0 auto; } .videoBackground .videoBoxInfoDescription p, .videoBackground .imageBoxInfoDescription p { font-size: 18px; line-height: 28px; color: #FFF; } .videoBackground .emailBox { position: absolute; top: 0; left: 0; right: 0; background-color: transparent; padding: 20px; z-index: 10; @media (max-width: 768px) { width: 100%; padding: 0 20px; } } .videoBackground .emailBoxForm { display: flex; justify-content: center; align-items: center; } .videoBackground .emailBoxForm input[type="email"] { width: 100%; padding: 10px; border: 1px solid #ccc; } .videoBackground .emailBoxForm button { margin-left: 10px; padding: 10px; border: none; background-color: #000; color: #fff; } </style> {% schema %} { "name": "Video Background", "tag": "section", "class": "videoBackground", "settings": [ { "type": "checkbox", "id": "show_video_controls", "default": true, "label": "Show Video Controls" }, { "type": "select", "id": "video_alignment", "options": [ { "value": "left", "label": "Left" }, { "value": "center", "label": "Center" }, { "value": "right", "label": "Right" } ], "default": "center", "label": "Video Alignment" } ], "blocks": [ { "type": "video", "name": "Video Block", "limit": 1, "settings": [ { "type": "url", "id": "video_link", "label": "Video Link" }, { "type": "image_picker", "id": "video_image", "label": "Video Image" }, { "type": "range", "id": "overlay_opacity", "label": "Overlay Opacity", "min": 0, "max": 99, "step": 1, "unit": "%", "default": 0 }, { "type": "header", "content": "Text" }, { "type": "text", "id": "title", "label": "Title", "default": "Video Slide" }, { "type": "richtext", "id": "text", "label": "Text Description", "default": "<p>Use this text to share information about your brand with your customers. Describe a product, share announcements, or welcome customers to your store.</p>" }, { "type": "color", "id": "color_text", "label": "Text Color", "default": "#ffffff" }, { "type": "text", "id": "button_label", "label": "Button Label" }, { "type": "url", "id": "button_link", "label": "Button Link" }, { "type": "color", "id": "color_btn_bg", "label": "Button Background Color", "default": "#ffffff" }, { "type": "color", "id": "color_btn_text", "label": "Button Text Color", "default": "#ffffff" } ] }, { "type": "email_form", "name": "Email Form Block", "limit": 1, "settings": [ { "type": "checkbox", "id": "show_title", "default": true, "label": "Show Title" }, { "type": "text", "id": "title", "default": "Subscribe to Our Newsletter", "label": "Title" }, { "type": "richtext", "id": "text", "label": "Text Description" }, { "type": "url", "id": "button_link", "label": "Button Link" }, { "type": "text", "id": "button_label", "label": "Button Label" }, { "type": "color", "id": "color_text", "label": "Text Color" }, { "type": "color", "id": "color_btn_text", "label": "Button Text Color" }, { "type": "color", "id": "color_btn_bg", "label": "Button Background Color" } ] } ], "presets": [ { "name": "Video Background", "category": "Main", "blocks": [ { "type": "video" } ] } ] } {% endschema %}
1bc33d89cab6d2433a69507dc56036f5
{ "intermediate": 0.4732552468776703, "beginner": 0.25453507900238037, "expert": 0.27220970392227173 }
34,834
import gradio as gr import mysql.connector from mysql.connector import Error import matplotlib.pyplot as plt # Assume fetch_data function is defined properly def fetch_data(pr_number, status): # Your existing fetch_data implementation pass # Plotting pie chart for PR Status counts def plot_pie_chart(): try: connection = mysql.connector.connect( host='localhost', database='records', user='root', password='Nikki@1234' # Insert your correct password ) if connection.is_connected(): cursor = connection.cursor() cursor.execute("SELECT Status, COUNT(Status) FROM pr_details GROUP BY Status") result = cursor.fetchall() labels = [i[0] for i in result] sizes = [i[1] for i in result] cursor.close() connection.close() plt.figure(figsize=(8, 6)) plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=140) plt.axis('equal') return plt.gcf() except Error as e: print(f"Error: {e}") return plt.figure() # Return an empty figure in case of an error # Combined callback function for both fetch_data and plot_pie_chart def combined_callback(pr_number, status): details = fetch_data(pr_number, status) pie_chart = plot_pie_chart() if not pr_number and not status else None return details, pie_chart # Gradio Interface iface = gr.Interface( fn=combined_callback, inputs=[ gr.Textbox(placeholder="Enter PR Number", label="PR Number"), gr.Radio(choices=['Submitted', 'Ordered', 'Composing'], label="Status", type="value", default=None) ], outputs=[ gr.HTML(label="Details"), gr.Plot(label="Status Pie Chart") # Plot component to display the pie chart ], title="Purchase PO Automation Management System", live=False ) iface.launch(port=3306, share=True)
3273842f80ce2556422564663d752ea9
{ "intermediate": 0.5172383785247803, "beginner": 0.27789345383644104, "expert": 0.2048681527376175 }
34,835
hi
927d064c6fe0ad6ef1137e92581640a2
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
34,836
give me an r code to train ai to classify alzheimer patients based on mta score
98704a2a5d835b12fc6e958e9bc3df67
{ "intermediate": 0.18770140409469604, "beginner": 0.03910909965634346, "expert": 0.7731894850730896 }
34,837
import gradio as gr import mysql.connector from mysql.connector import Error import matplotlib.pyplot as plt def fetch_data(pr_number, status): try: connection = mysql.connector.connect( host='localhost', database='records', user='root', password='Nikki@1234' # Use your actual password and manage it securely ) query = "SELECT * FROM PR_Details WHERE TRUE" params = [] if pr_number: query += " AND PR_Number = %s" params.append(pr_number) if status: query += " AND Current_Status = %s" params.append(status) cursor = connection.cursor(dictionary=True) # Fetch results as dictionaries cursor.execute(query, params) records = cursor.fetchall() # Build HTML output details_html = "<div class='pr_record'><table>" for record in records: for column, value in record.items(): details_html += f"<tr><td><strong>{column}:</strong></td><td>{value}</td></tr>" details_html += "</table></div><br>" if not records: # If no records found details_html = "No matching records found." except Error as e: print(f"Error: {e}") details_html = "Failed to fetch data due to a database error." finally: if connection and connection.is_connected(): cursor.close() connection.close() return details_html def plot_pie_chart(): try: connection = mysql.connector.connect( host='localhost', database='records', user='root', password='Nikki@1234' # Placeholder for your password ) if connection.is_connected(): cursor = connection.cursor() cursor.execute("SELECT Status, COUNT(Status) FROM pr_details GROUP BY Status") result = cursor.fetchall() labels = [i[0] for i in result] sizes = [i[1] for i in result] cursor.close() connection.close() plt.figure(figsize=(8, 6)) plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=140) plt.axis('equal') return plt.gcf() except Error as e: print(f"Database Error: {e}") return plt.figure() def combined_callback(pr_number, status): details = fetch_data(pr_number, status) if pr_number else "Please enter a PR number to fetch details." pie_chart = plot_pie_chart() if not pr_number and not status else None return details, pie_chart iface = gr.Interface( fn=combined_callback, inputs=[ gr.Textbox(label="PR Number"), gr.Radio(choices=['Submitted', 'Ordered', 'Composing'], label="Status") ], outputs=[gr.HTML(label="Details"), gr.Plot(label="Status Pie Chart")], title="Purchase PO Automation Management System", live=False, theme="compact" ) iface.launch(share=True) The pie chart should be independent pie chart which shows the status of all the details present in the pr_details table. It should show the live pie chart when I open the link.
2d250434283cc1464de44a0f0ae880b9
{ "intermediate": 0.3614625334739685, "beginner": 0.5577812194824219, "expert": 0.08075625449419022 }