row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
3,614
ارجوا تعديل هذا الكود ليعمل بطريقه صحيحه وربط الاجزاء بعضها ببعض ليكون مثالي class MainActivity : AppCompatActivity() { private lateinit var player: SimpleExoPlayer private lateinit var playButton: Button private lateinit var lyricsTextView: TextView private lateinit var startRecordingButton: Button private lateinit var stopRecordingButton: Button private var mediaRecorder: MediaRecorder? = null private lateinit var outputFilePath: String private val lyricsHandler = Handler(Looper.getMainLooper()) private lateinit var lyricsRunnable: Runnable private var mediaPlayer: MediaPlayer? = null private lateinit var playRecordingButton: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) playButton = findViewById(R.id.playButton) lyricsTextView = findViewById(R.id.lyricsTextView) startRecordingButton = findViewById(R.id.startRecordingButton) stopRecordingButton = findViewById(R.id.stopRecordingButton) playButton.setOnClickListener { initializePlayer() displayLyrics() } startRecordingButton.setOnClickListener { requestAudioPermissionAndStartRecording() } stopRecordingButton.setOnClickListener { stopRecording() } playRecordingButton = findViewById(R.id.playRecordingButton) playRecordingButton.setOnClickListener { playRecording() } val soundEffectsButton1 = findViewById<Button>(R.id.soundEffectButton1) val soundEffectsButton2 = findViewById<Button>(R.id.soundEffectButton2) soundEffectsButton1.setOnClickListener { applySoundEffect1() } soundEffectsButton2.setOnClickListener { applySoundEffect2() } } private fun initializePlayer() { player = SimpleExoPlayer.Builder(this).build() val dataSourceFactory = DefaultDataSourceFactory( this, Util.getUserAgent(this, “KaraokeApp”) ) val mediaSource = ProgressiveMediaSource.Factory(dataSourceFactory) .createMediaSource(Uri.parse(“https://directsendwhats.xyz/background_music.mp3”)) player.setMediaSource(mediaSource) player.prepare() player.playWhenReady = true } private fun displayLyrics() { scheduleLyricsUpdate() } private fun scheduleLyricsUpdate() { lyricsRunnable = Runnable { updateLyrics() lyricsHandler.postDelayed(lyricsRunnable, 1000) // جدولة التحديث كل ثانية } lyricsHandler.post(lyricsRunnable) } private fun updateLyrics() { val currentPosition = player.currentPosition // استخدم currentPosition لتحديد الجزء المناسب من كلمات الأغنية // وقم بتحديث lyricsTextView بناءً على ذلك } private fun requestAudioPermissionAndStartRecording() { if (ContextCompat.checkSelfPermission( this, android.Manifest.permission.RECORD_AUDIO ) != PackageManager.PERMISSION_GRANTED ) { ActivityCompat.requestPermissions( this, arrayOf(android.Manifest.permission.RECORD_AUDIO), RECORD_AUDIO_REQUEST_CODE ) } else { startRecording() } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == RECORD_AUDIO_REQUEST_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { startRecording() } else { // الإذن مرفوض، يمكنك إظهار رسالة توضيحية هنا } } } private fun startRecording() { outputFilePath = “${getExternalFilesDir(Environment.DIRECTORY_MUSIC)?.absolutePath}/recording.3gp” mediaRecorder = MediaRecorder().apply { setAudioSource(MediaRecorder.AudioSource.MIC) setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP) setOutputFile(outputFilePath) setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB) try { prepare() } catch (e: IOException) { e.printStackTrace() } start() } } private fun stopRecording() { mediaRecorder?.apply { stop() release() } mediaRecorder = null } override fun onStop() { super.onStop() lyricsHandler.removeCallbacks(lyricsRunnable) releasePlayer() mediaRecorder?.apply { stop() release() } mediaRecorder = null mediaPlayer?.apply { stop() release() } mediaPlayer = null } private fun releasePlayer() { if (::player.isInitialized) { player.release() } } companion object { private const val RECORD_AUDIO_REQUEST_CODE = 200 } // تطبيق التأثيرات الصوتية private fun applySoundEffect1() { if (outputFilePath.isNotEmpty()) { mediaPlayer = MediaPlayer().apply { try { setDataSource(outputFilePath) val effect = PresetReverb(1, 0).apply { preset = PresetReverb.PRESET_LARGEROOM } setAuxEffectSendLevel(1f) attachAuxEffect(effect.id) prepare() start() setOnCompletionListener { setAuxEffectSendLevel(0f) attachAuxEffect(0) effect.release() } } catch (e: IOException) { e.printStackTrace() } } } } private fun applySoundEffect2() { if (outputFilePath.isNotEmpty()) { mediaPlayer = MediaPlayer().apply { try { setDataSource(outputFilePath) val effect = BassBoost(1, 0).apply { setStrength(500) } setAuxEffectSendLevel(1f) attachAuxEffect(effect.id) prepare() start() setOnCompletionListener { setAuxEffectSendLevel(0f) attachAuxEffect(0) effect.release() } } catch (e: IOException) { e.printStackTrace() } } } } // تشغيل التسجيل private fun playRecording() { if (outputFilePath.isNotEmpty()) { mediaPlayer = MediaPlayer().apply { try { setDataSource(outputFilePath) prepare() start() } catch (e: IOException) { e.printStackTrace() } } } } }
2f45cabe0fa658c854971402e851c84f
{ "intermediate": 0.29472148418426514, "beginner": 0.4478877782821655, "expert": 0.25739070773124695 }
3,615
explain some approaches in formal verification that are based on explicit-value analysis
deddb5ac25f76ebd4c8b25ef6bae8e50
{ "intermediate": 0.31498926877975464, "beginner": 0.3037436604499817, "expert": 0.38126710057258606 }
3,616
في هذا الكود class MainActivity : AppCompatActivity() { private lateinit var player: SimpleExoPlayer private lateinit var playButton: Button private lateinit var lyricsTextView: TextView private lateinit var startRecordingButton: Button private lateinit var stopRecordingButton: Button private var mediaRecorder: MediaRecorder? = null private lateinit var outputFilePath: String private val lyricsHandler = Handler(Looper.getMainLooper()) private lateinit var lyricsRunnable: Runnable private var mediaPlayer: MediaPlayer? = null private lateinit var playRecordingButton: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) playButton = findViewById(R.id.playButton) lyricsTextView = findViewById(R.id.lyricsTextView) startRecordingButton = findViewById(R.id.startRecordingButton) stopRecordingButton = findViewById(R.id.stopRecordingButton) playButton.setOnClickListener { initializePlayer() displayLyrics() } startRecordingButton.setOnClickListener { requestAudioPermissionAndStartRecording() } stopRecordingButton.setOnClickListener { stopRecording() } playRecordingButton = findViewById(R.id.playRecordingButton) playRecordingButton.setOnClickListener { playRecording() } val soundEffectsButton1 = findViewById<Button>(R.id.soundEffectButton1) val soundEffectsButton2 = findViewById<Button>(R.id.soundEffectButton2) soundEffectsButton1.setOnClickListener { applySoundEffect1() } soundEffectsButton2.setOnClickListener { applySoundEffect2() } } private fun initializePlayer() { player = SimpleExoPlayer.Builder(this).build() val dataSourceFactory = DefaultDataSourceFactory( this, Util.getUserAgent(this, "KaraokeApp") ) val mediaSource = ProgressiveMediaSource.Factory(dataSourceFactory) .createMediaSource(Uri.parse("https://directsendwhats.xyz/background_music.mp3")) player.setMediaSource(mediaSource) player.prepare() player.playWhenReady = true } private fun displayLyrics() { scheduleLyricsUpdate() } private fun scheduleLyricsUpdate() { lyricsRunnable = Runnable { updateLyrics() lyricsHandler.postDelayed(lyricsRunnable, 1000) // جدولة التحديث كل ثانية } lyricsHandler.post(lyricsRunnable) } private fun updateLyrics() { val currentPosition = player.currentPosition // استخدم currentPosition لتحديد الجزء المناسب من كلمات الأغنية // وقم بتحديث lyricsTextView بناءً على ذلك } private fun requestAudioPermissionAndStartRecording() { if (ContextCompat.checkSelfPermission( this, android.Manifest.permission.RECORD_AUDIO ) != PackageManager.PERMISSION_GRANTED ) { ActivityCompat.requestPermissions( this, arrayOf(android.Manifest.permission.RECORD_AUDIO), RECORD_AUDIO_REQUEST_CODE ) } else { startRecording() } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == RECORD_AUDIO_REQUEST_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { startRecording() } else { // الإذن مرفوض، يمكنك إظهار رسالة توضيحية هنا } } } private fun startRecording() { outputFilePath = "${getExternalFilesDir(Environment.DIRECTORY_MUSIC)?.absolutePath}/recording.3gp" mediaRecorder = MediaRecorder().apply { setAudioSource(MediaRecorder.AudioSource.MIC) setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP) setOutputFile(outputFilePath) setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB) try { prepare() } catch (e: IOException) { e.printStackTrace() } start() } } private fun stopRecording() { mediaRecorder?.apply { stop() release() player.stop() } mediaRecorder = null } override fun onStop() { super.onStop() lyricsHandler.removeCallbacks(lyricsRunnable) releasePlayer() mediaRecorder?.apply { stop() release() } mediaRecorder = null mediaPlayer?.apply { stop() release() } mediaPlayer = null } private fun releasePlayer() { if (::player.isInitialized) { player.release() } } companion object { private const val RECORD_AUDIO_REQUEST_CODE = 200 } private fun applySoundEffect1() { if (outputFilePath.isNotEmpty()) { mediaPlayer = MediaPlayer().apply { try { setDataSource(outputFilePath) val effect = PresetReverb(1, 0).apply { preset = PresetReverb.PRESET_LARGEROOM } setAuxEffectSendLevel(1f) attachAuxEffect(effect.id) prepare() start() setOnCompletionListener { setAuxEffectSendLevel(0f) attachAuxEffect(0) effect.release() } } catch (e: IOException) { e.printStackTrace() } } } } private fun applySoundEffect2() { if (outputFilePath.isNotEmpty()) { mediaPlayer = MediaPlayer().apply { try { setDataSource(outputFilePath) val effect = BassBoost(1, 0).apply { setStrength(500) } setAuxEffectSendLevel(1f) attachAuxEffect(effect.id) prepare() start() setOnCompletionListener { setAuxEffectSendLevel(0f) attachAuxEffect(0) effect.release() } } catch (e: IOException) { e.printStackTrace() } } } } private fun playRecording() { if (outputFilePath.isNotEmpty()) { mediaPlayer = MediaPlayer().apply { try { setDataSource(outputFilePath) prepare() start() } catch (e: IOException) { e.printStackTrace() } } } } } عند تشغيل الصوت وبدا التسجيل وانهاء التسجيل والضغط علي المؤثرات يحدث هذا الخطا FATAL EXCEPTION: main Process: com.dm.myapplication2, PID: 9022 java.lang.RuntimeException: Cannot initialize effect engine for type: 47382d60-ddd8-11db-bf3a-0002a5d5c51b Error: -3 at android.media.audiofx.AudioEffect.<init>(AudioEffect.java:543) at android.media.audiofx.AudioEffect.<init>(AudioEffect.java:501) at android.media.audiofx.AudioEffect.<init>(AudioEffect.java:475) at android.media.audiofx.PresetReverb.<init>(PresetReverb.java:128) at com.dm.myapplication2.MainActivity.applySoundEffect1(MainActivity.kt:209) at com.dm.myapplication2.MainActivity.onCreate$lambda$4(MainActivity.kt:75) at com.dm.myapplication2.MainActivity.$r8$lambda$Wbigeh48ug95VEh-x8UxzmQg3io(Unknown Source:0) at com.dm.myapplication2.MainActivity$$ExternalSyntheticLambda5.onClick(Unknown Source:2) ارجوا تعديل الكود ليعمل بدون اخطاء
57af556b54529c3b90a91e472137baee
{ "intermediate": 0.3474002480506897, "beginner": 0.513088047504425, "expert": 0.13951171934604645 }
3,617
is docker using linux?
26129f394453d453c5f9cbcbd77fb6e2
{ "intermediate": 0.5430224537849426, "beginner": 0.21151068806648254, "expert": 0.24546685814857483 }
3,618
في هذا الكود class MainActivity : AppCompatActivity() { private lateinit var player: SimpleExoPlayer private lateinit var playButton: Button private lateinit var lyricsTextView: TextView private lateinit var startRecordingButton: Button private lateinit var stopRecordingButton: Button private var mediaRecorder: MediaRecorder? = null private lateinit var outputFilePath: String private val lyricsHandler = Handler(Looper.getMainLooper()) private lateinit var lyricsRunnable: Runnable private var mediaPlayer: MediaPlayer? = null private lateinit var playRecordingButton: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) playButton = findViewById(R.id.playButton) lyricsTextView = findViewById(R.id.lyricsTextView) startRecordingButton = findViewById(R.id.startRecordingButton) stopRecordingButton = findViewById(R.id.stopRecordingButton) playButton.setOnClickListener { initializePlayer() displayLyrics() } startRecordingButton.setOnClickListener { requestAudioPermissionAndStartRecording() } stopRecordingButton.setOnClickListener { stopRecording() } playRecordingButton = findViewById(R.id.playRecordingButton) playRecordingButton.setOnClickListener { playRecording() } val soundEffectsButton1 = findViewById<Button>(R.id.soundEffectButton1) val soundEffectsButton2 = findViewById<Button>(R.id.soundEffectButton2) soundEffectsButton1.setOnClickListener { applySoundEffect1() } soundEffectsButton2.setOnClickListener { applySoundEffect2() } } private fun initializePlayer() { player = SimpleExoPlayer.Builder(this).build() val dataSourceFactory = DefaultDataSourceFactory( this, Util.getUserAgent(this, "KaraokeApp") ) val mediaSource = ProgressiveMediaSource.Factory(dataSourceFactory) .createMediaSource(Uri.parse("https://directsendwhats.xyz/background_music.mp3")) player.setMediaSource(mediaSource) player.prepare() player.playWhenReady = true } private fun displayLyrics() { scheduleLyricsUpdate() } private fun scheduleLyricsUpdate() { lyricsRunnable = Runnable { updateLyrics() lyricsHandler.postDelayed(lyricsRunnable, 1000) // جدولة التحديث كل ثانية } lyricsHandler.post(lyricsRunnable) } private fun updateLyrics() { val currentPosition = player.currentPosition // استخدم currentPosition لتحديد الجزء المناسب من كلمات الأغنية // وقم بتحديث lyricsTextView بناءً على ذلك } private fun requestAudioPermissionAndStartRecording() { if (ContextCompat.checkSelfPermission( this, android.Manifest.permission.RECORD_AUDIO ) != PackageManager.PERMISSION_GRANTED ) { ActivityCompat.requestPermissions( this, arrayOf(android.Manifest.permission.RECORD_AUDIO), RECORD_AUDIO_REQUEST_CODE ) } else { startRecording() } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == RECORD_AUDIO_REQUEST_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { startRecording() } else { // الإذن مرفوض، يمكنك إظهار رسالة توضيحية هنا } } } private fun startRecording() { outputFilePath = "${getExternalFilesDir(Environment.DIRECTORY_MUSIC)?.absolutePath}/recording.3gp" mediaRecorder = MediaRecorder().apply { setAudioSource(MediaRecorder.AudioSource.MIC) setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP) setOutputFile(outputFilePath) setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB) try { prepare() } catch (e: IOException) { e.printStackTrace() } start() } } private fun stopRecording() { mediaRecorder?.apply { stop() release() player.stop() } mediaRecorder = null } override fun onStop() { super.onStop() lyricsHandler.removeCallbacks(lyricsRunnable) releasePlayer() mediaRecorder?.apply { stop() release() } mediaRecorder = null mediaPlayer?.apply { stop() release() } mediaPlayer = null } private fun releasePlayer() { if (::player.isInitialized) { player.release() } } companion object { private const val RECORD_AUDIO_REQUEST_CODE = 200 } private fun applySoundEffect1() { if (outputFilePath.isNotEmpty()) { mediaPlayer = MediaPlayer().apply { try { setDataSource(outputFilePath) // تأكد من توافر PresetReverb قبل استخدامه if (checkIfAudioEffectIsAvailable(PresetReverb.EFFECT_TYPE_VIRTUALIZER)) { val effect = PresetReverb(0, audioSessionId).apply { preset = PresetReverb.PRESET_LARGEROOM } setAuxEffectSendLevel(1f) attachAuxEffect(effect.id) prepare() start() setOnCompletionListener { setAuxEffectSendLevel(0f) attachAuxEffect(0) effect.release() } } else { Toast.makeText(applicationContext,"not work",Toast.LENGTH_SHORT).show() } } catch (e: IOException) { e.printStackTrace() } } } } private fun applySoundEffect2() { if (outputFilePath.isNotEmpty()) { mediaPlayer = MediaPlayer().apply { try { setDataSource(outputFilePath) // تأكد من توافر BassBoost قبل استخدامه if (checkIfAudioEffectIsAvailable(BassBoost.EFFECT_TYPE_BASS_BOOST)) { val effect = BassBoost(0, audioSessionId).apply { setStrength(500) } setAuxEffectSendLevel(1f) attachAuxEffect(effect.id) prepare() start() setOnCompletionListener { setAuxEffectSendLevel(0f) attachAuxEffect(0) effect.release() } } else { Toast.makeText(applicationContext,"not work 2",Toast.LENGTH_SHORT).show() } } catch (e: IOException) { e.printStackTrace() } } } } private fun playRecording() { if (outputFilePath.isNotEmpty()) { mediaPlayer = MediaPlayer().apply { try { setDataSource(outputFilePath) prepare() start() } catch (e: IOException) { e.printStackTrace() } } } } private fun checkIfAudioEffectIsAvailable(effectUUID: UUID): Boolean { val effects = AudioEffect.queryEffects() return effects.any { it.uuid == effectUUID } } } كيف يتم اضافة تاثيرات خارجيه غير متعلقه بالهاتف يرجي تعديل الكود ووضع عدد من التاثيرات الخارجية وضمها للتطبيق
44bb01a34d7e37100fec5539178f4c64
{ "intermediate": 0.32739219069480896, "beginner": 0.5286462306976318, "expert": 0.1439615935087204 }
3,619
في هذا الكود class MainActivity : AppCompatActivity() { private lateinit var player: SimpleExoPlayer private lateinit var playButton: Button private lateinit var lyricsTextView: TextView private lateinit var startRecordingButton: Button private lateinit var stopRecordingButton: Button private var mediaRecorder: MediaRecorder? = null private lateinit var outputFilePath: String private val lyricsHandler = Handler(Looper.getMainLooper()) private lateinit var lyricsRunnable: Runnable private var mediaPlayer: MediaPlayer? = null private lateinit var playRecordingButton: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) playButton = findViewById(R.id.playButton) lyricsTextView = findViewById(R.id.lyricsTextView) startRecordingButton = findViewById(R.id.startRecordingButton) stopRecordingButton = findViewById(R.id.stopRecordingButton) playButton.setOnClickListener { initializePlayer() displayLyrics() } startRecordingButton.setOnClickListener { requestAudioPermissionAndStartRecording() } stopRecordingButton.setOnClickListener { stopRecording() } playRecordingButton = findViewById(R.id.playRecordingButton) playRecordingButton.setOnClickListener { playRecording() } val soundEffectsButton1 = findViewById<Button>(R.id.soundEffectButton1) val soundEffectsButton2 = findViewById<Button>(R.id.soundEffectButton2) soundEffectsButton1.setOnClickListener { applySoundEffect1() } soundEffectsButton2.setOnClickListener { applySoundEffect2() } } private fun initializePlayer() { player = SimpleExoPlayer.Builder(this).build() val dataSourceFactory = DefaultDataSourceFactory( this, Util.getUserAgent(this, "KaraokeApp") ) val mediaSource = ProgressiveMediaSource.Factory(dataSourceFactory) .createMediaSource(Uri.parse("https://directsendwhats.xyz/background_music.mp3")) player.setMediaSource(mediaSource) player.prepare() player.playWhenReady = true } private fun displayLyrics() { scheduleLyricsUpdate() } private fun scheduleLyricsUpdate() { lyricsRunnable = Runnable { updateLyrics() lyricsHandler.postDelayed(lyricsRunnable, 1000) // جدولة التحديث كل ثانية } lyricsHandler.post(lyricsRunnable) } private fun updateLyrics() { val currentPosition = player.currentPosition // استخدم currentPosition لتحديد الجزء المناسب من كلمات الأغنية // وقم بتحديث lyricsTextView بناءً على ذلك } private fun requestAudioPermissionAndStartRecording() { if (ContextCompat.checkSelfPermission( this, android.Manifest.permission.RECORD_AUDIO ) != PackageManager.PERMISSION_GRANTED ) { ActivityCompat.requestPermissions( this, arrayOf(android.Manifest.permission.RECORD_AUDIO), RECORD_AUDIO_REQUEST_CODE ) } else { startRecording() } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == RECORD_AUDIO_REQUEST_CODE) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { startRecording() } else { // الإذن مرفوض، يمكنك إظهار رسالة توضيحية هنا } } } private fun startRecording() { outputFilePath = "${getExternalFilesDir(Environment.DIRECTORY_MUSIC)?.absolutePath}/recording.3gp" mediaRecorder = MediaRecorder().apply { setAudioSource(MediaRecorder.AudioSource.MIC) setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP) setOutputFile(outputFilePath) setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB) try { prepare() } catch (e: IOException) { e.printStackTrace() } start() } } private fun stopRecording() { mediaRecorder?.apply { stop() release() player.stop() } mediaRecorder = null } override fun onStop() { super.onStop() lyricsHandler.removeCallbacks(lyricsRunnable) releasePlayer() mediaRecorder?.apply { stop() release() } mediaRecorder = null mediaPlayer?.apply { stop() release() } mediaPlayer = null } private fun releasePlayer() { if (::player.isInitialized) { player.release() } } companion object { private const val RECORD_AUDIO_REQUEST_CODE = 200 } private fun applySoundEffect1() { if (outputFilePath.isNotEmpty()) { mediaPlayer = MediaPlayer().apply { try { setDataSource(outputFilePath) // تأكد من توافر PresetReverb قبل استخدامه if (checkIfAudioEffectIsAvailable(PresetReverb.EFFECT_TYPE_VIRTUALIZER)) { val effect = PresetReverb(0, audioSessionId).apply { preset = PresetReverb.PRESET_LARGEROOM } setAuxEffectSendLevel(1f) attachAuxEffect(effect.id) prepare() start() setOnCompletionListener { setAuxEffectSendLevel(0f) attachAuxEffect(0) effect.release() } } else { Toast.makeText(applicationContext,"not work",Toast.LENGTH_SHORT).show() } } catch (e: IOException) { e.printStackTrace() } } } } private fun applySoundEffect2() { if (outputFilePath.isNotEmpty()) { mediaPlayer = MediaPlayer().apply { try { setDataSource(outputFilePath) // تأكد من توافر BassBoost قبل استخدامه if (checkIfAudioEffectIsAvailable(BassBoost.EFFECT_TYPE_BASS_BOOST)) { val effect = BassBoost(0, audioSessionId).apply { setStrength(500) } setAuxEffectSendLevel(1f) attachAuxEffect(effect.id) prepare() start() setOnCompletionListener { setAuxEffectSendLevel(0f) attachAuxEffect(0) effect.release() } } else { Toast.makeText(applicationContext,"not work 2",Toast.LENGTH_SHORT).show() } } catch (e: IOException) { e.printStackTrace() } } } } private fun playRecording() { if (outputFilePath.isNotEmpty()) { mediaPlayer = MediaPlayer().apply { try { setDataSource(outputFilePath) prepare() start() } catch (e: IOException) { e.printStackTrace() } } } } private fun checkIfAudioEffectIsAvailable(effectUUID: UUID): Boolean { val effects = AudioEffect.queryEffects() return effects.any { it.uuid == effectUUID } } } كيف يتم اضافة تاثيرات خارجيه غير متعلقه بالهاتف يرجي تعديل الكود ووضع عدد من التاثيرات الخارجية وضمها للتطبيق
faa8c5b0612ca7cbe767ac58a2b0dd78
{ "intermediate": 0.32739219069480896, "beginner": 0.5286462306976318, "expert": 0.1439615935087204 }
3,620
''' import requests import json import datetime import streamlit as st from itertools import zip_longest import os import seaborn as sns import matplotlib.pyplot as plt import pandas as pd import japanize_matplotlib def basic_info(): config = dict() config["access_token"] = st.secrets["access_token"] config['instagram_account_id'] = st.secrets.get("instagram_account_id", "") config["version"] = 'v16.0' config["graph_domain"] = 'https://graph.facebook.com/' config["endpoint_base"] = config["graph_domain"] + config["version"] + '/' return config def InstaApiCall(url, params, request_type): if request_type == 'POST': req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res["url"] = url res["endpoint_params"] = params res["endpoint_params_pretty"] = json.dumps(params, indent=4) res["json_data"] = json.loads(req.content) res["json_data_pretty"] = json.dumps(res["json_data"], indent=4) return res def getUserMedia(params, pagingUrl=''): Params = dict() Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None if pagingUrl == '': url = params['endpoint_base'] + params['instagram_account_id'] + '/media' else: url = pagingUrl return InstaApiCall(url, Params, 'GET') def getUser(params): Params = dict() Params['fields'] = 'followers_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None url = params['endpoint_base'] + params['instagram_account_id'] return InstaApiCall(url, Params, 'GET') def saveCount(count, filename): with open(filename, 'w') as f: json.dump(count, f, indent=4) def getCount(filename): try: with open(filename, 'r') as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {} st.set_page_config(layout="wide") params = basic_info() count_filename = "count.json" if not params['instagram_account_id']: st.write('.envファイルでinstagram_account_idを確認') else: response = getUserMedia(params) user_response = getUser(params) if not response or not user_response: st.write('.envファイルでaccess_tokenを確認') else: posts = response['json_data']['data'][::-1] user_data = user_response['json_data'] followers_count = user_data.get('followers_count', 0) NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400 yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d') follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count) st.markdown(f''' Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff}) ''', unsafe_allow_html=True) show_description = st.checkbox("キャプションを表示") show_summary_chart = st.checkbox("サマリーチャートを表示") show_like_comment_chart = st.checkbox("いいね/コメント数グラフを表示") posts.reverse() post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)] count = getCount(count_filename) today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d') if today not in count: count[today] = {} count[today]['followers_count'] = followers_count if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59': count[yesterday] = count[today] max_like_diff = 0 max_comment_diff = 0 summary_chart_data = {"Date": [], "Count": [], "Type": []} like_count_diff_data = {} comment_count_diff_data = {} for post_group in post_groups: for post in post_group: like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) max_like_diff = max(like_count_diff, max_like_diff) max_comment_diff = max(comment_count_diff, max_comment_diff) like_count_diff_data[post['id']] = like_count_diff comment_count_diff_data[post['id']] = comment_count_diff if show_summary_chart: for date in count.keys(): if date != today: summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(count[date].get("followers_count", 0)) summary_chart_data["Type"].append("Follower") for post_id in count[date].keys(): if post_id not in ["followers_count"]: summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(like_count_diff_data.get(post_id, 0)) summary_chart_data["Type"].append("Like") summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) summary_chart_data["Count"].append(comment_count_diff_data.get(post_id, 0)) summary_chart_data["Type"].append("Comment") summary_chart_df = pd.DataFrame(summary_chart_data) fig, ax1 = plt.subplots(figsize=(15, 10)) summary_chart_palette = {"Follower": "lightblue", "Like": "orange", "Comment": "green"} sns.lineplot(data=summary_chart_df[summary_chart_df["Type"] != "Comment"], x="Date", y="Count", hue="Type", palette=summary_chart_palette, ax=ax1) ax1.set_xlabel("Date") ax1.set_ylabel("Follower & Like Count") ax2 = ax1.twinx() sns.lineplot(data=summary_chart_df[summary_chart_df["Type"] == "Comment"], x="Date", y="Count", hue="Type", palette=summary_chart_palette, ax=ax2) ax2.set_ylabel("Comment Count") plt.title("日別 サマリーチャート") st.pyplot(fig) for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): with columns[i]: st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True) st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}") like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) st.markdown( f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+1' if like_count_diff >= 0 else ''}{like_count_diff})" f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+1' if comment_count_diff >= 0 else ''}{comment_count_diff})", unsafe_allow_html=True) if show_like_comment_chart: like_comment_chart_data = {"Date": [], "Count": [], "Type": []} for date in count.keys(): if date != today and post["id"] in count[date]: like_comment_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) like_comment_chart_data["Count"].append(like_count_diff_data.get(post["id"], 0)) like_comment_chart_data["Type"].append("Like") like_comment_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) like_comment_chart_data["Count"].append(comment_count_diff_data.get(post["id"], 0)) like_comment_chart_data["Type"].append("Comment") if like_comment_chart_data["Date"]: like_comment_chart_df = pd.DataFrame(like_comment_chart_data) fig, ax1 = plt.subplots(figsize=(5, 3)) like_comment_chart_palette = {"Like": "orange", "Comment": "green"} sns.lineplot(data=like_comment_chart_df[like_comment_chart_df["Type"] != "Comment"], x="Date", y="Count", hue="Type", palette=like_comment_chart_palette, ax=ax1) ax1.set_xlabel("Date") ax1.set_ylabel("Like Count") ax2 = ax1.twinx() sns.lineplot(data=like_comment_chart_df[like_comment_chart_df["Type"] == "Comment"], x="Date", y="Count", hue="Type", palette=like_comment_chart_palette, ax=ax2) ax2.set_ylabel("Comment Count") plt.title("日別 いいね/コメント数") st.pyplot(fig) caption = post['caption'] if caption is not None: caption = caption.strip() if "[Description]" in caption: caption = caption.split("[Description]")[1].lstrip() if "[Tags]" in caption: caption = caption.split("[Tags]")[0].rstrip() caption = caption.replace("#", "") caption = caption.replace("[model]", "👗") caption = caption.replace("[Equip]", "📷") caption = caption.replace("[Develop]", "🖨") if show_description: st.write(caption or "No caption provided") else: st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided") count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']} saveCount(count, count_filename) ''' 上記コードを実行すると下記のエラーが発生します。下記のすべての要件に従って修正してください。 - Python用のインデントを行頭に付与して、正常に表示されるかチェックしてから出力する - コードの説明文は表示しない - コードの最前部と最後尾に'''をつけコード様式で出力する - 修正済みのコード部分のみを表示する - 指示のないコードの改変はしない - "caption = post['caption']"以降のブロックについては改変しない ''' 2023-05-01 20:09:04.062 Uncaught app exception Traceback (most recent call last): File "/home/walhalax/anaconda3/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 565, in _run_script exec(code, module.__dict__) File "/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py", line 143, in <module> summary_chart_data["Date"].append(datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%m/%d')) File "/home/walhalax/anaconda3/lib/python3.9/_strptime.py", line 568, in _strptime_datetime tt, fraction, gmtoff_fraction = _strptime(data_string, format) File "/home/walhalax/anaconda3/lib/python3.9/_strptime.py", line 349, in _strptime raise ValueError("time data %r does not match format %r" % ValueError: time data 'timestamp' does not match format '%Y-%m-%d' 2023-05-01 20:09:08.977 Uncaught app exception Traceback (most recent call last): File "/home/walhalax/anaconda3/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 565, in _run_script exec(code, module.__dict__) File "/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py", line 189, in <module> if date != today and post["id"] in count[date]: TypeError: argument of type 'int' is not iterable '''
130878ac46341929acd55fb860128270
{ "intermediate": 0.32280293107032776, "beginner": 0.3790029287338257, "expert": 0.29819414019584656 }
3,621
if we had 3 stock in column a to c . write a vba to calculate optimum weight for every stock
7ec54a5ce036d201f668dfccb1803e35
{ "intermediate": 0.2832658886909485, "beginner": 0.30138957500457764, "expert": 0.4153445363044739 }
3,622
I need a powershell script which will delete all bin and obj folders in all the sub directories starting from a root folder
79fee2889346562840a1e95d9024dc9a
{ "intermediate": 0.35813212394714355, "beginner": 0.2525501847267151, "expert": 0.38931769132614136 }
3,623
In a Rails app using minitest and capybara, how do I assert that a html table element has properly been rendered on the page?
219efe0b14201c63a6ddf2638ab9c990
{ "intermediate": 0.8246645331382751, "beginner": 0.10011854022741318, "expert": 0.07521699368953705 }
3,624
write vba to find optimum weight for 3 stock that there is in column a to c. use Markowitz Model for that .and dont use solver
f55977a30a120bf32b95990e0d826aa4
{ "intermediate": 0.2574422061443329, "beginner": 0.22994670271873474, "expert": 0.5126110911369324 }
3,625
vb.net datagridview column index by name
c51453db2227f7d96fc51cf43b2b0be7
{ "intermediate": 0.31904950737953186, "beginner": 0.2753147482872009, "expert": 0.4056357145309448 }
3,626
Офис компании N оборудован по принципу «умного дома» рядом устройств интернета вещей. В один из рабочих дней была зафиксирована попытка DDoSатаки на веб-сервер компании. При первичном анализе журнала регистрации межсетевого экрана были обнаружены IP-адреса некоторых из таких устройств, а именно датчика движения, отвечающего за включение и выключение освещения, а также датчика температуры воздуха, контролирующего систему кондиционирования. Установку и настройку данных устройств осуществляли специалисты компании-поставщика, а также системный администратор компании N. В процессе работы все участники использовали ноутбуки, а также личные смартфоны. Нужно определить объекты исследования и перечень вопросов, на которые требуется получить ответы эксперта, для расследования описанного инцидента. Требуется определить, была ли атака организована поставщиками устройств или их сотрудниками, сотрудниками компании N или посторонними лицами, а также установить, каким образом контролировались участвовавшие в атаке устройства.
da3eaa1ea59a16f3363e390deafdffac
{ "intermediate": 0.17267318069934845, "beginner": 0.5046117901802063, "expert": 0.32271504402160645 }
3,627
usr@test:~$ curl --resolve golang.org -sL https://dl.google.com/go/go1.20.3.src.tar.gz | tar xzf - && mv go /usr/local gzip: stdin: unexpected end of file tar: Child returned status 1 tar: Error is not recoverable: exiting now
294cc3e295074efacaf8fc14d2e7a012
{ "intermediate": 0.4081146717071533, "beginner": 0.3138001561164856, "expert": 0.2780851721763611 }
3,628
what is computer
c0b90565d1b9d0d0613fbffef9c8082f
{ "intermediate": 0.22831615805625916, "beginner": 0.2832443416118622, "expert": 0.4884394705295563 }
3,629
write a vba code to receive data from website tsetmc to excel
d372d6ef70215d928af81029dd91de88
{ "intermediate": 0.5272927284240723, "beginner": 0.13255161046981812, "expert": 0.340155690908432 }
3,630
Задача: Программа с графическим интерфейсом, реализующая через класс каталог косметики, с указанием наименования, цены, описания и изображения каждой позиции и хранящая свои данные в SQL базе данных В приведенном ниже коде мне нужно изменить TDBGrid да StringGrid, а вывод изображения из базы данных изменить от DBImage на Image2 void __fastcall TForm108::FormCreate(TObject *Sender) { // создание базы данных / таблицы, если их ещё не существует String s; s = "CREATE DATABASE IF NOT EXISTS `catalog`"; ADOQuery1->SQL->Text = s; ADOQuery1->ExecSQL(); s = "CREATE TABLE IF NOT EXISTS `catalog`.`products` (`ID` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(255) CHARACTER SET utf8mb4 NOT NULL, `price` FLOAT(8, 2) NOT NULL, `description` TEXT CHARACTER SET utf8mb4 NOT NULL, `image` LONGBLOB NOT NULL, PRIMARY KEY (`ID`))"; ADOQuery1->SQL->Text = s; ADOQuery1->ExecSQL(); ADOQuery1->Close(); ADOQuery1->SQL->Text = "SELECT * FROM `catalog`.`products`"; ADOQuery1->Open(); } void __fastcall TForm108::Button2Click(TObject *Sender) { if (Edit1->Text.IsEmpty() || Edit2->Text.IsEmpty() || Memo1->Lines->Text.IsEmpty()) { ShowMessage("Пожалуйста, заполните все поля!"); return; } if (OpenPictureDialog1->FileName.IsEmpty()) { ShowMessage("Пожалуйста, загрузите изображение!"); return; } try { TFileStream *fs = new TFileStream(OpenPictureDialog1->FileName, fmOpenRead); try { // Указываем параметры для запроса ADOQuery1->SQL->Text = "INSERT INTO `catalog`.`products` (`name`, `price`, `description`, `image`) VALUES (:name, :price, :description, :image)"; ADOQuery1->Parameters->ParamByName("name")->Value = Edit1->Text; ADOQuery1->Parameters->ParamByName("price")->Value = StrToFloat(Edit2->Text); ADOQuery1->Parameters->ParamByName("description")->Value = Memo1->Lines->Text; ADOQuery1->Parameters->ParamByName("name")->DataType = ftWideString; ADOQuery1->Parameters->ParamByName("description")->DataType = ftWideString; // Создаем поток для передачи изображения в базу данных TMemoryStream *stream = new TMemoryStream(); try { stream->CopyFrom(fs, 0); stream->Position = 0; ADOQuery1->Parameters->ParamByName("image")->LoadFromStream(stream, ftBlob); ADOQuery1->ExecSQL(); } __finally { delete stream; } } __finally { delete fs; } // Очистка полей ввода Edit1->Text="Название товара"; Edit2->Text="0"; Memo1->Lines->Text="Описание товара"; // Очистка изображения Image1->Picture->Assign(NULL); // Обновление данных в таблице ADOQuery1->Close(); ADOQuery1->SQL->Text = "SELECT * FROM `catalog`.`products`"; ADOQuery1->Open(); } catch (Exception &e) { ShowMessage("Ошибка при добавлении товара: " + e.Message); } } void __fastcall TForm108::Button3Click(TObject *Sender) { if (OpenPictureDialog1->Execute()) { Image1->Picture->LoadFromFile(OpenPictureDialog1->FileName); } } void __fastcall TForm108::Button1Click(TObject *Sender) { int id = ADOQuery1->FieldByName("ID")->AsInteger; if (OpenPictureDialog1->Execute()) { TFileStream *fs = new TFileStream(OpenPictureDialog1->FileName, fmOpenRead); TMemoryStream *stream = new TMemoryStream(); try { fs->Position = 0; // сброс позиции в потоке stream->CopyFrom(fs, 0); // скопировать содержимое потока fs в stream stream->Position = 0; ADOQuery1->SQL->Text = "UPDATE `catalog`.`products` SET `image` = :image WHERE `ID` = :ID"; ADOQuery1->Parameters->ParamByName("ID")->Value = id; ADOQuery1->Parameters->ParamByName("image")->LoadFromStream(stream, ftBlob); ADOQuery1->ExecSQL(); } __finally { if (stream != NULL) { delete stream; } if (fs != NULL) { delete fs; } } ADOQuery1->Close(); ADOQuery1->SQL->Text = "SELECT * FROM `catalog`.`products`"; ADOQuery1->Open(); Image1->Picture->Assign(NULL); } } void __fastcall TForm108::Button4Click(TObject *Sender) { // Получаем номер выделенной строки int row = DBGrid1->DataSource->DataSet->RecNo; // Переходим к соответствующей строке в ADOQuery ADOQuery1->First(); // переходим к первой строке for (int i = 1; i < row; i++) { // идем по каждой строке до нужной ADOQuery1->Next(); } // Получаем значение поля ID текущей строки int id = ADOQuery1->FieldByName("ID")->AsInteger; // Показываем диалоговое окно и ждем подтверждения int dialog_answer = MessageDlg("Вы действительно хотите удалить товар?", mtConfirmation, TMsgDlgButtons() << mbYes << mbNo, 0); // Если пользователь подтвердил удаление, то выполняем удаление товара if (dialog_answer == mrYes) { // Выполняем SQL-запрос на удаление товара ADOQuery1->SQL->Text = "DELETE from `catalog`.`products` WHERE `ID` = :ID"; ADOQuery1->Parameters->ParamByName("ID")->Value = id; ADOQuery1->ExecSQL(); // Обновляем данные в TDBGrid ADOQuery1->Close(); ADOQuery1->SQL->Text = "SELECT * FROM `catalog`.`products`"; ADOQuery1->Open(); } // Если пользователь не подтвердил удаление, то ничего не делаем else if (dialog_answer == mrNo) { return; } } void __fastcall TForm108::Button5Click(TObject *Sender) { if (ADOQuery1->State == dsEdit || ADOQuery1->State == dsInsert) { ADOQuery1->Post(); } try { ADOQuery1->UpdateBatch(arCurrent); ADOQuery1->Close(); ADOQuery1->SQL->Text = "SELECT * FROM `catalog`.`products`"; ADOQuery1->Open(); } catch (const Exception& e) { ShowMessage("Ошибка при сохранении: " + e.Message); } }
742b970748a1757d32d723871fa2d627
{ "intermediate": 0.3872174024581909, "beginner": 0.4479820728302002, "expert": 0.1648004800081253 }
3,631
campingController.createCamping = async (req, res, next) => { delete req.body.owner; const session = await mongoose.startSession(); session.startTransaction(); const campingLodgingsOperations = []; const campingUnitsOperations = []; let camping; try { if (req.body._id) { camping = await Camping.findById(req.body._id); if (!camping.owner.equals(req.user._id)) { return next(new Unauthorized()) } } else { delete req.body._id; camping = new Camping({ ...req.body, owner: req.user._id }); } for (let lodging of req.body.lodgings) { if (!lodging._id || lodging._id.startsWith('new')) { lodging.camping = camping._id; delete lodging._id; campingLodgingsOperations.push( { insertOne: { document: lodging} }); } else { if (!camping._id.equals(lodging.camping)) { console.log(lodging._id, lodging.camping); return next(new Unauthorized()) } campingLodgingsOperations.push( { updateOne: { filter: { _id: lodging._id }, update: { $set: lodging }} }); } lodging.units.forEach(unit => { if (unit._id.startsWith('new')) { unit.campingLodging = lodging._id; delete unit._id; campingUnitsOperations.push( { insertOne: { document: unit } }); } else { if (lodging._id !== unit.lodging) { return next(new Unauthorized()) } campingUnitsOperations.push({ updateOne: { filter: { _id: unit._id }, update: { $set: unit }} }); } }) }; await CampingLodging.bulkWrite(campingLodgingsOperations, { session }); await CampingUnit.bulkWrite(campingUnitsOperations, { session }); console.log(camping); const response = await camping.save(); await session.commitTransaction(); res.status(201).json({ message: "Camping created successfully", camping: response }); } catch (error) { await session.abortTransaction(); return next(error); } session.endSession(); }; Mejoramela que sea lo mas corta posible. Es una funcion de mongoose
8b89b5c03b84424e7bcb24f13089bf37
{ "intermediate": 0.31715893745422363, "beginner": 0.4118782579898834, "expert": 0.27096280455589294 }
3,632
in nix how do I loop over all attributes in the lowest attrset in something like {a = { b =1; c =2; }; d ={ e=2;};} ?
5fb6b329a03261d959375aaad19ec525
{ "intermediate": 0.2405814379453659, "beginner": 0.5791299939155579, "expert": 0.18028853833675385 }
3,633
Какой переключатель Nmap позволяет добавлять случайные данные произвольной длины в конец пакетов?
f2012121f00814fa2d96878d620ddd47
{ "intermediate": 0.17711903154850006, "beginner": 0.1165560632944107, "expert": 0.7063249349594116 }
3,634
can you fractalize it more circularly around the central flag and adjust the text sizes in dependent of the flag size, so it fill at the center with appropriate translation of the same phrase “YES, WE CARE!” in all languages. also add more languages with appropriate translations and icons symbols used for their corresponding country flags. use only css and html, without any externals images links or javascripts.: <html lang=“en”> <head> <meta charset=“UTF-8” /> <meta name=“viewport” content=“width=device-width, initial-scale=1.0” /> <style> .main { display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; } .backgrounds { display: grid; grid-template-columns: repeat(3, 1fr); grid-gap: 20px; justify-items: center; align-items: center; } .background { font-weight: bold; padding: 0px; text-align: center; justify-content: center; align-items: center; position: relative; display: flex; } .background-text { display: flex; flex-direction: column; justify-content: center; align-items: center; position: relative; z-index: 1; } .background:before { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); opacity: 0.15; display: flex; } .uk:before { content: ‘🇬🇧’; font-size: 10em; } .spain:before { content: ‘🇪🇸’; font-size: 4em; } .france:before { content: ‘🇫🇷’; font-size: 4em; } .usa:before { content: ‘🇺🇸’; font-size: 4em; } .germany:before { content: ‘🇩🇪’; font-size: 4em; } </style> <title>Flag Backgrounds</title> </head> <body> <div class=“main”> <div class=“backgrounds”> <span class=“background spain”> <span class=“background-text”>¡SÍ, NOS IMPORTA!</span> </span> <span class=“background uk”> <span class=“background-text”>YES, WE CARE!</span> </span> <span class=“background france”> <span class=“background-text”>OUI, NOUS NOUS SOUCIONS!</span> </span> <span class=“background usa”> <span class=“background-text”>YES, WE CARE!</span> </span> <span class=“background germany”> <span class=“background-text”>JA, UNS KÜMMERT ES!</span> </span> </div> </div> </body> </html>
72685aaa96a4207e01a4b7a46f821ab6
{ "intermediate": 0.32548901438713074, "beginner": 0.3985152840614319, "expert": 0.2759957015514374 }
3,635
Please give a latex code using TiKZ for drawing a boundry of a 3-dimensional simplex
bad4fccc2f0a175def3cf4c4a97269d0
{ "intermediate": 0.42170605063438416, "beginner": 0.1992601454257965, "expert": 0.3790338337421417 }
3,636
can you fractalize it more circularly around the central flag and adjust the text sizes in dependent of the flag size, so it fill at the center with appropriate translation of the same phrase “YES, WE CARE!” in all languages. also add more languages with appropriate translations and icons symbols used for their corresponding country flags. use only css and html, without any externals images links or javascripts.: <html lang=“en”> <head> <meta charset=“UTF-8” /> <meta name=“viewport” content=“width=device-width, initial-scale=1.0” /> <style> .main { display: flex; justify-content: center; align-items: center; min-height: 100vh; margin: 0; } .backgrounds { display: grid; grid-template-columns: repeat(3, 1fr); grid-gap: 20px; justify-items: center; align-items: center; } .background { font-weight: bold; padding: 0px; text-align: center; justify-content: center; align-items: center; position: relative; display: flex; } .background-text { display: flex; flex-direction: column; justify-content: center; align-items: center; position: relative; z-index: 1; } .background:before { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); opacity: 0.15; display: flex; } .uk:before { content: ‘🇬🇧’; font-size: 10em; } .spain:before { content: ‘🇪🇸’; font-size: 4em; } .france:before { content: ‘🇫🇷’; font-size: 4em; } .usa:before { content: ‘🇺🇸’; font-size: 4em; } .germany:before { content: ‘🇩🇪’; font-size: 4em; } </style> <title>Flag Backgrounds</title> </head> <body> <div class=“main”> <div class=“backgrounds”> <span class=“background spain”> <span class=“background-text”>¡SÍ, NOS IMPORTA!</span> </span> <span class=“background uk”> <span class=“background-text”>YES, WE CARE!</span> </span> <span class=“background france”> <span class=“background-text”>OUI, NOUS NOUS SOUCIONS!</span> </span> <span class=“background usa”> <span class=“background-text”>YES, WE CARE!</span> </span> <span class=“background germany”> <span class=“background-text”>JA, UNS KÜMMERT ES!</span> </span> </div> </div> </body> </html>
f165455035009375159d500cc0ec3b23
{ "intermediate": 0.32548901438713074, "beginner": 0.3985152840614319, "expert": 0.2759957015514374 }
3,637
exlain what the script at https://github.com/NSFWUTILS/RedditScrape/blob/main/json-crawler.py does and how to modify it to only download .gif files
0b8cfd83c611dc783b1b0d9ae64f9d4d
{ "intermediate": 0.4967202842235565, "beginner": 0.288998544216156, "expert": 0.21428117156028748 }
3,638
Hello, how a u&
f24ec2ef9595ff181101322249c50b1a
{ "intermediate": 0.28233760595321655, "beginner": 0.42177435755729675, "expert": 0.2958880364894867 }
3,639
python fix: ModuleNotFoundError: No module named 'urllib2'
70188def460bad208f9585bcc2b83dc7
{ "intermediate": 0.47891297936439514, "beginner": 0.15560713410377502, "expert": 0.3654799163341522 }
3,640
my @c = (1..6); for (@c){ print("$_ \n"); } In Perl, can I put the my and assignment in the for?
aaff97d39a4eaa8880fffe37f9813638
{ "intermediate": 0.24327972531318665, "beginner": 0.6255950927734375, "expert": 0.13112519681453705 }
3,641
is this valid perl? for (my @c = (1..6){ print("$_ \n"); }
e82033aedc019a7368dd8360c18495bd
{ "intermediate": 0.07198352366685867, "beginner": 0.8434162735939026, "expert": 0.08460025489330292 }
3,642
I am trying to create a DatePicker that selects multiple dates. I am able to select multiple dates but I would like to keep the DatePicker open while I select them. Problem is, the DatePicker will close every time I select a date. javafx
035ba4bac64592d497ae7826af3fbf9e
{ "intermediate": 0.4087110757827759, "beginner": 0.1708535999059677, "expert": 0.4204353392124176 }
3,643
java code to record and replay midi keyboard events using a simple lib
892b2c5b9acd858dc2be3ff080abb309
{ "intermediate": 0.7078849077224731, "beginner": 0.09492887556552887, "expert": 0.19718623161315918 }
3,644
build a simple game
72e336adef0439ec8cc07631146637fc
{ "intermediate": 0.30443382263183594, "beginner": 0.4154440760612488, "expert": 0.2801221013069153 }
3,645
exlain what the script at https://github.com/NSFWUTILS/RedditScrape/blob/main/json-crawler.py does and how to modify it to only download .gif files
5d7361aa31893c8151e8b4ae50c537c1
{ "intermediate": 0.4967202842235565, "beginner": 0.288998544216156, "expert": 0.21428117156028748 }
3,646
exlain what the script at https://github.com/NSFWUTILS/RedditScrape/blob/main/json-crawler.py does and how to modify it to only download .gif files
a0648f9b94a6b5660892546769507a8f
{ "intermediate": 0.4967202842235565, "beginner": 0.288998544216156, "expert": 0.21428117156028748 }
3,647
exlain what the script at https://github.com/NSFWUTILS/RedditScrape/blob/main/json-crawler.py does and how to modify it to only download .gif files
6c36fd02fc9a055c818ee4b9b6caa002
{ "intermediate": 0.4967202842235565, "beginner": 0.288998544216156, "expert": 0.21428117156028748 }
3,648
in the below code, get the master drone and follower drone local location inetgrated and print them using pymavlink and give me correct code. basically i want the proximity checker, distance between master and follower drone should be always minimum 5 meters between then , if nbot, prints alert, priximity breach # main loop for the code while True: # checking for heartbeat msg = the_connection.recv_match(type='HEARTBEAT', blocking=False) if msg: print("***ACTION: Heartbeat connection established***") sysid = msg.get_srcSystem() # checking for mode of both drones connt. and print the current mode if sysid in [2, 3]: mode = mavutil.mode_string_v10(msg) if mode != previous_mode[sysid]: # check if the mode has changed previous_mode[sysid] = mode # update the previous_mode variable print(f"***ACTION: System ID: {sysid}, Mode: {mode}***") # save the mode for sysid 2 and 3 in separate variables if sysid == 2: mode_sysid_2 = mode elif sysid == 3: mode_sysid_3 = mode # Run the following code only when mode_sysid_3 and mode_sysid_2 is set to "GUIDED" time_start = time.time() if mode_sysid_3 == "GUIDED": while mode_sysid_2 == "GUIDED": if abort(): print("***ACTION: aborting from terminal***") exit() # runs every second if time.time() - time_start >= 1: # if mode is not set to guided, set the mode to rtl and disarm the drone for index, master_wp in enumerate(waypoints[:-1]): if mode_sysid_2 != "GUIDED": for drone in [master_drone, follower_drone]: drone.set_mode(6) drone.arm(False) # get the next waypoint of the mission next_wp = waypoints[index + 1] # send the master drone to waypoint master_drone.send_waypoint(master_wp, next_wp, speed=1) print("***ACTION: master done is going to waypoint: {}***".format(master_wp)) # get the current position of follower position follower_position = master_drone.get_position() # Print follower position print("***ACTION: follower position is : {}***".format(follower_position)) # if follower position is not found, set the mode to rtl for both drones and disarms the drones if follower_position is None: for drone in [master_drone, follower_drone]: print("INFO: setting mod to rtl because follower position is not found") drone.set_mode(6) drone.arm(False) break # calculate the follower drone coordinates with the distance and angle follower_wp = calculate_follower_coordinates(follower_position, distance, angle) dt = time.time() - time_start # get the pid latitude anad longitude for followe drone to get the accurate positioning pid_lat_output = pid_lat.update(follower_wp[0] - follower_position[0], dt) pid_lon_output = pid_lon.update(follower_wp[1] - follower_position[1], dt) # Print PID output adjustments print("***ACTION: PID adjustments: lat={}, lon={}***".format(pid_lat_output, pid_lon_output)) # get the adjusted coordinates of follower drones adjusted_follower_wp = ( follower_wp[0] + pid_lat_output, follower_wp[1] + pid_lon_output, follower_wp[2]) # Print adjusted follower waypoint print("***ACTION: Adjusted follower waypoint: {}***".format(adjusted_follower_wp)) # send the follower drone to adjusted coordinates follower_drone.send_waypoint(adjusted_follower_wp, next_wp, speed=1) # check for abort if abort(): print("***ACTION: aborting from terminal***") exit() # check for mode of master drone, if not on GUIDED mode, then set the mode to rtl for both drones if mode_sysid_2 != "GUIDED": for drone in [master_drone, follower_drone]: print("***ACTION: setting mode to rtl because mode is not set to rtl***") drone.set_mode(6) drone.arm(False) time.sleep(30) # set the mode to rtl and disarms the drone for drone in [master_drone, follower_drone]: print("***ACTION: setting mode to rtl because waypoint mision finished") drone.set_mode(6) drone.arm(False) # set mode to rtl # master_drone.set_mode(6) # follower_drone.set_mode(6) break
e941879d08e22383563edc8d30f6e649
{ "intermediate": 0.24870918691158295, "beginner": 0.6183023452758789, "expert": 0.13298845291137695 }
3,649
hi
33b04afdbe9427cfe4111d8731b69a7d
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
3,650
I have a Rails app with a User model that has_one :profile. How do i select only those users who have a profile that has status: "live"
02a38b68dfa72a34d34d91df0455c5fd
{ "intermediate": 0.4405022859573364, "beginner": 0.29233893752098083, "expert": 0.26715877652168274 }
3,651
Give me rust code to check is current process elevated or no
cd83ae4672f10ed434cc741bf69d30c0
{ "intermediate": 0.44465065002441406, "beginner": 0.24900305271148682, "expert": 0.3063463270664215 }
3,652
pouvez vous corriger ces érreurs: Gravité Code Description Projet Fichier Ligne État de la suppression Erreur LNK2019 symbole externe non résolu _main référencé dans la fonction "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ) Xevyyy Cheat C:\Users\Tilio\source\repos\Xevyyy Cheat\Xevyyy Cheat\MSVCRTD.lib(exe_main.obj) 1 Avertissement C28251 Annotation incohérente pour 'wWinMain' : cette instance contient aucune annotation. Voir c:\program files (x86)\windows kits\10\include\10.0.19041.0\um\winbase.h(1019). Xevyyy Cheat C:\Users\Tilio\source\repos\Xevyyy Cheat\Xevyyy Cheat\Source.cpp 18 Erreur LNK1120 1 externes non résolus Xevyyy Cheat C:\Users\Tilio\source\repos\Xevyyy Cheat\Debug\Xevyyy Cheat.exe 1 de mon code: #include <iostream> #include <Windows.h> #include <CommCtrl.h> #pragma comment(lib, "comctl32.lib") #define WINDOW_WIDTH 480 #define WINDOW_HEIGHT 360 #define BUTTON_WIDTH 120 #define BUTTON_HEIGHT 30 #define JG_WIDTH 300 #define JG_HEIGHT 30 LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow) { // Register window class WNDCLASSEX wc; wc.cbSize = sizeof(WNDCLASSEX); wc.style = 0; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = NULL; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW); wc.lpszMenuName = NULL; wc.lpszClassName = L"XevyyyCheat"; wc.hIconSm = NULL; if (!RegisterClassEx(&wc)) { MessageBoxW(NULL, L"Window Registration Failed!", L"Error", MB_ICONEXCLAMATION | MB_OK); return 0; } // Create window HWND hwnd = CreateWindowEx( WS_EX_CLIENTEDGE, L"XevyyyCheat", L"Xevyyy Cheat", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, WINDOW_WIDTH, WINDOW_HEIGHT, NULL, NULL, hInstance, NULL); if (hwnd == NULL) { MessageBoxW(NULL, L"Window Creation Failed!", L"Error", MB_ICONEXCLAMATION | MB_OK); return 0; } // Create button controls HWND aimbotBtn = CreateWindow( L"BUTTON", // Predefined class; Unicode assumed L"Aimbot", // Button text WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, // Styles 20, // x position 20, // y position BUTTON_WIDTH, // Button width BUTTON_HEIGHT, // Button height hwnd, // Parent window NULL, // No menu. hInstance, NULL); // Pointer not needed. HWND triggerbotBtn = CreateWindow( L"BUTTON", // Predefined class; Unicode assumed L"Triggerbot", // Button text WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, // Styles 160, // x position 20, // y position BUTTON_WIDTH, // Button width BUTTON_HEIGHT, // Button height hwnd, // Parent window NULL, // No menu. hInstance, NULL); // Pointer not needed. HWND spinbotBtn = CreateWindow( L"BUTTON", // Predefined class; Unicode assumed L"Spinbot", // Button text WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, // Styles 300, // x position 20, // y position BUTTON_WIDTH, // Button width BUTTON_HEIGHT, // Button height hwnd, // Parent window NULL, // No menu. hInstance, NULL); // Pointer not needed. // Create Jiggle control HWND jiggleControl = CreateWindowEx( 0, TRACKBAR_CLASSW, NULL, WS_CHILD | WS_VISIBLE | TBS_AUTOTICKS, (WINDOW_WIDTH - JG_WIDTH) / 2, 100, JG_WIDTH, JG_HEIGHT, hwnd, (HMENU)1, hInstance, NULL); SendMessageW(jiggleControl, TBM_SETRANGE, TRUE, MAKELONG(0, 100)); SendMessageW(jiggleControl, TBM_SETPOS, TRUE, 50); // Show window ShowWindow(hwnd, nCmdShow); UpdateWindow(hwnd); // Message loop MSG msg; while (GetMessage(&msg, NULL, 0, 0) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; } LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_COMMAND: { if (LOWORD(wParam) == BN_CLICKED) { if (HIWORD(wParam) == 0) // Aimbot button clicked { MessageBoxW(hwnd, L"Aimbot activated!", L"Message", MB_OK); } else if (HIWORD(wParam) == 1) // Triggerbot button clicked { MessageBoxW(hwnd, L"Triggerbot activated!", L"Message", MB_OK); } else if (HIWORD(wParam) == 2) // Spinbot button clicked { MessageBoxW(hwnd, L"Spinbot activated!", L"Message", MB_OK); } } } break; case WM_DESTROY: { PostQuitMessage(0); } break; default: return DefWindowProc(hwnd, msg, wParam, lParam); } return 0; }
e4b80c2427f5348638f810914e5e72b8
{ "intermediate": 0.36330604553222656, "beginner": 0.30427974462509155, "expert": 0.3324142098426819 }
3,653
почему код повторно выводит некторые данные from bs4 import BeautifulSoup import requests url = f'https://www.poizon.us/collections/sneakers-1?page=20' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # gf-products > li:nth-child(1) > div > div > div.card__content > div.card__information > h3 > a links = soup.select('a.full-unstyled-link') for link in links: if link is not None: href = link.get('href') if href is not None: full_link = 'https://www.poizon.us' + href else: print('Ссылка не найдена') continue response = requests.get(full_link) soup = BeautifulSoup(response.text, 'html.parser') photo_selector = '#Thumbnail-template--16663852253403__main-1' photo_links = soup.select_one(photo_selector).get('srcset').split(', ') photo_link = photo_links[0].split(' ')[0] size_selector = 'div.product-popup-modal__content-info:nth-child(1) > variant-radios:nth-child(1) > fieldset:nth-child(2) > label:nth-child(3) > div:nth-child(1)' price_selector = 'div.product-popup-modal__content-info:nth-child(1) > variant-radios:nth-child(1) > fieldset:nth-child(2) > label:nth-child(3) > div:nth-child(2)' size_element = soup.select_one(size_selector) if size_element is not None: size = size_element.text.strip() else: size = 'Размер не найден' price_element = soup.select_one(price_selector) if price_element is not None: price = price_element.text.strip() else: price = 'Цена не найдена' name_element = soup.select_one('div.product__title > h1:nth-child(1)') if name_element is not None: name = name_element.text.strip() else: name = 'Название не найдено' info_element = soup.select_one('#ProductAccordion-ea1014ee-ae9d-4eee-b23c-d2dfe9ba75b4-template--16663852253403__main') if info_element is not None: info = info_element.text.strip() else: info = 'Информация не найдена' urls = photo_link.replace("//", "https://") url = urls+'111' photo_lin = photo_link.replace('//cdn.shopify.com', 'https://cdn.shopify.com') print(f'Название: {name}\nРазмер: {size}\nИнформация: {info}') print(f"цена: {price} (Цена является ориентировочной, за точной информацией можете обращаться к @egvv6.Обычно цена товара значительно меньше указанной здесь") print(url)
dd4c4ecafb9223f6788d6bfa4a0ef773
{ "intermediate": 0.3118726313114166, "beginner": 0.5322622060775757, "expert": 0.15586517751216888 }
3,654
python fix: Traceback (most recent call last): File "C:\Users\curbisJM28\downloads\app\sync\my_projects\web_unblckr\prxy\pr.py", line 9, in <module> response = requests.post(url, proxies=proxies, verify=False) File "C:\Users\curbisJM28\AppData\Roaming\Python\Python310\site-packages\requests\api.py", line 115, in post return request("post", url, data=data, json=json, **kwargs) File "C:\Users\curbisJM28\AppData\Roaming\Python\Python310\site-packages\requests\api.py", line 59, in request return session.request(method=method, url=url, **kwargs) File "C:\Users\curbisJM28\AppData\Roaming\Python\Python310\site-packages\requests\sessions.py", line 587, in request resp = self.send(prep, **send_kwargs) File "C:\Users\curbisJM28\AppData\Roaming\Python\Python310\site-packages\requests\sessions.py", line 701, in send r = adapter.send(request, **kwargs) File "C:\Users\curbisJM28\AppData\Roaming\Python\Python310\site-packages\requests\adapters.py", line 578, in send raise ReadTimeout(e, request=request) requests.exceptions.ReadTimeout: HTTPSConnectionPool(host='github.com', port=443): Read timed out. (read timeout=None)
e5b6b3f644312ca9b9c2a66cd0c1f62f
{ "intermediate": 0.48503053188323975, "beginner": 0.34696394205093384, "expert": 0.16800546646118164 }
3,655
"Azerbaijan 338 km; Belarus 1,312 km; China (southeast) 4,133 km and China (south) 46 km; Estonia 324 km; Finland 1,309 km; Georgia 894 km; Kazakhstan 7,644 km; North Korea 18 km; Latvia 332 km; Lithuania (Kaliningrad Oblast) 261 km; Mongolia 3,452 km; Norway 191 km; Poland (Kaliningrad Oblast) 209 km; Ukraine 1,944 km", write a js function which will encapulate each country into a key and the border distance as the value and keep in mind some country names have "(data)" keep it in the key string.
91455607ddacf540742cbb69106d1533
{ "intermediate": 0.35880520939826965, "beginner": 0.38363465666770935, "expert": 0.2575601041316986 }
3,656
Найди ошибку в коде Java Connection connect; try { String drivername = "com.mysql.jdbc.Driver"; Class.forName(drivername); String servername = "***"; String database = "***"; String username = "***"; String password = "***"; String url = "jdbc:mysql://" + servername + "/" + database; connect = DriverManager.getConnection(url, username, password); System.out.println("[MYSQL] — Успешное подключение к базе данных MySQL!"); String query = "SELECT * FROM `accounts`"; Statement stmt = connect.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String login_sql = rs.getString("login"); String login_field = login_textField.getText(); if (login_field == login_sql) { System.out.println("+"); } System.out.println(login_sql); System.out.println(login_field); } } catch (Exception e) { System.out.println("[MYSQL ERROR] — Ошибка при подключении к базе данных MySQL."); JOptionPane.showMessageDialog(null, "Ошибка при подключении к базе данных MySQL.", "MySQL Error", 0); System.exit(0); }
e5de410cd6877d02cf3c5d0053a811f4
{ "intermediate": 0.2983134984970093, "beginner": 0.46251755952835083, "expert": 0.23916897177696228 }
3,657
which part of the script has to be changed, make a code block modify this script so it only cares for .gif and .gifv and .mp4 import requests import urllib.parse from datetime import datetime import json import gzip import os import shutil import signal from contextlib import contextmanager import time import argparse import configparser import concurrent.futures from contextlib import contextmanager from queue import Queue config = configparser.ConfigParser() config.read("config") #maxWorkers = int(config["CONFIG"]["MAX_WORKERS"]) maxWorkers = 4 # Go easy on Push shift root_folder = config["CONFIG"]["MEDIA_FOLDER"] global interrupted interrupted = False last_character = root_folder[-1] if last_character != "/": root_folder = root_folder + "/" global successful_subs global failed_subs successful_subs = Queue() failed_subs = Queue() class NoQuotedCommasSession(requests.Session): """ A custom session class that inherits from requests.Session and overrides the send method to avoid URL encoding of commas and allows setting a custom timeout. """ def __init__(self, timeout=None): super().__init__() self.timeout = timeout def send(self, *a, **kw): a[0].url = a[0].url.replace(urllib.parse.quote(','), ',') if self.timeout is not None: kw['timeout'] = self.timeout return super().send(*a, **kw) class GracefulInterrupt(Exception): """ A custom exception class to handle graceful interruption of the script. """ pass #@contextmanager class handle_interrupt: def __init__(self, func): self.func = func def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): global interrupted if exc_type == KeyboardInterrupt: interrupted = True print("Interrupt requested. Waiting for tasks to finish...") time.sleep(1) return True return False def __call__(self, *args, **kwargs): return self.func(*args, **kwargs) def displayOutput(): global sub_status_dict for sub in sub_status_dict: if sub_status_dict[sub]['completed'] == True: print(f"\rDownloading {sub} complete",end="",flush=True) else: print(f"\rDownloading {sub}...chunk {sub_status_dict[sub]['chunks']}",end="",flush=True) def fetch_chunk(sub_name, after=None, before=None, max_retries=7, retry_delay=5): """ Fetch a chunk of subreddit posts from the Pushshift API. Args: sub_name (str): The name of the subreddit to fetch posts from. after (int, optional): The timestamp to fetch posts after. max_retries (int, optional): The maximum number of retries before giving up. retry_delay (int, optional): The delay between retries in seconds. Returns: list: A list of post dictionaries fetched from the API. """ params = { 'subreddit': sub_name, 'fields': 'id,created_utc,domain,author,title,selftext,permalink', 'sort': 'created_utc', 'order': 'asc', 'size': 1000, } if after is not None: params['after'] = after if before is not None: params['before'] = before retries = 0 while retries <= max_retries: try: resp = NoQuotedCommasSession().get('https://api.pushshift.io/reddit/submission/search', params=params) resp.raise_for_status() return resp.json()['data'] except requests.HTTPError as e: if e.response.status_code == 524: print(f"Server timeout. Retrying in {retry_delay} seconds... (attempt {retries + 1}/{max_retries})") retries += 1 time.sleep(retry_delay) else: raise raise RuntimeError("Max retries exceeded. Aborting.") def fetch_all_subreddit_posts(sub_name, after=None, before=None): """ Fetch all subreddit posts using the Pushshift API, in chunks. Args: sub_name (str): The name of the subreddit to fetch posts from. after (int, optional): The timestamp to fetch posts after. before (int, optional): The timestamp to fetch posts before. Yields: dict: A dictionary containing post data. """ global interrupted global sub_status_dict if interrupted: print("Interrupted by user. Aborting.") return i = 1 while True: print(f'loading {sub_name} - chunk {i}',flush=True) sub_status_dict[sub_name]['chunks'] = i chunk = fetch_chunk(sub_name, after, before) #displayOutput() if not chunk: break yield from chunk after = chunk[-1]['created_utc'] + 1 # if i % 5 == 0: # print(f'loaded until {datetime.fromtimestamp(after)}') i += 1 print(f'{sub_name} done! loaded until {datetime.fromtimestamp(after)}') successful_subs.put(sub_name) sub_status_dict[sub_name]['completed'] = True #displayOutput() def compress_and_delete_json(input_file_path): """ Compress a JSON file using gzip and delete the original file. This function reads the input JSON file, compresses it using gzip, and saves the compressed content to a new file. It then deletes the original JSON file. Args: input_file_path (str): The path to the input JSON file. Example usage: compress_and_delete_json('subreddit_posts.json') """ output_file_path = input_file_path + '.gz' with open(input_file_path, 'rb') as input_file: with gzip.open(output_file_path, 'wb') as output_file: shutil.copyfileobj(input_file, output_file) os.remove(input_file_path) def write_posts_to_file(file_path, sub_name, is_incomplete=False, after=None, before=None): """ Write the posts yielded by the post_generator to a compressed JSON file. This function writes each post in the post_generator to the specified compressed JSON file. The posts are written as a JSON array, with each post separated by a comma and a newline. Args: file_path (str): The path to the compressed file to save the posts. sub_name (str): The name of the subreddit to fetch posts from. is_incomplete (bool, optional): Whether the file is incomplete. after (int, optional): The timestamp to fetch posts after. Example usage: write_posts_to_file('subreddit_posts.json.gz', 'eyebleach') """ global interrupted filename = os.path.basename(file_path) if not os.path.isfile(file_path): # Create file so we can open it in 'rb+' mode f = open(file_path, 'w') f.close() # Files are written uncompressed initially, so we can seek to the end when necessary with open(file_path, 'rb+') as f: post_generator = fetch_all_subreddit_posts(sub_name, after, before) if not is_incomplete: f.write(b'[') first_post = True else: first_post = False f.seek(0, os.SEEK_END) current_position = f.tell() while current_position > 0: current_position -= 1 f.seek(current_position) current_char = f.read(1) if current_char == b'}': current_position += 1 f.seek(current_position) break save_incomplete = False delete_incomplete = False file_finished = False post = None try: #with handle_graceful_interrupt(): for post in post_generator: if interrupted: break if not first_post: f.write(b',\n') else: first_post = False json_string = json.dumps(post) json_bytes = json_string.encode('utf-8') f.write(json_bytes) f.write(b'\n]') file_finished = True except requests.HTTPError as e: if e.response.status_code == 524: print("Server timeout.") elif e.response.status_code == 429: print(f"Rate Limit: Sleeping for 15 seconds") time.sleep(15) else: print(f"Unexpected server error: {e.response.status_code}") if first_post: delete_incomplete = True else: save_incomplete = True except KeyboardInterrupt: print("Interrupted by user. Finishing up the file.") save_incomplete = True interrupted = True except Exception as e: print(f"Unexpected error for sub {sub_name}: {e}") failed_subs.put(sub_name) if first_post: delete_incomplete = True else: save_incomplete = True if save_incomplete: print(f"Saving incomplete file: \"{filename}\"") f.write(b'\n]') if post is not None: timestamp = post["created_utc"] return timestamp else: after = 0 return after if delete_incomplete: print("No file saved") os.remove(file_path) return None if file_finished: # Compression time compress_and_delete_json(file_path) #print(f"File {filename} finished and compressed") return None def dump_subreddit_json(sub_name, out_dir='./', stop_early=False): """ Dump subreddit posts into a JSON file. This function checks if the JSON file with subreddit posts exists, and if it is complete or incomplete. If it is incomplete, the function resumes the data collection from the last known timestamp. If the file doesn't exist, the function starts collecting data from the beginning. The collected data is saved to a JSON file, and if the process is interrupted, an '.incomplete' file is created to store the last post's timestamp. Args: sub_name (str): The name of the subreddit to fetch posts from. """ #last_character = root_folder[-1] #if last_character == "/": out_dir = root_folder + "json/" #else: # out_dir = root_folder + "/json" if not os.path.exists(out_dir): os.makedirs(out_dir) filename = f'{sub_name}_subreddit_posts_raw.json' file_path = os.path.join(out_dir, filename) incomplete_path = file_path + '.incomplete' is_incomplete = os.path.isfile(incomplete_path) file_exists = os.path.isfile(file_path) if os.path.isfile(file_path + ".gz"): print(f"Zipped version of file already exists: {filename}.gz\nTo generate a new one, \ manually delete it and rerun the script.") return if is_incomplete and not file_exists: os.remove(incomplete_path) is_incomplete = False if file_exists and not is_incomplete: print(f"Error. File \"{filename}\" exists and does not seem to be incomplete. If it is \ incomplete, create a new '.incomplete' file with the last post's timestamp. If it is completely \ broken, delete it. Then, rerun the script. Otherwise, manually zip it with gzip.") return before = None if stop_early: before = 1577862000 # Jan 1, 2020: Onlyfans surges in popularity if is_incomplete: with open(incomplete_path, 'r') as incomplete_file: timestamp_s = incomplete_file.readline() timestamp = int(timestamp_s) with open(incomplete_path, 'w') as incomplete_file: result = write_posts_to_file(file_path, sub_name, is_incomplete=True, after=timestamp, before=before) if result is not None: incomplete_file.write(str(result)) if result is None: os.remove(incomplete_path) else: result = None with open(incomplete_path, 'w') as incomplete_file: result = write_posts_to_file(file_path, sub_name, before=before) if (result is not None): incomplete_file.write(str(result)) if (result is None): os.remove(incomplete_path) def main_func(func): with handle_interrupt(func) as wrapped_func: wrapped_func() @handle_interrupt def main(): global sub_status_dict sub_status_dict = {} subreddit_file = 'subs' out_dir = root_folder + "json/" if not os.path.exists(out_dir): os.makedirs(out_dir) print(f"Opening subs file: {subreddit_file}") print(f"Downloading json to {out_dir}") with open(subreddit_file) as f: subreddit_names = f.read().splitlines() with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor: futures = [] for subreddit_name in subreddit_names: sub_status_dict[subreddit_name] = { "completed": False, "chunks": 0 } # print(f"Gathering JSON for {subreddit_name}") future = executor.submit(dump_subreddit_json, subreddit_name) futures.append(future) for future in concurrent.futures.as_completed(futures): try: result = future.result() except Exception as exc: print(f'Exception {exc} generated while processing {future}') if __name__ == '__main__': main_func(main) #ChatGPT made me do it print(f"Successfully Downloaded") while not successful_subs.empty(): item = successful_subs.get() print(f" - {item.strip()}") if failed_subs.empty(): print(f"No reported error with any subs") else: print(f"Failed to retrieve data for these subs") while not failed_subs.empty(): item = failed_subs.get() print(f" - {item.strip()}")
5170b679fcf1062239c815d3527a7a68
{ "intermediate": 0.41906967759132385, "beginner": 0.41092145442962646, "expert": 0.17000886797904968 }
3,658
which part of the script has to be changed, make a code block modify this script so it only cares for .gif and .gifv and .mp4 import requests import urllib.parse from datetime import datetime import json import gzip import os import shutil import signal from contextlib import contextmanager import time import argparse import configparser import concurrent.futures from contextlib import contextmanager from queue import Queue config = configparser.ConfigParser() config.read("config") #maxWorkers = int(config["CONFIG"]["MAX_WORKERS"]) maxWorkers = 4 # Go easy on Push shift root_folder = config["CONFIG"]["MEDIA_FOLDER"] global interrupted interrupted = False last_character = root_folder[-1] if last_character != "/": root_folder = root_folder + "/" global successful_subs global failed_subs successful_subs = Queue() failed_subs = Queue() class NoQuotedCommasSession(requests.Session): """ A custom session class that inherits from requests.Session and overrides the send method to avoid URL encoding of commas and allows setting a custom timeout. """ def __init__(self, timeout=None): super().__init__() self.timeout = timeout def send(self, *a, **kw): a[0].url = a[0].url.replace(urllib.parse.quote(','), ',') if self.timeout is not None: kw['timeout'] = self.timeout return super().send(*a, **kw) class GracefulInterrupt(Exception): """ A custom exception class to handle graceful interruption of the script. """ pass #@contextmanager class handle_interrupt: def __init__(self, func): self.func = func def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): global interrupted if exc_type == KeyboardInterrupt: interrupted = True print("Interrupt requested. Waiting for tasks to finish...") time.sleep(1) return True return False def __call__(self, *args, **kwargs): return self.func(*args, **kwargs) def displayOutput(): global sub_status_dict for sub in sub_status_dict: if sub_status_dict[sub]['completed'] == True: print(f"\rDownloading {sub} complete",end="",flush=True) else: print(f"\rDownloading {sub}...chunk {sub_status_dict[sub]['chunks']}",end="",flush=True) def fetch_chunk(sub_name, after=None, before=None, max_retries=7, retry_delay=5): """ Fetch a chunk of subreddit posts from the Pushshift API. Args: sub_name (str): The name of the subreddit to fetch posts from. after (int, optional): The timestamp to fetch posts after. max_retries (int, optional): The maximum number of retries before giving up. retry_delay (int, optional): The delay between retries in seconds. Returns: list: A list of post dictionaries fetched from the API. """ params = { 'subreddit': sub_name, 'fields': 'id,created_utc,domain,author,title,selftext,permalink', 'sort': 'created_utc', 'order': 'asc', 'size': 1000, } if after is not None: params['after'] = after if before is not None: params['before'] = before retries = 0 while retries <= max_retries: try: resp = NoQuotedCommasSession().get('https://api.pushshift.io/reddit/submission/search', params=params) resp.raise_for_status() return resp.json()['data'] except requests.HTTPError as e: if e.response.status_code == 524: print(f"Server timeout. Retrying in {retry_delay} seconds... (attempt {retries + 1}/{max_retries})") retries += 1 time.sleep(retry_delay) else: raise raise RuntimeError("Max retries exceeded. Aborting.") def fetch_all_subreddit_posts(sub_name, after=None, before=None): """ Fetch all subreddit posts using the Pushshift API, in chunks. Args: sub_name (str): The name of the subreddit to fetch posts from. after (int, optional): The timestamp to fetch posts after. before (int, optional): The timestamp to fetch posts before. Yields: dict: A dictionary containing post data. """ global interrupted global sub_status_dict if interrupted: print("Interrupted by user. Aborting.") return i = 1 while True: print(f'loading {sub_name} - chunk {i}',flush=True) sub_status_dict[sub_name]['chunks'] = i chunk = fetch_chunk(sub_name, after, before) #displayOutput() if not chunk: break yield from chunk after = chunk[-1]['created_utc'] + 1 # if i % 5 == 0: # print(f'loaded until {datetime.fromtimestamp(after)}') i += 1 print(f'{sub_name} done! loaded until {datetime.fromtimestamp(after)}') successful_subs.put(sub_name) sub_status_dict[sub_name]['completed'] = True #displayOutput() def compress_and_delete_json(input_file_path): """ Compress a JSON file using gzip and delete the original file. This function reads the input JSON file, compresses it using gzip, and saves the compressed content to a new file. It then deletes the original JSON file. Args: input_file_path (str): The path to the input JSON file. Example usage: compress_and_delete_json('subreddit_posts.json') """ output_file_path = input_file_path + '.gz' with open(input_file_path, 'rb') as input_file: with gzip.open(output_file_path, 'wb') as output_file: shutil.copyfileobj(input_file, output_file) os.remove(input_file_path) def write_posts_to_file(file_path, sub_name, is_incomplete=False, after=None, before=None): """ Write the posts yielded by the post_generator to a compressed JSON file. This function writes each post in the post_generator to the specified compressed JSON file. The posts are written as a JSON array, with each post separated by a comma and a newline. Args: file_path (str): The path to the compressed file to save the posts. sub_name (str): The name of the subreddit to fetch posts from. is_incomplete (bool, optional): Whether the file is incomplete. after (int, optional): The timestamp to fetch posts after. Example usage: write_posts_to_file('subreddit_posts.json.gz', 'eyebleach') """ global interrupted filename = os.path.basename(file_path) if not os.path.isfile(file_path): # Create file so we can open it in 'rb+' mode f = open(file_path, 'w') f.close() # Files are written uncompressed initially, so we can seek to the end when necessary with open(file_path, 'rb+') as f: post_generator = fetch_all_subreddit_posts(sub_name, after, before) if not is_incomplete: f.write(b'[') first_post = True else: first_post = False f.seek(0, os.SEEK_END) current_position = f.tell() while current_position > 0: current_position -= 1 f.seek(current_position) current_char = f.read(1) if current_char == b'}': current_position += 1 f.seek(current_position) break save_incomplete = False delete_incomplete = False file_finished = False post = None try: #with handle_graceful_interrupt(): for post in post_generator: if interrupted: break if not first_post: f.write(b',\n') else: first_post = False json_string = json.dumps(post) json_bytes = json_string.encode('utf-8') f.write(json_bytes) f.write(b'\n]') file_finished = True except requests.HTTPError as e: if e.response.status_code == 524: print("Server timeout.") elif e.response.status_code == 429: print(f"Rate Limit: Sleeping for 15 seconds") time.sleep(15) else: print(f"Unexpected server error: {e.response.status_code}") if first_post: delete_incomplete = True else: save_incomplete = True except KeyboardInterrupt: print("Interrupted by user. Finishing up the file.") save_incomplete = True interrupted = True except Exception as e: print(f"Unexpected error for sub {sub_name}: {e}") failed_subs.put(sub_name) if first_post: delete_incomplete = True else: save_incomplete = True if save_incomplete: print(f"Saving incomplete file: \"{filename}\"") f.write(b'\n]') if post is not None: timestamp = post["created_utc"] return timestamp else: after = 0 return after if delete_incomplete: print("No file saved") os.remove(file_path) return None if file_finished: # Compression time compress_and_delete_json(file_path) #print(f"File {filename} finished and compressed") return None def dump_subreddit_json(sub_name, out_dir='./', stop_early=False): """ Dump subreddit posts into a JSON file. This function checks if the JSON file with subreddit posts exists, and if it is complete or incomplete. If it is incomplete, the function resumes the data collection from the last known timestamp. If the file doesn't exist, the function starts collecting data from the beginning. The collected data is saved to a JSON file, and if the process is interrupted, an '.incomplete' file is created to store the last post's timestamp. Args: sub_name (str): The name of the subreddit to fetch posts from. """ #last_character = root_folder[-1] #if last_character == "/": out_dir = root_folder + "json/" #else: # out_dir = root_folder + "/json" if not os.path.exists(out_dir): os.makedirs(out_dir) filename = f'{sub_name}_subreddit_posts_raw.json' file_path = os.path.join(out_dir, filename) incomplete_path = file_path + '.incomplete' is_incomplete = os.path.isfile(incomplete_path) file_exists = os.path.isfile(file_path) if os.path.isfile(file_path + ".gz"): print(f"Zipped version of file already exists: {filename}.gz\nTo generate a new one, \ manually delete it and rerun the script.") return if is_incomplete and not file_exists: os.remove(incomplete_path) is_incomplete = False if file_exists and not is_incomplete: print(f"Error. File \"{filename}\" exists and does not seem to be incomplete. If it is \ incomplete, create a new '.incomplete' file with the last post's timestamp. If it is completely \ broken, delete it. Then, rerun the script. Otherwise, manually zip it with gzip.") return before = None if stop_early: before = 1577862000 # Jan 1, 2020: Onlyfans surges in popularity if is_incomplete: with open(incomplete_path, 'r') as incomplete_file: timestamp_s = incomplete_file.readline() timestamp = int(timestamp_s) with open(incomplete_path, 'w') as incomplete_file: result = write_posts_to_file(file_path, sub_name, is_incomplete=True, after=timestamp, before=before) if result is not None: incomplete_file.write(str(result)) if result is None: os.remove(incomplete_path) else: result = None with open(incomplete_path, 'w') as incomplete_file: result = write_posts_to_file(file_path, sub_name, before=before) if (result is not None): incomplete_file.write(str(result)) if (result is None): os.remove(incomplete_path) def main_func(func): with handle_interrupt(func) as wrapped_func: wrapped_func() @handle_interrupt def main(): global sub_status_dict sub_status_dict = {} subreddit_file = 'subs' out_dir = root_folder + "json/" if not os.path.exists(out_dir): os.makedirs(out_dir) print(f"Opening subs file: {subreddit_file}") print(f"Downloading json to {out_dir}") with open(subreddit_file) as f: subreddit_names = f.read().splitlines() with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor: futures = [] for subreddit_name in subreddit_names: sub_status_dict[subreddit_name] = { "completed": False, "chunks": 0 } # print(f"Gathering JSON for {subreddit_name}") future = executor.submit(dump_subreddit_json, subreddit_name) futures.append(future) for future in concurrent.futures.as_completed(futures): try: result = future.result() except Exception as exc: print(f'Exception {exc} generated while processing {future}') if __name__ == '__main__': main_func(main) #ChatGPT made me do it print(f"Successfully Downloaded") while not successful_subs.empty(): item = successful_subs.get() print(f" - {item.strip()}") if failed_subs.empty(): print(f"No reported error with any subs") else: print(f"Failed to retrieve data for these subs") while not failed_subs.empty(): item = failed_subs.get() print(f" - {item.strip()}")
c20f0cc746d4bf9a08564e2d4459c6b7
{ "intermediate": 0.41906967759132385, "beginner": 0.41092145442962646, "expert": 0.17000886797904968 }
3,659
which part of the script has to be changed, make a code block modify this script so it only cares for .gif and .gifv and .mp4 import requests import urllib.parse from datetime import datetime import json import gzip import os import shutil import signal from contextlib import contextmanager import time import argparse import configparser import concurrent.futures from contextlib import contextmanager from queue import Queue config = configparser.ConfigParser() config.read("config") #maxWorkers = int(config["CONFIG"]["MAX_WORKERS"]) maxWorkers = 4 # Go easy on Push shift root_folder = config["CONFIG"]["MEDIA_FOLDER"] global interrupted interrupted = False last_character = root_folder[-1] if last_character != "/": root_folder = root_folder + "/" global successful_subs global failed_subs successful_subs = Queue() failed_subs = Queue() class NoQuotedCommasSession(requests.Session): """ A custom session class that inherits from requests.Session and overrides the send method to avoid URL encoding of commas and allows setting a custom timeout. """ def __init__(self, timeout=None): super().__init__() self.timeout = timeout def send(self, *a, **kw): a[0].url = a[0].url.replace(urllib.parse.quote(','), ',') if self.timeout is not None: kw['timeout'] = self.timeout return super().send(*a, **kw) class GracefulInterrupt(Exception): """ A custom exception class to handle graceful interruption of the script. """ pass #@contextmanager class handle_interrupt: def __init__(self, func): self.func = func def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): global interrupted if exc_type == KeyboardInterrupt: interrupted = True print("Interrupt requested. Waiting for tasks to finish...") time.sleep(1) return True return False def __call__(self, *args, **kwargs): return self.func(*args, **kwargs) def displayOutput(): global sub_status_dict for sub in sub_status_dict: if sub_status_dict[sub]['completed'] == True: print(f"\rDownloading {sub} complete",end="",flush=True) else: print(f"\rDownloading {sub}...chunk {sub_status_dict[sub]['chunks']}",end="",flush=True) def fetch_chunk(sub_name, after=None, before=None, max_retries=7, retry_delay=5): """ Fetch a chunk of subreddit posts from the Pushshift API. Args: sub_name (str): The name of the subreddit to fetch posts from. after (int, optional): The timestamp to fetch posts after. max_retries (int, optional): The maximum number of retries before giving up. retry_delay (int, optional): The delay between retries in seconds. Returns: list: A list of post dictionaries fetched from the API. """ params = { 'subreddit': sub_name, 'fields': 'id,created_utc,domain,author,title,selftext,permalink', 'sort': 'created_utc', 'order': 'asc', 'size': 1000, } if after is not None: params['after'] = after if before is not None: params['before'] = before retries = 0 while retries <= max_retries: try: resp = NoQuotedCommasSession().get('https://api.pushshift.io/reddit/submission/search', params=params) resp.raise_for_status() return resp.json()['data'] except requests.HTTPError as e: if e.response.status_code == 524: print(f"Server timeout. Retrying in {retry_delay} seconds... (attempt {retries + 1}/{max_retries})") retries += 1 time.sleep(retry_delay) else: raise raise RuntimeError("Max retries exceeded. Aborting.") def fetch_all_subreddit_posts(sub_name, after=None, before=None): """ Fetch all subreddit posts using the Pushshift API, in chunks. Args: sub_name (str): The name of the subreddit to fetch posts from. after (int, optional): The timestamp to fetch posts after. before (int, optional): The timestamp to fetch posts before. Yields: dict: A dictionary containing post data. """ global interrupted global sub_status_dict if interrupted: print("Interrupted by user. Aborting.") return i = 1 while True: print(f'loading {sub_name} - chunk {i}',flush=True) sub_status_dict[sub_name]['chunks'] = i chunk = fetch_chunk(sub_name, after, before) #displayOutput() if not chunk: break yield from chunk after = chunk[-1]['created_utc'] + 1 # if i % 5 == 0: # print(f'loaded until {datetime.fromtimestamp(after)}') i += 1 print(f'{sub_name} done! loaded until {datetime.fromtimestamp(after)}') successful_subs.put(sub_name) sub_status_dict[sub_name]['completed'] = True #displayOutput() def compress_and_delete_json(input_file_path): """ Compress a JSON file using gzip and delete the original file. This function reads the input JSON file, compresses it using gzip, and saves the compressed content to a new file. It then deletes the original JSON file. Args: input_file_path (str): The path to the input JSON file. Example usage: compress_and_delete_json('subreddit_posts.json') """ output_file_path = input_file_path + '.gz' with open(input_file_path, 'rb') as input_file: with gzip.open(output_file_path, 'wb') as output_file: shutil.copyfileobj(input_file, output_file) os.remove(input_file_path) def write_posts_to_file(file_path, sub_name, is_incomplete=False, after=None, before=None): """ Write the posts yielded by the post_generator to a compressed JSON file. This function writes each post in the post_generator to the specified compressed JSON file. The posts are written as a JSON array, with each post separated by a comma and a newline. Args: file_path (str): The path to the compressed file to save the posts. sub_name (str): The name of the subreddit to fetch posts from. is_incomplete (bool, optional): Whether the file is incomplete. after (int, optional): The timestamp to fetch posts after. Example usage: write_posts_to_file('subreddit_posts.json.gz', 'eyebleach') """ global interrupted filename = os.path.basename(file_path) if not os.path.isfile(file_path): # Create file so we can open it in 'rb+' mode f = open(file_path, 'w') f.close() # Files are written uncompressed initially, so we can seek to the end when necessary with open(file_path, 'rb+') as f: post_generator = fetch_all_subreddit_posts(sub_name, after, before) if not is_incomplete: f.write(b'[') first_post = True else: first_post = False f.seek(0, os.SEEK_END) current_position = f.tell() while current_position > 0: current_position -= 1 f.seek(current_position) current_char = f.read(1) if current_char == b'}': current_position += 1 f.seek(current_position) break save_incomplete = False delete_incomplete = False file_finished = False post = None try: #with handle_graceful_interrupt(): for post in post_generator: if interrupted: break if not first_post: f.write(b',\n') else: first_post = False json_string = json.dumps(post) json_bytes = json_string.encode('utf-8') f.write(json_bytes) f.write(b'\n]') file_finished = True except requests.HTTPError as e: if e.response.status_code == 524: print("Server timeout.") elif e.response.status_code == 429: print(f"Rate Limit: Sleeping for 15 seconds") time.sleep(15) else: print(f"Unexpected server error: {e.response.status_code}") if first_post: delete_incomplete = True else: save_incomplete = True except KeyboardInterrupt: print("Interrupted by user. Finishing up the file.") save_incomplete = True interrupted = True except Exception as e: print(f"Unexpected error for sub {sub_name}: {e}") failed_subs.put(sub_name) if first_post: delete_incomplete = True else: save_incomplete = True if save_incomplete: print(f"Saving incomplete file: \"{filename}\"") f.write(b'\n]') if post is not None: timestamp = post["created_utc"] return timestamp else: after = 0 return after if delete_incomplete: print("No file saved") os.remove(file_path) return None if file_finished: # Compression time compress_and_delete_json(file_path) #print(f"File {filename} finished and compressed") return None def dump_subreddit_json(sub_name, out_dir='./', stop_early=False): """ Dump subreddit posts into a JSON file. This function checks if the JSON file with subreddit posts exists, and if it is complete or incomplete. If it is incomplete, the function resumes the data collection from the last known timestamp. If the file doesn't exist, the function starts collecting data from the beginning. The collected data is saved to a JSON file, and if the process is interrupted, an '.incomplete' file is created to store the last post's timestamp. Args: sub_name (str): The name of the subreddit to fetch posts from. """ #last_character = root_folder[-1] #if last_character == "/": out_dir = root_folder + "json/" #else: # out_dir = root_folder + "/json" if not os.path.exists(out_dir): os.makedirs(out_dir) filename = f'{sub_name}_subreddit_posts_raw.json' file_path = os.path.join(out_dir, filename) incomplete_path = file_path + '.incomplete' is_incomplete = os.path.isfile(incomplete_path) file_exists = os.path.isfile(file_path) if os.path.isfile(file_path + ".gz"): print(f"Zipped version of file already exists: {filename}.gz\nTo generate a new one, \ manually delete it and rerun the script.") return if is_incomplete and not file_exists: os.remove(incomplete_path) is_incomplete = False if file_exists and not is_incomplete: print(f"Error. File \"{filename}\" exists and does not seem to be incomplete. If it is \ incomplete, create a new '.incomplete' file with the last post's timestamp. If it is completely \ broken, delete it. Then, rerun the script. Otherwise, manually zip it with gzip.") return before = None if stop_early: before = 1577862000 # Jan 1, 2020: Onlyfans surges in popularity if is_incomplete: with open(incomplete_path, 'r') as incomplete_file: timestamp_s = incomplete_file.readline() timestamp = int(timestamp_s) with open(incomplete_path, 'w') as incomplete_file: result = write_posts_to_file(file_path, sub_name, is_incomplete=True, after=timestamp, before=before) if result is not None: incomplete_file.write(str(result)) if result is None: os.remove(incomplete_path) else: result = None with open(incomplete_path, 'w') as incomplete_file: result = write_posts_to_file(file_path, sub_name, before=before) if (result is not None): incomplete_file.write(str(result)) if (result is None): os.remove(incomplete_path) def main_func(func): with handle_interrupt(func) as wrapped_func: wrapped_func() @handle_interrupt def main(): global sub_status_dict sub_status_dict = {} subreddit_file = 'subs' out_dir = root_folder + "json/" if not os.path.exists(out_dir): os.makedirs(out_dir) print(f"Opening subs file: {subreddit_file}") print(f"Downloading json to {out_dir}") with open(subreddit_file) as f: subreddit_names = f.read().splitlines() with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor: futures = [] for subreddit_name in subreddit_names: sub_status_dict[subreddit_name] = { "completed": False, "chunks": 0 } # print(f"Gathering JSON for {subreddit_name}") future = executor.submit(dump_subreddit_json, subreddit_name) futures.append(future) for future in concurrent.futures.as_completed(futures): try: result = future.result() except Exception as exc: print(f'Exception {exc} generated while processing {future}') if __name__ == '__main__': main_func(main) #ChatGPT made me do it print(f"Successfully Downloaded") while not successful_subs.empty(): item = successful_subs.get() print(f" - {item.strip()}") if failed_subs.empty(): print(f"No reported error with any subs") else: print(f"Failed to retrieve data for these subs") while not failed_subs.empty(): item = failed_subs.get() print(f" - {item.strip()}")
646deb3fe4535250a274121d62dbcc2c
{ "intermediate": 0.41906967759132385, "beginner": 0.41092145442962646, "expert": 0.17000886797904968 }
3,660
модифицируй код так, чтобы в коде результаты добавлялись в базу данных 'kross' , а также, чтобы код проходил цикл проходил цикл от n=2 до 200 в коде from bs4 import BeautifulSoup import requests url = f'https://www.poizon.us/collections/sneakers-1?page={n}' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # gf-products > li:nth-child(1) > div > div > div.card__content > div.card__information > h3 > a links = soup.select('a.full-unstyled-link') processed_links = set() for link in links: if link is not None: href = link.get('href') if href is not None: full_link = 'https://www.poizon.us' + href else: print('Ссылка не найдена') continue if full_link in processed_links: continue processed_links.add(full_link) response = requests.get(full_link) soup = BeautifulSoup(response.text, 'html.parser') photo_selector = '#Thumbnail-template--16663852253403__main-1' photo_links = soup.select_one(photo_selector).get('srcset').split(', ') photo_link = photo_links[0].split(' ')[0] size_selector = 'div.product-popup-modal__content-info:nth-child(1) > variant-radios:nth-child(1) > fieldset:nth-child(2) > label:nth-child(3) > div:nth-child(1)' price_selector = 'div.product-popup-modal__content-info:nth-child(1) > variant-radios:nth-child(1) > fieldset:nth-child(2) > label:nth-child(3) > div:nth-child(2)' size_element = soup.select_one(size_selector) if size_element is not None: size = size_element.text.strip() else: size = 'Размер не найден' price_element = soup.select_one(price_selector) if price_element is not None: price = price_element.text.strip() else: price = 'Цена не найдена' name_element = soup.select_one('div.product__title > h1:nth-child(1)') if name_element is not None: name = name_element.text.strip() else: name = 'Название не найдено' info_element = soup.select_one('#ProductAccordion-ea1014ee-ae9d-4eee-b23c-d2dfe9ba75b4-template--16663852253403__main') if info_element is not None: info = info_element.text.strip() else: info = 'Информация не найдена' urls = photo_link.replace("//", "https://") url = urls+'111' photo_lin = photo_link.replace('//cdn.shopify.com', 'https://cdn.shopify.com') print(f'Название: {name}\nРазмер: {size}\nИнформация: {info}') print(f"цена: {price}") print(f'ссылка {url}')
78f8280fe825158e0bbc1eafdf380f55
{ "intermediate": 0.23016192018985748, "beginner": 0.5272055864334106, "expert": 0.24263252317905426 }
3,661
i want to use fetch function in browser to make a post request, the endpoint is /api/signin, the body is {email, password} in json format. can you write some js for this?
de7ec88714f4b2dc9a7fcf937ee24a18
{ "intermediate": 0.5632959604263306, "beginner": 0.3031294047832489, "expert": 0.13357460498809814 }
3,662
pouvez vous corriger ces érreurs: Gravité Code Description Projet Fichier Ligne État de la suppression Erreur LNK2019 symbole externe non résolu _main référencé dans la fonction "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ) Xevyyy Cheat C:\Users\Tilio\source\repos\Xevyyy Cheat\Xevyyy Cheat\MSVCRTD.lib(exe_main.obj) 1 Avertissement C28251 Annotation incohérente pour 'wWinMain' : cette instance contient aucune annotation. Voir c:\program files (x86)\windows kits\10\include\10.0.19041.0\um\winbase.h(1019). Xevyyy Cheat C:\Users\Tilio\source\repos\Xevyyy Cheat\Xevyyy Cheat\Source.cpp 18 Erreur LNK1120 1 externes non résolus Xevyyy Cheat C:\Users\Tilio\source\repos\Xevyyy Cheat\Debug\Xevyyy Cheat.exe 1 de mon code: #include <iostream> #include <Windows.h> #include <CommCtrl.h> #pragma comment(lib, "comctl32.lib") #define WINDOW_WIDTH 480 #define WINDOW_HEIGHT 360 #define BUTTON_WIDTH 120 #define BUTTON_HEIGHT 30 #define JG_WIDTH 300 #define JG_HEIGHT 30 LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow) { // Register window class WNDCLASSEX wc; wc.cbSize = sizeof(WNDCLASSEX); wc.style = 0; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = NULL; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW); wc.lpszMenuName = NULL; wc.lpszClassName = L"XevyyyCheat"; wc.hIconSm = NULL; if (!RegisterClassEx(&wc)) { MessageBoxW(NULL, L"Window Registration Failed!", L"Error", MB_ICONEXCLAMATION | MB_OK); return 0; } // Create window HWND hwnd = CreateWindowEx( WS_EX_CLIENTEDGE, L"XevyyyCheat", L"Xevyyy Cheat", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, WINDOW_WIDTH, WINDOW_HEIGHT, NULL, NULL, hInstance, NULL); if (hwnd == NULL) { MessageBoxW(NULL, L"Window Creation Failed!", L"Error", MB_ICONEXCLAMATION | MB_OK); return 0; } // Create button controls HWND aimbotBtn = CreateWindow( L"BUTTON", // Predefined class; Unicode assumed L"Aimbot", // Button text WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, // Styles 20, // x position 20, // y position BUTTON_WIDTH, // Button width BUTTON_HEIGHT, // Button height hwnd, // Parent window NULL, // No menu. hInstance, NULL); // Pointer not needed. HWND triggerbotBtn = CreateWindow( L"BUTTON", // Predefined class; Unicode assumed L"Triggerbot", // Button text WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, // Styles 160, // x position 20, // y position BUTTON_WIDTH, // Button width BUTTON_HEIGHT, // Button height hwnd, // Parent window NULL, // No menu. hInstance, NULL); // Pointer not needed. HWND spinbotBtn = CreateWindow( L"BUTTON", // Predefined class; Unicode assumed L"Spinbot", // Button text WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, // Styles 300, // x position 20, // y position BUTTON_WIDTH, // Button width BUTTON_HEIGHT, // Button height hwnd, // Parent window NULL, // No menu. hInstance, NULL); // Pointer not needed. // Create Jiggle control HWND jiggleControl = CreateWindowEx( 0, TRACKBAR_CLASSW, NULL, WS_CHILD | WS_VISIBLE | TBS_AUTOTICKS, (WINDOW_WIDTH - JG_WIDTH) / 2, 100, JG_WIDTH, JG_HEIGHT, hwnd, (HMENU)1, hInstance, NULL); SendMessageW(jiggleControl, TBM_SETRANGE, TRUE, MAKELONG(0, 100)); SendMessageW(jiggleControl, TBM_SETPOS, TRUE, 50); // Show window ShowWindow(hwnd, nCmdShow); UpdateWindow(hwnd); // Message loop MSG msg; while (GetMessage(&msg, NULL, 0, 0) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; } LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_COMMAND: { if (LOWORD(wParam) == BN_CLICKED) { if (HIWORD(wParam) == 0) // Aimbot button clicked { MessageBoxW(hwnd, L"Aimbot activated!", L"Message", MB_OK); } else if (HIWORD(wParam) == 1) // Triggerbot button clicked { MessageBoxW(hwnd, L"Triggerbot activated!", L"Message", MB_OK); } else if (HIWORD(wParam) == 2) // Spinbot button clicked { MessageBoxW(hwnd, L"Spinbot activated!", L"Message", MB_OK); } } } break; case WM_DESTROY: { PostQuitMessage(0); } break; default: return DefWindowProc(hwnd, msg, wParam, lParam); } return 0; }
c06bb596339c58ba33d8aa47f609e1cb
{ "intermediate": 0.3652128577232361, "beginner": 0.29074159264564514, "expert": 0.3440455198287964 }
3,663
how to make a trading bot for leverage trading?
8c2524ec7b7c303c96952d5e17d81c91
{ "intermediate": 0.17668354511260986, "beginner": 0.11093175411224365, "expert": 0.7123846411705017 }
3,664
I have the following python code file, model.py, containing sqlalchemy models, please analyse them and their relationships and advise of any problems with the schema, also, if I could get a demonstration of how to apply the UniqueConstraint I have in the comments of the code: from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() # UTILITY TABLES class HashType(Base): __tablename__ = "hash_types" id = Column(Integer, primary_key=True, index=True) name = Column(String, unique=True, nullable=False) hashes = relationship("Hash", back_populates="type") def __init__(self, name: str) -> None: self.name = name def __repr__(self): return f"[TABLE={self.__tablename__}, ID={self.id}] {self.name}" class File(Base): __tablename__ = "files" id = Column(Integer, primary_key=True, index=True) path = Column(String, unique=True, nullable=False) fingerprint_id = Column(Integer, ForeignKey("fingerprints.id"), nullable=False) fingerprint = relationship("Fingerprint", back_populates="files") def __init__(self, path) -> None: self.path = path def __repr__(self): return f"[TABLE={self.__tablename__}, ID={self.id}] Path=`{self.path}`" class Fingerprint(Base): __tablename__ = "fingerprints" id = Column(Integer, primary_key=True, index=True) fingerprint = Column(String, unique=True, nullable=False) files = relationship("File", back_populates="fingerprint") hashes = relationship("Hash") def __init__(self, fingerprint: str) -> None: self.fingerprint = fingerprint def __repr__(self): return f"[TABLE={self.__tablename__}, ID={self.id}] Fingerprint=`{self.fingerprint}`" class Hash(Base): __tablename__ = "hashes" id = Column(Integer, primary_key=True, index=True) hash = Column(String, nullable=False) hash_type_id = Column(Integer, ForeignKey("hash_types.id"), nullable=False) fingerprint_id = Column(Integer, ForeignKey("fingerprints.id"), nullable=False) # TODO: Figure out the proper usage for this: # UniqueConstraint(["hash", "hash_type_id", "fingerprint_id"]) type = relationship("HashType", back_populates="hashes") fingerprints = relationship("Fingerprint", back_populates="hashes") def __init__(self, hash: str): self.hash = hash def __repr__(self): return f"[TABLE={self.__tablename__}, ID={self.id}] `{self.hash}`)"
fb8154024a91c9c6867e33877b77c022
{ "intermediate": 0.3320375382900238, "beginner": 0.39435678720474243, "expert": 0.27360567450523376 }
3,665
Task 2 Spark Suppose you have two large datasets: the first dataset contains information about user activity on a website. It consists of log files in CSV format, where each row represents a single page visit by a user. Each row includes the following fields: • IP address (string) • Timestamp (int) • URL visited (string) The second dataset contains information about users themselves. It is also in CSV format, with one row per user. Each row includes the following fields: • User ID (int) • Name (string) • Email address (string) You can download a sample version of these datasets from the following link: https://www.kaggle.com/c/web-traffic-time-series-forecasting/data Task: Your task is to join these two datasets together based on user ID, and then perform some analysis on the resulting dataset. To do this, you'll need to use Apache Spark and PySpark on the Cloudera VM. You'll start by reading in both datasets as RDDs and caching them in memory for faster access. Then you'll perform a join operation on the user ID field using Spark transformations. Once you have your joined dataset, perform these actions on it to analyze the data: • Calculate the average time spent on the website per user. • Identify the most popular pages visited by each user. During this process, you'll also need to keep track of certain metrics using accumulators, such as the number of records processed, and the number of errors encountered. Additionally, you may want to use broadcast variables to efficiently share read-only data across multiple nodes
3edaefd7d3343caf5d8962e60d11732e
{ "intermediate": 0.4835427403450012, "beginner": 0.23891325294971466, "expert": 0.2775440514087677 }
3,666
I'm writing c++. Assume the following expression: const int a = foo(b), where foor returns a reference of int. Is this legal c++ code?
26020cae032f916915411cd5202c4b25
{ "intermediate": 0.2482144832611084, "beginner": 0.5612170100212097, "expert": 0.19056853652000427 }
3,667
how to code minecraft in unity
c90356f8f5108c0c6dd00e4a3e924ac4
{ "intermediate": 0.28205224871635437, "beginner": 0.3951365649700165, "expert": 0.32281115651130676 }
3,668
I have the following python code file, model.py, containing sqlalchemy models, please analyse them and their relationships and advise of any problems with the schema, also, if I could get a demonstration of how to apply the UniqueConstraint I have in the comments of the code: from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() # UTILITY TABLES class HashType(Base): __tablename__ = "hash_types" id = Column(Integer, primary_key=True, index=True) name = Column(String, unique=True, nullable=False) hashes = relationship("Hash", back_populates="type") def __init__(self, name: str) -> None: self.name = name def __repr__(self): return f"[TABLE={self.__tablename__}, ID={self.id}] {self.name}" class File(Base): __tablename__ = "files" id = Column(Integer, primary_key=True, index=True) path = Column(String, unique=True, nullable=False) fingerprint_id = Column(Integer, ForeignKey("fingerprints.id"), nullable=False) fingerprint = relationship("Fingerprint", back_populates="files") def __init__(self, path) -> None: self.path = path def __repr__(self): return f"[TABLE={self.__tablename__}, ID={self.id}] Path=`{self.path}`" class Fingerprint(Base): __tablename__ = "fingerprints" id = Column(Integer, primary_key=True, index=True) fingerprint = Column(String, unique=True, nullable=False) files = relationship("File", back_populates="fingerprint") hashes = relationship("Hash") def __init__(self, fingerprint: str) -> None: self.fingerprint = fingerprint def __repr__(self): return f"[TABLE={self.__tablename__}, ID={self.id}] Fingerprint=`{self.fingerprint}`" class Hash(Base): __tablename__ = "hashes" id = Column(Integer, primary_key=True, index=True) hash = Column(String, nullable=False) hash_type_id = Column(Integer, ForeignKey("hash_types.id"), nullable=False) fingerprint_id = Column(Integer, ForeignKey("fingerprints.id"), nullable=False) # TODO: Figure out the proper usage for this: # UniqueConstraint(["hash", "hash_type_id", "fingerprint_id"]) type = relationship("HashType", back_populates="hashes") fingerprints = relationship("Fingerprint", back_populates="hashes") def __init__(self, hash: str): self.hash = hash def __repr__(self): return f"[TABLE={self.__tablename__}, ID={self.id}] `{self.hash}`)"
86e8fc4fdb6d393d1d4774ebd2cc3234
{ "intermediate": 0.3320375382900238, "beginner": 0.39435678720474243, "expert": 0.27360567450523376 }
3,669
Hello, I have already implemented a matlab program for the question of lu decomposition, I need your help in formatting and commenting the code as per the below rules, can you kindly make the changes for me -------------------------Here are the styleguide details and after that is my code which needs to be formatted MATLAB Functions All MATLAB functions shall have the following format: function [c,d] = ubitname_ppN(a,b) %UBITNAME_PPN Summary of this function goes here % % Inputs: % a - One-line description of variable a, expected data type, and/or values % b - One-line description of variable b, expected data type, and/or values % % Outputs: % c - One-line description of variable c, expected data type, and/or values % d - One-line description of variable d, expected data type, and/or values Code_line_1; if a==1 Code_line_2; elseif a==2 Code_line 3; end for i=1:10 if a==i Code_line_4; else Code_line_5; end end switch a case 1 Code_line_6; otherwise Code_line_7; end end % ubitname_ppN 1 For all functions ubitname is replace with your ubitname. In the case of paired programming problems this would be replaced with ubitname1 ubitname2. The first line of the file must be the function declaration. This is followed by the filename fully capitalized and a short one or two line summary of the function purpose, followed by a blank comment line. The next line must contain a tab followed by Inputs:. The inputs are then described, one on each line following the ordering of the function call with two tabs preceding each variable name and a - separating the variable and the description. Each input variable must provide a single line description of the expected input with a data type and/or values if appropriate. If no input variables are present then the line following Inputs: shall contain two tabs followed by the text No input variables present. Once all inputs have been described a blank comment line is entered. Following this blank comment line all of the outputs are described following the same requirements and formatting as the inputs, replacing all of the words input with output, matching the appropriate case. Do not include any comment lines below the final output variable description or No output variables present, as appropriate. After the last comment line in the header block include a blank line before beginning your code. For the end corresponding to the function keyword enter a comment with the function name, as shown above. All lines in the header description must begin with a % in the first character location for each line. All code must be indented one tab from the function and it’s associated end keywords. All code contained within if, else, elseif, switch, case, otherwise, for, or while structures must also be indented to clearly show they are part of said structure. If there are any additional functions in the file they must all conform to this style guide. 3 Python Functions All Python functions shall have the following format: import module1 as md1 import module2 as md2 def functionName(a, b): #Summary of this function goes here # # Inputs: # a - Description of variable a, including expected data type and/or values # b - Description of variable b, including expected data type and/or values # # Outputs: # c - Description of variable c, including expected data type and/or values # d - Description of variable d, including expected data type and/or values Code_line_1 for i in range(b): Code_line_2 c = a + b d = a - b 2 return c, d After declaration of the function include a short one or two line summary of the function followed by a blank line. Then describe all inputs and output in a similar manner to the MATLAB comments above. As Python is whitespace sensitive all code with already be properly formatted.---------------------------------Follow the above instructions and formatt the below code accordingly --------------------------------------------------------------------------function [L,U,P] = hbommaka_aboda_pp12(A) x = length(A); L = zeros(x); U = zeros(x); P = eye(x); for y=1:x [~,a] = max(abs(A(y:end,y))); a = x-(x-y+1)+a; A([y a],:) = A([a y],:); P([y a],:) = P([a y],:); L([y a],:) = L([a y],:); L(y:x,y) = A(y:x,y) / A(y,y); U(y,1:x) = A(y,1:x); A(y+1:x,1:x) = A(y+1:x,1:x) - L(y+1:x,y)*A(y,1:x); end U(:,end) = A(:,end);
b6d9af68270a1cfde1e2d2451a53f2ec
{ "intermediate": 0.3934350609779358, "beginner": 0.3648180365562439, "expert": 0.2417469620704651 }
3,670
Setup On part d’un projet console Visual Studio. Afin d’éviter les soucis d’encoding, vous pouvez forcer l’utilisation du mode Multi-bytes via: Project properties > Advanced > Character Set > Multi-Bytes Sortie attendue On souhaite avoir une sortie comme : Owner: S-1-5-32-544 (BUILTIN\Administrators) User: S-...-1000 (VAGRANTVM\vagrant) Groups: - S-1-1-0 (\Everyone) - S-1-5-114 (NT AUTHORITY\Local account and member of Administrators group) ... Privileges: - SeDebugPrivilege (ENABLED ) - SeSystemEnvironmentPrivilege () - SeChangeNotifyPrivilege (ENABLED ENABLED_BY_DEFAULT ) - SeRemoteShutdownPrivilege () ... SessionID: 1 Notes et références Quelques références : • OpenProcessToken • GetTokenInformation • GetCurrentProcess • Droits TOKEN_ALL_ACCESS, MAXIMUM_ALLOWED et TOKEN_QUERY
1ff079f70f19a3026d4189a3eb12e53e
{ "intermediate": 0.44570493698120117, "beginner": 0.29753077030181885, "expert": 0.25676435232162476 }
3,671
import bybit key = “insert_your_api_key_here” secret = “insert_your_api_secret_key_here” client = bybit.bybit(test=False, api_key=key, api_secret=secret) spread = 0.5 # 0.5% spread between buy and sell orders stop_loss_pct = 2 # stop loss percentage qty = 100 # order quantity in USD current_price = float(client.Market.Market_symbolInfo(symbol=“BTCUSD”).result()[0][“last_price”]) support = current_price * 0.98 # Place buy orders just above the support level resistance = current_price * 1.02 # Place sell orders just below the resistance level while True: my_orders = client.Order.Order_getOrders(symbol=“BTCUSD”).result()[0] for order in my_orders: if order[“side”] == “Buy”: # Check for filled buy orders if order[“price”] <= support: # Sell just below resistance level price = round(resistance * (1 - spread/100), 1) client.Order.Order_new(side=“Sell”, symbol=“BTCUSD”, order_type=“Limit”, qty=qty/price, price=price, time_in_force=“GoodTillCancel”).result() elif order[“price”] > current_price * (1 + stop_loss_pct/100): # Stop loss at 2% below buy order price client.Order.Order_cancel(order_id=order[“order_id”], symbol=“BTCUSD”).result() elif order[“side”] == “Sell”: # Check for filled sell orders if order[“price”] >= resistance: # Buy just above support level price = round(support * (1 + spread/100), 1) client.Order.Order_new(side=“Buy”, symbol=“BTCUSD”, order_type=“Limit”, qty=qty/price, price=price, time_in_force=“GoodTillCancel”).result() elif order[“price”] < current_price * (1 - stop_loss_pct/100): # Stop loss at 2% above sell order price client.Order.Order_cancel(order_id=order[“order_id”], symbol=“BTCUSD”).result() time.sleep(10) # Wait for 10 seconds before checking orders again translate to english please?
85f0b874a65889ac0bd89a6d90f2482f
{ "intermediate": 0.4518263638019562, "beginner": 0.2565060257911682, "expert": 0.291667640209198 }
3,672
c++ load 2d array from json file
618c7e9a8355a79bd9a7826626766a64
{ "intermediate": 0.4717310965061188, "beginner": 0.3059597611427307, "expert": 0.2223091572523117 }
3,673
how to put a download into a unity
81a1493ae419d3eb5c709ea76f8bc5a7
{ "intermediate": 0.39080971479415894, "beginner": 0.2128053456544876, "expert": 0.39638498425483704 }
3,674
Напиши скрипт на языке пайтон, который подключится к postgreSQL таблице и заполнит её 10000 записей. SQL код таблицы: CREATE TABLE IF NOT EXISTS public.customer ( customer_id integer NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1 ), surname character varying(15) COLLATE pg_catalog."default" NOT NULL, name character varying(15) COLLATE pg_catalog."default" NOT NULL, father_name character varying(15) COLLATE pg_catalog."default" NOT NULL, customer_address character varying(15) COLLATE pg_catalog."default" NOT NULL, birthday date NOT NULL, bank_allocation_id integer NOT NULL, account integer NOT NULL, phone character varying COLLATE pg_catalog."default" NOT NULL, CONSTRAINT customer_pkey PRIMARY KEY (customer_id), CONSTRAINT bank_allocation_fkey FOREIGN KEY (bank_allocation_id) REFERENCES public.bank_allocation (bank_allocation_id) MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION NOT VALID, CONSTRAINT max_account CHECK (account <= 15), CONSTRAINT max_address_lenght CHECK (length(customer_address::text) <= 41), CONSTRAINT max_father_name_length CHECK (length(father_name::text) <= 40), CONSTRAINT max_name_length CHECK (length(name::text) <= 40), CONSTRAINT max_phone_length CHECK (length(phone::text) <= 10), CONSTRAINT max_surname_length CHECK (length(surname::text) <= 40) )
53897bc2d80717137c85a6a75378b5aa
{ "intermediate": 0.34947866201400757, "beginner": 0.3857433497905731, "expert": 0.2647779881954193 }
3,675
I need a c++ class that can hold up to three members of different or the same types. So some or all of these members can be nil. I want to be able to access these members liek this a.getFirst(), where getFirst() should be able to return a generic type. How can I go about that?
e3890cf77f6aa29efde33894125fd931
{ "intermediate": 0.29022103548049927, "beginner": 0.481940358877182, "expert": 0.22783860564231873 }
3,676
I need a c++ class that can hold up to three members of different or the same types. So some or all of these members can be nil. I want to be able to access these members liek this a.getFirst(), where getFirst() should be able to return a generic type. How can I go about that?
956ecddfefeda68ef4ee079e86945991
{ "intermediate": 0.29022103548049927, "beginner": 0.481940358877182, "expert": 0.22783860564231873 }
3,677
I need a c++ class that can hold up to three members of different or the same types. So the class might either have three or two or one or no members. I want to be able to access these members like this a.getFirst(), where getFirst() should be able to return a generic type. How can I go about that?
a8d36b0f083e5660177d83b764db4590
{ "intermediate": 0.2567664086818695, "beginner": 0.5405623316764832, "expert": 0.20267128944396973 }
3,678
c++ make array of 4 variables of 2d arrays
b12cc11acc47fdfb16b81f6a3afa7213
{ "intermediate": 0.24333597719669342, "beginner": 0.559280276298523, "expert": 0.1973837912082672 }
3,679
c++ initialize array with 4 variables
40a5cc03dcb15dc6b2f573fa7650391b
{ "intermediate": 0.2825721502304077, "beginner": 0.48067623376846313, "expert": 0.23675164580345154 }
3,680
can you make a roblox script for leaderstat "Donated" if someone buys a developer product made in game it adds to the stat
8e1fa506dd32fd99b6fec470aa124194
{ "intermediate": 0.34998273849487305, "beginner": 0.2701413035392761, "expert": 0.379876047372818 }
3,681
Question 1: EOQ, varying t [15 points] (a) In class we showed that the average inventory level under the EOQ model was Q/2 when we look over a time period that is a multiple of T. What is this average inventory level over the period of time from 0 to t for general t? Provide an exact expression for this. (b) Using your expression above, plot the average inventory (calculated exactly using your expression from part a) and the approximation Q/2 versus Q over the range of 1 to 30. Use t=100 and λ=2. Note that lambda is a keyword in python and using it as a variable name will cause problems. Pick a different variable name, like demand_rate. You should see that the approximation is quite accurate for large t, like 100, and is less accurate for small t.
2d44bb550a8006c868f855f260e7ac11
{ "intermediate": 0.19950106739997864, "beginner": 0.304959237575531, "expert": 0.49553972482681274 }
3,682
Can excel scan a folder and create or insert links to all files in the folder suing vba
a196905a3cdf63e8cb2c25eb88d66f93
{ "intermediate": 0.4108908474445343, "beginner": 0.30551809072494507, "expert": 0.28359106183052063 }
3,683
Question 1: EOQ, varying t [15 points] (a) In class we showed that the average inventory level under the EOQ model was Q/2 when we look over a time period that is a multiple of T. What is this average inventory level over the period of time from 0 to t for general t? Provide an exact expression for this. (b) Using your expression above, plot the average inventory (calculated exactly using your expression from part a) and the approximation Q/2 versus Q over the range of 1 to 30. Use t=100 and λ=2. Note that lambda is a keyword in python and using it as a variable name will cause problems. Pick a different variable name, like demand_rate. You should see that the approximation is quite accurate for large t, like 100, and is less accurate for small t.
f8f602c75a192b161cd559a6e31d10b6
{ "intermediate": 0.19630062580108643, "beginner": 0.3089706301689148, "expert": 0.49472877383232117 }
3,684
Hi
48c12dda9f71cd22abe5d346244cd9b3
{ "intermediate": 0.33010533452033997, "beginner": 0.26984941959381104, "expert": 0.400045245885849 }
3,685
Question 1: EOQ, varying t [15 points] (a) In class we showed that the average inventory level under the EOQ model was Q/2 when we look over a time period that is a multiple of T. What is this average inventory level over the period of time from 0 to t for general t? Provide an exact expression for this. (b) Using your expression above, plot the average inventory (calculated exactly using your expression from part a) and the approximation Q/2 versus Q over the range of 1 to 30. Use t=100 and λ=2. Note that lambda is a keyword in python and using it as a variable name will cause problems. Pick a different variable name, like demand_rate. You should see that the approximation is quite accurate for large t, like 100, and is less accurate for small t.
337952e3991b11680787437113eb75ae
{ "intermediate": 0.19950106739997864, "beginner": 0.304959237575531, "expert": 0.49553972482681274 }
3,686
Question 1: EOQ, varying t [15 points] (a) In class we showed that the average inventory level under the EOQ model was Q/2 when we look over a time period that is a multiple of T. What is this average inventory level over the period of time from 0 to t for general t? Provide an exact expression for this. (b) Using your expression above, plot the average inventory (calculated exactly using your expression from part a) and the approximation Q/2 versus Q over the range of 1 to 30. Use t=100 and λ=2. Note that lambda is a keyword in python and using it as a variable name will cause problems. Pick a different variable name, like demand_rate. You should see that the approximation is quite accurate for large t, like 100, and is less accurate for small t.
d9074f7fc078898c6d44ac630111717c
{ "intermediate": 0.19630062580108643, "beginner": 0.3089706301689148, "expert": 0.49472877383232117 }
3,687
Question 1: EOQ, varying t [15 points] (a) In class we showed that the average inventory level under the EOQ model was Q/2 when we look over a time period that is a multiple of T. What is this average inventory level over the period of time from 0 to t for general t? Provide an exact expression for this. (b) Using your expression above, plot the average inventory (calculated exactly using your expression from part a) and the approximation Q/2 versus Q over the range of 1 to 30. Use t=100 and λ=2. Note that lambda is a keyword in python and using it as a variable name will cause problems. Pick a different variable name, like demand_rate. You should see that the approximation is quite accurate for large t, like 100, and is less accurate for small t.
651f14ce225d9f3842a5dc2e622d3e65
{ "intermediate": 0.19630062580108643, "beginner": 0.3089706301689148, "expert": 0.49472877383232117 }
3,688
Question 1: Economic Order Quantity, varying t (a) In class we showed that the average inventory level under the EOQ model was Q/2 when we look over a time period that is a multiple of T. What is this average inventory level over the period of time from 0 to t for general t? Provide an exact expression for this. (b) Using your expression above, plot the average inventory (calculated exactly using your expression from part a) and the approximation Q/2 versus Q over the range of 1 to 30. Use t=100 and λ=2. Note that lambda is a keyword in python and using it as a variable name will cause problems. Pick a different variable name, like demand_rate. You should see that the approximation is quite accurate for large t, like 100, and is less accurate for small t.
f25639b3984d7b1bedebbf0abca7fa15
{ "intermediate": 0.2633453905582428, "beginner": 0.41832417249679565, "expert": 0.31833040714263916 }
3,689
Question 1: Economic Order Quantity, varying t (a) In class we showed that the average inventory level under the EOQ model was Q/2 when we look over a time period that is a multiple of T. What is this average inventory level over the period of time from 0 to t for general t? Provide an exact expression for this. (b) Using your expression above, plot the average inventory (calculated exactly using your expression from part a) and the approximation Q/2 versus Q over the range of 1 to 30. Use t=100 and λ=2. Note that lambda is a keyword in python and using it as a variable name will cause problems. Pick a different variable name, like demand_rate. You should see that the approximation is quite accurate for large t, like 100, and is less accurate for small t.
8a0de5c9bdb3031d2f161f9841104e69
{ "intermediate": 0.2633453905582428, "beginner": 0.41832417249679565, "expert": 0.31833040714263916 }
3,690
Question 1: Economic Order Quantity, varying t (a) In class we showed that the average inventory level under the EOQ model was Q/2 when we look over a time period that is a multiple of T. What is this average inventory level over the period of time from 0 to t for general t? Provide an exact expression for this. (b) Using your expression above, plot the average inventory (calculated exactly using your expression from part a) and the approximation Q/2 versus Q over the range of 1 to 30. Use t=100 and λ=2. Note that lambda is a keyword in python and using it as a variable name will cause problems. Pick a different variable name, like demand_rate. You should see that the approximation is quite accurate for large t, like 100, and is less accurate for small t.
aa8a1147c74474087eab82f8777f647b
{ "intermediate": 0.2633453905582428, "beginner": 0.41832417249679565, "expert": 0.31833040714263916 }
3,691
Is this Chat gpt?
82b73c2f043c3d95efb263684bf51ecc
{ "intermediate": 0.2404836118221283, "beginner": 0.33278894424438477, "expert": 0.42672744393348694 }
3,692
Question 1: Economic Order Quantity, varying t (a) In class we showed that the average inventory level under the EOQ model was Q/2 when we look over a time period that is a multiple of T. What is this average inventory level over the period of time from 0 to t for general t? Provide an exact expression for this. (b) Using your expression above, plot the average inventory (calculated exactly using your expression from part a) and the approximation Q/2 versus Q over the range of 1 to 30. Use t=100 and λ=2. Note that lambda is a keyword in python and using it as a variable name will cause problems. Pick a different variable name, like demand_rate. You should see that the approximation is quite accurate for large t, like 100, and is less accurate for small t.
77693e69a13eb27619a4206b9c6693a8
{ "intermediate": 0.2633453905582428, "beginner": 0.41832417249679565, "expert": 0.31833040714263916 }
3,693
write a vba to calculate best weight for 3 stock in portfoilio.use markowitz method.and dont use solver.
55307a1e7de74fa483fb929f6007a801
{ "intermediate": 0.34270915389060974, "beginner": 0.31830161809921265, "expert": 0.3389892280101776 }
3,694
C++ Builder 10.4 Rad Studio. Добавь проверку на PNG и JPEG изображение (если первое, то TPngImage *png = new TPngImage(); png->LoadFromStream(ms); Image1->Picture->Assign(png); delete png;, если второе, то TJPEGImage *jpeg = new TJPEGImage(); jpeg->LoadFromStream(ms); Image1->Picture->Assign(jpeg); delete jpeg; ) Код C++: void __fastcall TForm9::StringGrid1SelectCell(TObject *Sender, int ACol, int ARow, bool &CanSelect) { // Получение данных из столбца image таблицы ADOQuery1->RecNo = ARow; TMemoryStream *ms = new TMemoryStream(); TBlobField *blob = dynamic_cast<TBlobField*>(ADOQuery1->FieldByName("image")); blob->SaveToStream(ms); ms->Position = 0; TPngImage *png = new TPngImage(); png->LoadFromStream(ms); Image1->Picture->Assign(png); delete png; TJPEGImage *jpeg = new TJPEGImage(); jpeg->LoadFromStream(ms); Image1->Picture->Assign(jpeg); delete jpeg; // Отображение TImage на форме Image1->Visible = true; }
6352267078df0808e2820293b4710c4d
{ "intermediate": 0.3880300521850586, "beginner": 0.4519417881965637, "expert": 0.16002818942070007 }
3,695
Question 1: Economic Order Quantity, varying t (a) In class we showed that the average inventory level under the EOQ model was Q/2 when we look over a time period that is a multiple of T. What is this average inventory level over the period of time from 0 to t for general t? Provide an exact expression for this. (b) Using your expression above, plot the average inventory (calculated exactly using your expression from part a) and the approximation Q/2 versus Q over the range of 1 to 30. Use t=100 and λ=2. Note that lambda is a keyword in python and using it as a variable name will cause problems. Pick a different variable name, like demand_rate. You should see that the approximation is quite accurate for large t, like 100, and is less accurate for small t.
5ab7b5b2690e2dc9289f7ce75616f37a
{ "intermediate": 0.2603079378604889, "beginner": 0.4235021770000458, "expert": 0.31618988513946533 }
3,696
Question 1: Economic Order Quantity, varying t (a) In class we showed that the average inventory level under the EOQ model was Q/2 when we look over a time period that is a multiple of T. What is this average inventory level over the period of time from 0 to t for general t? Provide an exact expression for this. (b) Using your expression above, plot the average inventory (calculated exactly using your expression from part a) and the approximation Q/2 versus Q over the range of 1 to 30. Use t=100 and λ=2. Note that lambda is a keyword in python and using it as a variable name will cause problems. Pick a different variable name, like demand_rate. You should see that the approximation is quite accurate for large t, like 100, and is less accurate for small t.
1e8afcd273dbf6a891b57fe9cb755e0a
{ "intermediate": 0.2603079378604889, "beginner": 0.4235021770000458, "expert": 0.31618988513946533 }
3,697
Question 1: Economic Order Quantity, varying t (a) In class we showed that the average inventory level under the EOQ model was Q/2 when we look over a time period that is a multiple of T. What is this average inventory level over the period of time from 0 to t for general t? Provide an exact expression for this. (b) Using your expression above, plot the average inventory (calculated exactly using your expression from part a) and the approximation Q/2 versus Q over the range of 1 to 30. Use t=100 and λ=2. Note that lambda is a keyword in python and using it as a variable name will cause problems. Pick a different variable name, like demand_rate. You should see that the approximation is quite accurate for large t, like 100, and is less accurate for small t.
be2a1408415f7f9d2b9a6cb19fc97e4e
{ "intermediate": 0.2603079378604889, "beginner": 0.4235021770000458, "expert": 0.31618988513946533 }
3,698
Question 1: Economic Order Quantity, varying t (a) In class we showed that the average inventory level under the EOQ model was Q/2 when we look over a time period that is a multiple of T. What is this average inventory level over the period of time from 0 to t for general t? Provide an exact expression for this. (b) Using your expression above, plot the average inventory (calculated exactly using your expression from part a) and the approximation Q/2 versus Q over the range of 1 to 30. Use t=100 and λ=2. Note that lambda is a keyword in python and using it as a variable name will cause problems. Pick a different variable name, like demand_rate. You should see that the approximation is quite accurate for large t, like 100, and is less accurate for small t.
c024f296da7c71b64ef4eb5110509262
{ "intermediate": 0.2603079378604889, "beginner": 0.4235021770000458, "expert": 0.31618988513946533 }
3,699
import { init, dispose, Chart, DeepPartial, IndicatorFigureStylesCallbackData, Indicator, IndicatorStyle, KLineData, utils, } from "klinecharts"; const chart = useRef<Chart|null>(); const ref = useRef<HTMLDivElement>(null); useEffect(() => { chart.current = init(`chart-${tradeId}`, {styles: chartStyles}); return () => dispose(`chart-${tradeId}`); }, [tradeId]); useEffect(() => { chart.current?.applyNewData(candles); chart.current?.overrideIndicator({ name: "VOL", shortName: "Объем", calcParams: [], figures: [ { key: "volume", title: "", type: "bar", baseValue: 0, styles: (data: IndicatorFigureStylesCallbackData<Vol>, indicator: Indicator, defaultStyles: IndicatorStyle) => { const kLineData = data.current.kLineData as KLineData; let color: string; if (kLineData.close > kLineData.open) { color = utils.formatValue(indicator.styles, "bars[0].upColor", (defaultStyles.bars)[0].upColor) as string; } else if (kLineData.close < kLineData.open) { color = utils.formatValue(indicator.styles, "bars[0].downColor", (defaultStyles.bars)[0].downColor) as string; } else { color = utils.formatValue(indicator.styles, "bars[0].noChangeColor", (defaultStyles.bars)[0].noChangeColor) as string; } return {color}; }, }, ], }, paneId.current); chart.current?.createIndicator("VOL", false, {id: paneId.current}); chart.current?.setPriceVolumePrecision(+pricePrecision, +quantityPrecision); }, [candles]); <Box ref={ref} id={`chart-${tradeId}`} width="calc(100% - 55px)" height={!handle.active ? 550 : "100%"} sx={{borderLeft: "2px solid #F5F5F5"}} / > библиотека klinecharts, график размытый какой-то, как можно добавить четкости графику?
78d12ca731a2890593ac51743f58c74c
{ "intermediate": 0.2890385091304779, "beginner": 0.5344208478927612, "expert": 0.17654064297676086 }
3,700
For hl2, in depth, how could I mod in realistic interactions like giving Npcs a hug or playing paper scissors rock or Arm wrestling? Full detail on how to do all interactions.
18d36fc1549a8bc66b4ce05a6eb93250
{ "intermediate": 0.2756546139717102, "beginner": 0.1590193510055542, "expert": 0.5653259754180908 }
3,701
import { init, dispose, Chart, DeepPartial, IndicatorFigureStylesCallbackData, Indicator, IndicatorStyle, KLineData, utils, } from “klinecharts”; const chart = useRef<Chart|null>(); const ref = useRef<HTMLDivElement>(null); useEffect(() => { chart.current = init(chart-${tradeId}, {styles: chartStyles}); return () => dispose(chart-${tradeId}); }, [tradeId]); useEffect(() => { chart.current?.applyNewData(candles); chart.current?.overrideIndicator({ name: “VOL”, shortName: “Объем”, calcParams: [], figures: [ { key: “volume”, title: “”, type: “bar”, baseValue: 0, styles: (data: IndicatorFigureStylesCallbackData<Vol>, indicator: Indicator, defaultStyles: IndicatorStyle) => { const kLineData = data.current.kLineData as KLineData; let color: string; if (kLineData.close > kLineData.open) { color = utils.formatValue(indicator.styles, “bars[0].upColor”, (defaultStyles.bars)[0].upColor) as string; } else if (kLineData.close < kLineData.open) { color = utils.formatValue(indicator.styles, “bars[0].downColor”, (defaultStyles.bars)[0].downColor) as string; } else { color = utils.formatValue(indicator.styles, “bars[0].noChangeColor”, (defaultStyles.bars)[0].noChangeColor) as string; } return {color}; }, }, ], }, paneId.current); chart.current?.createIndicator(“VOL”, false, {id: paneId.current}); chart.current?.setPriceVolumePrecision(+pricePrecision, +quantityPrecision); }, [candles]); <Box ref={ref} id={chart-${tradeId}} width=“calc(100% - 55px)” height={!handle.active ? 550 : “100%”} sx={{borderLeft: “2px solid #F5F5F5”}} / > библиотека klinecharts, график размытый какой-то, как можно добавить четкости графику?
00283a92b2a7861eba748475e7dc384b
{ "intermediate": 0.42636388540267944, "beginner": 0.33739131689071655, "expert": 0.2362448275089264 }
3,702
import { init, dispose, Chart, DeepPartial, IndicatorFigureStylesCallbackData, Indicator, IndicatorStyle, KLineData, utils, } from “klinecharts”; const chart = useRef<Chart|null>(); const ref = useRef<HTMLDivElement>(null); useEffect(() => { chart.current = init(chart-${tradeId}, {styles: chartStyles}); return () => dispose(chart-${tradeId}); }, [tradeId]); useEffect(() => { chart.current?.applyNewData(candles); chart.current?.overrideIndicator({ name: “VOL”, shortName: “Объем”, calcParams: [], figures: [ { key: “volume”, title: “”, type: “bar”, baseValue: 0, styles: (data: IndicatorFigureStylesCallbackData<Vol>, indicator: Indicator, defaultStyles: IndicatorStyle) => { const kLineData = data.current.kLineData as KLineData; let color: string; if (kLineData.close > kLineData.open) { color = utils.formatValue(indicator.styles, “bars[0].upColor”, (defaultStyles.bars)[0].upColor) as string; } else if (kLineData.close < kLineData.open) { color = utils.formatValue(indicator.styles, “bars[0].downColor”, (defaultStyles.bars)[0].downColor) as string; } else { color = utils.formatValue(indicator.styles, “bars[0].noChangeColor”, (defaultStyles.bars)[0].noChangeColor) as string; } return {color}; }, }, ], }, paneId.current); chart.current?.createIndicator(“VOL”, false, {id: paneId.current}); chart.current?.setPriceVolumePrecision(+pricePrecision, +quantityPrecision); }, [candles]); <Box ref={ref} id={chart-${tradeId}} width=“calc(100% - 55px)” height={!handle.active ? 550 : “100%”} sx={{borderLeft: “2px solid #F5F5F5”}} / > библиотека klinecharts, график размытый какой-то, как можно добавить четкости графику?
036f6c2990bb21bac811944b91f96048
{ "intermediate": 0.42636388540267944, "beginner": 0.33739131689071655, "expert": 0.2362448275089264 }
3,703
i WILL
1020794092c0446c222390d9528d847d
{ "intermediate": 0.33789366483688354, "beginner": 0.2775276303291321, "expert": 0.384578675031662 }
3,704
can you do numbers generation?
03dd98cdf53ca88bff5976a9172404c3
{ "intermediate": 0.3190031349658966, "beginner": 0.14687387645244598, "expert": 0.5341230630874634 }
3,705
Write an oblivious RAM implementation using python
4a61100de80f4010db20269215d6bfaa
{ "intermediate": 0.29180896282196045, "beginner": 0.21407344937324524, "expert": 0.4941176176071167 }
3,706
How we can write a vba to automatically detect elliot waves
a87a5f549e8b37a51c6ab015231df0dc
{ "intermediate": 0.24239300191402435, "beginner": 0.07007405906915665, "expert": 0.6875329613685608 }
3,707
I need a c++ class that can hold up to three members of different or the same types. So the class might either have three or two or one or no members. I want to be able to access these members like this a.getFirst(), where getFirst() should be able to return a generic type. How can I go about that?
cbbd7ba9c1b14840c4254e4c2d47ff85
{ "intermediate": 0.2567664086818695, "beginner": 0.5405623316764832, "expert": 0.20267128944396973 }
3,708
Does perl have a nor operator
a527535e22979de30e9a1b51d3857ee3
{ "intermediate": 0.25789904594421387, "beginner": 0.4111621379852295, "expert": 0.33093881607055664 }
3,709
I need a c++ class that can hold up to three members of different or the same types. So the class might either have three or two or one or no members. I want to be able to access these members like this a.getFirst(), where getFirst() should be able to return a generic type. How can I go about that?
6e9d4a4853b55ec9a8261c0f84f703f1
{ "intermediate": 0.2567664086818695, "beginner": 0.5405623316764832, "expert": 0.20267128944396973 }
3,710
hi
9b82820ecf18e77c1903ab05d2056835
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
3,711
ERROR in ./src/App.js 12:19-33 export 'default' (imported as 'IpfsHttpClient') was not found in 'ipfs-http-client' (possible exports: CID, create, globSource, multiaddr, urlSource)
6ce05b7bd54b339a2523afafcf2b5999
{ "intermediate": 0.5365416407585144, "beginner": 0.2463480681180954, "expert": 0.2171103060245514 }
3,712
Задание: Код работает корректно, но при изменении значений ячейки появляется ошибка "Не удается найти строку для обновления. Некоторые значения могли быть изменены со времени ее последнего чтения". При это значения записываются в базу данных. Исправь эту ошибку. //--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include <Data.DB.hpp> #include "Unit9.h" #include <jpeg.hpp> #include <pngimage.hpp> //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm9 *Form9; using namespace std; //--------------------------------------------------------------------------- __fastcall TForm9::TForm9(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TForm9::FormCreate(TObject *Sender) { // создание базы данных / таблицы, если их ещё не существует String s; s = "CREATE DATABASE IF NOT EXISTS `catalog`"; ADOQuery1->SQL->Text = s; ADOQuery1->ExecSQL(); s = "CREATE TABLE IF NOT EXISTS `catalog`.`products` (`ID` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(255) CHARACTER SET utf8mb4 NOT NULL, `price` FLOAT(8, 2) NOT NULL, `description` TEXT CHARACTER SET utf8mb4 NOT NULL, `image` LONGBLOB NOT NULL, PRIMARY KEY (`ID`))"; ADOQuery1->SQL->Text = s; ADOQuery1->ExecSQL(); ADOQuery1->Close(); ADOQuery1->SQL->Text = "SELECT * FROM `catalog`.`products`"; ADOQuery1->Open(); StringGrid1->RowCount = ADOQuery1->RecordCount + 1; StringGrid1->Cells[0][0] = "№"; StringGrid1->Cells[1][0] = "Наименование"; StringGrid1->Cells[2][0] = "Описание"; StringGrid1->Cells[3][0] = "Стоимость"; int row = 1; while (!ADOQuery1->Eof) { StringGrid1->Cells[0][row] = ADOQuery1->FieldByName("ID")->AsString; StringGrid1->Cells[1][row] = ADOQuery1->FieldByName("name")->AsString; StringGrid1->Cells[2][row] = ADOQuery1->FieldByName("description")->AsString; StringGrid1->Cells[3][row] = ADOQuery1->FieldByName("price")->AsString; row++; ADOQuery1->Next(); } } //--------------------------------------------------------------------------- void __fastcall TForm9::StringGrid1SelectCell(TObject *Sender, int ACol, int ARow, bool &CanSelect) { // Получение данных из столбца image таблицы ADOQuery1->RecNo = ARow; TMemoryStream *ms = new TMemoryStream(); TBlobField *blob = dynamic_cast<TBlobField *>(ADOQuery1->FieldByName("image")); blob->SaveToStream(ms); ms->Position = 0; // Получение первых байт для определения типа изображения BYTE bytes[4]; ms->ReadBuffer(bytes, 4); ms->Position = 0; // Сигнатура PNG: 137 80 78 71 (0x89 0x50 0x4E 0x47) if (bytes[0] == 0x89 && bytes[1] == 0x50 && bytes[2] == 0x4E && bytes[3] == 0x47) { TPngImage *png = new TPngImage; png->LoadFromStream(ms); Image1->Picture->Assign(png); delete png; } // Сигнатура JPEG: 255 216 (0xFF 0xD8) else if (bytes[0] == 0xFF && bytes[1] == 0xD8) { TJPEGImage *jpeg = new TJPEGImage; jpeg->LoadFromStream(ms); Image1->Picture->Assign(jpeg); delete jpeg; } // Отображение TImage на форме Image1->Visible = true; delete ms; } //--------------------------------------------------------------------------- void __fastcall TForm9::Button1Click(TObject *Sender) { if (Edit1->Text.IsEmpty() || Edit2->Text.IsEmpty() || Memo1->Lines->Text.IsEmpty()) { ShowMessage("Пожалуйста, заполните все поля!"); return; } if (OpenPictureDialog1->FileName.IsEmpty()) { ShowMessage("Пожалуйста, загрузите изображение!"); return; } try { TFileStream *fs = new TFileStream(OpenPictureDialog1->FileName, fmOpenRead); try { // Указываем параметры для запроса ADOQuery1->SQL->Text = "INSERT INTO `catalog`.`products` (`name`, `price`, `description`, `image`) VALUES (:name, :price, :description, :image)"; ADOQuery1->Parameters->ParamByName("name")->Value = Edit1->Text; ADOQuery1->Parameters->ParamByName("price")->Value = StrToFloat(Edit2->Text); ADOQuery1->Parameters->ParamByName("description")->Value = Memo1->Lines->Text; ADOQuery1->Parameters->ParamByName("name")->DataType = ftWideString; ADOQuery1->Parameters->ParamByName("description")->DataType = ftWideString; // Создаем поток для передачи изображения в базу данных TMemoryStream *stream = new TMemoryStream(); try { stream->CopyFrom(fs, 0); stream->Position = 0; ADOQuery1->Parameters->ParamByName("image")->LoadFromStream(stream, ftBlob); ADOQuery1->ExecSQL(); } __finally { delete stream; } } __finally { delete fs; } // Очистка полей ввода Edit1->Text="Название товара"; Edit2->Text="0"; Memo1->Lines->Text="Описание товара"; // Очистка изображения Image2->Picture->Assign(NULL); // Обновление данных в таблице ADOQuery1->Close(); ADOQuery1->SQL->Text = "SELECT * FROM `catalog`.`products`"; ADOQuery1->Open(); } catch (Exception &e) { ShowMessage("Ошибка при добавлении товара: " + e.Message); } } //--------------------------------------------------------------------------- void __fastcall TForm9::Button2Click(TObject *Sender) { if (OpenPictureDialog1->Execute()) { Image2->Picture->LoadFromFile(OpenPictureDialog1->FileName); } } //--------------------------------------------------------------------------- void __fastcall TForm9::StringGrid1SetEditText(TObject *Sender, int ACol, int ARow, const UnicodeString Value) { if ((ARow >= 1) && (ARow <= ADOQuery1->RecordCount)) { ADOQuery1->RecNo = ARow; TField* field = ADOQuery1->FindField("name"); switch (ACol) { case 1: if (field) { ADOQuery1->Edit(); field->AsString = Value; ADOQuery1->Post(); } break; case 2: field = ADOQuery1->FindField("description"); if (field) { ADOQuery1->Edit(); field->AsString = Value; ADOQuery1->Post(); } break; case 3: field = ADOQuery1->FindField("price"); float price; if (TryStrToFloat(Value, price) && field) { ADOQuery1->Edit(); field->AsFloat = price; ADOQuery1->Post(); } else { ShowMessage("Некорректное значение цены"); } break; } } }
62c04499461f6db3d4d71866165b4649
{ "intermediate": 0.330118864774704, "beginner": 0.5059736371040344, "expert": 0.1639074981212616 }
3,713
package it.polito.mas.courtreservation import android.content.Context import androidx.core.content.ContentProviderCompat.requireContext import androidx.room.* import java.util.* @Database( entities = [ Reservation::class, User::class, SportPlayground::class] , version = 1, exportSchema = false) abstract class AppDatabase : RoomDatabase() { abstract fun reservationDao(): ReservationDao abstract fun userDao(): UserDao abstract fun sportPlaygroundDao(): SportPlaygroundDao companion object { @Volatile private var INSTANCE: AppDatabase? = null fun getDatabase(context: Context): AppDatabase { return INSTANCE ?: synchronized(this) { val instance = Room.databaseBuilder( context.applicationContext, AppDatabase::class.java, "reservation_database" ).build() INSTANCE = instance instance } } } }
0ed6998e5f84bcea8c3ff7244f7ec522
{ "intermediate": 0.4563944935798645, "beginner": 0.28132084012031555, "expert": 0.26228469610214233 }