row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
7,027
|
write test in jest to check if there is <Form /> and <ContactDetails />
|
280998612842586ed64fe0dfe8293510
|
{
"intermediate": 0.4834526479244232,
"beginner": 0.2572249472141266,
"expert": 0.2593224346637726
}
|
7,028
|
Laravel 10. How to order by hasOne relation?
|
8513ecfc74f9a2387b0b6321de810acb
|
{
"intermediate": 0.4490733742713928,
"beginner": 0.15352272987365723,
"expert": 0.39740386605262756
}
|
7,029
|
how to test <component/> in jest
|
2271d09f0258f38b9e0fa0240763aefb
|
{
"intermediate": 0.4356972873210907,
"beginner": 0.22472286224365234,
"expert": 0.33957982063293457
}
|
7,030
|
how to test component in react in jest
|
ecdcc6a869fdc00130fdd9b4593dbf00
|
{
"intermediate": 0.5632877349853516,
"beginner": 0.1610521525144577,
"expert": 0.27566009759902954
}
|
7,031
|
in python, how to store jason dta into csv file with more than 200000 records
|
11103c0e3ee6741bc1fd0ef0c0b91c43
|
{
"intermediate": 0.4355590045452118,
"beginner": 0.1834457367658615,
"expert": 0.3809952139854431
}
|
7,032
|
write test component in react in jest
|
f2753e478de30f13a3034ff5cfc8fe9a
|
{
"intermediate": 0.47776612639427185,
"beginner": 0.23442882299423218,
"expert": 0.2878050208091736
}
|
7,033
|
in java, any 3rd party library to add Specific Days To Current Date
|
648b0c04e0356ca99f7709fb14c09969
|
{
"intermediate": 0.7487891912460327,
"beginner": 0.11347313225269318,
"expert": 0.1377376914024353
}
|
7,034
|
For a ‘dramatic flashback sequence triggered by an object or area of map’ for Garry’s mod, how exactly can I make it work?
|
8ffe4c2b192d0fd0ca3ee42535275bca
|
{
"intermediate": 0.45653462409973145,
"beginner": 0.12285178899765015,
"expert": 0.4206136167049408
}
|
7,035
|
why am I getting this error? LogNetPackageMap: Warning: FNetGUIDCache::SupportsObject: GameplayAbilityPayloadData /Engine/Transient.GameplayAbilityPayloadData_0 NOT Supported. Can you show me c++ code// Copyright 2022 Sabre Dart Studios
#pragma once
#include "CoreMinimal.h"
#include "RagnaAbilTargetActor_GroundTrace.h"
#include "GameplayAbilityPayloadData.generated.h"
UCLASS()
class OPENWORLDSTARTER_API UGameplayAbilityPayloadData : public UObject
{
GENERATED_BODY()
public:
UGameplayAbilityPayloadData();
int GetCurrentAbilityLevel() const { return CurrentAbilityLevel; }
void SetCurrentAbilityLevel(int val) { CurrentAbilityLevel = val; }
TWeakObjectPtr<ARagnaAbilTargetActor_GroundTrace> GetTargetingActor() const { return TargetingActor; }
void SetTargetingActor(TWeakObjectPtr<ARagnaAbilTargetActor_GroundTrace> val) { TargetingActor = val; }
void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const;
private:
UPROPERTY(Replicated)
int CurrentAbilityLevel = 0;
UPROPERTY(Replicated)
TWeakObjectPtr<ARagnaAbilTargetActor_GroundTrace> TargetingActor = nullptr;
};// Copyright 2022 Sabre Dart Studios
#include "GameplayAbilityPayloadData.h"
#include <Net/UnrealNetwork.h>
UGameplayAbilityPayloadData::UGameplayAbilityPayloadData()
{
}
void UGameplayAbilityPayloadData::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME(UGameplayAbilityPayloadData, CurrentAbilityLevel);
DOREPLIFETIME(UGameplayAbilityPayloadData, TargetingActor);
}
|
e508e13106047c6c6a937970f1b79939
|
{
"intermediate": 0.44689708948135376,
"beginner": 0.41393065452575684,
"expert": 0.1391722708940506
}
|
7,036
|
sử dụng useRef để đến index là năm hiện tại trong list import React, {useCallback, useMemo, useState} from 'react';
import {FlatList, SafeAreaView, StyleSheet, Text, View} from 'react-native';
const Test = () => {
const currentYear = new Date().getFullYear();
const yearList = useMemo(() => {
const arr = [];
for (let i = -50; i < 50; i++) {
arr.push({year: currentYear + i});
}
return arr;
}, [currentYear]);
const monthList = useMemo(
() => [
{name: 'January', days: 31},
{name: 'February', days: 28},
{name: 'March', days: 31},
{name: 'April', days: 30},
{name: 'May', days: 31},
{name: 'June', days: 30},
{name: 'July', days: 31},
{name: 'August', days: 31},
{name: 'September', days: 30},
{name: 'October', days: 31},
{name: 'November', days: 30},
{name: 'December', days: 31},
],
[],
);
const daysInMonth = useCallback((year, month) => {
if (month === 2) {
if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
return 29;
} else {
return 28;
}
}
return [4, 6, 9, 11].includes(month) ? 30 : 31;
}, []);
const isCurrentDate = useCallback((year, month, i) => {
const currentDate = new Date();
return year === currentDate.getFullYear() && month - 1 === currentDate.getMonth() && i === currentDate.getDate();
}, []);
const MonthList = React.memo(({year, month}) => {
const firstDay = new Date(year.year, month.month - 1, 1).getDay();
const daysInMonthCount = daysInMonth(year.year, month.month);
const days = useMemo(() => {
const arr = [];
for (let i = 1; i <= firstDay; i++) {
arr.push(<View key={`empty-${i}`} style={[styles.day, styles.emptyDay]} />);
}
for (let i = 1; i <= daysInMonthCount; i++) {
arr.push(
<View key={i} style={styles.day}>
<Text style={[styles.dayText, isCurrentDate(year.year, month.month, i) && styles.red]}>{i}</Text>
</View>,
);
}
return arr;
}, [year, month, firstDay, daysInMonthCount, isCurrentDate]);
const isCurrentMonth = year.year === new Date().getFullYear() && month.month - 1 === new Date().getMonth();
return (
<View style={styles.month}>
<Text style={[styles.monthName, isCurrentMonth && styles.red]}>{month.name}</Text>
<View style={styles.days}>{days}</View>
</View>
);
});
const YearList = React.memo(({year}) => {
const monthData = monthList.map((month, index) => ({...month, month: index + 1}));
const isCurrentYear = year.year === new Date().getFullYear();
return (
<View>
<Text style={[styles.title, isCurrentYear && styles.red]}>{year.year}</Text>
<View style={styles.line} />
<View style={styles.monthsContainer}>
{monthData.map((month, index) => (
<MonthList key={index} month={month} year={year} />
))}
</View>
</View>
);
});
return (
<SafeAreaView style={styles.container}>
<FlatList data={yearList} renderItem={({item}) => <YearList year={item} />} keyExtractor={(item, index) => `${item.year}-${index}`} />
</SafeAreaView>
);
};
export default Test;
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 10,
backgroundColor: '#fff',
},
title: {
fontSize: 30,
fontWeight: 'bold',
marginBottom: 5,
marginLeft: 15,
},
line: {
backgroundColor: 'grey',
height: 0.5,
opacity: 0.5,
marginBottom: 20,
},
monthsContainer: {
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'space-between',
},
month: {
width: '33%',
marginBottom: 10,
},
monthName: {
fontSize: 18,
fontWeight: 'bold',
marginBottom: 10,
marginLeft: 5,
},
days: {
flexDirection: 'row',
flexWrap: 'wrap',
},
day: {
flexBasis: '14%',
height: 20,
width: 20,
alignItems: 'center',
justifyContent: 'center',
},
dayText: {
fontSize: 10,
fontWeight: '600',
},
emptyDay: {
backgroundColor: 'transparent',
borderWidth: 0,
},
red: {
color: 'red',
},
});
|
99bcabb7ff53ee4c2a3b59025c322913
|
{
"intermediate": 0.30054590106010437,
"beginner": 0.5186981558799744,
"expert": 0.18075591325759888
}
|
7,037
|
In C++, A function can include more than one return statement, but only one return statements will be executed.
|
32af8fb8a523d849cbc0c92291cd26fd
|
{
"intermediate": 0.2287830263376236,
"beginner": 0.4856553077697754,
"expert": 0.2855616807937622
}
|
7,038
|
in code a = pow(2, 5) , what is pow short for?
|
6ba4362d626089a61b26301e9b7371bb
|
{
"intermediate": 0.24939437210559845,
"beginner": 0.4103400707244873,
"expert": 0.34026554226875305
}
|
7,039
|
Mysql. How to put inner join data to subvalue? If I select users.* and their profile, I want profile be at profile.*
|
0cf513bd86da2d1cf88ca163f925a558
|
{
"intermediate": 0.5403101444244385,
"beginner": 0.2094610184431076,
"expert": 0.2502288818359375
}
|
7,040
|
Hi, I got a cool task for you to implement. Let's I want you to implement a Evader class in the following manner: Subscribe to the LaserScan, Odometry and publish drive commands to the AckermannDrive. Once you successfully established those connections, The car has four actions left forward, right forward, reverse and forward. Now our task is to make our car navigate in maze like env filled with obstacles and using the data generated we need to train our DQN . You can refer to ros docs for all the information related to the ros topics required for this task. Initalize the ros node using this: rospy.init_node('evader_node', anonymous=True). Laser scan is at topic 'car_1/scan' , Odometry at car_1/base/odom' and Drive commands at 'car_1/command'. You can initialize action space as the following : forward: 0, left : 1, right: 2 and reverse : 3. I want your 100% in this task. Your output should be something that the people has never such wonderful implementation of Evader in python. So, do it like you own this thing. Let's go!.
|
cafa908d0d1929f98709cd15a346d78a
|
{
"intermediate": 0.3732699751853943,
"beginner": 0.19789071381092072,
"expert": 0.4288392961025238
}
|
7,041
|
create a countdown timer for a squarespace website to put in the code of the webpage.
|
679f68dcf740f69a6b07402142ae354d
|
{
"intermediate": 0.39588654041290283,
"beginner": 0.25076618790626526,
"expert": 0.3533472716808319
}
|
7,042
|
In which of the following is searching for a key value the fastest on average ?
a. Height-Balanced Binary Search Trees
b. Wide Binary Search Trees
c. Binary Trees
d. Tall Binary Search Trees
|
c4b7e7a7ea994f97582a5cb2b4d50140
|
{
"intermediate": 0.16304369270801544,
"beginner": 0.1069515198469162,
"expert": 0.7300047874450684
}
|
7,043
|
laravel 10. how to run plain mysql command to set mysql global variable?
|
9ba9226d70de2d1d3fa681187a7991eb
|
{
"intermediate": 0.5668429732322693,
"beginner": 0.2752971649169922,
"expert": 0.1578598916530609
}
|
7,044
|
import os
import torchaudio
import matplotlib.pyplot as plt
import torch
import librosa as lr
import numpy as np
# Define the vad function
def vad(audio_data, sample_rate, frame_duration=0.025, energy_threshold=0.6):
frame_size = int(sample_rate * frame_duration)
num_frames = len(audio_data) // frame_size
silence = np.ones(len(audio_data), dtype=bool)
for idx in range(num_frames):
start = idx * frame_size
end = (idx + 1) * frame_size
frame_energy = np.sum(np.square(audio_data[start:end]))
if frame_energy > energy_threshold:
silence[start:end] = False
segments = []
start = None
for idx, value in enumerate(silence):
if not value and start is None: # Start of speech segment
start = idx
elif value and start is not None: # End of speech segment
segments.append([start, idx - 1])
start = None
return segments, silence
directory = '/content/drive/MyDrive/School21/day09/datasets/audio_yes_no/waves_yesno 2'
# Loop through all files in the directory
for filename in os.listdir(directory):
if filename.endswith('.wav'):
# Load the audio file and find the speech boundaries
audio_data, sample_rate = torchaudio.load(os.path.join(directory, filename))
audio_data_resampled = lr.resample(audio_data.numpy()[0], orig_sr=sample_rate, target_sr=8000)
segments, silence = vad(audio_data_resampled, 8000)
# Resample the silence mask
silence_resampled = np.interp(np.linspace(0, len(silence), len(audio_data_resampled)), np.arange(len(silence)), silence.astype(float))
# Plot the audio signal and speech boundaries
fig, ax = plt.subplots(figsize=(10, 3))
time = torch.linspace(0, len(audio_data_resampled)/8000, len(audio_data_resampled))
ax.plot(time, audio_data_resampled)
ax.plot(time, silence_resampled.squeeze())
ax.set_xlabel('Time (s)')
ax.set_ylabel('Amplitude')
plt.show()
|
6996c6738d8a92b84ad4efca7666a04c
|
{
"intermediate": 0.4187052249908447,
"beginner": 0.3711378276348114,
"expert": 0.21015694737434387
}
|
7,045
|
Make a telegram bot on python that will make a message about entering and (or) finishing maintenance of project
At the start user should choose one of nine project names
Then he needs to choose language of the message - russian or english
After this he needs to enter the reason of entering the project to the maintenance
And as the last step user must choose the duration of the maintenance - less than 10 minutes or more than 10 minutes
The pattern of the message for the maintenance that lasts less than 10 minutes (line about time must consists of entering and finishing time):
Project:
Time of maintenance entry:
Time of exit:
Reason:
The pattern of the message for the maintenance that lasts more than 10 minutes must consists of two messages - entering part (time of project got into maintenance) and finishing part (time of project getting out of maintenance)
Entering message -
Maintenance entry message
Project:
Maintenance entry time:
Reason:
Finishing message -
Maintenance ending message
Project:
Maintenance exit time:
|
a7918befbdf7490c27a599123838ddcc
|
{
"intermediate": 0.39613068103790283,
"beginner": 0.22168798744678497,
"expert": 0.3821813464164734
}
|
7,046
|
Hi, I got a cool task for you to implement. Let’s I want you to implement an end to end complete Evader class in the following manner: Subscribe to the LaserScan, Odometry and publish drive commands to the AckermannDrive. Once you successfully established those connections, The car has four actions left forward, right forward, reverse and forward. Now our task is to make our car navigate in maze like env filled with obstacles and using the data generated we need to train our DQN . You can refer to ros docs for all the information related to the ros topics required for this task. Initalize the ros node using this: rospy.init_node(‘evader_node’, anonymous=True). Laser scan is at topic ‘car_1/scan’ , Odometry at car_1/base/odom’ and Drive commands at ‘car_1/command’. You can initialize action space as the following : forward: 0, left : 1, right: 2 and reverse : 3. You can read the metadata of the LaserScan message using rostopic echo (you can echo only one message by passing arguments to this command) to check the metadata values of this particular scanner. The laser scanner on the car has a field of view from -3π/4 tо зπ/4 with a resolution of 0.0043633 radians and the car publishes it's odometry on the topic_car_1/base/odom using an Odometry essage (nav_msgs/odometry). You can get the global position and orientation of the car from this message. Orientations are represented using Quaternions and not Euler angles. You can use ROS provided functions to convert between them.I want your 100% in this task. Your output should be something that the people has never such wonderful implementation of Evader in python. So, do it like you own this thing. Let’s go!.
|
fcd50a74b9cd4ea1a98e8b6892d7efb6
|
{
"intermediate": 0.3504910171031952,
"beginner": 0.18574023246765137,
"expert": 0.46376869082450867
}
|
7,047
|
use jest create ut for this vue component <template>
<div v-loading="isLoading" class="interface">
<retry
v-if="isError"
v-bind="errorProps"
@retry="__handleRetry"
/>
<empty
v-else-if="empty"
v-bind="emptyProps"
/>
<slot v-else />
</div>
</template>
<script>
import empty from 'packages/empty'
import retry from 'packages/retry'
export default {
name: 'GdProtect',
components: {
empty,
retry
},
props: {
loading: {
type: Boolean,
default: false
},
empty: {
type: Boolean,
default: false
},
error: {
type: Boolean,
default: false
},
emptyProps: {
type: Object,
default: () => {
return {}
}
},
errorProps: {
type: Object,
default: () => {
return {}
}
}
},
data() {
return {
isLoading: false,
isError: false,
loadIndex: 0
}
},
watch: {
error: {
handler: function(newVal) {
this.isError = newVal
},
immediate: true
},
loading: {
handler: function(newVal) {
this.isLoading = newVal
},
immediate: true
}
},
created() {},
mounted() {},
methods: {
__handleRetry() {
this.$emit('retry')
},
getData(axiosParams) {
return new Promise((resolve, reject) => {
this.isLoading = true
this.loadIndex++
var curLoadIndex = this.loadIndex
this.$axios(axiosParams).then((res) => {
let data = res.data
if (curLoadIndex === this.loadIndex) {
this.isLoading = false
this.isError = false
resolve(data)
}
}).catch((error) => {
if (curLoadIndex === this.loadIndex) {
this.isLoading = false
this.isError = true
reject(error)
}
})
})
}
}
}
</script>
|
0bd9b288990a9c24086eb8d2cc3eefcf
|
{
"intermediate": 0.33097466826438904,
"beginner": 0.5048040747642517,
"expert": 0.16422121226787567
}
|
7,048
|
LogNetPackageMap: Warning: FNetGUIDCache::SupportsObject: GameplayAbilityPayloadComponent /Engine/Transient.GameplayAbilityPayloadComponent_29 NOT Supported. Can you show me c++ code
|
aaf95d5c6f70cb2a4c8367686a4ece51
|
{
"intermediate": 0.3785795271396637,
"beginner": 0.4484253525733948,
"expert": 0.17299512028694153
}
|
7,049
|
Для решения задачи Voice Activity Detection (VAD) я предлагаю использовать библиотеку pydub для работы с аудиофайлами и matplotlib для визуализации результатов. Вам потребуется установить эти библиотеки, если у вас их еще нет:
pip install pydub
pip install matplotlib
Далее, вот пример кода для обработки аудиофайлов и вывода графика с сегментами речи:
import os
from pydub import AudioSegment
from pydub.silence import detect_nonsilent
import matplotlib.pyplot as plt
def detect_speech(audio_file, silence_threshold=-50, min_silence_len=100, padding=50):
audio = AudioSegment.from_wav(audio_file)
nonsilent_slices = detect_nonsilent(audio, min_silence_len, silence_threshold, padding)
return nonsilent_slices
def plot_speech_detection(audio_file, speech_segments):
audio = AudioSegment.from_wav(audio_file)
audio_length = len(audio)
plt.figure(figsize=(10, 2))
plt.plot([0, audio_length], [0, 0], ‘b-’)
for segment in speech_segments:
plt.plot(segment, [0, 0], ‘r-’, linewidth=5)
plt.xlim(0, audio_length)
plt.ylim(-1, 1)
plt.xlabel(‘Samples’)
plt.title(f’Speech Detection for {os.path.basename(audio_file)}‘)
plt.show()
# Замените ‘path/to/audio/files’ на путь к вашей директории с аудиофайлами
audio_files_dir = ‘path/to/audio/files’
audio_files = [os.path.join(audio_files_dir, f) for f in os.listdir(audio_files_dir) if f.endswith(’.wav’)]
for audio_file in audio_files:
speech_segments = detect_speech(audio_file)
print(f"Speech segments for {os.path.basename(audio_file)}: {speech_segments}")
plot_speech_detection(audio_file, speech_segments)
Этот код сначала определяет сегменты речи в аудиофайле с помощью функции detect_speech, а затем выводит график с сегментами речи с помощью функции plot_speech_detection. Вы можете настроить параметры silence_threshold, min_silence_len и padding в функции detect_speech для улучшения качества определения речи.
Обратите внимание, что этот код предполагает, что все аудиофайлы имеют формат WAV. Если у вас есть файлы в других форматах, вам потребуется изменить код для работы с этими форматами.
|
317d4d02a364f351c0f2c15ccb38f075
|
{
"intermediate": 0.310569167137146,
"beginner": 0.5163562297821045,
"expert": 0.17307455837726593
}
|
7,050
|
I have a small C# bot that check for an available date/time and book it if any,
it uses 2 external APIs which many other users use so it is a race, My main goal is to get an available date/time that I didn't use before if possible,
Please let me know if you have a better approach or any optimization on the logic:
private static readonly Dictionary<string, List<string>> TestedDateTimes = new();
public async void Main()
{
// Checking
string? date, time;
while (true)
{
(date, time) = await SelectAvailableDateTime().ConfigureAwait(false);
if (date != null && time != null) break;
await Task.Delay(3000).ConfigureAwait(false);
}
//Do something with the date/time...
}
public async Task<(string date, string time)> SelectAvailableDateTime()
{
var date = await GetNonUsedRandomDate().ConfigureAwait(false);
if (date == default) return default;
var time = await GetNonUsedRandomTimeByDate(date).ConfigureAwait(false);
if (time == null) return default;
if (!TestedDateTimes.ContainsKey(date))
TestedDateTimes[date] = new List<string>();
if (!TestedDateTimes[date].Contains(time))
TestedDateTimes[date].Add(time);
return (date, time);
}
private async Task<string?> GetNonUsedRandomDate()
{
var allDates = await GetAllDates(_applicant.CentreId, _applicant.CategoryId, _applicant.VisaTypeId).ConfigureAwait(false);
var availableDates = allDates
?.Where(d => d.AppointmentDateType == AppointmentDateType.Available &&
(_applicant.Members.Count < 2 || d.SingleSlotAvailable))
.ToArray();
if (availableDates == null || availableDates.Length == 0) return default;
var nonUsedDates = availableDates.Where(d => !TestedDateTimes.ContainsKey(d.DateText)).ToArray();
if (nonUsedDates.Length == 0)
{
TestedDateTimes.Clear();
nonUsedDates = availableDates;
}
// So if the user uses a custom date selector and there is no date fulfill his needs, search on all
return (GetRandomDate(nonUsedDates) ?? GetRandomDate(availableDates))?.DateText;
}
private async Task<string?> GetNonUsedRandomTimeByDate(string date)
{
var allTimes = await GetAllTimes(date, _applicant.CentreId, _applicant.CategoryId, _applicant.VisaTypeId).ConfigureAwait(false);
var availableTimes = allTimes
?.Where(d => d.Count >= _applicant.Members.Count)
.ToArray();
if (availableTimes == null || availableTimes.Length == 0) return default;
var nonUsedTimes = availableTimes.Where(d => !TestedDateTimes.ContainsKey(date) || !TestedDateTimes["date"].Contains(d.Id)).ToArray();
if (nonUsedTimes.Length == 0)
{
TestedDateTimes.Clear();
nonUsedTimes = availableTimes;
}
return FetchHelper.GetRandomElement(nonUsedTimes)?.Id;
}
private Date? GetRandomDate(IEnumerable<Date>? enumerable)
{
if (enumerable == null) return default;
var dates = enumerable as Date[] ?? enumerable.ToArray();
if (!dates.Any()) return null;
if (_applicant.DateSelector == DateSelector.Custom)
{
dates = dates
.Where(d => StringToDate(d.DateText) is var dateTime &&
dateTime >= StringToDate(_applicant.CustomDateFrom) &&
dateTime <= StringToDate(_applicant.CustomDateTo))
.ToArray();
return FetchHelper.GetRandomElement(dates);
}
var ordered = dates.OrderBy(d => StringToDate(d.DateText)).ToArray();
var takeAmount = ordered.Length == 1 ? 1 : ordered.Length / 2;
return _applicant.DateSelector switch
{
DateSelector.Soon => FetchHelper.GetRandomElement(ordered.Take(takeAmount)),
DateSelector.Later => FetchHelper.GetRandomElement(ordered.Reverse().Take(takeAmount)),
DateSelector.Any => FetchHelper.GetRandomElement(ordered),
_ => FetchHelper.GetRandomElement(ordered)
};
}
private static DateTime? StringToDate(string? date, string format = "yyyy-MM-dd")
{
var valid = DateTime.TryParseExact(date, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out var result);
return valid ? result : null;
}
private async Task<Date[]?> GetAllDates()
{
// FROM EXTERNAL API
}
private async Task<Time[]?> GetAllTimes(string date)
{
// FROM EXTERNAL API
}
|
d64a45cc8015b1cde2e0611666ad14ff
|
{
"intermediate": 0.380330890417099,
"beginner": 0.3951403498649597,
"expert": 0.2245287299156189
}
|
7,051
|
chooseFirstFabric() {
if (this.app.helpers.hasAttribute('fabric')) {
const fabric = this.configure.run('getAttribute', { alias: 'fabric' });
const values = fabric.values.filter((v) => v.selectable && !v.selected);
this.configure.run(
'selectValue',
{
ca: { id: fabric.id },
av: { id: values[0].id }
},
(err) => {
if (err) {
throw err;
}
this.app.mergedParams.noColorsAvailable = false;
this.app.cart.updateAddToCart();
}
);
}
}
is this code throwing me a infinite loop?
|
963ab2ad30087ba6af576c6d40cf605a
|
{
"intermediate": 0.3244451582431793,
"beginner": 0.4617210924625397,
"expert": 0.21383368968963623
}
|
7,052
|
you need to put some EOF or EOL to define end of your outputs of uncommented codes for the user to be sure that you have not got cutoffed, simply.
|
c91ce229ae6dc33b0ba526fbf3f1aafd
|
{
"intermediate": 0.31708696484565735,
"beginner": 0.46336451172828674,
"expert": 0.21954850852489471
}
|
7,053
|
flatpak list only Application id
|
d99a1a838cc165170318efe5e83fea09
|
{
"intermediate": 0.3016773462295532,
"beginner": 0.33033525943756104,
"expert": 0.36798742413520813
}
|
7,054
|
const {futures24hSubscribe, futures24hUnSubscribe} = useBinanceWsProvider();
useEffect(() => {
futures24hSubscribe(symbol);
return () => {
futures24hUnSubscribe(symbol);
};
}, [symbol]);
import {BinanceWsProviderProps} from “./BinanceWsProvider.props”;
import {ReadyState, useBinancePrice} from “…/…/hooks/binancePrices”;
import {createContext, useContext, useEffect, useState} from “react”;
interface BinanceWsProviderContext {
futures24hSubscribe: (symbol: string) => void;
futures24hUnSubscribe: (symbol: string) => void;
futures24hReadyState: number;
}
const defaultContextValue: BinanceWsProviderContext = {
futures24hSubscribe: (symbol: string) => {},
futures24hUnSubscribe: (symbol: string) => {},
futures24hReadyState: 0,
};
const Context = createContext(defaultContextValue);
export function useBinanceWsProvider() {
return useContext(Context);
}
const [futures24hSymbols, setFutures24hSymbols] = useState<Array<string>>([]);
const [futures24hQueue, setFutures24hQueue] = useState<Array<string>>([]);
futures24hSubscribe,
// futures24hUnSubscribe,
futures24hReadyState,
const futures24hSymbolSubscribe = (symbol: string) => {
if (futures24hSymbols.includes(symbol) || futures24hQueue.includes(symbol)) return;
setFutures24hQueue(prev => […prev, symbol]);
};
const futures24hSymbolUnsubscribe = (symbol: string) => {
if (!futures24hSymbols.includes(symbol) && !futures24hQueue.includes(symbol)) return;
setFutures24hQueue(prev => prev.filter(item => item !== symbol));
};
const subscribeFromFutures24hQueue = () => {
futures24hSubscribe(futures24hQueue);
setFutures24hSymbols([…futures24hSymbols, …futures24hQueue]);
setFutures24hQueue([]);
};
useEffect(() => {
if (futures24hQueue.length > 0 && futures24hReadyState === ReadyState.OPEN) {
subscribeFromFutures24hQueue();
}
}, [futures24hQueue]);
useEffect(() => {
if (futures24hReadyState === ReadyState.CLOSED) {
setFutures24hQueue([…futures24hSymbols, …futures24hQueue]);
setFutures24hSymbols([]);
}
if (futures24hQueue.length > 0 && futures24hReadyState === ReadyState.OPEN) {
subscribeFromFutures24hQueue();
}
}, [futures24hReadyState]);
return <Context.Provider
value={{
futures24hSubscribe: futures24hSymbolSubscribe,
futures24hUnSubscribe: futures24hSymbolUnsubscribe,
futures24hReadyState: futures24hReadyState,
}}
>
{children}
</Context.Provider>;
};
export default BinanceWsProvider;
import {useCallback, useEffect, useState} from “react”;
import {useDispatch} from “react-redux”;
import {setFutures24hBinancePriceState, setFuturesBinancePriceState, setSpotBinancePriceState} from “…/store/binancePriceSlice”;
export enum ReadyState {
UNINSTANTIATED = -1,
CONNECTING = 0,
OPEN = 1,
CLOSING = 2,
CLOSED = 3,
}
export function useBinancePrice() {
const [futures24hWs, setFutures24hWs] = useState<WebSocket | null>(null);
const [futures24hReadyState, setFutures24hReadyState] = useState(0);
const connectToWs = () => {
if (“undefined” === typeof window) {
setTimeout(“connectToWs”, 250);
return;
}
setFutures24hWs(new WebSocket(“wss://fstream.binance.com/ws”));
};
const futures24hSubscribe = useCallback((symbols: Array<string>) => {
if (null === futures24hWs || futures24hReadyState !== ReadyState.OPEN) return;
const symbolsTicker = symbols.map(symbol => {symbol.toLowerCase()}@miniTicker);
futures24hWs.send(JSON.stringify({
id: ((new Date()).getTime() + Math.floor(Math.random() * 10000) + 10000).toFixed(0),
method: “SUBSCRIBE”,
params: symbolsTicker,
}));
}, [futures24hReadyState]);
const futures24hUnSubscribe = useCallback((symbols: Array<string>) => {
if (null === futures24hWs || futures24hReadyState !== ReadyState.OPEN) return;
const symbolsTicker = symbols.map(symbol =>{symbol.toLowerCase()}@miniTicker);
futures24hWs.send(JSON.stringify({
id: ((new Date()).getTime() + Math.floor(Math.random() * 10000) + 10000).toFixed(0),
method: “UNSUBSCRIBE”,
params: symbolsTicker,
}));
}, [futures24hReadyState]);
useEffect(() => {
if (null === futures24hWs) return;
console.log(futures24hWs);
futures24hWs.onmessage = (message: MessageEvent) => {
if (!message.data) return;
const data = JSON.parse(message.data);
const symbol = data.s;
const priceChangePercent = ((parseFloat(data.c) - parseFloat(data.o)) / parseFloat(data.o)) * 100;
dispatch(setFutures24hBinancePriceState({symbol, price: data.c, percent: priceChangePercent.toFixed(2)}));
};
futures24hWs.onopen = () => {
setFutures24hReadyState(ReadyState.OPEN);
};
futures24hWs.onclose = () => {
setFutures24hReadyState(ReadyState.CLOSED);
};
}, [futures24hWs]);
useEffect(() => {
connectToWs();
}, []);
return {
futures24hSubscribe,
futures24hUnSubscribe,
futures24hReadyState,
};
}
import {createSlice} from “@reduxjs/toolkit”;
import {HYDRATE} from “next-redux-wrapper”;
export interface BinancePriceSlice {
futures24h: {[key: string]: {price: number; percent: number}};
}
const initialState: BinancePriceSlice = {
futures24h: {},
};
export const binancePriceSlice = createSlice({
name: “binancePrice”,
initialState,
reducers: {
setFutures24hBinancePriceState(state, action) {
const {symbol, price, percent} = action.payload;
state.futures24h[symbol] = {price, percent};
},
},
extraReducers: {
[HYDRATE]: (state, action) => {
return {
…state,
…action.payload,
};
},
},
});
export const {
setFutures24hBinancePriceState,
} = binancePriceSlice.actions;
export default binancePriceSlice.reducer;
не работает отписка от бесокетов.
Срабатывает return () => {
futures24hUnSubscribe(symbol);
}; в useEffect при демонтировании.
Но отписка UNSUBSCRIBE не происходит. Проанализируй код и найди баг, почему не происходит отписка
futures24hUnSubscribe в компоненте BinanceWsProvider не используется, как мне организовать и передавать туда массив символов для отписки
|
f313118088811c2deebdb50125b32329
|
{
"intermediate": 0.3806920051574707,
"beginner": 0.4473915696144104,
"expert": 0.1719164401292801
}
|
7,055
|
const futures24hUnSubscribe = useCallback((symbols: Array<string>) => {
if (null === futures24hWs || futures24hReadyState !== ReadyState.OPEN) return;
const symbolsTicker = symbols.map(symbol => `${symbol.toLowerCase()}@miniTicker`);
futures24hWs.send(JSON.stringify({
id: ((new Date()).getTime() + Math.floor(Math.random() * 10000) + 10000).toFixed(0),
method: "UNSUBSCRIBE",
params: symbolsTicker,
}));
}, [futures24hReadyState]);
у нас есть функция futures24hUnSubscribe
import {BinanceWsProviderProps} from “./BinanceWsProvider.props”;
import {ReadyState, useBinancePrice} from “…/…/hooks/binancePrices”;
import {createContext, useContext, useEffect, useState} from “react”;
interface BinanceWsProviderContext {
futures24hSubscribe: (symbol: string) => void;
futures24hUnSubscribe: (symbol: string) => void;
futures24hReadyState: number;
}
const defaultContextValue: BinanceWsProviderContext = {
futures24hSubscribe: (symbol: string) => {},
futures24hUnSubscribe: (symbol: string) => {},
futures24hReadyState: 0,
};
const Context = createContext(defaultContextValue);
export function useBinanceWsProvider() {
return useContext(Context);
}
const [futures24hSymbols, setFutures24hSymbols] = useState<Array<string>>([]);
const [futures24hQueue, setFutures24hQueue] = useState<Array<string>>([]);
futures24hSubscribe,
// futures24hUnSubscribe,
futures24hReadyState,
const futures24hSymbolSubscribe = (symbol: string) => {
if (futures24hSymbols.includes(symbol) || futures24hQueue.includes(symbol)) return;
setFutures24hQueue(prev => […prev, symbol]);
};
const futures24hSymbolUnsubscribe = (symbol: string) => {
if (!futures24hSymbols.includes(symbol) && !futures24hQueue.includes(symbol)) return;
setFutures24hQueue(prev => prev.filter(item => item !== symbol));
};
const subscribeFromFutures24hQueue = () => {
futures24hSubscribe(futures24hQueue);
setFutures24hSymbols([…futures24hSymbols, …futures24hQueue]);
setFutures24hQueue([]);
};
useEffect(() => {
if (futures24hQueue.length > 0 && futures24hReadyState === ReadyState.OPEN) {
subscribeFromFutures24hQueue();
}
}, [futures24hQueue]);
useEffect(() => {
if (futures24hReadyState === ReadyState.CLOSED) {
setFutures24hQueue([…futures24hSymbols, …futures24hQueue]);
setFutures24hSymbols([]);
}
if (futures24hQueue.length > 0 && futures24hReadyState === ReadyState.OPEN) {
subscribeFromFutures24hQueue();
}
}, [futures24hReadyState]);
return <Context.Provider
value={{
futures24hSubscribe: futures24hSymbolSubscribe,
futures24hUnSubscribe: futures24hSymbolUnsubscribe,
futures24hReadyState: futures24hReadyState,
}}
>
{children}
</Context.Provider>;
};
export default BinanceWsProvider;
есть компонент BinanceWsProvider
export const Component = () => {
<Box className="scroll-block" sx={{overflowY: "scroll", overflowX: "hidden", height: 640}}>
{symbols.map((symbol) => (
<Symbols
key={symbol}
symbol={symbol}
activeSymbol={activeSymbol}
setActiveSymbol={setActiveSymbol}
/>
))}
</Box>
}
type SymbolsProps = {
symbol: string
activeSymbol: string
setActiveSymbol: (symbol: string) => void
}
const Symbols = ({symbol, activeSymbol, setActiveSymbol}:SymbolsProps) => {
const {futures24hSubscribe, futures24hUnSubscribe} = useBinanceWsProvider();
useEffect(() => {
futures24hSubscribe(symbol);
return () => futures24hUnSubscribe(symbol);
}, [symbol]);
return <Grid item xs={5.5} display="flex" justifyContent="space-between">
<Typography fontSize={13} color={activeSymbol === symbol ? "#fff" : ""} fontWeight={300}>${FormatPrice({amount: coin.price, currency_iso_code: "USD", dec: "decimal"})}</Typography>
<Typography fontSize={13} color={activeSymbol === symbol ? "#fff" : coin.percent >= 0 ? "#006943" : "#B41C18"} fontWeight={300}>
{coin.percent >= 0 ? `+${coin.percent}` : coin.percent}%
</Typography>
</Grid>
};
и есть компонент где вызывается futures24hUnSubscribe ..
проанализируй код..
Нужно в компоненте BinanceWsProvider const {
futures24hSubscribe,
futures24hUnSubscribe,
futures24hReadyState,
} = useBinancePrice(); // futures24hUnSubscribe нигде не исполльзуется, нужно, чтобы когда вызывался useEffect(() => {
return () => futures24hUnSubscribe(symbol);
}, []); демонтировании, то в BinanceWsProvider организовать такую логику, чтобы futures24hUnSubscribe принимал массив символов, например как futures24hSubscribe(futures24hQueue);, и происходила отписка метод UNSUBSCRIBE
|
196b5c73b259ad3c3105ea92dcdabe65
|
{
"intermediate": 0.27856868505477905,
"beginner": 0.5051132440567017,
"expert": 0.2163180708885193
}
|
7,056
|
You are supposed to generate appropriate python code following the instructions.
There are three functions given:
# calculate the sum of two numbers
def sum(a, b)
# calculate the product of two numbers
def times(a, b)
# calculate the difference of two numbers
def minus(a, b)
now, generate a code that calculates the sum of the square of each entry in a vector. the interface is:
def square_sum(v):
{code here}
|
db603f232da26103255af76dce690738
|
{
"intermediate": 0.3875952661037445,
"beginner": 0.33497053384780884,
"expert": 0.27743417024612427
}
|
7,057
|
In Julia I would like to plot histogram. All the negative values I would like to be painted by pink, ad the lowest quantile = 0.05 I would like to be painted by red even if it is negative. Then I would like to connect created in that way 3 histograms on the same plot and adjust the scale.
|
78576c086feb3fb332356315886cf244
|
{
"intermediate": 0.43328195810317993,
"beginner": 0.16422973573207855,
"expert": 0.40248823165893555
}
|
7,058
|
PowerMock 怎么mock private static final CacheService CACHE_SERVICE = CacheServiceImpl.getInstance();
|
ea0429d394f5d10a359b7cf5eaf27f0f
|
{
"intermediate": 0.36366143822669983,
"beginner": 0.25628769397735596,
"expert": 0.380050927400589
}
|
7,059
|
const futures24hUnSubscribe = useCallback((symbols: Array<string>) => {
if (null === futures24hWs || futures24hReadyState !== ReadyState.OPEN) return;
const symbolsTicker = symbols.map(symbol => `${symbol.toLowerCase()}@miniTicker`);
futures24hWs.send(JSON.stringify({
id: ((new Date()).getTime() + Math.floor(Math.random() * 10000) + 10000).toFixed(0),
method: "UNSUBSCRIBE",
params: symbolsTicker,
}));
}, [futures24hReadyState]);
у нас есть функция futures24hUnSubscribe
import {BinanceWsProviderProps} from “./BinanceWsProvider.props”;
import {ReadyState, useBinancePrice} from “…/…/hooks/binancePrices”;
import {createContext, useContext, useEffect, useState} from “react”;
interface BinanceWsProviderContext {
futures24hSubscribe: (symbol: string) => void;
futures24hUnSubscribe: (symbol: string) => void;
futures24hReadyState: number;
}
const defaultContextValue: BinanceWsProviderContext = {
futures24hSubscribe: (symbol: string) => {},
futures24hUnSubscribe: (symbol: string) => {},
futures24hReadyState: 0,
};
const Context = createContext(defaultContextValue);
export function useBinanceWsProvider() {
return useContext(Context);
}
const [futures24hSymbols, setFutures24hSymbols] = useState<Array<string>>([]);
const [futures24hQueue, setFutures24hQueue] = useState<Array<string>>([]);
futures24hSubscribe,
// futures24hUnSubscribe,
futures24hReadyState,
const futures24hSymbolSubscribe = (symbol: string) => {
if (futures24hSymbols.includes(symbol) || futures24hQueue.includes(symbol)) return;
setFutures24hQueue(prev => […prev, symbol]);
};
const futures24hSymbolUnsubscribe = (symbol: string) => {
if (!futures24hSymbols.includes(symbol) && !futures24hQueue.includes(symbol)) return;
setFutures24hQueue(prev => prev.filter(item => item !== symbol));
};
const subscribeFromFutures24hQueue = () => {
futures24hSubscribe(futures24hQueue);
setFutures24hSymbols([…futures24hSymbols, …futures24hQueue]);
setFutures24hQueue([]);
};
useEffect(() => {
if (futures24hQueue.length > 0 && futures24hReadyState === ReadyState.OPEN) {
subscribeFromFutures24hQueue();
}
}, [futures24hQueue]);
useEffect(() => {
if (futures24hReadyState === ReadyState.CLOSED) {
setFutures24hQueue([…futures24hSymbols, …futures24hQueue]);
setFutures24hSymbols([]);
}
if (futures24hQueue.length > 0 && futures24hReadyState === ReadyState.OPEN) {
subscribeFromFutures24hQueue();
}
}, [futures24hReadyState]);
return <Context.Provider
value={{
futures24hSubscribe: futures24hSymbolSubscribe,
futures24hUnSubscribe: futures24hSymbolUnsubscribe,
futures24hReadyState: futures24hReadyState,
}}
>
{children}
</Context.Provider>;
};
export default BinanceWsProvider;
есть компонент BinanceWsProvider
export const Component = () => {
<Box className="scroll-block" sx={{overflowY: "scroll", overflowX: "hidden", height: 640}}>
{symbols.map((symbol) => (
<Symbols
key={symbol}
symbol={symbol}
activeSymbol={activeSymbol}
setActiveSymbol={setActiveSymbol}
/>
))}
</Box>
}
type SymbolsProps = {
symbol: string
activeSymbol: string
setActiveSymbol: (symbol: string) => void
}
const Symbols = ({symbol, activeSymbol, setActiveSymbol}:SymbolsProps) => {
const {futures24hSubscribe, futures24hUnSubscribe} = useBinanceWsProvider();
useEffect(() => {
futures24hSubscribe(symbol);
return () => futures24hUnSubscribe(symbol);
}, [symbol]);
return <Grid item xs={5.5} display="flex" justifyContent="space-between">
<Typography fontSize={13} color={activeSymbol === symbol ? "#fff" : ""} fontWeight={300}>${FormatPrice({amount: coin.price, currency_iso_code: "USD", dec: "decimal"})}</Typography>
<Typography fontSize={13} color={activeSymbol === symbol ? "#fff" : coin.percent >= 0 ? "#006943" : "#B41C18"} fontWeight={300}>
{coin.percent >= 0 ? `+${coin.percent}` : coin.percent}%
</Typography>
</Grid>
};
и есть компонент где вызывается futures24hUnSubscribe ..
проанализируй код..
Нужно в компоненте BinanceWsProvider const {
futures24hSubscribe,
futures24hUnSubscribe,
futures24hReadyState,
} = useBinancePrice(); // futures24hUnSubscribe нигде не исполльзуется, нужно, чтобы когда вызывался useEffect(() => {
return () => futures24hUnSubscribe(symbol);
}, []); демонтировании, то в BinanceWsProvider организовать такую логику, чтобы futures24hUnSubscribe принимал массив символов, например как futures24hSubscribe(futures24hQueue);, и происходила отписка метод UNSUBSCRIBE
|
8f6b84ddf6b9ad397331c38099176a2a
|
{
"intermediate": 0.27856868505477905,
"beginner": 0.5051132440567017,
"expert": 0.2163180708885193
}
|
7,060
|
in python, how to store jason data with more than 200000 rows into csv
|
40bb5e11096187e484728948430d9a93
|
{
"intermediate": 0.5297525525093079,
"beginner": 0.22010670602321625,
"expert": 0.25014063715934753
}
|
7,061
|
in python, how to write code like set value to one field if condition meets, the value is 1, or else set 2
|
2143c730dc163def2901e2dccb8d3bc8
|
{
"intermediate": 0.30803200602531433,
"beginner": 0.27036741375923157,
"expert": 0.4216006100177765
}
|
7,062
|
const futures24hUnSubscribe = useCallback((symbols: Array<string>) => {
if (null === futures24hWs || futures24hReadyState !== ReadyState.OPEN) return;
const symbolsTicker = symbols.map(symbol => `${symbol.toLowerCase()}@miniTicker`);
futures24hWs.send(JSON.stringify({
id: ((new Date()).getTime() + Math.floor(Math.random() * 10000) + 10000).toFixed(0),
method: "UNSUBSCRIBE",
params: symbolsTicker,
}));
}, [futures24hReadyState]);
у нас есть функция futures24hUnSubscribe
import {BinanceWsProviderProps} from “./BinanceWsProvider.props”;
import {ReadyState, useBinancePrice} from “…/…/hooks/binancePrices”;
import {createContext, useContext, useEffect, useState} from “react”;
interface BinanceWsProviderContext {
futures24hSubscribe: (symbol: string) => void;
futures24hUnSubscribe: (symbol: string) => void;
futures24hReadyState: number;
}
const defaultContextValue: BinanceWsProviderContext = {
futures24hSubscribe: (symbol: string) => {},
futures24hUnSubscribe: (symbol: string) => {},
futures24hReadyState: 0,
};
const Context = createContext(defaultContextValue);
export function useBinanceWsProvider() {
return useContext(Context);
}
const [futures24hSymbols, setFutures24hSymbols] = useState<Array<string>>([]);
const [futures24hQueue, setFutures24hQueue] = useState<Array<string>>([]);
futures24hSubscribe,
// futures24hUnSubscribe,
futures24hReadyState,
const futures24hSymbolSubscribe = (symbol: string) => {
if (futures24hSymbols.includes(symbol) || futures24hQueue.includes(symbol)) return;
setFutures24hQueue(prev => […prev, symbol]);
};
const futures24hSymbolUnsubscribe = (symbol: string) => {
if (!futures24hSymbols.includes(symbol) && !futures24hQueue.includes(symbol)) return;
setFutures24hQueue(prev => prev.filter(item => item !== symbol));
};
const subscribeFromFutures24hQueue = () => {
futures24hSubscribe(futures24hQueue);
setFutures24hSymbols([…futures24hSymbols, …futures24hQueue]);
setFutures24hQueue([]);
};
useEffect(() => {
if (futures24hQueue.length > 0 && futures24hReadyState === ReadyState.OPEN) {
subscribeFromFutures24hQueue();
}
}, [futures24hQueue]);
useEffect(() => {
if (futures24hReadyState === ReadyState.CLOSED) {
setFutures24hQueue([…futures24hSymbols, …futures24hQueue]);
setFutures24hSymbols([]);
}
if (futures24hQueue.length > 0 && futures24hReadyState === ReadyState.OPEN) {
subscribeFromFutures24hQueue();
}
}, [futures24hReadyState]);
return <Context.Provider
value={{
futures24hSubscribe: futures24hSymbolSubscribe,
futures24hUnSubscribe: futures24hSymbolUnsubscribe,
futures24hReadyState: futures24hReadyState,
}}
>
{children}
</Context.Provider>;
};
export default BinanceWsProvider;
есть компонент BinanceWsProvider
export const Component = () => {
<Box className="scroll-block" sx={{overflowY: "scroll", overflowX: "hidden", height: 640}}>
{symbols.map((symbol) => (
<Symbols
key={symbol}
symbol={symbol}
activeSymbol={activeSymbol}
setActiveSymbol={setActiveSymbol}
/>
))}
</Box>
}
type SymbolsProps = {
symbol: string
activeSymbol: string
setActiveSymbol: (symbol: string) => void
}
const Symbols = ({symbol, activeSymbol, setActiveSymbol}:SymbolsProps) => {
const {futures24hSubscribe, futures24hUnSubscribe} = useBinanceWsProvider();
useEffect(() => {
futures24hSubscribe(symbol);
return () => futures24hUnSubscribe(symbol);
}, [symbol]);
return <Grid item xs={5.5} display="flex" justifyContent="space-between">
<Typography fontSize={13} color={activeSymbol === symbol ? "#fff" : ""} fontWeight={300}>${FormatPrice({amount: coin.price, currency_iso_code: "USD", dec: "decimal"})}</Typography>
<Typography fontSize={13} color={activeSymbol === symbol ? "#fff" : coin.percent >= 0 ? "#006943" : "#B41C18"} fontWeight={300}>
{coin.percent >= 0 ? `+${coin.percent}` : coin.percent}%
</Typography>
</Grid>
};
и есть компонент где вызывается futures24hUnSubscribe ..
проанализируй код..
Нужно в компоненте BinanceWsProvider const {
futures24hSubscribe,
futures24hUnSubscribe,
futures24hReadyState,
} = useBinancePrice(); // futures24hUnSubscribe нигде не исполльзуется, нужно, чтобы когда вызывался useEffect(() => {
return () => futures24hUnSubscribe(symbol);
}, []); демонтировании, то в BinanceWsProvider организовать такую логику, чтобы futures24hUnSubscribe принимал массив символов, например как futures24hSubscribe(futures24hQueue);, и происходила отписка метод UNSUBSCRIBE
|
914ad239fb59f0e672761838814ad4f5
|
{
"intermediate": 0.27856868505477905,
"beginner": 0.5051132440567017,
"expert": 0.2163180708885193
}
|
7,063
|
in c++, i use template class AutoRegisterTemplate to do some automatic registration in class constructor. Suppose ModuleClass is the template parameter, for different ModuleClass , the constructor extract their `ModuleClass::Register` function pointer in a static std::map variable all_register_funcs. Now i have this problem, I write `static AutoRegisterTemplate<ModuleClassA> file_local_var` in a .cpp file my_module_a.cpp, hoping ModuleClassA will trigger it's constructor and inturn put ModuleClassA::Register pointer into the `all_register_funcs`. However, when I run the program, the .cpp file my_module_a.cpp was never linked, it seems that this cpp file was optimized away by linker. How do i achieve what i want, aka implement the automatic registration process of aquiring different classes' interface function pointers.
|
f5f9166c6e855dce83deadd6e1793296
|
{
"intermediate": 0.48477351665496826,
"beginner": 0.3682125210762024,
"expert": 0.14701396226882935
}
|
7,064
|
in python, with csv module, how to check if there are headers in the csv file
|
162578aa44afb2168368f81f42c1f36a
|
{
"intermediate": 0.5191686153411865,
"beginner": 0.2103443294763565,
"expert": 0.2704870104789734
}
|
7,065
|
Please create a macro vb6 function that able get the each row of the distinct serial number in workbook A, and then using the serial number to lookup in each of the worksheet in workbook B, once found it needs to copy the row data of the serial number from each column that exactly the same column name with workbook A.
|
2d72a51b221164d1002ef04c8db32678
|
{
"intermediate": 0.5364391803741455,
"beginner": 0.1431233137845993,
"expert": 0.3204374313354492
}
|
7,066
|
how to write chinese characters into csv file with csv module in python
|
810532cf4947ff72b971f8e025d8c1b2
|
{
"intermediate": 0.40436774492263794,
"beginner": 0.2841988801956177,
"expert": 0.3114334046840668
}
|
7,067
|
how to read chinese characters stored in data list and save into csv file with csv module in python
|
637d7c92654ce5e7f817e717af5f6202
|
{
"intermediate": 0.5296955108642578,
"beginner": 0.2173377424478531,
"expert": 0.2529667317867279
}
|
7,068
|
how to backup gnome extention settings
|
9b593fc94eb67990ae64b95ac7046b03
|
{
"intermediate": 0.37304118275642395,
"beginner": 0.37190163135528564,
"expert": 0.25505709648132324
}
|
7,069
|
aside from /INCLUDE , are there ways to tell compiler to link certain source file even if the source file is not used, in c++ code
|
69f60b987fb14299e4d2242a05494c05
|
{
"intermediate": 0.49549344182014465,
"beginner": 0.16270510852336884,
"expert": 0.3418014645576477
}
|
7,070
|
give me a nginx config to make nginx a proxy for https requests
|
e97202c1a43329dd30476a368c91388f
|
{
"intermediate": 0.43715935945510864,
"beginner": 0.2505509853363037,
"expert": 0.3122897446155548
}
|
7,071
|
We’ll frame our problem as follows. We have historical price data for Bitcoin, which includes the following predictors for each day (where we have daily time steps):
Opening price
High price
Low price
Volume traded
Our goal is to take some sequence of the above four values (say, for 100 previous days), and predict the target variable (Bitcoin’s price) for the next 50 days into the future. Consequently, we need a way to feed in these multiple values at each time step to our LSTM using Google Colab with our csv file located in goodle drive with the csv link in https://drive.google.com/file/d/1J_0IgW_Ef6acETKT5r87J2aaX8Iy-OuS/view?usp=share_link , and to produce a singular output representing the prediction at the next time step in return. In this way, we construct a multivariate LSTM. then we clean the data by removing adjusted close from the csv:
df = pd.read_csv('BTC-USD.csv', index_col = 'Date', parse_dates=True)
df.drop(columns=['Adj Close'], inplace=True)
df.head(5)
from now on you will refeer to historical prices csv as: https://drive.google.com/file/d/1J_0IgW_Ef6acETKT5r87J2aaX8Iy-OuS/view?usp=share_link.
At the bare minimum, your exploratory data analysis should consist of plotting the target variable of interest. Let’s plot the Bitcoin price over time to see what we’re actually trying to predict.
plt.plot(df.Close)
plt.xlabel("Time")
plt.ylabel("Price (USD)")
plt.title("Bitcoin price over time")
plt.savefig("initial_plot.png", dpi=250)
plt.show();
We want a realistic emulation of what would happen in the real-world. That is, we want a few years of historical data, and train an LSTM to predict what will happen to the price of Bitcoin in the next few months.
Setting inputs and outputs
Recall that our predictors will consist of all the columns except our target, closing price. Note that we want to use an sklearn preprocessor below, which requires reshaping the array if it consists of a single feature, as our target does. Hence, for the target y, we have to call values, which removes the axes labels and will allow us to reshape the array.
X, y = df.drop(columns=['Close']), df.Close.values
X.shape, y.shape
>>> ((5438, 4), (5438,))
-----
We’ll use standardisation for our training features X by removing the mean and scaling to unit variance. Standardisation helps the deep learning model to learn by ensuring that parameters can exist in the same multi-dimensional space; it wouldn’t make much sense to have the weights have to change their size simply because all the variables have different scales. For our target y, we will scale and translate each feature individually to between 0 and 1. This transformation is often used as an alternative to zero mean, unit variance scaling:
from sklearn.preprocessing import StandardScaler, MinMaxScaler
mm = MinMaxScaler()
ss = StandardScaler()
X_trans = ss.fit_transform(X)
y_trans = mm.fit_transform(y.reshape(-1, 1))
---
We want to feed in 100 samples, up to the current day, and predict the next 50 time step values. To do this, we need a special function to ensure that the corresponding indices of X and y represent this structure. Examine this function carefully, but essentially it just boils down to getting 100 samples from X, then looking at the 50 next indices in y, and patching these together. Note that because of this we'll throw out the first 50 values of y. :
# split a multivariate sequence past, future samples (X and y)
def split_sequences(input_sequences, output_sequence, n_steps_in, n_steps_out):
X, y = list(), list() # instantiate X and y
for i in range(len(input_sequences)):
# find the end of the input, output sequence
end_ix = i + n_steps_in
out_end_ix = end_ix + n_steps_out - 1
# check if we are beyond the dataset
if out_end_ix > len(input_sequences): break
# gather input and output of the pattern
seq_x, seq_y = input_sequences[i:end_ix], output_sequence[end_ix-1:out_end_ix, -1]
X.append(seq_x), y.append(seq_y)
return np.array(X), np.array(y)
X_ss, y_mm = split_sequences(X_trans, y_trans, 100, 50)
print(X_ss.shape, y_mm.shape)
>>> (2529, 100, 4) (2529, 50)
------
we wanted to predict the data a several months into the future. Thus, we’ll use a training data size of 95%, with 5% left for the remaining data that we’re going to predict. This gives us a training set size of 2763 days, or about seven and a half years. We will predict 145 days into the future, which is almost 5 months:
total_samples = len(X)
train_test_cutoff = round(0.90 * total_samples)
X_train = X_ss[:-150]
X_test = X_ss[-150:]
y_train = y_mm[:-150]
y_test = y_mm[-150:]
print("Training Shape:", X_train.shape, y_train.shape)
print("Testing Shape:", X_test.shape, y_test.shape)
>>> Training Shape: (2379, 100, 4) (2379, 50)
Testing Shape: (150, 100, 4) (150, 50)
-------
input tensor to be forward propagated has to be can facilitate automatic back propagation (through backward()) without being wrapped in a variable:
# convert to pytorch tensors
X_train_tensors = Variable(torch.Tensor(X_train))
X_test_tensors = Variable(torch.Tensor(X_test))
y_train_tensors = Variable(torch.Tensor(y_train))
y_test_tensors = Variable(torch.Tensor(y_test))
--------
|
813fcf50f9620eacefac02c9c2a8c358
|
{
"intermediate": 0.3223542869091034,
"beginner": 0.40976962447166443,
"expert": 0.2678760886192322
}
|
7,072
|
in c++, i use template class AutoRegisterTemplate to do some automatic registration in class constructor. Suppose ModuleClass is the template parameter, for different ModuleClass , the constructor extract their `ModuleClass::Register` function pointer in a static std::map variable all_register_funcs. Now i have this problem, I write `static AutoRegisterTemplate<ModuleClassA> file_local_var` in a .cpp file my_module_a.cpp, hoping ModuleClassA will trigger it's constructor and inturn put ModuleClassA::Register pointer into the `all_register_funcs`. However, when I run the program, the .cpp file my_module_a.cpp was never linked, it seems that this cpp file was optimized away by linker. Is this a template thing? how do i avoid the problem and achive my goal of using the instantiation mechanic of template to do automatic registration.
|
e872a8c890ae52a19514809af8cfec91
|
{
"intermediate": 0.424786239862442,
"beginner": 0.3949792981147766,
"expert": 0.1802344173192978
}
|
7,073
|
Ich habe eine App die responsive auf Android, iOS und Web sein soll. ich benutzte das Flutter Package responsive_framework. Die Version ist von 0.2 auf 1.0 gestiegen und mein Code funktioniert nicht mehr. Wie muss ich meinen Code ändern, dass es wieder funktioniert.
hier mein Code:
child: MaterialApp.router(
routeInformationParser: _patientAppRouteInformationParser,
routerDelegate: _patientAppRouterDelegate,
onGenerateTitle: (BuildContext context) =>
AppLocalizations.of(context)!.appTitle,
theme: theme.PatientAppTheme.defaultTheme(),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
locale: context.select<GlobalStateProvider, Locale?>(
(globalState) => globalState.locale),
builder: (context, widget) => ResponsiveBreakpoints.builder(
child: MaxWidthBox(
maxWidth: double.infinity,
background: const ColoredBox(
color: Colors.white,
child:
SizedBox(height: what height, width: what width?),
), // does nothing?
child:
widget! // TODO: ResponsiveScaledBox(width: 1200,child: widget!), ?? how to scale
),
breakpoints: [],
breakpointsLandscape: [
const Breakpoint(
start: theme.breakPointMobileStart,
end: theme.breakPointMobileEnd,
name: MOBILE),
const Breakpoint(
start: theme.breakPointTabletStart,
end: theme.breakPointTabletEnd,
name: TABLET),
const Breakpoint(
start: theme.breakPointDesktopStart,
end: theme.breakPointDesktopEnd,
name: DESKTOP),
],
),
Und hier das neue von 1.0
Import this library into your project:
responsive_framework: ^latest_version
Add ResponsiveBreakpoints.builder to your MaterialApp or CupertinoApp. Define your own breakpoints and labels.
import 'package:responsive_framework/responsive_framework.dart';
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
builder: (context, child) => ResponsiveBreakpoints.builder(
child: child!,
breakpoints: [
const Breakpoint(start: 0, end: 450, name: MOBILE),
const Breakpoint(start: 451, end: 800, name: TABLET),
const Breakpoint(start: 801, end: 1920, name: DESKTOP),
const Breakpoint(start: 1921, end: double.infinity, name: '4K'),
],
),
initialRoute: "/",
);
}
}
Use the labels you defined for layouts and values.
// Example: if the screen is bigger than the Mobile breakpoint, build full width AppBar icons and labels.
if (ResponsiveBreakpoints.of(context).largerThan(MOBILE))
FullWidthAppBarItems()
// Booleans
ResponsiveBreakpoints.of(context).isDesktop;
ResponsiveBreakpoints.of(context).isTablet;
ResponsiveBreakpoints.of(context).isMobile;
ResponsiveBreakpoints.of(context).isPhone;
// Conditionals
ResponsiveBreakpoints.of(context).equals(DESKTOP)
ResponsiveBreakpoints.of(context).largerThan(MOBILE)
ResponsiveBreakpoints.of(context).smallerThan(TABLET)
...
Customization
You can define your own breakpoint labels and use them in your conditionals.
For example, if we're building a Material 3 Navigation Rail and want to expand the menu to full width once there is enough room, we can add a custom EXPAND_SIDE_PANEL breakpoint.
breakpoints: [
...
const Breakpoint(start: 801, end: 1920, name: DESKTOP),
const Breakpoint(start: 900, end: 900, name: 'EXPAND_SIDE_PANEL') <- Custom label.
const Breakpoint(start: 1921, end: double.infinity, name: '4K'),
...
]
Then, in our code, set the value based on the breakpoint condition.
expand: ResponsiveBreakpoints.of(context).largerThan('EXPAND_SIDE_PANEL')
Responsive Framework Widgets
The ResponsiveFramework includes a few custom widgets that supplement Flutter's responsive capabilities. They are showcased in the demo projects.
ResponsiveValue
ResponsiveRowColumn
ResponsiveGridView
ResponsiveScaledBox
MaxWidthBox
Legacy ReadMe (v0.2.0 and below)
ResponsiveWrapper Migration
The legacy ResponsiveWrapper combined multiple features into one widget. This made it difficult to use at times when custom behavior was required. The updated V1 implementation separates each feature into its own widget.
Responsive Framework v1 introduces some new widgets as well:
ResponsiveScaledBox
MaxWidthBox
ConditionalRouteWidget
ResponsiveScaledBox
ResponsiveScaledBox(width: width, child: child);
Replaces the core AutoScale functionality of ResponsiveWrapper. ResponsiveScaledBox renders the child widget with the specified width.
This widget wraps the Flutter FittedBox widget with a LayoutBuilder and MediaQuery.
Why should you use a ResponsiveScaledBox?
Use a ResponsiveScaledBox instead of a FittedBox if the layout is full screen as the widget helps calculate correctly scaled MediaQueryData.
MaxWidthBox
MaxWidthBox(maxWidth: maxWidth, background: background, child: child);
Limit the child widget to the maxWidth and paints an optional background behind the widget.
This widget is helpful for limiting the content width on large desktop displays and creating gutters on the left and right side of the page.
The remainder of the legacy ReadMe is preserved below as the concepts are still useful and used by the new widgets. ResponsiveWrapper has been deprecated and removed.
The Problem
Supporting multiple display sizes often means recreating the same layout multiple times. Under the traditional Bootstrap approach, building responsive UI is time consuming, frustrating and repetitive. Furthermore, getting everything pixel perfect is near impossible and simple edits take hours.
import 'package:flutter/material.dart';
@immutable
class Breakpoint {
final double start;
final double end;
final String? name;
final dynamic data;
const Breakpoint(
{required this.start, required this.end, this.name, this.data});
Breakpoint copyWith({
double? start,
double? end,
String? name,
dynamic data,
}) =>
Breakpoint(
start: start ?? this.start,
end: end ?? this.end,
name: name ?? this.name,
data: data ?? this.data,
);
@override
String toString() => 'Breakpoint(start: $start, end: $end, name: $name)';
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Breakpoint &&
runtimeType == other.runtimeType &&
start == other.start &&
end == other.end &&
name == other.name;
@override
int get hashCode => start.hashCode * end.hashCode * name.hashCode;
}
import 'dart:math';
import 'package:flutter/material.dart';
class ResponsiveScaledBox extends StatelessWidget {
final double? width;
final Widget child;
final bool autoCalculateMediaQueryData;
const ResponsiveScaledBox(
{Key? key,
required this.width,
required this.child,
this.autoCalculateMediaQueryData = true})
: super(key: key);
@override
Widget build(BuildContext context) {
if (width != null) {
return LayoutBuilder(
builder: (context, constraints) {
MediaQueryData mediaQueryData = MediaQuery.of(context);
double aspectRatio = constraints.maxWidth / constraints.maxHeight;
double scaledWidth = width!;
double scaledHeight = width! / aspectRatio;
bool overrideMediaQueryData = autoCalculateMediaQueryData &&
(mediaQueryData.size ==
Size(constraints.maxWidth, constraints.maxHeight));
EdgeInsets scaledViewInsets = getScaledViewInsets(
mediaQueryData: mediaQueryData,
screenSize: mediaQueryData.size,
scaledSize: Size(scaledWidth, scaledHeight));
EdgeInsets scaledViewPadding = getScaledViewPadding(
mediaQueryData: mediaQueryData,
screenSize: mediaQueryData.size,
scaledSize: Size(scaledWidth, scaledHeight));
EdgeInsets scaledPadding = getScaledPadding(
padding: scaledViewPadding, insets: scaledViewInsets);
Widget childHolder = FittedBox(
fit: BoxFit.fitWidth,
alignment: Alignment.topCenter,
child: Container(
width: width,
height: scaledHeight,
alignment: Alignment.center,
child: child,
),
);
if (overrideMediaQueryData) {
return MediaQuery(
data: mediaQueryData.copyWith(
size: Size(scaledWidth, scaledHeight),
viewInsets: scaledViewInsets,
viewPadding: scaledViewPadding,
padding: scaledPadding),
child: childHolder,
);
}
return childHolder;
},
);
}
return child;
}
EdgeInsets getScaledViewInsets(
{required MediaQueryData mediaQueryData,
required Size screenSize,
required Size scaledSize}) {
double leftInsetFactor = mediaQueryData.viewInsets.left / screenSize.width;
double topInsetFactor = mediaQueryData.viewInsets.top / screenSize.height;
double rightInsetFactor =
mediaQueryData.viewInsets.right / screenSize.width;
double bottomInsetFactor =
mediaQueryData.viewInsets.bottom / screenSize.height;
double scaledLeftInset = leftInsetFactor * scaledSize.width;
double scaledTopInset = topInsetFactor * scaledSize.height;
double scaledRightInset = rightInsetFactor * scaledSize.width;
double scaledBottomInset = bottomInsetFactor * scaledSize.height;
return EdgeInsets.fromLTRB(
scaledLeftInset, scaledTopInset, scaledRightInset, scaledBottomInset);
}
EdgeInsets getScaledViewPadding(
{required MediaQueryData mediaQueryData,
required Size screenSize,
required Size scaledSize}) {
double scaledLeftPadding;
double scaledTopPadding;
double scaledRightPadding;
double scaledBottomPadding;
double leftPaddingFactor =
mediaQueryData.viewPadding.left / screenSize.width;
double topPaddingFactor =
mediaQueryData.viewPadding.top / screenSize.height;
double rightPaddingFactor =
mediaQueryData.viewPadding.right / screenSize.width;
double bottomPaddingFactor =
mediaQueryData.viewPadding.bottom / screenSize.height;
scaledLeftPadding = leftPaddingFactor * scaledSize.width;
scaledTopPadding = topPaddingFactor * scaledSize.height;
scaledRightPadding = rightPaddingFactor * scaledSize.width;
scaledBottomPadding = bottomPaddingFactor * scaledSize.height;
return EdgeInsets.fromLTRB(scaledLeftPadding, scaledTopPadding,
scaledRightPadding, scaledBottomPadding);
}
EdgeInsets getScaledPadding(
{required EdgeInsets padding, required EdgeInsets insets}) {
double scaledLeftPadding;
double scaledTopPadding;
double scaledRightPadding;
double scaledBottomPadding;
scaledLeftPadding = max(0.0, padding.left - insets.left);
scaledTopPadding = max(0.0, padding.top - insets.top);
scaledRightPadding = max(0.0, padding.right - insets.right);
scaledBottomPadding = max(0.0, padding.bottom - insets.bottom);
return EdgeInsets.fromLTRB(scaledLeftPadding, scaledTopPadding,
scaledRightPadding, scaledBottomPadding);
}
}// ignore_for_file: constant_identifier_names
import 'package:collection/collection.dart' show IterableExtension;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'breakpoint.dart';
import 'utils/responsive_utils.dart';
class ResponsiveBreakpoints extends StatefulWidget {
final Widget child;
final List<Breakpoint> breakpoints;
/// A list of breakpoints that are active when the device is in landscape orientation.
///
/// In Flutter, the returned device orientation is not the real device orientation,
/// but is calculated based on the screen width and height.
/// This means that landscape only makes sense on devices that support
/// orientation changes. By default, landscape breakpoints are only
/// active when the [ResponsiveTargetPlatform] is Android, iOS, or Fuchsia.
/// To enable landscape breakpoints on other platforms, pass a custom
/// list of supported platforms to [landscapePlatforms].
final List<Breakpoint>? breakpointsLandscape;
/// Override list of platforms to enable landscape mode on.
/// By default, only mobile platforms support landscape mode.
/// This override exists primarily to enable custom landscape vs portrait behavior
/// and future compatibility with Fuschia.
final List<ResponsiveTargetPlatform>? landscapePlatforms;
/// Calculate responsiveness based on the shortest
/// side of the screen, instead of the actual
/// landscape orientation.
///
/// This is useful for apps that want to avoid
/// scrolling screens and distribute their content
/// based on width/height regardless of orientation.
/// Size units can remain the same when the phone
/// is in landscape mode or portrait mode.
/// The developer needs only change a few widgets'
/// hard-coded size depending on the orientation.
/// The rest of the widgets maintain their size but
/// change the way they are displayed.
///
/// `useShortestSide` can be used in conjunction with
/// [breakpointsLandscape] for additional configurability.
/// Landscape breakpoints will activate when the
/// physical device is in landscape mode but base
/// calculations on the shortest side instead of
/// the actual landscape width.
final bool useShortestSide;
/// Print a visualization of the breakpoints.
final bool debugLog;
/// A wrapper widget that makes child widgets responsive.
const ResponsiveBreakpoints({
Key? key,
required this.child,
required this.breakpoints,
this.breakpointsLandscape,
this.landscapePlatforms,
this.useShortestSide = false,
this.debugLog = false,
}) : super(key: key);
@override
ResponsiveBreakpointsState createState() => ResponsiveBreakpointsState();
static Widget builder({
required Widget child,
required List<Breakpoint> breakpoints,
List<Breakpoint>? breakpointsLandscape,
List<ResponsiveTargetPlatform>? landscapePlatforms,
bool useShortestSide = false,
bool debugLog = false,
}) {
return ResponsiveBreakpoints(
breakpoints: breakpoints,
breakpointsLandscape: breakpointsLandscape,
landscapePlatforms: landscapePlatforms,
useShortestSide: useShortestSide,
debugLog: debugLog,
child: child,
);
}
static ResponsiveBreakpointsData of(BuildContext context) {
final InheritedResponsiveBreakpoints? data = context
.dependOnInheritedWidgetOfExactType<InheritedResponsiveBreakpoints>();
if (data != null) return data.data;
throw FlutterError.fromParts(
<DiagnosticsNode>[
ErrorSummary(
'ResponsiveBreakpoints.of() called with a context that does not contain ResponsiveBreakpoints.'),
ErrorDescription(
'No Responsive ancestor could be found starting from the context that was passed '
'to ResponsiveBreakpoints.of(). Place a ResponsiveBreakpoints at the root of the app '
'or supply a ResponsiveBreakpoints.builder.'),
context.describeElement('The context used was')
],
);
}
}
class ResponsiveBreakpointsState extends State<ResponsiveBreakpoints>
with WidgetsBindingObserver {
double windowWidth = 0;
double getWindowWidth() {
return MediaQuery.of(context).size.width;
}
double windowHeight = 0;
double getWindowHeight() {
return MediaQuery.of(context).size.height;
}
Breakpoint breakpoint = const Breakpoint(start: 0, end: 0);
List<Breakpoint> breakpoints = [];
/// Get screen width calculation.
double screenWidth = 0;
double getScreenWidth() {
double widthCalc = useShortestSide
? (windowWidth < windowHeight ? windowWidth : windowHeight)
: windowWidth;
return widthCalc;
}
/// Get screen height calculations.
double screenHeight = 0;
double getScreenHeight() {
double heightCalc = useShortestSide
? (windowWidth < windowHeight ? windowHeight : windowWidth)
: windowHeight;
return heightCalc;
}
Orientation get orientation => (windowWidth > windowHeight)
? Orientation.landscape
: Orientation.portrait;
static const List<ResponsiveTargetPlatform> _landscapePlatforms = [
ResponsiveTargetPlatform.iOS,
ResponsiveTargetPlatform.android,
ResponsiveTargetPlatform.fuchsia,
];
ResponsiveTargetPlatform? platform;
void setPlatform() {
platform = kIsWeb
? ResponsiveTargetPlatform.web
: Theme.of(context).platform.responsiveTargetPlatform;
}
bool get isLandscapePlatform =>
(widget.landscapePlatforms ?? _landscapePlatforms).contains(platform);
bool get isLandscape =>
orientation == Orientation.landscape && isLandscapePlatform;
bool get useShortestSide => widget.useShortestSide;
/// Calculate updated dimensions.
void setDimensions() {
windowWidth = getWindowWidth();
windowHeight = getWindowHeight();
screenWidth = getScreenWidth();
screenHeight = getScreenHeight();
breakpoint = breakpoints.firstWhereOrNull((element) =>
screenWidth >= element.start && screenWidth <= element.end) ??
const Breakpoint(start: 0, end: 0);
}
/// Get enabled breakpoints based on [orientation] and [platform].
List<Breakpoint> getActiveBreakpoints() {
// If the device is landscape enabled and the current orientation is landscape, use landscape breakpoints.
if (isLandscape) {
return widget.breakpointsLandscape ?? [];
}
return widget.breakpoints;
}
/// Set [breakpoints] and [breakpointSegments].
void setBreakpoints() {
// Optimization. Only update breakpoints if dimensions have changed.
if ((windowWidth != getWindowWidth()) ||
(windowHeight != getWindowHeight()) ||
(windowWidth == 0)) {
windowWidth = getWindowWidth();
windowHeight = getWindowHeight();
breakpoints.clear();
breakpoints.addAll(getActiveBreakpoints());
breakpoints.sort(ResponsiveUtils.breakpointComparator);
}
}
@override
void initState() {
super.initState();
// Log breakpoints to console.
if (widget.debugLog) {
// Add Portrait and Landscape annotations if landscape breakpoints are provided.
if (widget.breakpointsLandscape != null) {
debugPrint('**PORTRAIT**');
}
ResponsiveUtils.debugLogBreakpoints(widget.breakpoints);
// Print landscape breakpoints.
if (widget.breakpointsLandscape != null) {
debugPrint('**LANDSCAPE**');
ResponsiveUtils.debugLogBreakpoints(widget.breakpointsLandscape);
}
}
// Dimensions are only available after first frame paint.
WidgetsBinding.instance.addObserver(this);
WidgetsBinding.instance.addPostFrameCallback((_) {
// Breakpoints must be initialized before the first frame is drawn.
setBreakpoints();
// Directly updating dimensions is safe because frame callbacks
// in initState are guaranteed.
setDimensions();
setState(() {});
});
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeMetrics() {
super.didChangeMetrics();
// When physical dimensions change, update state.
// The required MediaQueryData is only available
// on the next frame for physical dimension changes.
WidgetsBinding.instance.addPostFrameCallback((_) {
// Widget could be destroyed by resize. Verify widget
// exists before updating dimensions.
if (mounted) {
setBreakpoints();
setDimensions();
setState(() {});
}
});
}
@override
void didUpdateWidget(ResponsiveBreakpoints oldWidget) {
super.didUpdateWidget(oldWidget);
// When [ResponsiveWrapper]'s constructor is
// used directly in the widget tree and a parent
// MediaQueryData changes, update state.
// The screen dimensions are passed immediately.
setBreakpoints();
setDimensions();
setState(() {});
}
@override
Widget build(BuildContext context) {
// Platform initialization requires context.
setPlatform();
return InheritedResponsiveBreakpoints(
data: ResponsiveBreakpointsData.fromResponsiveWrapper(this),
child: widget.child,
);
}
}
// Device Type Constants.
const String MOBILE = 'MOBILE';
const String TABLET = 'TABLET';
const String PHONE = 'PHONE';
const String DESKTOP = 'DESKTOP';
/// Responsive data about the current screen.
///
/// Resized and scaled values can be accessed
/// such as [ResponsiveBreakpointsData.scaledWidth].
@immutable
class ResponsiveBreakpointsData {
final double screenWidth;
final double screenHeight;
final Breakpoint breakpoint;
final List<Breakpoint> breakpoints;
final bool isMobile;
final bool isPhone;
final bool isTablet;
final bool isDesktop;
final Orientation orientation;
/// Creates responsive data with explicit values.
///
/// Alternatively, use [ResponsiveBreakpointsData.fromResponsiveWrapper]
/// to create data based on the [ResponsiveBreakpoints] state.
const ResponsiveBreakpointsData({
this.screenWidth = 0,
this.screenHeight = 0,
this.breakpoint = const Breakpoint(start: 0, end: 0),
this.breakpoints = const [],
this.isMobile = false,
this.isPhone = false,
this.isTablet = false,
this.isDesktop = false,
this.orientation = Orientation.portrait,
});
/// Creates data based on the [ResponsiveBreakpoints] state.
static ResponsiveBreakpointsData fromResponsiveWrapper(
ResponsiveBreakpointsState state) {
return ResponsiveBreakpointsData(
screenWidth: state.screenWidth,
screenHeight: state.screenHeight,
breakpoint: state.breakpoint,
breakpoints: state.breakpoints,
isMobile: state.breakpoint.name == MOBILE,
isPhone: state.breakpoint.name == PHONE,
isTablet: state.breakpoint.name == TABLET,
isDesktop: state.breakpoint.name == DESKTOP,
orientation: state.orientation,
);
}
@override
String toString() =>
'ResponsiveWrapperData(breakpoint: $breakpoint, breakpoints: ${breakpoints.asMap()}, isMobile: $isMobile, isPhone: $isPhone, isTablet: $isTablet, isDesktop: $isDesktop)';
/// Returns if the active breakpoint is [name].
bool equals(String name) => breakpoint.name == name;
/// Is the [screenWidth] larger than [name]?
/// Defaults to false if the [name] cannot be found.
bool largerThan(String name) =>
screenWidth >
(breakpoints.firstWhereOrNull((element) => element.name == name)?.end ??
double.infinity);
/// Is the [screenWidth] larger than or equal to [name]?
/// Defaults to false if the [name] cannot be found.
bool largerOrEqualTo(String name) =>
screenWidth >=
(breakpoints.firstWhereOrNull((element) => element.name == name)?.start ??
double.infinity);
/// Is the [screenWidth] smaller than the [name]?
/// Defaults to false if the [name] cannot be found.
bool smallerThan(String name) =>
screenWidth <
(breakpoints.firstWhereOrNull((element) => element.name == name)?.start ??
0);
/// Is the [screenWidth] smaller than or equal to the [name]?
/// Defaults to false if the [name] cannot be found.
bool smallerOrEqualTo(String name) =>
screenWidth <=
(breakpoints.firstWhereOrNull((element) => element.name == name)?.end ??
0);
/// Is the [screenWidth] smaller than or equal to the [name]?
/// Defaults to false if the [name] cannot be found.
bool between(String name, String name1) {
return (screenWidth >=
(breakpoints
.firstWhereOrNull((element) => element.name == name)
?.start ??
0) &&
screenWidth <=
(breakpoints
.firstWhereOrNull((element) => element.name == name1)
?.end ??
0));
}
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is ResponsiveBreakpointsData &&
runtimeType == other.runtimeType &&
screenWidth == other.screenWidth &&
screenHeight == other.screenHeight &&
breakpoint == other.breakpoint;
@override
int get hashCode =>
screenWidth.hashCode * screenHeight.hashCode * breakpoint.hashCode;
}
/// Creates an immutable widget that exposes [ResponsiveBreakpointsData]
/// to child widgets.
///
/// Access values such as the [ResponsiveBreakpointsData.scaledWidth]
/// property through [ResponsiveBreakpoints.of]
/// `ResponsiveWrapper.of(context).scaledWidth`.
///
/// Querying this widget with [ResponsiveBreakpoints.of]
/// creates a dependency that causes an automatic
/// rebuild whenever the [ResponsiveBreakpointsData]
/// changes.
///
/// If no [ResponsiveBreakpoints] is in scope then the
/// [MediaQuery.of] method will throw an exception,
/// unless the `nullOk` argument is set to true, in
/// which case it returns null.
@immutable
class InheritedResponsiveBreakpoints extends InheritedWidget {
final ResponsiveBreakpointsData data;
/// Creates a widget that provides [ResponsiveBreakpointsData] to its descendants.
///
/// The [data] and [child] arguments must not be null.
const InheritedResponsiveBreakpoints(
{Key? key, required this.data, required Widget child})
: super(key: key, child: child);
@override
bool updateShouldNotify(InheritedResponsiveBreakpoints oldWidget) =>
data != oldWidget.data;
}
|
79528e4f3f026d920c4ade84269406ea
|
{
"intermediate": 0.378984659910202,
"beginner": 0.392151802778244,
"expert": 0.22886350750923157
}
|
7,074
|
这个代码啥意思export default class LineChart extends Component<any> {
pieRefs: any;
myChart: any;
state = {
visible: false,
infoStatus: []
}
handleClick = () => {
this.setState((state: any) => ({
visible: !state.visible,
}));
}
closeModal = () => {
this.setState({
visible: false,
});
}
componentDidMount(): void {
this.loadChart(() => {
const Window = window as any;
this.myChart = Window.echarts.init(this.pieRefs);
// this.myChart.on('click', (params: any) => {
// // this.getResultList(params);
// });
this.drawCanvas(this.props);
// 监听表格自适应
window.addEventListener('resize', this.bindResize);
});
}
componentWillReceiveProps(nextProps: any): any {
if (JSON.stringify(this.props.data) !== JSON.stringify(nextProps.data)) {
setTimeout(() => this.drawCanvas(nextProps));
}
}
componentWillUnmount(): void {
window.removeEventListener('resize', this.bindResize);
}
drawCanvas = (props: any) => {
const { data, lineLegend, lineCategory } = this.props;
console.log(data);
// 转换雷达图为折线图
var series = [];
const option = {
title: {
text: ''
},
tooltip: {
trigger: 'item',
formatter: function (params) {
var index = params.dataIndex;
var name = params.seriesName;
var value = params.value;
var sameRatio = params.seriesIndex < data.length ? data[params.seriesIndex].sameRatio[index] : '';
var chainRatio = params.seriesIndex < data.length ? data[params.seriesIndex].chainRatio[index] : '';
var tooltipHtml = '<div style="background-color:#000; padding:10px; width:160px">';
tooltipHtml += '<div style="display: inline-block; margin-right: 16px;">' +
'<div style="color:#fff; font-weight:bold; font-size:16px">' + name + '</div>' +
'<div style="color:#fff; font-size:14px; margin-top:5px">当前值:' + value.toFixed(2) + '</div>' +
'<div style="color:#fff; font-size:14px; margin-top:5px">月环比:' + chainRatio + '</div>' +
'<div style="color:#fff; font-size:14px; margin-top:5px">年同比:' + sameRatio + '</div>' +
'</div>';
tooltipHtml += '</div>';
return tooltipHtml;
}
},
legend: {
data: lineLegend
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
toolbox: {
feature: {
saveAsImage: {}
}
},
xAxis: {
type: 'category',
data: lineCategory
},
yAxis: {
type: 'value'
},
series: series,
};
for (var i = 0; i < data.length; i++) {
series.push({
name: data[i].name,
type: 'line',
data: data[i].value,
});
}
if (!this.myChart) return '';
this.myChart.setOption(option);
}
bindResize = () => {
this.myChart.resize();
}
loadChart = (callBack: Function) => {
if ((window as any).echarts) {
if (callBack) {
callBack();
}
return;
}
const script = document.createElement('script');
script.src = 'https://s3plus.vip.sankuai.com/v1/mss_0f1209db61b048fa97009f13d1b4f911/camp-micro-ability-extension-flowchart/echars.js';
script.onload = () => {
if (callBack) {
callBack();
}
};
document.head.appendChild(script);
}
render(): JSX.Element {
return (
<>
<div
id="e-charts"
style={{ height: '100%', width: '100%' }}
// eslint-disable-next-line no-return-assign
ref={(refs: any) => this.pieRefs = refs}
/>
</>
);
}
}
|
dd24b97316513504609f0a205f07575b
|
{
"intermediate": 0.38766321539878845,
"beginner": 0.45195892453193665,
"expert": 0.1603778600692749
}
|
7,075
|
def generate_future_timesteps(data1, data2, data3, data4, num_timesteps):
# Use the last `num_timesteps` data points as input
max_length = max(len(data1), len(data2), len(data3), len(data4))
future_input = np.zeros((4, max_length, 1))
future_input[0, :len(data1), :] = np.array(data1).reshape(-1, 1)
future_input[1, :len(data2), :] = np.array(data2).reshape(-1, 1)
future_input[2, :len(data3), :] = np.array(data3).reshape(-1, 1)
future_input[3, :len(data4), :] = np.array(data4).reshape(-1, 1)
# Reshape the input data to match the model's input shape
future_input = future_input[:, :num_timesteps, :]
future_input = np.swapaxes(future_input, 0, 1)
return future_input
def create_dataset(dataset, look_back=1):
dataX, dataY = [], []
for i in range(len(dataset) - look_back - 1):
a = dataset[i:(i + look_back), 0]
dataX.append(a)
dataY.append(dataset[i + look_back, :])
return np.array(dataX), np.array(dataY)
def create_rnn_model(trainX, trainY, testX, testY, rnn_units, name='RNN Model'):
# Define the RNN model
model = Sequential()
model.add(SimpleRNN(rnn_units[0], activation='tanh', input_shape=(1, 1), return_sequences=True))
model.add(SimpleRNN(rnn_units[1], activation='tanh'))
model.add(Dense(rnn_units[2]))
model.add(Dense(4))
# Compile the model
model.compile(optimizer='adam', loss='mae')
# Train the model on the training data
history = model.fit(trainX, trainY, epochs=25, batch_size=16, verbose=1, validation_split=0.2)
# Evaluate the model on the testing data
loss = model.evaluate(testX, testY, batch_size=64)
print(f'{name} loss: {loss}')
return model
def create_lstm_model(trainX, trainY, testX, testY, lstm_units, name='LSTM Model'):
# Define the LSTM autoencoder model
model = Sequential()
model.add(LSTM(lstm_units[0], activation='relu', input_shape = (1, 1), return_sequences = True))
model.add(LSTM(lstm_units[1], activation='relu', return_sequences = True))
model.add(LSTM(lstm_units[2], activation='relu'))
model.add(Dense(lstm_units[3]))
model.add(Dense(4))
# Compile the model
model.compile(optimizer='adam', loss ='mae')
# Train the model on the training data
history = model.fit(trainX, trainY, epochs=25, batch_size=16, verbose=1, validation_split=0.2)
# Evaluate the model on the testing data
loss = model.evaluate(testX, testY, batch_size=64)
print(f'{name} loss: {loss}')
return model
def ensemble_models(data1, data2, data3, data4, future_timesteps):
min_length = min(len(data1), len(data2), len(data3), len(data4))
# Slice each array to the minimum length
data1 = data1[len(data1) - min_length:]
data2 = data2[len(data2) - min_length:]
data3 = data3[len(data3) - min_length:]
data4 = data4[len(data4) - min_length:]
# Pad the sequences with zeros so that they all have the same length
max_length = max(len(data1), len(data2), len(data3), len(data4))
all_data = np.zeros((4, max_length, 1))
for i, data in enumerate([data1, data2, data3, data4]):
all_data[i, :len(data), :] = np.array(data).reshape(-1, 1)
d = {'hum': data1, 'light': data2, 'temp': data3, 'mois': data4}
dataset = pandas.DataFrame(d)
dataset = dataset.values
dataset = dataset.astype("float32")
train_size = int(len(dataset) * 0.7)
test_size = len(dataset) - train_size
train, test = dataset[0:train_size, :], dataset[train_size:len(dataset), :]
trainX, trainY = create_dataset(train)
testX, testY = create_dataset(test)
trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
# Create the first LSTM model
lstm1 = create_lstm_model(trainX, trainY, testX, testY, lstm_units=[128, 64, 32, 64], name='LSTM Model 1')
# Create the second LSTM model with a different architecture
#lstm2 = create_lstm_model(trainX, trainY, testX, testY, lstm_units=[64, 32, 16, 32], name='LSTM Model 2')
rnn = create_rnn_model(trainX, trainY, testX, testY, rnn_units=[128, 64, 32, 64], name='RNN Model')
# Get predictions from both models
predictions1 = lstm1.predict(testX)
predictions2 = rnn.predict(testX)
# Combine the predictions using a weighted average
ensemble_weight_1 = 0.5
ensemble_weight_2 = 1.0 - ensemble_weight_1
ensemble_predictions = ensemble_weight_1 * predictions1 + ensemble_weight_2 * predictions2
# Evaluate the ensemble model’s performance
mae = np.mean(np.abs(ensemble_predictions - testY), axis=0)
print(f'Ensemble MAE: {mae}')
max_humidity = 100 # Set the maximum possible value for humidity
max_light = 100 # Set the maximum possible value for light
max_temperature = 50 # Set the maximum possible value for temperature
max_moisture = 100 # Set the maximum possible value for moisture
mae_humidity = np.mean(np.abs(ensemble_predictions[:, 0] - testY[:, 0]))
mae_light = np.mean(np.abs(ensemble_predictions[:, 1] - testY[:, 1]))
mae_temperature = np.mean(np.abs(ensemble_predictions[:, 2] - testY[:, 2]))
mae_moisture = np.mean(np.abs(ensemble_predictions[:, 3] - testY[:, 3]))
percentage_error_humidity = (mae_humidity / max_humidity) * 100
percentage_error_light = (mae_light / max_light) * 100
percentage_error_temperature = (mae_temperature / max_temperature) * 100
percentage_error_moisture = (mae_moisture / max_moisture) * 100
print(f'Humidity Percentage Error: {round(percentage_error_humidity, 2)}%')
print(f'Light Percentage Error: {round(percentage_error_light, 2)}%')
print(f'Temperature Percentage Error: {round(percentage_error_temperature, 2)}%')
print(f'Moisture Percentage Error: {round(percentage_error_moisture, 2)}%')
print(f'Mean error: {round(np.mean([percentage_error_light, percentage_error_humidity, percentage_error_moisture, percentage_error_temperature]), 2)}%')
# Reshape the data for future predictions
future_input = generate_future_timesteps(data1, data2, data3, data4, 500)
# Get predictions for future timesteps
future_predictions1 = lstm1.predict(future_input)
future_predictions2 = rnn.predict(future_input)
# Combine the predictions using a weighted average
future_ensemble_predictions = (ensemble_weight_1 * future_predictions1 + ensemble_weight_2 * future_predictions2)
# Reshape array2 to match the first dimension of array1
array2_reshaped = np.repeat(future_ensemble_predictions, ensemble_predictions.shape[0] // future_ensemble_predictions.shape[0], axis=0)
# Concatenate the reshaped arrays along axis 0
future_ensemble_predictions = np.concatenate((ensemble_predictions, array2_reshaped), axis=0)
# (Optional) Visualization code
plt.figure(figsize=(12, 6))
#plt.plot(ensemble_predictions[:, 0], label='Humidity Predictions', linestyle ='-')
#plt.plot(ensemble_predictions[:, 1], label='Light Predictions', linestyle ='-')
#plt.plot(ensemble_predictions[:, 2], label='Temperature Predictions', linestyle ='-')
#plt.plot(ensemble_predictions[:, 3], label='Moisture Predictions', linestyle ='-')
plt.plot(future_ensemble_predictions[:, 0], label='Humidity Predictions', linestyle='-')
plt.plot(future_ensemble_predictions[:, 1], label='Light Predictions', linestyle='-')
plt.plot(future_ensemble_predictions[:, 2], label='Temperature Predictions', linestyle='-')
plt.plot(future_ensemble_predictions[:, 3], label='Moisture Predictions', linestyle='-')
plt.plot(testY[:, 0], label='Humidity Real', alpha=0.7, linestyle='dashed')
plt.plot(testY[:, 1], label='Light Real', alpha=0.7, linestyle='dashed')
plt.plot(testY[:, 2], label='Temperature Real', alpha=0.7, linestyle='dashed')
plt.plot(testY[:, 3], label='Moisture Real', alpha=0.7, linestyle='dashed')
plt.xlabel('Time Steps')
plt.ylabel('Sensor Values')
plt.legend()
plt.show()
return lstm1, rnn
What is wrong with my code the future timesteps prediction is not working at all, giving me weird results and also not the number of future timesteps that I specify
|
37c4e6aa636e7c407f3c30795671b1e8
|
{
"intermediate": 0.258230984210968,
"beginner": 0.4766334593296051,
"expert": 0.2651355564594269
}
|
7,076
|
select a record that is a description of an item,show the first 25 characters
|
92168e7879810123478c7b7872f5d493
|
{
"intermediate": 0.4289588928222656,
"beginner": 0.22422181069850922,
"expert": 0.34681934118270874
}
|
7,077
|
Suppose you are senior researcher on image processing, you have written at least 100 papers on your implementation of image resolution upscaler, can you write an article on your recent work, with the code ?
|
6cc9367964be95cb0c9226ae076a833b
|
{
"intermediate": 0.1879022717475891,
"beginner": 0.14479117095470428,
"expert": 0.6673065423965454
}
|
7,078
|
in python how to check if csv file has header
|
ee576ecf4f253b03e762cdf04a7a5476
|
{
"intermediate": 0.48878946900367737,
"beginner": 0.22110910713672638,
"expert": 0.29010140895843506
}
|
7,079
|
how to output a format string.assuming we have a table toys,it has column id,name,description,output id-name-description
|
c1b3f6d64c61d2a47676f89303f3ce84
|
{
"intermediate": 0.4492260813713074,
"beginner": 0.27341917157173157,
"expert": 0.27735471725463867
}
|
7,080
|
can you improve this code export const httpClient = axios.create({
baseURL: BASE_URL,
headers: {
"Content-Type": "application/json",
},
});
const get = async (url: string) => {
const response = await httpClient.get(url);
return response.data;
};
const post = async (url: string, data: any) => {
const response = await httpClient.post(url, data);
return response.data;
};
export default {
get,
post,
};
|
dedf5b85b4a1ca00adbe5524cbd96677
|
{
"intermediate": 0.5034072995185852,
"beginner": 0.3182292878627777,
"expert": 0.17836342751979828
}
|
7,081
|
select the top 5 most expensive toys based on price from the “toys” table in sql server
|
f2e6dcbb82840227059b09e30d9a9740
|
{
"intermediate": 0.3357637822628021,
"beginner": 0.3323831856250763,
"expert": 0.33185306191444397
}
|
7,082
|
My language is python. Can you help me finish some code
|
0d522f9934bfb7c879fa0abb9f016ba8
|
{
"intermediate": 0.2745479643344879,
"beginner": 0.43606290221214294,
"expert": 0.28938916325569153
}
|
7,083
|
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.metrics import dp
import JsonUtl as jsonutil
import cv2
class MainScreen(Screen):
ServerListVar = jsonutil.OpenJsontoArray()
BtnId = 0
DelBtnId = 0
def __init__(self, **kw):
super().__init__(**kw)
print(self.ServerListVar)
print(len(self.ServerListVar))
for i in range (0,len(self.ServerListVar)):
self.CreateButtons()
def Clicked(self,widget):
Adress = self.ids.StreamAdress
Login = self.ids.StreamLogin
Password = self.ids.StreamPassword
if Password.text == "" and Login.text == "":
self.ServerListVar.append("rtsp://" + Adress.text.strip())
else:
self.ServerListVar.append("rtsp://" + Login.text.strip() + ":" + Password.text.strip() + "@" + Adress.text.strip())
jsonutil.SaveArraytoJson(self.ServerListVar)
self.CreateButtons()
def CamSelectButtonPressed(self,x):
print("selectu " + str(x))
def CamDeleteButtonPressed(self,x):
del self.ServerListVar[x - 1]
self.ids.CamSelectBoxLayout.clear_widgets()
jsonutil.SaveArraytoJson(self.ServerListVar)
self.ServerListVar = jsonutil.OpenJsontoArray()
self.BtnId = 0
self.DelBtnId = 0
for i in range (0,len(self.ServerListVar)):
self.CreateButtons()
def CreateButtons(self):
b = Button(size_hint = (0.2, None), height = dp(100))
b2 = Button(size_hint = (0.05, None), height = dp(100), background_color = (1,0,0,1))
b.bind(on_press=lambda instance, button_id=self.BtnId: self.CamSelectButtonPressed(button_id))
self.BtnId = self.BtnId + 1
self.ids.CamSelectBoxLayout.add_widget(b)
b2.bind(on_press=lambda instance, button_id=self.DelBtnId: self.CamDeleteButtonPressed(button_id))
self.DelBtnId = self.DelBtnId + 1
self.ids.CamSelectBoxLayout.add_widget(b2)
class StreamView(Screen):
pass
class ScreenMan(ScreenManager):
pass
class IPCAMApp(App):
def build(self):
sm = ScreenMan()
sm.add_widget(MainScreen(name="Main"))
sm.add_widget(StreamView(name="Stream"))
sm.current = "Stream"
return StreamView()
IPCAMApp().run()
|
55f0cf0731299d6a96a63e738b0204e0
|
{
"intermediate": 0.28977248072624207,
"beginner": 0.48535290360450745,
"expert": 0.2248746007680893
}
|
7,084
|
A small Deep Learning project about Depth Estimation.
|
2e3af55927cfef665773f7bb31ef4b80
|
{
"intermediate": 0.03886689245700836,
"beginner": 0.03945860266685486,
"expert": 0.9216744899749756
}
|
7,085
|
write me a react code that on button click adds string to array of strings using usestate
|
5f36f126aede43c70bebef57ff395a7c
|
{
"intermediate": 0.5030197501182556,
"beginner": 0.18378183245658875,
"expert": 0.3131984770298004
}
|
7,086
|
show me useeffect example with dependency array
|
67c956e893ab4e6aa8daaef481d86b73
|
{
"intermediate": 0.4632004499435425,
"beginner": 0.28596827387809753,
"expert": 0.2508312463760376
}
|
7,087
|
what difference response_model and class_response in fastapi
|
fecd4080e727621cab697da379d7b848
|
{
"intermediate": 0.3567630350589752,
"beginner": 0.16259795427322388,
"expert": 0.4806390106678009
}
|
7,088
|
remake this page
<html>
<body>
<h1>
Hello
</h1>
<p>This is my.<b>PTifou</b></p>
<img src="https://cdn.glitch.global/ee196111-c29a-485a-953c-55f9c53da442/ptifou.png?v=1684489841642"><p>
pitifou!
</p>
<iframe src="Planny.html">
</iframe>
</body>
</html>
|
e34f46c85cd1ea956893a2d1d5ade92f
|
{
"intermediate": 0.40561389923095703,
"beginner": 0.2982693016529083,
"expert": 0.29611676931381226
}
|
7,089
|
FHIR orderDetail
|
689a1a1600bf96dc7c2384542b1507af
|
{
"intermediate": 0.36106517910957336,
"beginner": 0.25708872079849243,
"expert": 0.3818461298942566
}
|
7,090
|
kotlin add 10 items in list
|
614bf7c639eaadbc1904922fe862c86b
|
{
"intermediate": 0.4751327633857727,
"beginner": 0.3239334225654602,
"expert": 0.2009338140487671
}
|
7,091
|
Generate a code for a game thingy. Adds 10 points if you proceed onto a + tile. If it's not then - is the -10 points.
|
62884162b06d7e3784ab0fcc746c58fd
|
{
"intermediate": 0.3420295715332031,
"beginner": 0.33628973364830017,
"expert": 0.32168078422546387
}
|
7,092
|
cmake set global property
|
5f056208308cc0b1cad350d3c8e45069
|
{
"intermediate": 0.3990465998649597,
"beginner": 0.2958936393260956,
"expert": 0.3050597310066223
}
|
7,093
|
Generate a page sheet in C, when you type a thing and press enter, it adds a inptu to the page sheet.
|
a6a945442bc9b62a35ae4d3a8917e186
|
{
"intermediate": 0.3434849679470062,
"beginner": 0.260618656873703,
"expert": 0.3958963453769684
}
|
7,094
|
i am running mongodb at port 27017 of localhost and I have created a user myTester in a database called test, now I want to connect to the database using nodejs/expressjs , what would be the database link?
|
4baee1f5325126f33a0a08954d6ad579
|
{
"intermediate": 0.7808226346969604,
"beginner": 0.07709640264511108,
"expert": 0.14208097755908966
}
|
7,095
|
i am running mongodb at port 27017 of localhost and I have created a user myTester in a database called test, now I want to connect to the database using nodejs/expressjs , what would be the database link?
|
339a2b6757ef453f47c74ae9cad77bd5
|
{
"intermediate": 0.7808226346969604,
"beginner": 0.07709640264511108,
"expert": 0.14208097755908966
}
|
7,096
|
In the C# code, generate a page sheet variable, when you type a thing and press enter, it adds a input to the page sheet.
|
6b9f43ff541b112c9391b3681ac4d7df
|
{
"intermediate": 0.32568541169166565,
"beginner": 0.39111819863319397,
"expert": 0.283196359872818
}
|
7,097
|
Java code, generate a page sheet variable, when you type a thing and press enter, it adds a input to the page sheet.
|
217c0a293155a306f1c3e20603491d4f
|
{
"intermediate": 0.2975914180278778,
"beginner": 0.4856373965740204,
"expert": 0.2167711853981018
}
|
7,098
|
Make this into a real code
print("What.")
print("Is.")
print("This.")
print("You have to escape. Type this thingy.")
The rest is unfinished.
|
ef32688c681fd9b51ab426b4e76a70dd
|
{
"intermediate": 0.288700670003891,
"beginner": 0.4327855110168457,
"expert": 0.2785137891769409
}
|
7,099
|
Create a typeorm database seed function for the following json {
"masculineEndings": [
"age",
"aire",
"isme",
"ment",
"oir",
"sme",
"é"
],
"feminineEndings": [
"ade",
"ance",
"ence",
"ette",
"ie",
"ine",
"ion",
"ique",
"isse",
"ité",
"lle",
"ure"
]
}
for postgre database
|
57df07e7d5937dc98d7cfc70da39e4b6
|
{
"intermediate": 0.47512856125831604,
"beginner": 0.28179416060447693,
"expert": 0.2430773228406906
}
|
7,100
|
from kivy.app import App
from kivy.uix.screenmanager import Screen , ScreenManager
from kivy.uix.video import Video
import cv2
class StreamScreen(Video):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.capture = cv2.VideoCapture('rtsp://192.168.1.202:554/ch01.264')
self.capture.set(cv2.CAP_PROP_BUFFERSIZE, 1)
self.fps = int(self.capture.get(cv2.CAP_PROP_FPS))
self.update()
def update(self, *args):
ret, frame = self.capture.read()
if ret:
self.texture.blit_buffer(frame.tobytes(), colorfmt='bgr')
return True
class MainScreen(Screen):
pass
class StreamView(Screen):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.stream_screen = StreamScreen()
self.add_widget(self.stream_screen)
class ScreenMan(ScreenManager):
pass
class MyApp(App):
def build(self):
sm = ScreenMan()
sm.add_widget(MainScreen(name="Main"))
sm.add_widget(StreamView(name="Stream"))
sm.current = "Stream"
return sm
if __name__ == '__main__':
MyApp().run()
|
cceb0dc4e28aca23b6968f298f0cca87
|
{
"intermediate": 0.38372310996055603,
"beginner": 0.3358686566352844,
"expert": 0.28040820360183716
}
|
7,101
|
Доделай профиль а также сделай его вызов в четвертом пункте нижнего меню , помни что данные профиля должны обновляться после каждой авторизации, а также для каждого пункта профиля где должны быть все данные о пользователе , должна быть возможность изменить эти данные (все это должно сохраняться после перезагрузки приложения) :package com.example.myapp_2.Data.register;
public class LoginFragment extends Fragment {
private EditText editTextEmail, editTextPassword;
private Button buttonLogin;
private UserDAO userDAO;
public LoginFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
userDAO = new UserDAO(getActivity());
userDAO.open();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.login, container, false);
getActivity().findViewById(R.id.bottomNavigationView).setVisibility(View.GONE);
editTextEmail = view.findViewById(R.id.editTextEmail);
editTextPassword = view.findViewById(R.id.editTextPassword);
buttonLogin = view.findViewById(R.id.buttonLogin);
buttonLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = editTextEmail.getText().toString();
String password = editTextPassword.getText().toString();
if (userDAO.login(email, password)) {
Toast.makeText(getActivity(), “Login successful”, Toast.LENGTH_SHORT).show();
// переход на другой фрагмент
FragmentTransaction transaction = requireActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_container, new FirstFragment());
transaction.addToBackStack(null);
transaction.commit();
} else {
Toast.makeText(getActivity(), “Invalid email or password”, Toast.LENGTH_SHORT).show();
}
}
});
Button buttonReturn = view.findViewById(R.id.buttonReturn);
buttonReturn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentTransaction transaction = requireActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_container, new RegistrationFragment());
transaction.addToBackStack(null);
transaction.commit();
}
});
return view;
}
@Override
public void onDestroy() {
super.onDestroy();
userDAO.close();
}
}
package com.example.myapp_2.Data.register;
i
import java.util.List;
public class RegistrationFragment extends Fragment {
private EditText editTextName, editTextEmail, editTextPassword;
private Button buttonRegister_1;
private UserDAO userDAO;
public RegistrationFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
userDAO = new UserDAO(getActivity());
userDAO.open();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.refister, container, false);
getActivity().findViewById(R.id.bottomNavigationView).setVisibility(View.GONE);
editTextName = view.findViewById(R.id.editTextName);
editTextEmail = view.findViewById(R.id.editTextEmail);
editTextPassword = view.findViewById(R.id.editTextPassword);
buttonRegister_1 = view.findViewById(R.id.buttonRegister_1);
buttonRegister_1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = editTextName.getText().toString();
String email = editTextEmail.getText().toString();
String password = editTextPassword.getText().toString();
long rowID = userDAO.register(name, email, password);
if (rowID > 0) {
Toast.makeText(getActivity(), “Registration successful”, Toast.LENGTH_SHORT).show();
// вывод всех пользователей в лог
List<User> users = userDAO.getAllUsers();
Log.d(“UserDatabase”, “All users:”);
for (User user : users) {
Log.d(“UserDatabase”, user.toString());
}
getFragmentManager().popBackStack();
FragmentTransaction transaction = requireActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_container, new FirstFragment());
transaction.addToBackStack(null);
transaction.commit();
} else if (rowID == -1) {
Toast.makeText(getActivity(), “Invalid email”, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), “Registration failed”, Toast.LENGTH_SHORT).show();
}
}
});
Button buttonLogin_1 = view.findViewById(R.id.buttonLogin_1);
buttonLogin_1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentTransaction transaction = requireActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_container, new LoginFragment());
transaction.addToBackStack(null);
transaction.commit();
}
});
Button buttonExit = view.findViewById(R.id.buttonExit);
buttonExit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getFragmentManager().popBackStack();
FragmentTransaction transaction = requireActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_container, new FirstFragment());
transaction.addToBackStack(null);
transaction.commit();
}
});
return view;
}
@Override
public void onDestroy() {
super.onDestroy();
userDAO.close();
}
}
package com.example.myapp_2.Data.register;
public class UserDAO {
private SQLiteDatabase database;
private UserDatabaseHelper dbHelper;
public UserDAO(Context context) {
dbHelper = new UserDatabaseHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public long register(String name, String email, String password) {
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
return -1; // email не соответствует формату
}
Cursor cursor = database.query(UserDatabaseHelper.TABLE_USERS,
new String[]{UserDatabaseHelper.COLUMN_EMAIL},
UserDatabaseHelper.COLUMN_EMAIL + " = ?“,
new String[]{email}, null, null, null, null);
if (cursor != null && cursor.getCount() > 0) { // если уже есть пользователь с такой почтой
cursor.close();
return -2;
}
ContentValues values = new ContentValues();
values.put(UserDatabaseHelper.COLUMN_NAME, name);
values.put(UserDatabaseHelper.COLUMN_EMAIL, email);
values.put(UserDatabaseHelper.COLUMN_PASSWORD, password);
return database.insert(UserDatabaseHelper.TABLE_USERS, null, values);
}
public boolean login(String email, String password) {
Cursor cursor = database.query(UserDatabaseHelper.TABLE_USERS,
new String[]{UserDatabaseHelper.COLUMN_EMAIL, UserDatabaseHelper.COLUMN_PASSWORD},
UserDatabaseHelper.COLUMN_EMAIL + " = ? AND " + UserDatabaseHelper.COLUMN_PASSWORD + " = ?”,
new String[]{email, password}, null, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
cursor.close();
return true;
} else {
return false;
}
}
@SuppressLint(“Range”)
public List<User> getAllUsers() {
List<User> users = new ArrayList<>();
Cursor cursor = database.query(UserDatabaseHelper.TABLE_USERS,
new String[]{UserDatabaseHelper.COLUMN_ID, UserDatabaseHelper.COLUMN_NAME,
UserDatabaseHelper.COLUMN_EMAIL, UserDatabaseHelper.COLUMN_PASSWORD},
null, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
do {
User user = new User();
user.setId(cursor.getInt(cursor.getColumnIndex(UserDatabaseHelper.COLUMN_ID)));
user.setName(cursor.getString(cursor.getColumnIndex(UserDatabaseHelper.COLUMN_NAME)));
user.setEmail(cursor.getString(cursor.getColumnIndex(UserDatabaseHelper.COLUMN_EMAIL)));
user.setPassword(cursor.getString(cursor.getColumnIndex(UserDatabaseHelper.COLUMN_PASSWORD)));
users.add(user);
} while (cursor.moveToNext());
cursor.close();
}
return users;
}
public User getUserById(int id) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.query(UserDatabaseHelper.TABLE_USERS,
new String[]{UserDatabaseHelper.COLUMN_ID, UserDatabaseHelper.COLUMN_NAME, UserDatabaseHelper.COLUMN_EMAIL, UserDatabaseHelper.COLUMN_PASSWORD},
UserDatabaseHelper.COLUMN_ID + “= ?”, new String[]{String.valueOf(id)},
null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
@SuppressLint(“Range”) User user = new User(cursor.getInt(cursor.getColumnIndex(UserDatabaseHelper.COLUMN_ID)),
cursor.getString(cursor.getColumnIndex(UserDatabaseHelper.COLUMN_NAME)),
cursor.getString(cursor.getColumnIndex(UserDatabaseHelper.COLUMN_EMAIL)),
cursor.getString(cursor.getColumnIndex(UserDatabaseHelper.COLUMN_PASSWORD)));
cursor.close();
return user;
}
public void updateUser(User user) {
ContentValues values = new ContentValues();
values.put(UserDatabaseHelper.COLUMN_NAME, user.getName());
values.put(UserDatabaseHelper.COLUMN_EMAIL, user.getEmail());
values.put(UserDatabaseHelper.COLUMN_PASSWORD, user.getPassword());
database.update(UserDatabaseHelper.TABLE_USERS, values,
UserDatabaseHelper.COLUMN_ID + " = ?“,
new String[]{String.valueOf(user.getId())});
}
}
package com.example.myapp_2.Data.register;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class UserDatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = “UserDatabase”;
public static final String TABLE_USERS = “users”;
public static final String COLUMN_ID = “_id”;
public static final String COLUMN_NAME = “name”;
public static final String COLUMN_EMAIL = “email”;
public static final String COLUMN_PASSWORD = “password”;
public UserDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_USERS_TABLE = “CREATE TABLE " + TABLE_USERS + “(”
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,”
+ COLUMN_NAME + " TEXT,”
+ COLUMN_EMAIL + " TEXT,“
+ COLUMN_PASSWORD + " TEXT”
+ “)”;
db.execSQL(CREATE_USERS_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
onCreate(db);
}
}package com.example.myapp_2.UI.view.activities;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private NoteViewModel noteViewModel;
private BroadcastReceiver broadcastReceiver;
static boolean isRegister = false;
Button button1;
Button button3;
// private FirstFragment firstFragment = new FirstFragment();
ActivityMainBinding binding;
private Button btn_fragment1,btn_fragment2,btn_fragment3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
replaceFragment(new FirstFragment());
binding.bottomNavigationView.setOnItemSelectedListener(item -> {
switch(item.getItemId()){
case R.id.home:
replaceFragment(new FirstFragment());
break;
case R.id.profile:
replaceFragment(new SecondFragment());
break;
case R.id.settings:
replaceFragment(new ThirdFragment());
break;
case R.id.menu_profile:
replaceFragment(new ProfileFragment());
break;
}
return true;
});
getSupportFragmentManager().beginTransaction().replace(R.id.nav_container, new FirstFragment()).addToBackStack(null).commit();
if (isRegister) {
binding.bottomNavigationView.setVisibility(View.GONE);
} else {
binding.bottomNavigationView.setVisibility(View.VISIBLE);
}
}
private void registerBroadcastReceiver() {
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Получение сообщения
String action = intent.getAction();
if(action.equals(“com.example.myapplication_2.SEND_MESSAGE”)) {
String message = intent.getStringExtra(“MESSAGE”);
// Вывод сообщения в лог
Log.d(“MyApp2”, "Received message: " + message);
}
}
};
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(“com.example.myapplication_2.SEND_MESSAGE”);
registerReceiver(broadcastReceiver, intentFilter);
}
@Override
public void onClick(View view) {//2 способ
}
@Override
protected void onDestroy() {
super.onDestroy();
// Удаление приемника
unregisterReceiver(broadcastReceiver);
}
private void replaceFragment(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.nav_container,fragment);
String A = “HELLO”;
Bundle bundle = new Bundle();
bundle.putInt(“hello world”, 4344);
fragment.setArguments(bundle);
fragmentTransaction.commit();
}
// вызов фрагмента регистрации с передачей кода запроса
public void startRegistration() {
isRegister = true;
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.nav_container, new RegistrationFragment()).addToBackStack(null).commit();
}
// обработка полученного результата (кода запроса)
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
isRegister = true; // установка значения переменной isRegister в true
}
}
}
package com.example.myapp_2.Data.register;
i
import com.example.myapp_2.R;
public class ProfileFragment extends Fragment {
private UserDAO userDAO;
private int userId = 1;
private User user;
private EditText editTextName, editTextEmail, editTextPassword;
private Button buttonUpdate;
public ProfileFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
userDAO = new UserDAO(getActivity());
userDAO.open();
// получение текущего пользователя из базы данных
user = userDAO.getUserById(userId);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile, container, false);
getActivity().findViewById(R.id.bottomNavigationView).setVisibility(View.VISIBLE);
// отображение имени текущего пользователя
TextView textViewName = view.findViewById(R.id.textViewName);
textViewName.setText(user.getName());
editTextName = view.findViewById(R.id.editTextName);
editTextEmail = view.findViewById(R.id.editTextEmail);
editTextPassword = view.findViewById(R.id.editTextPassword);
// отображение данных текущего пользователя в editText
editTextName.setText(user.getName());
editTextEmail.setText(user.getEmail());
editTextPassword.setText(user.getPassword());
buttonUpdate = view.findViewById(R.id.buttonUpdate);
buttonUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updateUser();
}
});
return view;
}
// метод обновления данных пользователя
private void updateUser() {
String name = editTextName.getText().toString();
String email = editTextEmail.getText().toString();
String password = editTextPassword.getText().toString();
// обновление данных пользователя в базе данных
user.setName(name);
user.setEmail(email);
user.setPassword(password);
userDAO.updateUser(user);
Toast.makeText(getActivity(), “User updated”, Toast.LENGTH_SHORT).show();
}
@Override
public void onDestroy() {
super.onDestroy();
userDAO.close();
}
}
продолжай
Ниже приведены изменения в классе MainActivity для вызова фрагмента профиля из нижнего меню, а также для обработки возвращаемых значений:
package com.example.myapp_2.UI.view.activities;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private NoteViewModel noteViewModel;
private BroadcastReceiver broadcastReceiver;
static boolean isRegister = false;
Button button1;
Button button3;
// private FirstFragment firstFragment = new FirstFragment();
ActivityMainBinding binding;
private Button btn_fragment1,btn_fragment2,btn_fragment3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
replaceFragment(new FirstFragment());
binding.bottomNavigationView.setOnItemSelectedListener(item -> {
switch(item.getItemId()){
case R.id.home:
replaceFragment(new FirstFragment());
break;
case R.id.profile:
replaceFragment(new SecondFragment());
break;
case R.id.settings:
replaceFragment(new ThirdFragment());
break;
case R.id.menu_profile:
replaceFragment(new ProfileFragment());
break;
}
return true;
});
getSupportFragmentManager().beginTransaction().replace(R.id.nav_container, new FirstFragment()).addToBackStack(null).commit();
if (isRegister) {
binding.bottomNavigationView.setVisibility(View.GONE);
} else {
binding.bottomNavigationView.setVisibility(View.VISIBLE);
}
// получение данных пользователя при каждой авторизации
if (getIntent().getExtras() != null) {
if (getIntent().getExtras().containsKey(“user_id”)) {
int userId = getIntent().getExtras().getInt(“user_id”);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_container, new ProfileFragment());
transaction.addToBackStack(null);
transaction.commit();
}
}
}
private void register
BroadcastReceiver() {
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Получение сообщения
String action = intent.getAction();
if(action.equals(“com.example.myapplication_2.SEND_MESSAGE”)) {
String message = intent.getStringExtra(“MESSAGE”);
// Вывод сообщения в лог
Log.d(“MyApp2”, "Received message: " + message);
}
}
};
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(“com.example.myapplication_2.SEND_MESSAGE”);
registerReceiver(broadcastReceiver, intentFilter);
}
@Override
public void onClick(View view) {//2 способ
}
@Override
protected void onDestroy() {
super.onDestroy();
// Удаление приемника
unregisterReceiver(broadcastReceiver);
}
private void replaceFragment(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.nav_container,fragment);
String A = “HELLO”;
Bundle bundle = new Bundle();
bundle.putInt(“hello world”, 4344);
fragment.setArguments(bundle);
fragmentTransaction.commit();
}
// вызов фрагмента регистрации с передачей кода запроса
public void startRegistration() {
isRegister = true;
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.nav_container, new RegistrationFragment()).addToBackStack(null).commit();
}
// обработка полученного результата (кода запроса)
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
isRegister = true; // установка значения переменной
|
43e281de237897a412408a6037ababbf
|
{
"intermediate": 0.3385840058326721,
"beginner": 0.4393588900566101,
"expert": 0.22205710411071777
}
|
7,102
|
Rewrite this
This code has been improved through the use of more descriptive variable names and better error handling. The code prompts the user to input an escape code and offers the option to check and update the variable or restore it to a previous backup value. The “check_variable” function verifies and updates the variable with user input, while the “restore_backup” function allows the user to revert the variable to a previous state. The program continuously prompts the user to choose between checking/updating the variable or restoring it, until the user chooses to exit.
|
50e1812d797eba2e9ea7b36df2e65bb9
|
{
"intermediate": 0.3230525851249695,
"beginner": 0.4593483507633209,
"expert": 0.2175990492105484
}
|
7,103
|
Es wird nur ein Overflow in der Breite erzeugt weil das Logo zu nah an den Copyright kommt. Es muss früher von einer Row in die Column gewechselt werden. Wo und wie mache ich das? Und die volle Breite soll wie bei Tablet und Desktop beibehalten werden.
import ‘package:flutter/foundation.dart’;
import ‘package:flutter/gestures.dart’;
import ‘package:flutter/material.dart’;
import ‘package:flutter_gen/gen_l10n/patient_app_localizations.dart’;
import ‘package:patient_app/terms_and_conditions_config.dart’;
import ‘package:patient_app/settings.dart’ show AppSettingsProvider;
import ‘package:patient_app/theme/patient_app_colors.dart’;
import ‘package:patient_app/theme/patient_app_theme.dart’ as theme;
import ‘package:patient_app/tools/legal_dialog_provider.dart’;
import ‘package:patient_app/widgets/footer/language_selector.dart’;
import ‘package:provider/provider.dart’;
import ‘package:responsive_framework/responsive_framework.dart’;
class Footer extends StatelessWidget {
const Footer({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final responsive = ResponsiveBreakpoints.of(context);
if (kIsWeb) {
return Container(
padding: theme.footerEdgeInsets,
color: AppColors.grey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(height: theme.smallSpacing),
ResponsiveRowColumn(
layout: responsive.smallerThan(DESKTOP)
? ResponsiveRowColumnType.COLUMN
: ResponsiveRowColumnType.ROW,
columnCrossAxisAlignment: CrossAxisAlignment.start,
children: [
const ResponsiveRowColumnItem(
child: LanguageSelector(),
),
ResponsiveRowColumnItem(
child: responsive.smallerThan(DESKTOP)
? const SizedBox(height: theme.mediumSpacing)
: const SizedBox(width: theme.mediumSpacing),
),
ResponsiveRowColumnItem(
child: _buildConditionPolicyDisclaimer(context),
),
],
),
const SizedBox(height: theme.largeSpacing),
ResponsiveRowColumn(
columnVerticalDirection: VerticalDirection.up,
layout: responsive.isMobile
? ResponsiveRowColumnType.COLUMN
: ResponsiveRowColumnType.ROW,
columnMainAxisAlignment: MainAxisAlignment.start,
columnCrossAxisAlignment: CrossAxisAlignment.start,
children: [
ResponsiveRowColumnItem(
child: _buildCopyright(context),
),
ResponsiveRowColumnItem(
child: responsive.smallerThan(TABLET)
? const SizedBox(height: theme.mediumSpacing)
: const Spacer(),
),
ResponsiveRowColumnItem(
child: _buildLogo(),
),
]),
],
),
);
} else {
return const SizedBox();
}
}
Widget _buildCopyright(BuildContext context) {
return FittedBox(
child: Text(
AppLocalizations.of(context)!.copyright(DateTime.now().year),
style: const TextStyle(
fontSize: theme.minimumFontSize,
fontWeight: FontWeight.bold,
color: AppColors.blackOpacity130,
),
),
);
}
Widget _buildLogo() {
return Image.asset(
AppSettingsProvider().assets.poweredByOpascaLogoImage,
width: theme.poweredByOpascaWidthModifier,
);
}
Widget _buildConditionPolicyDisclaimer(BuildContext context) {
final responsive = ResponsiveBreakpoints.of(context);
final showTermsAndConditions = context.select(
(TermsAndConditionsConfig termsAndConditionsConfig) =>
termsAndConditionsConfig.showTermsAndConditions);
return ResponsiveRowColumn(
layout: responsive.isMobile
? ResponsiveRowColumnType.COLUMN
: ResponsiveRowColumnType.ROW,
columnMainAxisAlignment: MainAxisAlignment.start,
columnCrossAxisAlignment: CrossAxisAlignment.start,
children: [
if (showTermsAndConditions)
ResponsiveRowColumnItem(
child: RichText(
text: TextSpan(
text: AppLocalizations.of(context)!.legal_conditionsOfUse,
style: theme.footerTextStyle,
recognizer: TapGestureRecognizer()
…onTap = () {
LegalDialogProvider.showTermsAndConditionsDialog(context);
}),
)),
if (showTermsAndConditions)
ResponsiveRowColumnItem(
child: responsive.smallerThan(TABLET)
? const SizedBox(height: theme.extraSmallSpacing)
: const SizedBox(width: theme.mediumSpacing),
),
ResponsiveRowColumnItem(
child: RichText(
text: TextSpan(
text: AppLocalizations.of(context)!.legal_privacyNotice,
style: theme.footerTextStyle,
recognizer: TapGestureRecognizer()
…onTap = () {
LegalDialogProvider.showPrivatePolicyDialog(context);
}),
)),
ResponsiveRowColumnItem(
child: responsive.smallerThan(TABLET)
? const SizedBox(height: theme.extraSmallSpacing)
: const SizedBox(width: theme.mediumSpacing),
),
ResponsiveRowColumnItem(
child: RichText(
text: TextSpan(
text: AppLocalizations.of(context)!.legal_disclaimer,
style: theme.footerTextStyle,
recognizer: TapGestureRecognizer()
…onTap = () {
LegalDialogProvider.showDisclaimerDialog(context);
}),
)),
]);
}
}
|
1b4d534cc76dfbfd262164b0fab3c8fd
|
{
"intermediate": 0.39261627197265625,
"beginner": 0.36413276195526123,
"expert": 0.2432509809732437
}
|
7,104
|
code to create a view poage in visualforce
|
82b8597992776d08ac7f4a8936eb11f9
|
{
"intermediate": 0.28542453050613403,
"beginner": 0.24703866243362427,
"expert": 0.4675368070602417
}
|
7,105
|
Task 1
Изучите структуру шаблона. Обратите внимание, что для классов сделаны отдельные файлы. Обратите внимание, как и в какой последовательности подключены файлы в index.html. Порядок подключения важен!!!!
В файле Goods.js создайте класс Goods. В конструкторе класса создайте два свойства. Первое - name, второе price. Как понятно из названия - имя товара и цена.
Для проверки сделанного напишите в unit_28.js следующий код:
const goods_1 = new Goods('apple', 23.5);
console.log(goods_1);
Если объект создан и в нем появилось свойство name равное 'apple' и свойство цены с заданным значением - переходите к следующему таску. Данную проверку в файле unit_28.js нужно удалить или закомментировать.
FAQ ПО ЗАДАЧЕ
Task 2
Допишите в класс Goods свойства image - и count. Image - ссылка на изображение товара, а count - число, определяющее количество товара на складе.
Для проверки сделанного напишите в unit_28.js следующий код:
const goods_1 = new Goods('apple', 23.5, 'https://cdn0.iconfinder.com/data/icons/fruity-3/512/Apple-48.png', 400);
console.log(goods_1);
Если объект создан и в нем появились все заданные свойства - переходите к следующему таску. Данную проверку в файле unit_28.js нужно удалить или закомментировать.
FAQ ПО ЗАДАЧЕ
Task 3
Время выводить товар на страницу. Допишем в класс Goods метод draw() который будет делать следующее:
<div class="goods">
<h1>Тут будет имя товара</h1>
<p class="price">Тут будет цена товара</p>
<img src="тут будет ссылка на изображение" alt="тут будет имя товара">
</div>
Конечно же вместо "Тут будет имя товара" - вы подставите свойство this.name и так далее. Надеюсь создавать данную верстку вы будете через createElement (Юнит 9 - если забыли).
Метод должен возвращать созданный div.
Теперь как проверить данный код? Для проверки сделанного напишите в unit_28.js следующий код:
const goods_1 = new Goods('apple', 23.5, 'https://cdn0.iconfinder.com/data/icons/fruity-3/512/Apple-48.png', 400 );
console.log(goods_1);
// И теперь выведем на страницу
document.querySelector('.out-3').append(goods_1.draw());
Если все верно сделано - то на странице появится верстка товара.
|
a5f588ded38acff95917de2d029a0ff1
|
{
"intermediate": 0.24166220426559448,
"beginner": 0.5224829316139221,
"expert": 0.2358548790216446
}
|
7,106
|
s
|
d66fdc14b03ee99e6ba512ad226d6fa5
|
{
"intermediate": 0.3237691819667816,
"beginner": 0.299067884683609,
"expert": 0.37716299295425415
}
|
7,107
|
compose get devicewidth in px
|
97257333bcc94c0b146143ca90d737dd
|
{
"intermediate": 0.3552272617816925,
"beginner": 0.2135656476020813,
"expert": 0.4312070906162262
}
|
7,108
|
i have a function in next.js which updates a row using prisma, it is server side. I want to redirect after the insert is completed to the path /admin
|
f582518060b90c5e7a0cd9b737e420cb
|
{
"intermediate": 0.46090179681777954,
"beginner": 0.28019118309020996,
"expert": 0.2589070498943329
}
|
7,109
|
write me a js function that validates string by regex accepting only letters and numbers
|
cfd8a996c66bdd2a832e9a5841ce3b76
|
{
"intermediate": 0.47912833094596863,
"beginner": 0.3198433518409729,
"expert": 0.20102833211421967
}
|
7,110
|
in linux, how do i turn a word per line to one line with space between words
|
89671edaefbc09310d40dca1941fddc4
|
{
"intermediate": 0.31896907091140747,
"beginner": 0.29121097922325134,
"expert": 0.3898199200630188
}
|
7,111
|
После успешного входа или регистрации ты должен сделать переменную public static int profile_num равной id этого пользователя : package com.example.myapp_2.Data.register;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import com.example.myapp_2.R;
import com.example.myapp_2.UI.view.fragments.FirstFragment;
public class LoginFragment extends Fragment {
public static int profile_num ;
private EditText editTextEmail, editTextPassword;
private Button buttonLogin;
private UserDAO userDAO;
public LoginFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
userDAO = new UserDAO(getActivity());
userDAO.open();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.login, container, false);
getActivity().findViewById(R.id.bottomNavigationView).setVisibility(View.GONE);
editTextEmail = view.findViewById(R.id.editTextEmail);
editTextPassword = view.findViewById(R.id.editTextPassword);
buttonLogin = view.findViewById(R.id.buttonLogin);
buttonLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String email = editTextEmail.getText().toString();
String password = editTextPassword.getText().toString();
if (userDAO.login(email, password)) {
Toast.makeText(getActivity(), "Login successful", Toast.LENGTH_SHORT).show();
// переход на другой фрагмент
FragmentTransaction transaction = requireActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_container, new FirstFragment());
transaction.addToBackStack(null);
transaction.commit();
} else {
Toast.makeText(getActivity(), "Invalid email or password", Toast.LENGTH_SHORT).show();
}
}
});
Button buttonReturn = view.findViewById(R.id.buttonReturn);
buttonReturn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentTransaction transaction = requireActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_container, new RegistrationFragment());
transaction.addToBackStack(null);
transaction.commit();
}
});
return view;
}
@Override
public void onDestroy() {
super.onDestroy();
userDAO.close();
}
}
package com.example.myapp_2.Data.register;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import com.example.myapp_2.R;
import com.example.myapp_2.UI.view.fragments.FirstFragment;
import java.util.List;
public class RegistrationFragment extends Fragment {
private EditText editTextName, editTextEmail, editTextPassword;
private Button buttonRegister_1;
private UserDAO userDAO;
public RegistrationFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
userDAO = new UserDAO(getActivity());
userDAO.open();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.refister, container, false);
getActivity().findViewById(R.id.bottomNavigationView).setVisibility(View.GONE);
editTextName = view.findViewById(R.id.editTextName);
editTextEmail = view.findViewById(R.id.editTextEmail);
editTextPassword = view.findViewById(R.id.editTextPassword);
buttonRegister_1 = view.findViewById(R.id.buttonRegister_1);
buttonRegister_1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = editTextName.getText().toString();
String email = editTextEmail.getText().toString();
String password = editTextPassword.getText().toString();
long rowID = userDAO.register(name, email, password);
if (rowID > 0) {
Toast.makeText(getActivity(), "Registration successful", Toast.LENGTH_SHORT).show();
getFragmentManager().popBackStack();
FragmentTransaction transaction = requireActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_container, new FirstFragment());
transaction.addToBackStack(null);
transaction.commit();
} else if (rowID == -1) {
Toast.makeText(getActivity(), "Invalid email", Toast.LENGTH_SHORT).show();
// вывод всех пользователей в лог
List<User> users = userDAO.getAllUsers();
Log.d("UserDatabase", "All users:");
for (User user : users) {
Log.d("UserDatabase", user.toString());
}
} else {
Toast.makeText(getActivity(), "Registration failed", Toast.LENGTH_SHORT).show();
}
}
});
Button buttonLogin_1 = view.findViewById(R.id.buttonLogin_1);
buttonLogin_1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentTransaction transaction = requireActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_container, new LoginFragment());
transaction.addToBackStack(null);
transaction.commit();
}
});
Button buttonExit = view.findViewById(R.id.buttonExit);
buttonExit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getFragmentManager().popBackStack();
FragmentTransaction transaction = requireActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.nav_container, new FirstFragment());
transaction.addToBackStack(null);
transaction.commit();
}
});
return view;
}
@Override
public void onDestroy() {
super.onDestroy();
userDAO.close();
}
}
package com.example.myapp_2.Data.register;
public class User {
private int id;
private String name;
private String email;
private String password;
public User() {
}
public User(int id, String name, String email, String password) {
this.id = id;
this.name = name;
this.email = email;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User {id=" + id + ", name='" + name + "‘, email=’" + email + "‘, password=’" + password + "'}";
}
}package com.example.myapp_2.Data.register;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
public class UserDAO {
private SQLiteDatabase database;
private UserDatabaseHelper dbHelper;
public UserDAO(Context context) {
dbHelper = new UserDatabaseHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public long register(String name, String email, String password) {
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
return -1; // email не соответствует формату
}
Cursor cursor = database.query(UserDatabaseHelper.TABLE_USERS,
new String[]{UserDatabaseHelper.COLUMN_EMAIL},
UserDatabaseHelper.COLUMN_EMAIL + " = ?",
new String[]{email}, null, null, null, null);
if (cursor != null && cursor.getCount() > 0) { // если уже есть пользователь с такой почтой
cursor.close();
return -2;
}
ContentValues values = new ContentValues();
values.put(UserDatabaseHelper.COLUMN_NAME, name);
values.put(UserDatabaseHelper.COLUMN_EMAIL, email);
values.put(UserDatabaseHelper.COLUMN_PASSWORD, password);
return database.insert(UserDatabaseHelper.TABLE_USERS, null, values);
}
public boolean login(String email, String password) {
Cursor cursor = database.query(UserDatabaseHelper.TABLE_USERS,
new String[]{UserDatabaseHelper.COLUMN_EMAIL, UserDatabaseHelper.COLUMN_PASSWORD},
UserDatabaseHelper.COLUMN_EMAIL + " = ? AND " + UserDatabaseHelper.COLUMN_PASSWORD + " = ?",
new String[]{email, password}, null, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
cursor.close();
return true;
} else {
return false;
}
}
@SuppressLint("Range")
public List<User> getAllUsers() {
List<User> users = new ArrayList<>();
Cursor cursor = database.query(UserDatabaseHelper.TABLE_USERS,
new String[]{UserDatabaseHelper.COLUMN_ID, UserDatabaseHelper.COLUMN_NAME,
UserDatabaseHelper.COLUMN_EMAIL, UserDatabaseHelper.COLUMN_PASSWORD},
null, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
do {
User user = new User();
user.setId(cursor.getInt(cursor.getColumnIndex(UserDatabaseHelper.COLUMN_ID)));
user.setName(cursor.getString(cursor.getColumnIndex(UserDatabaseHelper.COLUMN_NAME)));
user.setEmail(cursor.getString(cursor.getColumnIndex(UserDatabaseHelper.COLUMN_EMAIL)));
user.setPassword(cursor.getString(cursor.getColumnIndex(UserDatabaseHelper.COLUMN_PASSWORD)));
users.add(user);
} while (cursor.moveToNext());
cursor.close();
}
return users;
}
public User getUserById(int id) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.query(UserDatabaseHelper.TABLE_USERS,
new String[]{UserDatabaseHelper.COLUMN_ID, UserDatabaseHelper.COLUMN_NAME, UserDatabaseHelper.COLUMN_EMAIL, UserDatabaseHelper.COLUMN_PASSWORD},
UserDatabaseHelper.COLUMN_ID + "= ?", new String[]{String.valueOf(id)},
null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
@SuppressLint("Range") User user = new User(cursor.getInt(cursor.getColumnIndex(UserDatabaseHelper.COLUMN_ID)),
cursor.getString(cursor.getColumnIndex(UserDatabaseHelper.COLUMN_NAME)),
cursor.getString(cursor.getColumnIndex(UserDatabaseHelper.COLUMN_EMAIL)),
cursor.getString(cursor.getColumnIndex(UserDatabaseHelper.COLUMN_PASSWORD)));
cursor.close();
return user;
}
public void updateUser(User user) {
ContentValues values = new ContentValues();
values.put(UserDatabaseHelper.COLUMN_NAME, user.getName());
values.put(UserDatabaseHelper.COLUMN_EMAIL, user.getEmail());
values.put(UserDatabaseHelper.COLUMN_PASSWORD, user.getPassword());
database.update(UserDatabaseHelper.TABLE_USERS, values,
UserDatabaseHelper.COLUMN_ID + " = ?",
new String[]{String.valueOf(user.getId())});
}
}
package com.example.myapp_2.Data.register;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class UserDatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "UserDatabase";
public static final String TABLE_USERS = "users";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_EMAIL = "email";
public static final String COLUMN_PASSWORD = "password";
public UserDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_USERS_TABLE = "CREATE TABLE " + TABLE_USERS + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_NAME + " TEXT,"
+ COLUMN_EMAIL + " TEXT,"
+ COLUMN_PASSWORD + " TEXT"
+ ")";
db.execSQL(CREATE_USERS_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
onCreate(db);
}
}
|
b91fa9d2403bd2aa58020228cf467677
|
{
"intermediate": 0.30981266498565674,
"beginner": 0.530584990978241,
"expert": 0.15960225462913513
}
|
7,112
|
sed command to change a text file from one word per line to on line with space between words
|
c993dd8fbacdcc694dd1302e136243aa
|
{
"intermediate": 0.34990614652633667,
"beginner": 0.16288632154464722,
"expert": 0.48720747232437134
}
|
7,113
|
call by value and call by reference in Delphi
|
abf5f6507e3363ad286721aab41755b4
|
{
"intermediate": 0.39840590953826904,
"beginner": 0.3221566379070282,
"expert": 0.27943745255470276
}
|
7,114
|
This is my current ide code for highsum game:
"import GUIExample.GameTableFrame;
import Model.*;
public class GUIExample {
private Dealer dealer;
private Player player;
private GameTableFrame app;
public GUIExample() {
}
public void run() {
dealer.shuffleCards();
app = new GameTableFrame(dealer, player);
app.run();
}
public static void main(String[] args) {
LoginDialog loginDialog = new LoginDialog(null);
loginDialog.setVisible(true);
if (loginDialog.isLoggedIn()) {
String login = loginDialog.getLogin();
String password = loginDialog.getPassword();
GUIExample example = new GUIExample();
example.dealer = new Dealer();
example.player = new Player(login, password, 10000);
example.run();
}
}
}
import Model.*;
import Controller.*;
import View.*;
public class HighSum {
private Dealer dealer;
private Player player;
private ViewController view;
private GameController gc;
public HighSum() {
}
public void init(String login, String password) {
//create all the required objects
this.dealer = new Dealer();
this.player = new Player(login, password, 50);
this.view = new ViewController();
//bring them together
this.gc = new GameController(this.dealer, this.player, this.view);
}
public void run() {
//starts the game!
gc.run();
}
public static void main(String[] args) {
LoginDialog loginDialog = new LoginDialog(null);
loginDialog.setVisible(true);
if (loginDialog.isLoggedIn()) {
String login = loginDialog.getLogin();
String password = loginDialog.getPassword();
HighSum highSum = new HighSum();
highSum.init(login, password);
highSum.run();
}
}
}
Controller package:
package Controller;
import Model.Dealer;
import Model.Player;
import View.ViewController;
public class GameController {
private Dealer dealer;
private Player player;
private ViewController view;
private int chipsOnTable;
public GameController(Dealer dealer,Player player,ViewController view) {
this.dealer = dealer;
this.player = player;
this.view = view;
this.chipsOnTable = 0;
}
public void run() {
boolean carryOn= true;
while(carryOn) {
runOneRound();
char r = this.view.getPlayerNextGame();
if(r=='n') {
carryOn = false;
}
}
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayExitGame();
}
public void runOneRound() {
this.view.displayGameTitle();
this.view.displayDoubleLine();
this.view.displayPlayerNameAndChips(this.player);
this.view.displaySingleLine();
this.view.displayGameStart();
this.view.displaySingleLine();
this.dealer.shuffleCards();
this.chipsOnTable = 0;
boolean playerQuit = false;
for(int round = 1;round<=4;round++) {
this.view.displaySingleLine();
this.view.displayDealerDealCardsAndGameRound(round);
this.view.displaySingleLine();
if(round==1) {//round 1 deal extra card
this.dealer.dealCardTo(this.player);
this.dealer.dealCardTo(this.dealer);
}
this.dealer.dealCardTo(this.player);
this.dealer.dealCardTo(this.dealer);
this.view.displayPlayerCardsOnHand(this.dealer);
this.view.displayBlankLine();
this.view.displayPlayerCardsOnHand(player);
this.view.displayPlayerTotalCardValue(player);
int whoCanCall = this.dealer.determineWhichCardRankHigher(dealer.getLastCard(), player.getLastCard());
if(whoCanCall==1) {//dealer call
int chipsToBet = this.view. getDealerCallBetChips();
//ask player want to follow?
char r = this.view.getPlayerFollowOrNot(this.player,chipsToBet);
if(r=='y') {
this.player.deductChips(chipsToBet);
this.chipsOnTable+=2*chipsToBet;
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayBetOntable(this.chipsOnTable);
}else {
playerQuit = true;
break;
}
}else {//player call
if(round==1) {//round 1 player cannot quit
int chipsToBet = view.getPlayerCallBetChip(this.player);
this.player.deductChips(chipsToBet);
this.chipsOnTable+=2*chipsToBet;
this.view.displayBetOntable(this.chipsOnTable);
}else {
char r = this.view.getPlayerCallOrQuit();
if(r=='c') {
int chipsToBet = view.getPlayerCallBetChip(this.player);
this.player.deductChips(chipsToBet);
this.chipsOnTable+=2*chipsToBet;
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayBetOntable(this.chipsOnTable);
}else {
playerQuit = true;
break;
}
}
}
}
//check who win
if(playerQuit) {
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayPlayerQuit();
}
else if(this.player.getTotalCardsValue()>this.dealer.getTotalCardsValue()) {
this.view.displayPlayerWin(this.player);
this.player.addChips(chipsOnTable);
this.chipsOnTable=0;
this.view.displayPlayerNameAndLeftOverChips(this.player);
}else if(this.player.getTotalCardsValue()<this.dealer.getTotalCardsValue()) {
this.view.displayDealerWin();
this.view.displayPlayerNameAndLeftOverChips(this.player);
}else {
this.view.displayTie();
this.player.addChips(chipsOnTable/2);
this.view.displayPlayerNameAndLeftOverChips(this.player);
}
//put all the cards back to the deck
dealer.addCardsBackToDeck(dealer.getCardsOnHand());
dealer.addCardsBackToDeck(player.getCardsOnHand());
dealer.clearCardsOnHand();
player.clearCardsOnHand();
}
}
package GUIExample;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginDialog extends JDialog {
private JTextField loginField;
private JPasswordField passwordField;
private JButton loginButton;
private boolean loggedIn = false;
public LoginDialog(JFrame parent) {
super(parent, "Login", true);
loginField = new JTextField(20);
passwordField = new JPasswordField(20);
loginButton = new JButton("Login");
loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
loggedIn = true;
dispose();
}
});
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2));
panel.add(new JLabel("Login:"));
panel.add(loginField);
panel.add(new JLabel("Password:"));
panel.add(passwordField);
panel.add(loginButton);
add(panel);
pack();
setLocationRelativeTo(parent);
}
public String getLogin() {
return loginField.getText();
}
public String getPassword() {
return new String(passwordField.getPassword());
}
public boolean isLoggedIn() {
return loggedIn;
}
}
package GUIExample;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import Model.*;
public class GameTableFrame extends JFrame{
private GameTablePanel gameTablePanel;
private Dealer dealer;
private Player player;
private int count=0;
private JButton playButton;
private JButton quitButton;
public GameTableFrame(Dealer dealer, Player player)
{
this.dealer = dealer;
this.player = player;
gameTablePanel = new GameTablePanel(dealer,player);
this.count=0;
playButton = new JButton("Play");
quitButton = new JButton("Quit");
playButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Call run() when playButton is clicked
run();
}
});
quitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Close the program when quitButton is clicked
System.exit(0);
}
});
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(playButton);
buttonsPanel.add(quitButton);
add(gameTablePanel, BorderLayout.CENTER);
add(buttonsPanel, BorderLayout.SOUTH);
pack();
setVisible(true);
}
public void updateGameTable()
{
gameTablePanel.repaint();
}
public void run() {
for(int i=0;i<5;i++) {
dealer.dealCardTo(dealer);
dealer.dealCardTo(player);
pause();
updateGameTable();
}
}
//pause for 500msec
private void pause() {
try{
Thread.sleep(500);
}catch(Exception e){}
}
}
package GUIExample;
import java.awt.*;
import javax.swing.*;
import Model.*;
public class GameTablePanel extends JPanel {
private Player player;
private Dealer dealer;
private ImageIcon cardBackImage;
public GameTablePanel(Dealer dealer, Player player) {
setBackground(Color.GREEN);
setPreferredSize(new Dimension(1024, 768));
cardBackImage = new ImageIcon("images/back.png");
this.dealer = dealer;
this.player = player;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
int x = 50;
int y = 70;
int i = 0;
for (Card c : dealer.getCardsOnHand()) {
// display dealer cards
if (i == 0d) {
cardBackImage.paintIcon(this, g, x, y);
i++;
} else {
c.paintIcon(this, g, x, y);
}
x += 200;
}
// display player cards
x = 50;
y = 550;
for (Card c : player.getCardsOnHand()) {
// display dealer cards
c.paintIcon(this, g, x, y);
x += 200;
}
}
}
Helper Package:
package Helper;
public class Keyboard {
public static String readString(String prompt) {
System.out.print(prompt);
return new java.util.Scanner(System.in).nextLine();
}
public static int readInt(String prompt) {
int input = 0;
boolean valid = false;
while (!valid) {
try {
input = Integer.parseInt(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
System.out.println("*** Please enter an integer ***");
}
}
return input;
}
public static double readDouble(String prompt) {
double input = 0;
boolean valid = false;
while (!valid) {
try {
input = Double.parseDouble(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
System.out.println("*** Please enter a double ***");
}
}
return input;
}
public static float readFloat(String prompt) {
float input = 0;
boolean valid = false;
while (!valid) {
try {
input = Float.parseFloat(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
System.out.println("*** Please enter a float ***");
}
}
return input;
}
public static long readLong(String prompt) {
long input = 0;
boolean valid = false;
while (!valid) {
try {
input = Long.parseLong(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
e.printStackTrace();
System.out.println("*** Please enter a long ***");
}
}
return input;
}
public static char readChar(String prompt,char[] choices) {
boolean validChoice = false;
char r = ' ';
while(!validChoice) {
r = Keyboard.readChar(prompt+" "+charArrayToString(choices)+":");
if(!validateChoice(choices,r)) {
System.out.println("Invalid input");
}else {
validChoice = true;
}
}
return r;
}
private static String charArrayToString(char[] charArray) {
String s = "[";
for(int i=0;i<charArray.length;i++) {
s+=charArray[i];
if(i!=charArray.length-1) {
s+=",";
}
}
s += "]";
return s;
}
private static boolean validateChoice(char[] choices, char choice) {
boolean validChoice = false;
for(int i=0;i<choices.length;i++) {
if(choices[i]==choice) {
validChoice = true;
break;
}
}
return validChoice;
}
public static char readChar(String prompt) {
char input = 0;
boolean valid = false;
while (!valid) {
String temp = readString(prompt);
if (temp.length() != 1) {
System.out.println("*** Please enter a character ***");
} else {
input = temp.charAt(0);
valid = true;
}
}
return input;
}
public static boolean readBoolean(String prompt) {
boolean valid = false;
while (!valid) {
String input = readString(prompt);
if (input.equalsIgnoreCase("yes") || input.equalsIgnoreCase("y") || input.equalsIgnoreCase("true")
|| input.equalsIgnoreCase("t")) {
return true;
} else if (input.equalsIgnoreCase("no") || input.equalsIgnoreCase("n") || input.equalsIgnoreCase("false")
|| input.equalsIgnoreCase("f")) {
return false;
} else {
System.out.println("*** Please enter Yes/No or True/False ***");
}
}
return false;
}
public static java.util.Date readDate(String prompt) {
java.util.Date date = null;
boolean valid = false;
while (!valid) {
try {
String input = readString(prompt).trim();
if (input.matches("\\d\\d/\\d\\d/\\d\\d\\d\\d")) {
int day = Integer.parseInt(input.substring(0, 2));
int month = Integer.parseInt(input.substring(3, 5));
int year = Integer.parseInt(input.substring(6, 10));
java.util.Calendar cal = java.util.Calendar.getInstance();
cal.setLenient(false);
cal.set(year, month - 1, day, 0, 0, 0);
date = cal.getTime();
valid = true;
} else {
System.out.println("*** Please enter a date (DD/MM/YYYY) ***");
}
} catch (IllegalArgumentException e) {
System.out.println("*** Please enter a date (DD/MM/YYYY) ***");
}
}
return date;
}
private static String quit = "0";
public static int getUserOption(String title, String[] menu) {
displayMenu(title, menu);
int choice = Keyboard.readInt("Enter Choice --> ");
while (choice > menu.length || choice < 0) {
choice = Keyboard.readInt("Invalid Choice, Re-enter --> ");
}
return choice;
}
private static void displayMenu(String title, String[] menu) {
line(80, "=");
System.out.println(title.toUpperCase());
line(80, "-");
for (int i = 0; i < menu.length; i++) {
System.out.println("[" + (i + 1) + "] " + menu[i]);
}
System.out.println("[" + quit + "] Quit");
line(80, "-");
}
public static void line(int len, String c) {
System.out.println(String.format("%" + len + "s", " ").replaceAll(" ", c));
}
}
package Helper;
import java.security.MessageDigest;
public class Utility {
public static String getHash(String base)
{
String message="";
try{
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(base.getBytes("UTF-8"));
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if(hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
message = hexString.toString();
} catch(Exception ex){
throw new RuntimeException(ex);
}
return message;
}
public static void printLine(int num)
{
printLine(num,'-');
}
public static void printDoubleLine(int num)
{
printLine(num,'=');
}
public static void printLine(int num,char pattern)
{
for(int i =0;i<num;i++)
{
System.out.print(pattern);
}
System.out.println("");
}
}
Model Package:
package Model;
import javax.swing.*;
public class Card extends ImageIcon{
private String suit;
private String name;
private int value;
//used for card ranking - see below
//to determine which card has higher power to determine who can call.
private int rank;
public Card(String suit, String name, int value,int rank) {
super("images/"+suit+name+".png");
this.suit = suit;
this.name = name;
this.value = value;
this.rank = rank;
}
public String getSuit() {
return this.suit;
}
public String getName() {
return this.name;
}
public int getValue() {
return this.value;
}
public int getRank() {
return this.rank;
}
public String toString() {
return "<"+this.suit+" "+this.name+">";
}
public String display() {
return "<"+this.suit+" "+this.name+" "+this.rank+">";
}
}
//card rank
// D C H S
//1 1 2 3 4
//2 5 6 7 8
//3 9 10 11 12
//4 13 14 15 16
//5 17 18 19 20
//6 21 22 23 24
//7 25 26 27 28
//8 29 30 31 32
//9 33 34 35 36
//10 37 38 39 40
//J 41 42 43 44
//Q 45 46 47 48
//K 49 50 51 52
package Model;
import java.util.*;
public class Dealer extends Player{
private Deck deck;
public Dealer() {
super("Dealer","",0);
deck = new Deck();
}
public void shuffleCards() {
System.out.println("Dealer shuffle deck");
deck.shuffle();
}
public void dealCardTo(Player player) {
Card card = deck.dealCard();//take a card out from deck
player.addCard(card);//pass the card into player
}
public void addCardsBackToDeck(ArrayList<Card> cards) {
deck.appendCard(cards);
}
//return 1 if card1 rank higher, else return 2
public int determineWhichCardRankHigher(Card card1, Card card2) {
if(card1.getRank()>card2.getRank()) {
return 1;
}else {
return 2;
}
}
}
package Model;
import java.util.*;
public class Deck {
private ArrayList<Card> cards;
public Deck() {
cards = new ArrayList<Card>();
String[] suits = { "Diamond", "Club","Heart","Spade", };
for (int i = 0; i < suits.length; i++) {
String suit = suits[i];
Card card = new Card(suit, "Ace", 1,1+i);
cards.add(card);
int c = 5;
for (int n = 2; n <= 10; n++) {
Card oCard = new Card(suit, "" + n, n,c+i);
cards.add(oCard);
c+=4;
}
Card jackCard = new Card(suit, "Jack", 10,41+i);
cards.add(jackCard);
Card queenCard = new Card(suit, "Queen", 10,45+i);
cards.add(queenCard);
Card kingCard = new Card(suit, "King", 10,49+i);
cards.add(kingCard);
}
}
public Card dealCard() {
return cards.remove(0);
}
//add back one card
public void appendCard(Card card) {
cards.add(card);
}
//add back arraylist of cards
public void appendCard(ArrayList<Card> cards) {
for(Card card: cards) {
this.cards.add(card);
}
}
public void shuffle() {
Random random = new Random();
for(int i=0;i<10000;i++) {
int indexA = random.nextInt(cards.size());
int indexB = random.nextInt(cards.size());
Card cardA = cards.get(indexA);
Card cardB = cards.get(indexB);
cards.set(indexA, cardB);
cards.set(indexB, cardA);
}
}
//for internal use only
private void showCards() {
for (Card card : cards) {
System.out.println(card);
}
}
//for internal use only
private void displayCards() {
for (Card card : cards) {
System.out.println(card.display());
}
}
public static void main(String[] args) {
Deck deck = new Deck();
//deck.shuffle();
/*Card card1 = deck.dealCard();
Card card2 = deck.dealCard();
Card card3 = deck.dealCard();
deck.showCards();
ArrayList<Card> cards = new ArrayList<Card>();
cards.add(card1);
cards.add(card2);
cards.add(card3);
deck.appendCard(cards);
System.out.println();*/
deck.displayCards();
}
}
//card rank
//D C H S
//1 1 2 3 4
//2 5 6 7 8
//3 9 10 11 12
//4 13 14 15 16
//5 17 18 19 20
//6 21 22 23 24
//7 25 26 27 28
//8 29 30 31 32
//9 33 34 35 36
//10 37 38 39 40
//J 41 42 43 44
//Q 45 46 47 48
//K 49 50 51 52
package Model;
import java.util.*;
public class Player extends User{
private int chips;
protected ArrayList<Card> cardsOnHand;
public Player(String loginName, String password, int chips) {
super(loginName, password);
this.chips = chips;
this.cardsOnHand = new ArrayList<Card>();
}
public int getChips() {
return this.chips;
}
public void addChips(int amount) {
this.chips+=amount;//no error check
}
public void deductChips(int amount) {
this.chips-=amount;//no error check
}
public void addCard(Card card) {
this.cardsOnHand.add(card);
}
public ArrayList<Card> getCardsOnHand() {
return this.cardsOnHand;
}
public int getTotalCardsValue() {
int total = 0;
for(Card card: this.cardsOnHand) {
total+=card.getValue();
}
return total;
}
public Card getLastCard() {
return this.cardsOnHand.get(this.cardsOnHand.size()-1);
}
public void clearCardsOnHand() {
this.cardsOnHand.clear();
}
//Think of the action that a player can take
//implement more related methods here
public static void main(String[] args) {
// TODO Auto-generated method stub
Player player = new Player("IcePeak","A",100);
System.out.println(player.getChips());
player.deductChips(10);
System.out.println(player.getChips());
player.addChips(20);
System.out.println(player.getChips());
}
}
package Model;
import Helper.*;
abstract public class User {
private String loginName;
private String hashPassword;
public User(String loginName, String password) {
this.loginName = loginName;
this.hashPassword = Utility.getHash(password);
}
public String getLoginName() {
return this.loginName;
}
public boolean checkPassword(String password) {
return this.hashPassword.equals(Utility.getHash(password));
}
}
View Package:
package View;
import Helper.Keyboard;
import Model.*;
//all input and output should be done view ViewController
//so that it is easier to implement GUI later
public class ViewController {
public void displayExitGame() {
System.out.println("Thank you for playing HighSum game");
}
public void displayBetOntable(int bet) {
System.out.println("Bet on table : "+bet);
}
public void displayPlayerWin(Player player) {
System.out.println(player.getLoginName()+" Wins!");
}
public void displayDealerWin() {
System.out.println("Dealer Wins!");
}
public void displayTie() {
System.out.println("It is a tie!.");
}
public void displayPlayerQuit() {
System.out.println("You have quit the current game.");
}
public void displayPlayerCardsOnHand(Player player) {
System.out.println(player.getLoginName());
if(player instanceof Dealer) {
for(int i=0;i<player.getCardsOnHand().size();i++) {
if(i==0) {
System.out.print("<HIDDEN CARD> ");
}else {
System.out.print(player.getCardsOnHand().get(i).toString()+" ");
}
}
}else {
for(Card card:player.getCardsOnHand()) {
System.out.print(card+" ");
}
}
System.out.println();
}
public void displayBlankLine() {
System.out.println();
}
public void displayPlayerTotalCardValue(Player player) {
System.out.println("Value:"+player.getTotalCardsValue());
}
public void displayDealerDealCardsAndGameRound(int round) {
System.out.println("Dealer dealing cards - ROUND "+round);
}
public void displayGameStart() {
System.out.println("Game starts - Dealer shuffle deck");
}
public void displayPlayerNameAndChips(Player player) {
System.out.println(player.getLoginName()+", You have "+player.getChips()+" chips");
}
public void displayPlayerNameAndLeftOverChips(Player player) {
System.out.println(player.getLoginName()+", You are left with "+player.getChips()+" chips");
}
public void displayGameTitle() {
System.out.println("HighSum GAME");
}
public void displaySingleLine() {
for(int i=0;i<30;i++) {
System.out.print("-");
}
System.out.println();
}
public void displayDoubleLine() {
for(int i=0;i<30;i++) {
System.out.print("=");
}
System.out.println();
}
public char getPlayerCallOrQuit() {
char[] choices = {'c','q'};
char r = Keyboard.readChar("Do you want to [c]all or [q]uit?:",choices);
return r;
}
public char getPlayerFollowOrNot(Player player, int dealerBet) {
boolean validChoice = false;
char[] choices = {'y','n'};
char r = 'n';
while(!validChoice) {
r = Keyboard.readChar("Do you want to follow?",choices);
//check if player has enff chips to follow
if(r=='y' && player.getChips()<dealerBet) {
System.out.println("You do not have enough chips to follow");
displayPlayerNameAndChips(player);
}else {
validChoice = true;
}
}
return r;
}
public char getPlayerNextGame() {
char[] choices = {'y','n'};
char r = Keyboard.readChar("Next game?",choices);
return r;
}
public int getPlayerCallBetChip(Player player) {
boolean validBetAmount = false;
int chipsToBet = 0;
while(!validBetAmount) {
chipsToBet = Keyboard.readInt("Player call, state bet:");
if(chipsToBet<0) {
System.out.println("Chips cannot be negative");
}else if(chipsToBet>player.getChips()) {
System.out.println("You do not have enough chips");
}else {
validBetAmount = true;
}
}
return chipsToBet;
}
public int getDealerCallBetChips() {
System.out.println("Dealer call, state bet: 10");
return 10;
}
}"
These are the requirements:
“On completion of this assignment a student should be able to write a Java application that: • Makes use of Java API "Swing" and "AWT" packages • Handles generated events • Makes use of layout manager to organize the GUI components • Know how to apply and design a program using object-oriented concepts 2. Task Enhance the one player Java game application "HighSum" done in Assignment 1 with Graphical User Interface (GUI). 2.1 Login The game starts by the player logging into the game. Page 2 Copyright SCIT, University of Wollongong, 2023 2.2 Play Game The game starts after the player click on “Login”. First, the dealer will shuffles the deck. (You may include animation in this frame to simulate “shuffle” effect as enhancement.) Then the dealer deals two cards from the top of the deck to the player and itself. Since the player’s last card is higher than the dealer’s last card, the player gets to Call the game. Assume the player states 10 as the bet chips. The player’s chip will be deducted by 10. Page 3 Copyright SCIT, University of Wollongong, 2023 The chips on table will be updated to 20 and the dealer deals cards for next round. Assume the dealer’s last card is higher than the player’s last card. The dealer Call the game and the player gets to choose to Follow or Quit the game. If the player follows the game, 10 chips will be deducted from the player’s balance chips. (Asumme the dealer place 10 chips.) The games carry on for maximum of four rounds. In the last round, the player with the highest total sum wins the game. And the game continues until the player exits the game. "
and there are 5 errors : Description Resource Path Location Type
LoginDialog cannot be resolved to a type GUIExample.java /A3Skeleton/src line 20 Java Problem
LoginDialog cannot be resolved to a type GUIExample.java /A3Skeleton/src line 20 Java Problem
LoginDialog cannot be resolved to a type HighSum.java /A3Skeleton/src line 31 Java Problem
LoginDialog cannot be resolved to a type HighSum.java /A3Skeleton/src line 31 Java Problem
The public type LoginDialog must be defined in its own file LoginDIalog.java /A3Skeleton/src/GUIExample line 8 Java Problem
|
eea4812f1a2af65dd3ef80ee489a7d53
|
{
"intermediate": 0.2906542420387268,
"beginner": 0.4795202910900116,
"expert": 0.2298254817724228
}
|
7,115
|
librtmp发送@setDataFrame和onMetaData代码,包括duration、width、height、videodatarate、videocodecid、audiodatarate、audiosamplerate、audiosamplesize、stereo、audiocodecid、filesize
|
9d8a637dd18831cf13a5a367b6406bb0
|
{
"intermediate": 0.5508072972297668,
"beginner": 0.17526644468307495,
"expert": 0.2739262282848358
}
|
7,116
|
jetpack compose get screenwidth in px
|
491a833dcbd26d8dac90c7d623cc67fd
|
{
"intermediate": 0.4034483730792999,
"beginner": 0.2304765284061432,
"expert": 0.3660751283168793
}
|
7,117
|
write me an error message for failed validation
|
aefe7b7530c29760d6565ba1a5591372
|
{
"intermediate": 0.4214862883090973,
"beginner": 0.21563956141471863,
"expert": 0.3628741502761841
}
|
7,118
|
librtmp发送@setDataFrame和onMetaData代码,包括duration、width、height、videodatarate、videocodecid、audiodatarate、audiosamplerate、audiosamplesize、stereo、audiocodecid、filesize
|
a5c378fa53daf6b751e1e9cacaead27d
|
{
"intermediate": 0.5508072972297668,
"beginner": 0.17526644468307495,
"expert": 0.2739262282848358
}
|
7,119
|
Stored Procedure and Functions difference
|
36988b9b34dfe9264b8948bbc8cd9617
|
{
"intermediate": 0.3426281809806824,
"beginner": 0.400300532579422,
"expert": 0.25707125663757324
}
|
7,120
|
edit my java code so that historyEntry is added to a list which I can then show on the Jlabel Commande: import java.awt.EventQueue;
public class PizzaOrder extends JFrame {
private JPanel contentPane;
private JTextField NumPizza;
private JTextField NumTopping;
private JTextField NumBreuvage;
private JButton Ajouter;
private double totales;
private String History;
private static String previousHistory;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PizzaOrder frame = new PizzaOrder(previousHistory);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public PizzaOrder(String previousHistory) {
History = previousHistory;
setTitle("Order");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 630, 689);
contentPane = new JPanel();
contentPane.setBackground(new Color(255, 147, 0));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel Menu = new JPanel();
Menu.setBackground(new Color(255, 147, 0));
Menu.setBorder(new TitledBorder(new LineBorder(new Color(0, 0, 0)), "Menu", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.setBounds(6, 6, 618, 158);
contentPane.add(Menu);
Menu.setLayout(new GridLayout(0, 3, 0, 0));
JPanel PizzaPrice = new JPanel();
PizzaPrice.setBackground(new Color(255, 147, 0));
PizzaPrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Pizza", TitledBorder.LEADING, TitledBorder.TOP, null, null));
Menu.add(PizzaPrice);
PizzaPrice.setLayout(null);
JLabel PetitPizza = new JLabel("Petit: 6.79$");
PetitPizza.setBounds(17, 21, 72, 16);
PizzaPrice.add(PetitPizza);
JLabel MoyenPizza = new JLabel("Moyen: 8.29$");
MoyenPizza.setBounds(17, 40, 85, 16);
PizzaPrice.add(MoyenPizza);
JLabel LargePizza = new JLabel("Large: 9.49$");
LargePizza.setBounds(17, 59, 85, 16);
PizzaPrice.add(LargePizza);
JLabel ExtraLargePizza = new JLabel("Extra Large: 10.29$");
ExtraLargePizza.setBounds(17, 78, 127, 16);
PizzaPrice.add(ExtraLargePizza);
JLabel FetePizza = new JLabel("Fete: 15.99$");
FetePizza.setBounds(17, 97, 93, 16);
PizzaPrice.add(FetePizza);
JPanel ToppingPrice = new JPanel();
ToppingPrice.setBackground(new Color(255, 147, 0));
ToppingPrice.setLayout(null);
ToppingPrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Toppings", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.add(ToppingPrice);
JLabel Petittopping = new JLabel("Petit: 1.20$");
Petittopping.setBounds(17, 21, 72, 16);
ToppingPrice.add(Petittopping);
JLabel Moyentopping = new JLabel("Moyen: 1.40$");
Moyentopping.setBounds(17, 40, 85, 16);
ToppingPrice.add(Moyentopping);
JLabel Largetopping = new JLabel("Large: 1.60$");
Largetopping.setBounds(17, 59, 85, 16);
ToppingPrice.add(Largetopping);
JLabel ExtraLargetopping = new JLabel("Extra Large: 1.80$");
ExtraLargetopping.setBounds(17, 78, 127, 16);
ToppingPrice.add(ExtraLargetopping);
JLabel Fetetopping = new JLabel("Fete: 2.30$");
Fetetopping.setBounds(17, 97, 93, 16);
ToppingPrice.add(Fetetopping);
JPanel BreuvagePrice = new JPanel();
BreuvagePrice.setBackground(new Color(255, 147, 0));
BreuvagePrice.setLayout(null);
BreuvagePrice.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "Breuvages", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
Menu.add(BreuvagePrice);
JLabel Pop = new JLabel("Pop: 1.10$");
Pop.setBounds(17, 21, 72, 16);
BreuvagePrice.add(Pop);
JLabel Jus = new JLabel("Jus: 1.35$");
Jus.setBounds(17, 40, 85, 16);
BreuvagePrice.add(Jus);
JLabel Eau = new JLabel("Eau: 1.00$");
Eau.setBounds(17, 59, 85, 16);
BreuvagePrice.add(Eau);
JPanel PizzaSelect = new JPanel();
PizzaSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
PizzaSelect.setBackground(new Color(255, 147, 0));
PizzaSelect.setBounds(16, 187, 350, 300);
contentPane.add(PizzaSelect);
PizzaSelect.setLayout(null);
JComboBox<String> ChoixPizza = new JComboBox<String>();
ChoixPizza.setModel(new DefaultComboBoxModel(PizzaSize.values()));
ChoixPizza.setBounds(44, 8, 126, 27);
ChoixPizza.setMaximumRowCount(5);
PizzaSelect.add(ChoixPizza);
NumPizza = new JTextField();
NumPizza.setText("0");
NumPizza.setBounds(175, 8, 130, 26);
PizzaSelect.add(NumPizza);
NumPizza.setColumns(10);
JLabel PizzaIcon = new JLabel("");
PizzaIcon.setBounds(6, 6, 350, 279);
PizzaSelect.add(PizzaIcon);
PizzaIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/PizzaImage.png")));
JPanel ToppingSelect;
ToppingSelect = new JPanel();
ToppingSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
ToppingSelect.setBackground(new Color(255, 147, 0));
ToppingSelect.setBounds(400, 187, 208, 129);
contentPane.add(ToppingSelect);
ToppingSelect.setLayout(null);
JComboBox<String> ChoixTopping = new JComboBox<String>();;
ChoixTopping.setModel(new DefaultComboBoxModel(ToppingSize.values()));
ChoixTopping.setBounds(41, 8, 126, 27);
ChoixTopping.setMaximumRowCount(5);
ToppingSelect.add(ChoixTopping);
NumTopping = new JTextField();
NumTopping.setText("0");
NumTopping.setBounds(39, 40, 130, 26);
NumTopping.setColumns(10);
ToppingSelect.add(NumTopping);
JLabel ToppingIcon = new JLabel("");
ToppingIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/ToppingImage.png")));
ToppingIcon.setBounds(6, 8, 208, 109);
ToppingSelect.add(ToppingIcon);
JPanel BreuvageSelect = new JPanel();
BreuvageSelect.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
BreuvageSelect.setBackground(new Color(255, 147, 0));
BreuvageSelect.setBounds(400, 358, 208, 129);
contentPane.add(BreuvageSelect);
BreuvageSelect.setLayout(null);
JComboBox<String> ChoixBreuvage = new JComboBox<String>();;
ChoixBreuvage.setModel(new DefaultComboBoxModel(Breuvages.values()));
ChoixBreuvage.setBounds(64, 8, 79, 27);
ChoixBreuvage.setMaximumRowCount(3);
BreuvageSelect.add(ChoixBreuvage);
NumBreuvage = new JTextField();
NumBreuvage.setText("0");
NumBreuvage.setBounds(39, 40, 130, 26);
NumBreuvage.setColumns(10);
BreuvageSelect.add(NumBreuvage);
JLabel BreuvageIcon = new JLabel("");
BreuvageIcon.setIcon(new ImageIcon(PizzaOrder.class.getResource("/Image/BreuvageImage.png")));
BreuvageIcon.setBounds(0, 0, 209, 129);
BreuvageSelect.add(BreuvageIcon);
Ajouter = new JButton("Ajouter");
Ajouter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// retrieve selected values from combo boxes
PizzaSize selectedPizzaSize = (PizzaSize) ChoixPizza.getSelectedItem();
ToppingSize selectedToppingSize = (ToppingSize) ChoixTopping.getSelectedItem();
Breuvages selectedBreuvage = (Breuvages) ChoixBreuvage.getSelectedItem();
int numPizza = Integer.parseInt(NumPizza.getText());
int numTopping = Integer.parseInt(NumTopping.getText());
int numBreuvage = Integer.parseInt(NumBreuvage.getText());
// calculate total amount
totales += selectedPizzaSize.getPrice() * numPizza;
totales += selectedToppingSize.getPrice() * numTopping;
totales += selectedBreuvage.getPrice() * numBreuvage;
double historytotal = (numPizza * selectedPizzaSize.getPrice()) + (numTopping * selectedToppingSize.getPrice() + (numBreuvage * selectedBreuvage.getPrice()));
String historyEntry = numPizza + " Pizza de taille " + selectedPizzaSize + " avec " + numTopping + " " + selectedToppingSize + " \ngarniture - Cout: " + historytotal;
// clear text fields
NumPizza.setText("0");
NumTopping.setText("0");
NumBreuvage.setText("0");
}
});
Ajouter.setBounds(234, 552, 160, 50);
contentPane.add(Ajouter);
JButton Quitter = new JButton("Quitter");
Quitter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
Quitter.setBounds(33, 552, 160, 50);
contentPane.add(Quitter);
JButton Payer = new JButton("Payer");
Payer.setBounds(431, 552, 160, 50);
contentPane.add(Payer);
Payer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Receipt receiptWindow = new Receipt(totales, History);
receiptWindow.setVisible(true);
setVisible(false);
}
});
}
}
import java.awt.EventQueue;
public class Receipt extends JFrame {
private double totales;
private String history;
private JPanel contentPane;
private JTable table;
private DefaultTableModel model;
private static String previousHistory;
public Receipt(double totales, String history) {
this.totales = totales;
this.history=history;
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 680, 440);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(81, 23, 496, 368);
panel.setBackground(new Color(254, 255, 255));
panel.setBorder(null);
contentPane.add(panel);
panel.setLayout(null);
JLabel Order = new JLabel("Commande:");
Order.setHorizontalAlignment(SwingConstants.CENTER);
Order.setFont(new Font("Zapfino", Font.PLAIN, 13));
Order.setBounds(118, 24, 283, 29);
panel.add(Order);
String formattedTotal = String.format("%.2f", totales * 1.13);
JLabel Total = new JLabel("Total +Tax: " + formattedTotal);
Total.setFont(new Font("Lucida Grande", Font.BOLD, 13));
Total.setBounds(147, 283, 182, 21);
panel.add(Total);
Total.setVisible(false);
JTextArea commandArea = new JTextArea();
commandArea.setFont(new Font("Monospaced", Font.PLAIN, 12));
commandArea.setEditable(false);
commandArea.setLineWrap(true);
commandArea.setText(history);
JScrollPane scrollPane = new JScrollPane(commandArea);
scrollPane.setBounds(86, 78, 315, 168);
panel.add(scrollPane);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
commandArea.setPreferredSize(new Dimension(300, 200));
JLabel Commande = new JLabel(history);
Commande.setHorizontalAlignment(SwingConstants.LEFT);
Commande.setVerticalAlignment(SwingConstants.TOP);
Commande.setBounds(86, 78, 315, 168);
panel.add(Commande);
JButton modifierCommande = new JButton("Modifier commande");
modifierCommande.setBounds(6, 316, 182, 29);
panel.add(modifierCommande);
modifierCommande.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
PizzaOrder PizzaOrderWindow = new PizzaOrder(previousHistory);
PizzaOrderWindow.setVisible(true);
}
});
JButton Quitter = new JButton("Fermer");
Quitter.setBounds(367, 316, 101, 29);
panel.add(Quitter);
JLabel Totale = new JLabel("Total: " + totales);
Totale.setFont(new Font("Lucida Grande", Font.BOLD, 13));
Totale.setBounds(147, 262, 86, 21);
panel.add(Totale);
JButton btntax = new JButton("+Tax(13%)");
btntax.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Total.setVisible(true);
}
});
btntax.setBounds(228, 259, 101, 29);
panel.add(btntax);
Quitter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
Total.setVisible(false);
}
});
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Receipt frame = new Receipt(0,"");
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
|
2a24b768c4fc9d571f5f160bd4bc5b00
|
{
"intermediate": 0.34704896807670593,
"beginner": 0.41011470556259155,
"expert": 0.2428363561630249
}
|
7,121
|
code java app for android that when started opens tcp socket connection. Implement this functionality in separate thread and encapsulate the functionality in separate class called networkconnection
|
5324e195d6614aaa6af27c9e33de8c29
|
{
"intermediate": 0.3954944610595703,
"beginner": 0.3594651222229004,
"expert": 0.24504047632217407
}
|
7,122
|
this is a script for a service selling google reviews: “Hello, As I see that you do not have many positive reviews on Google Maps, which means that you will not be able to get new customers, But the good news today is that I can increase this to any number of five-star reviews you want, 100% real reviews with a lifetime money back guarantee, And of course you can write the reviews you want us to add
Getting google maps reviews from your customers has always been a beneficial exercise for business, but today its importance is even greater. Let’s attract new customers by making your business in the first Google search results, 72% of customers will take action only after reading a positive online review.”, make a better cold calling script based on an overly concerned client. Make sure to mention that we're a small business concerned with business development and that we handpick our clients whom's business has more potential than it currently has. but in a better, more professional tone.
|
bbe45e7c4df3daf7301af3f8269eacf9
|
{
"intermediate": 0.3553157448768616,
"beginner": 0.3793576955795288,
"expert": 0.2653265595436096
}
|
7,123
|
I want, in my python program, delete a specific line of the windows command interpreter
|
244e3a0ab5bfa5b9478dbbdf2b6ba534
|
{
"intermediate": 0.32732152938842773,
"beginner": 0.17527508735656738,
"expert": 0.4974033534526825
}
|
7,124
|
in python how do I fit using polyfit a 1st order polinomial?
|
a5f43c8c9075ab5e1181f5dd021cd697
|
{
"intermediate": 0.3041827380657196,
"beginner": 0.10819888859987259,
"expert": 0.5876184105873108
}
|
7,125
|
Give me the html code to include a link code with the image and description in this format embed?url=
|
dd5a95d28e20789fc3516d5bbbf93a93
|
{
"intermediate": 0.39622458815574646,
"beginner": 0.21804285049438477,
"expert": 0.3857325613498688
}
|
7,126
|
This is my current ide code for highsum game:
"import GUIExample.GameTableFrame;
import Model.*;
public class GUIExample {
private Dealer dealer;
private Player player;
private GameTableFrame app;
public GUIExample() {
}
public void run() {
dealer.shuffleCards();
app = new GameTableFrame(dealer, player);
app.run();
}
public static void main(String[] args) {
LoginDialog loginDialog = new LoginDialog(null);
loginDialog.setVisible(true);
if (loginDialog.isLoggedIn()) {
String login = loginDialog.getLogin();
String password = loginDialog.getPassword();
GUIExample example = new GUIExample();
example.dealer = new Dealer();
example.player = new Player(login, password, 10000);
example.run();
}
}
}
import Model.*;
import Controller.*;
import View.*;
public class HighSum {
private Dealer dealer;
private Player player;
private ViewController view;
private GameController gc;
public HighSum() {
}
public void init(String login, String password) {
//create all the required objects
this.dealer = new Dealer();
this.player = new Player(login, password, 50);
this.view = new ViewController();
//bring them together
this.gc = new GameController(this.dealer, this.player, this.view);
}
public void run() {
//starts the game!
gc.run();
}
public static void main(String[] args) {
LoginDialog loginDialog = new LoginDialog(null);
loginDialog.setVisible(true);
if (loginDialog.isLoggedIn()) {
String login = loginDialog.getLogin();
String password = loginDialog.getPassword();
HighSum highSum = new HighSum();
highSum.init(login, password);
highSum.run();
}
}
}
Controller package:
package Controller;
import Model.Dealer;
import Model.Player;
import View.ViewController;
public class GameController {
private Dealer dealer;
private Player player;
private ViewController view;
private int chipsOnTable;
public GameController(Dealer dealer,Player player,ViewController view) {
this.dealer = dealer;
this.player = player;
this.view = view;
this.chipsOnTable = 0;
}
public void run() {
boolean carryOn= true;
while(carryOn) {
runOneRound();
char r = this.view.getPlayerNextGame();
if(r=='n') {
carryOn = false;
}
}
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayExitGame();
}
public void runOneRound() {
this.view.displayGameTitle();
this.view.displayDoubleLine();
this.view.displayPlayerNameAndChips(this.player);
this.view.displaySingleLine();
this.view.displayGameStart();
this.view.displaySingleLine();
this.dealer.shuffleCards();
this.chipsOnTable = 0;
boolean playerQuit = false;
for(int round = 1;round<=4;round++) {
this.view.displaySingleLine();
this.view.displayDealerDealCardsAndGameRound(round);
this.view.displaySingleLine();
if(round==1) {//round 1 deal extra card
this.dealer.dealCardTo(this.player);
this.dealer.dealCardTo(this.dealer);
}
this.dealer.dealCardTo(this.player);
this.dealer.dealCardTo(this.dealer);
this.view.displayPlayerCardsOnHand(this.dealer);
this.view.displayBlankLine();
this.view.displayPlayerCardsOnHand(player);
this.view.displayPlayerTotalCardValue(player);
int whoCanCall = this.dealer.determineWhichCardRankHigher(dealer.getLastCard(), player.getLastCard());
if(whoCanCall==1) {//dealer call
int chipsToBet = this.view. getDealerCallBetChips();
//ask player want to follow?
char r = this.view.getPlayerFollowOrNot(this.player,chipsToBet);
if(r=='y') {
this.player.deductChips(chipsToBet);
this.chipsOnTable+=2*chipsToBet;
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayBetOntable(this.chipsOnTable);
}else {
playerQuit = true;
break;
}
}else {//player call
if(round==1) {//round 1 player cannot quit
int chipsToBet = view.getPlayerCallBetChip(this.player);
this.player.deductChips(chipsToBet);
this.chipsOnTable+=2*chipsToBet;
this.view.displayBetOntable(this.chipsOnTable);
}else {
char r = this.view.getPlayerCallOrQuit();
if(r=='c') {
int chipsToBet = view.getPlayerCallBetChip(this.player);
this.player.deductChips(chipsToBet);
this.chipsOnTable+=2*chipsToBet;
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayBetOntable(this.chipsOnTable);
}else {
playerQuit = true;
break;
}
}
}
}
//check who win
if(playerQuit) {
this.view.displayPlayerNameAndLeftOverChips(this.player);
this.view.displayPlayerQuit();
}
else if(this.player.getTotalCardsValue()>this.dealer.getTotalCardsValue()) {
this.view.displayPlayerWin(this.player);
this.player.addChips(chipsOnTable);
this.chipsOnTable=0;
this.view.displayPlayerNameAndLeftOverChips(this.player);
}else if(this.player.getTotalCardsValue()<this.dealer.getTotalCardsValue()) {
this.view.displayDealerWin();
this.view.displayPlayerNameAndLeftOverChips(this.player);
}else {
this.view.displayTie();
this.player.addChips(chipsOnTable/2);
this.view.displayPlayerNameAndLeftOverChips(this.player);
}
//put all the cards back to the deck
dealer.addCardsBackToDeck(dealer.getCardsOnHand());
dealer.addCardsBackToDeck(player.getCardsOnHand());
dealer.clearCardsOnHand();
player.clearCardsOnHand();
}
}
package GUIExample;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginDialog extends JDialog {
private JTextField loginField;
private JPasswordField passwordField;
private JButton loginButton;
private boolean loggedIn = false;
public LoginDialog(JFrame parent) {
super(parent, "Login", true);
loginField = new JTextField(20);
passwordField = new JPasswordField(20);
loginButton = new JButton("Login");
loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
loggedIn = true;
dispose();
}
});
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2));
panel.add(new JLabel("Login:"));
panel.add(loginField);
panel.add(new JLabel("Password:"));
panel.add(passwordField);
panel.add(loginButton);
add(panel);
pack();
setLocationRelativeTo(parent);
}
public String getLogin() {
return loginField.getText();
}
public String getPassword() {
return new String(passwordField.getPassword());
}
public boolean isLoggedIn() {
return loggedIn;
}
}
package GUIExample;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import Model.*;
package GUIExample;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import Model.*;
public class GameTableFrame extends JFrame{
private GameTablePanel gameTablePanel;
private Dealer dealer;
private Player player;
private int count=0;
private JButton playButton;
private JButton quitButton;
public GameTableFrame(Dealer dealer, Player player)
{
this.dealer = dealer;
this.player = player;
gameTablePanel = new GameTablePanel(dealer,player);
this.count=0;
playButton = new JButton("Play");
quitButton = new JButton("Quit");
playButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Call run() when playButton is clicked
run();
}
});
quitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Close the program when quitButton is clicked
System.exit(0);
}
});
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(playButton);
buttonsPanel.add(quitButton);
add(gameTablePanel, BorderLayout.CENTER);
add(buttonsPanel, BorderLayout.SOUTH);
pack();
setVisible(true);
}
public void updateGameTable()
{
gameTablePanel.repaint();
}
public void run() {
JLabel shufflingLabel = new JLabel("Shuffling");
shufflingLabel.setHorizontalAlignment(SwingConstants.CENTER);
add(shufflingLabel, BorderLayout.NORTH);
for (int i = 0; i < 5; i++) {
dealer.dealCardTo(dealer);
dealer.dealCardTo(player);
updateGameTable();
pause(); // You can adjust the pause duration to control the shuffling speed
}
remove(shufflingLabel); // Remove the shuffling label after dealing all cards
updateGameTable();
}
//pause for 500msec
private void pause() {
try{
Thread.sleep(500);
}catch(Exception e){}
}
}
package GUIExample;
import java.awt.*;
import javax.swing.*;
import Model.*;
public class GameTablePanel extends JPanel {
private Player player;
private Dealer dealer;
private ImageIcon cardBackImage;
public GameTablePanel(Dealer dealer, Player player) {
setBackground(Color.GREEN);
setPreferredSize(new Dimension(1024, 768));
cardBackImage = new ImageIcon("images/back.png");
this.dealer = dealer;
this.player = player;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
int x = 50;
int y = 70;
int i = 0;
for (Card c : dealer.getCardsOnHand()) {
// display dealer cards
if (i == 0d) {
cardBackImage.paintIcon(this, g, x, y);
i++;
} else {
c.paintIcon(this, g, x, y);
}
x += 200;
}
// display player cards
x = 50;
y = 550;
for (Card c : player.getCardsOnHand()) {
// display dealer cards
c.paintIcon(this, g, x, y);
x += 200;
}
}
}
Helper Package:
package Helper;
public class Keyboard {
public static String readString(String prompt) {
System.out.print(prompt);
return new java.util.Scanner(System.in).nextLine();
}
public static int readInt(String prompt) {
int input = 0;
boolean valid = false;
while (!valid) {
try {
input = Integer.parseInt(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
System.out.println("*** Please enter an integer ***");
}
}
return input;
}
public static double readDouble(String prompt) {
double input = 0;
boolean valid = false;
while (!valid) {
try {
input = Double.parseDouble(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
System.out.println("*** Please enter a double ***");
}
}
return input;
}
public static float readFloat(String prompt) {
float input = 0;
boolean valid = false;
while (!valid) {
try {
input = Float.parseFloat(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
System.out.println("*** Please enter a float ***");
}
}
return input;
}
public static long readLong(String prompt) {
long input = 0;
boolean valid = false;
while (!valid) {
try {
input = Long.parseLong(readString(prompt));
valid = true;
} catch (NumberFormatException e) {
e.printStackTrace();
System.out.println("*** Please enter a long ***");
}
}
return input;
}
public static char readChar(String prompt,char[] choices) {
boolean validChoice = false;
char r = ' ';
while(!validChoice) {
r = Keyboard.readChar(prompt+" "+charArrayToString(choices)+":");
if(!validateChoice(choices,r)) {
System.out.println("Invalid input");
}else {
validChoice = true;
}
}
return r;
}
private static String charArrayToString(char[] charArray) {
String s = "[";
for(int i=0;i<charArray.length;i++) {
s+=charArray[i];
if(i!=charArray.length-1) {
s+=",";
}
}
s += "]";
return s;
}
private static boolean validateChoice(char[] choices, char choice) {
boolean validChoice = false;
for(int i=0;i<choices.length;i++) {
if(choices[i]==choice) {
validChoice = true;
break;
}
}
return validChoice;
}
public static char readChar(String prompt) {
char input = 0;
boolean valid = false;
while (!valid) {
String temp = readString(prompt);
if (temp.length() != 1) {
System.out.println("*** Please enter a character ***");
} else {
input = temp.charAt(0);
valid = true;
}
}
return input;
}
public static boolean readBoolean(String prompt) {
boolean valid = false;
while (!valid) {
String input = readString(prompt);
if (input.equalsIgnoreCase("yes") || input.equalsIgnoreCase("y") || input.equalsIgnoreCase("true")
|| input.equalsIgnoreCase("t")) {
return true;
} else if (input.equalsIgnoreCase("no") || input.equalsIgnoreCase("n") || input.equalsIgnoreCase("false")
|| input.equalsIgnoreCase("f")) {
return false;
} else {
System.out.println("*** Please enter Yes/No or True/False ***");
}
}
return false;
}
public static java.util.Date readDate(String prompt) {
java.util.Date date = null;
boolean valid = false;
while (!valid) {
try {
String input = readString(prompt).trim();
if (input.matches("\\d\\d/\\d\\d/\\d\\d\\d\\d")) {
int day = Integer.parseInt(input.substring(0, 2));
int month = Integer.parseInt(input.substring(3, 5));
int year = Integer.parseInt(input.substring(6, 10));
java.util.Calendar cal = java.util.Calendar.getInstance();
cal.setLenient(false);
cal.set(year, month - 1, day, 0, 0, 0);
date = cal.getTime();
valid = true;
} else {
System.out.println("*** Please enter a date (DD/MM/YYYY) ***");
}
} catch (IllegalArgumentException e) {
System.out.println("*** Please enter a date (DD/MM/YYYY) ***");
}
}
return date;
}
private static String quit = "0";
public static int getUserOption(String title, String[] menu) {
displayMenu(title, menu);
int choice = Keyboard.readInt("Enter Choice --> ");
while (choice > menu.length || choice < 0) {
choice = Keyboard.readInt("Invalid Choice, Re-enter --> ");
}
return choice;
}
private static void displayMenu(String title, String[] menu) {
line(80, "=");
System.out.println(title.toUpperCase());
line(80, "-");
for (int i = 0; i < menu.length; i++) {
System.out.println("[" + (i + 1) + "] " + menu[i]);
}
System.out.println("[" + quit + "] Quit");
line(80, "-");
}
public static void line(int len, String c) {
System.out.println(String.format("%" + len + "s", " ").replaceAll(" ", c));
}
}
package Helper;
import java.security.MessageDigest;
public class Utility {
public static String getHash(String base)
{
String message="";
try{
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(base.getBytes("UTF-8"));
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if(hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
message = hexString.toString();
} catch(Exception ex){
throw new RuntimeException(ex);
}
return message;
}
public static void printLine(int num)
{
printLine(num,'-');
}
public static void printDoubleLine(int num)
{
printLine(num,'=');
}
public static void printLine(int num,char pattern)
{
for(int i =0;i<num;i++)
{
System.out.print(pattern);
}
System.out.println("");
}
}
Model Package:
package Model;
import javax.swing.*;
public class Card extends ImageIcon{
private String suit;
private String name;
private int value;
//used for card ranking - see below
//to determine which card has higher power to determine who can call.
private int rank;
public Card(String suit, String name, int value,int rank) {
super("images/"+suit+name+".png");
this.suit = suit;
this.name = name;
this.value = value;
this.rank = rank;
}
public String getSuit() {
return this.suit;
}
public String getName() {
return this.name;
}
public int getValue() {
return this.value;
}
public int getRank() {
return this.rank;
}
public String toString() {
return "<"+this.suit+" "+this.name+">";
}
public String display() {
return "<"+this.suit+" "+this.name+" "+this.rank+">";
}
}
//card rank
// D C H S
//1 1 2 3 4
//2 5 6 7 8
//3 9 10 11 12
//4 13 14 15 16
//5 17 18 19 20
//6 21 22 23 24
//7 25 26 27 28
//8 29 30 31 32
//9 33 34 35 36
//10 37 38 39 40
//J 41 42 43 44
//Q 45 46 47 48
//K 49 50 51 52
package Model;
import java.util.*;
public class Dealer extends Player{
private Deck deck;
public Dealer() {
super("Dealer","",0);
deck = new Deck();
}
public void shuffleCards() {
System.out.println("Dealer shuffle deck");
deck.shuffle();
}
public void dealCardTo(Player player) {
Card card = deck.dealCard();//take a card out from deck
player.addCard(card);//pass the card into player
}
public void addCardsBackToDeck(ArrayList<Card> cards) {
deck.appendCard(cards);
}
//return 1 if card1 rank higher, else return 2
public int determineWhichCardRankHigher(Card card1, Card card2) {
if(card1.getRank()>card2.getRank()) {
return 1;
}else {
return 2;
}
}
}
package Model;
import java.util.*;
public class Deck {
private ArrayList<Card> cards;
public Deck() {
cards = new ArrayList<Card>();
String[] suits = { "Diamond", "Club","Heart","Spade", };
for (int i = 0; i < suits.length; i++) {
String suit = suits[i];
Card card = new Card(suit, "Ace", 1,1+i);
cards.add(card);
int c = 5;
for (int n = 2; n <= 10; n++) {
Card oCard = new Card(suit, "" + n, n,c+i);
cards.add(oCard);
c+=4;
}
Card jackCard = new Card(suit, "Jack", 10,41+i);
cards.add(jackCard);
Card queenCard = new Card(suit, "Queen", 10,45+i);
cards.add(queenCard);
Card kingCard = new Card(suit, "King", 10,49+i);
cards.add(kingCard);
}
}
public Card dealCard() {
return cards.remove(0);
}
//add back one card
public void appendCard(Card card) {
cards.add(card);
}
//add back arraylist of cards
public void appendCard(ArrayList<Card> cards) {
for(Card card: cards) {
this.cards.add(card);
}
}
public void shuffle() {
Random random = new Random();
for(int i=0;i<10000;i++) {
int indexA = random.nextInt(cards.size());
int indexB = random.nextInt(cards.size());
Card cardA = cards.get(indexA);
Card cardB = cards.get(indexB);
cards.set(indexA, cardB);
cards.set(indexB, cardA);
}
}
//for internal use only
private void showCards() {
for (Card card : cards) {
System.out.println(card);
}
}
//for internal use only
private void displayCards() {
for (Card card : cards) {
System.out.println(card.display());
}
}
public static void main(String[] args) {
Deck deck = new Deck();
//deck.shuffle();
/*Card card1 = deck.dealCard();
Card card2 = deck.dealCard();
Card card3 = deck.dealCard();
deck.showCards();
ArrayList<Card> cards = new ArrayList<Card>();
cards.add(card1);
cards.add(card2);
cards.add(card3);
deck.appendCard(cards);
System.out.println();*/
deck.displayCards();
}
}
//card rank
//D C H S
//1 1 2 3 4
//2 5 6 7 8
//3 9 10 11 12
//4 13 14 15 16
//5 17 18 19 20
//6 21 22 23 24
//7 25 26 27 28
//8 29 30 31 32
//9 33 34 35 36
//10 37 38 39 40
//J 41 42 43 44
//Q 45 46 47 48
//K 49 50 51 52
package Model;
import java.util.*;
public class Player extends User{
private int chips;
protected ArrayList<Card> cardsOnHand;
public Player(String loginName, String password, int chips) {
super(loginName, password);
this.chips = chips;
this.cardsOnHand = new ArrayList<Card>();
}
public int getChips() {
return this.chips;
}
public void addChips(int amount) {
this.chips+=amount;//no error check
}
public void deductChips(int amount) {
this.chips-=amount;//no error check
}
public void addCard(Card card) {
this.cardsOnHand.add(card);
}
public ArrayList<Card> getCardsOnHand() {
return this.cardsOnHand;
}
public int getTotalCardsValue() {
int total = 0;
for(Card card: this.cardsOnHand) {
total+=card.getValue();
}
return total;
}
public Card getLastCard() {
return this.cardsOnHand.get(this.cardsOnHand.size()-1);
}
public void clearCardsOnHand() {
this.cardsOnHand.clear();
}
//Think of the action that a player can take
//implement more related methods here
public static void main(String[] args) {
// TODO Auto-generated method stub
Player player = new Player("IcePeak","A",100);
System.out.println(player.getChips());
player.deductChips(10);
System.out.println(player.getChips());
player.addChips(20);
System.out.println(player.getChips());
}
}
package Model;
import Helper.*;
abstract public class User {
private String loginName;
private String hashPassword;
public User(String loginName, String password) {
this.loginName = loginName;
this.hashPassword = Utility.getHash(password);
}
public String getLoginName() {
return this.loginName;
}
public boolean checkPassword(String password) {
return this.hashPassword.equals(Utility.getHash(password));
}
}
View Package:
package View;
import Helper.Keyboard;
import Model.*;
//all input and output should be done view ViewController
//so that it is easier to implement GUI later
public class ViewController {
public void displayExitGame() {
System.out.println("Thank you for playing HighSum game");
}
public void displayBetOntable(int bet) {
System.out.println("Bet on table : "+bet);
}
public void displayPlayerWin(Player player) {
System.out.println(player.getLoginName()+" Wins!");
}
public void displayDealerWin() {
System.out.println("Dealer Wins!");
}
public void displayTie() {
System.out.println("It is a tie!.");
}
public void displayPlayerQuit() {
System.out.println("You have quit the current game.");
}
public void displayPlayerCardsOnHand(Player player) {
System.out.println(player.getLoginName());
if(player instanceof Dealer) {
for(int i=0;i<player.getCardsOnHand().size();i++) {
if(i==0) {
System.out.print("<HIDDEN CARD> ");
}else {
System.out.print(player.getCardsOnHand().get(i).toString()+" ");
}
}
}else {
for(Card card:player.getCardsOnHand()) {
System.out.print(card+" ");
}
}
System.out.println();
}
public void displayBlankLine() {
System.out.println();
}
public void displayPlayerTotalCardValue(Player player) {
System.out.println("Value:"+player.getTotalCardsValue());
}
public void displayDealerDealCardsAndGameRound(int round) {
System.out.println("Dealer dealing cards - ROUND "+round);
}
public void displayGameStart() {
System.out.println("Game starts - Dealer shuffle deck");
}
public void displayPlayerNameAndChips(Player player) {
System.out.println(player.getLoginName()+", You have "+player.getChips()+" chips");
}
public void displayPlayerNameAndLeftOverChips(Player player) {
System.out.println(player.getLoginName()+", You are left with "+player.getChips()+" chips");
}
public void displayGameTitle() {
System.out.println("HighSum GAME");
}
public void displaySingleLine() {
for(int i=0;i<30;i++) {
System.out.print("-");
}
System.out.println();
}
public void displayDoubleLine() {
for(int i=0;i<30;i++) {
System.out.print("=");
}
System.out.println();
}
public char getPlayerCallOrQuit() {
char[] choices = {'c','q'};
char r = Keyboard.readChar("Do you want to [c]all or [q]uit?:",choices);
return r;
}
public char getPlayerFollowOrNot(Player player, int dealerBet) {
boolean validChoice = false;
char[] choices = {'y','n'};
char r = 'n';
while(!validChoice) {
r = Keyboard.readChar("Do you want to follow?",choices);
//check if player has enff chips to follow
if(r=='y' && player.getChips()<dealerBet) {
System.out.println("You do not have enough chips to follow");
displayPlayerNameAndChips(player);
}else {
validChoice = true;
}
}
return r;
}
public char getPlayerNextGame() {
char[] choices = {'y','n'};
char r = Keyboard.readChar("Next game?",choices);
return r;
}
public int getPlayerCallBetChip(Player player) {
boolean validBetAmount = false;
int chipsToBet = 0;
while(!validBetAmount) {
chipsToBet = Keyboard.readInt("Player call, state bet:");
if(chipsToBet<0) {
System.out.println("Chips cannot be negative");
}else if(chipsToBet>player.getChips()) {
System.out.println("You do not have enough chips");
}else {
validBetAmount = true;
}
}
return chipsToBet;
}
public int getDealerCallBetChips() {
System.out.println("Dealer call, state bet: 10");
return 10;
}
}"
These are the requirements:
“On completion of this assignment a student should be able to write a Java application that: • Makes use of Java API "Swing" and "AWT" packages • Handles generated events • Makes use of layout manager to organize the GUI components • Know how to apply and design a program using object-oriented concepts 2. Task Enhance the one player Java game application "HighSum" done in Assignment 1 with Graphical User Interface (GUI). 2.1 Login The game starts by the player logging into the game. Page 2 Copyright SCIT, University of Wollongong, 2023 2.2 Play Game The game starts after the player click on “Login”. First, the dealer will shuffles the deck. (You may include animation in this frame to simulate “shuffle” effect as enhancement.) Then the dealer deals two cards from the top of the deck to the player and itself. Since the player’s last card is higher than the dealer’s last card, the player gets to Call the game. Assume the player states 10 as the bet chips. The player’s chip will be deducted by 10. Page 3 Copyright SCIT, University of Wollongong, 2023 The chips on table will be updated to 20 and the dealer deals cards for next round. Assume the dealer’s last card is higher than the player’s last card. The dealer Call the game and the player gets to choose to Follow or Quit the game. If the player follows the game, 10 chips will be deducted from the player’s balance chips. (Asumme the dealer place 10 chips.) The games carry on for maximum of four rounds. In the last round, the player with the highest total sum wins the game. And the game continues until the player exits the game. "
after logging in, display the word “Shuffling” when dealing the cards.
label the top side of the cards dealt to be dealer’s card and the bottom to be Player’s card
Also, label the deck below as “Deck”
The dealer’s first dealt card is hidden faced down
“Chips on the table:” is also display in the middle of the game display
print the full GameTablePanel class after making the changes
|
fc7b233d919c1884401f1a92a6c08921
|
{
"intermediate": 0.2906542420387268,
"beginner": 0.4795202910900116,
"expert": 0.2298254817724228
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.