I'm Working on the following Component:
import {BudgetItem} from "../models/budget.model";
import {Injectable} from "#angular/core";
import {FirebaseListObservable, AngularFire, FirebaseObjectObservable} from "angularfire2";
#Injectable()
export class BudgetService{
public ausgaben:number;
public einnahmen:number;
public budgetArray = [];
private budget:FirebaseListObservable<any>;
private budgetItemToUpdate;
constructor(private af:AngularFire){
this.budget = af.database.list('/Budget');
this.ausgaben = this.getAusgaben();
this.einnahmen = this.getEinnahmen();
this.budget.subscribe(items => {
// items is an array
items.forEach(item => {
this.budgetArray.push(new BudgetItem(item.zweck,item.betrag,item.ausgabe));
});
});
}
//Nimmt ein BugetItem als Parameter und fügt dieses der Datenbank als neuen Datensatz bei
addToBuget(item:BudgetItem){
this.budget.push({zweck:item.zweck,betrag:item.betrag,ausgabe:item.ausgabe});
}
//Nimmt den Key eines Objekts und löscht das jewelige Objekt aus der Datenbank
removeFromInventar(key:string){
this.budget.remove(key);
}
//Synchronisiert ein bestehendes Objekt mit der Datenbank
updateBudgetItem(item){
this.budgetItemToUpdate = this.af.database.object("Budget/" + item.$key)
this.budgetItemToUpdate.update({zweck:item.zweck,betrag:item.betrag,ausgabe:item.ausgabe});
}
//berechnet die totalen Einnahmen. Als Anfangswert wird 2500(Budget) gesetzt.
getEinnahmen(){
this.einnahmen = 2500;
console.log(this.budgetArray);
for(let item of this.budgetArray){
if(item.ausgabe === "Einnahme"){
this.einnahmen = this.einnahmen + item.betrag;
}
}
console.log(this.einnahmen);
return this.einnahmen;
}
//berechnet die totalen Ausgaben. Als Anfangswert wird 0 gesetzt.
getAusgaben(){
this.ausgaben = 0;
console.log(this.budgetArray);
for(let item of (this.budgetArray)){
if(item.ausgabe === "Ausgabe"){
this.ausgaben = this.ausgaben + item.betrag;
}
}
console.log("Ausgaben: " + this.ausgaben)
return this.ausgaben;
}
}
I can suggestfully push my items in the array, but I want to add up the itempropertiy "Betrag" of the idividual Objects and display the sum of them.
Where is my Mistake or what kind of suggestions do you have to get the code working?
Here's the gist of it:
af.database.list('/Budget')
// Reduce all the items to a single value.
.map(items => items.reduce((acc, item) => acc + item.betrag, 0))
// Log the total
.do(total => console.log(total));
Hopefully you can adapt this code to your situation. Let me know if you need help.
getEinnahmen(){
this.einnahmen = 0
this.af.database.list("/Budget",{query:{
orderByChild:'ausgabe',
equalTo:'Einnahme'
}}).map(items => items.reduce((acc, item) => acc + item.betrag, 0))
// Log the total
.subscribe(total => {console.log(total);this.einnahmen = total;});
return this.einnahmen+2500;
}
I changed up the code with the reduce-method. Now I'm able to log the total to the console, but now i want to add it as the returnvalue of the method getEinnahmen.
Related
Problem
I am using Nextjs to submit a prompt variable via a <form/> to an api route, which makes a request via the openai library with a responseType: "stream". Then I try to stream the response to the Frontend like this:
answerStream.data
.on("data", (chunk: string) => res.write(chunk))
.on("error", error => {
console.error(error);
res.end();
})
.on("end", () => res.end());
My problem is that while this works, the initial chunks are just ghibberish. For example if I ask for "Ghibberisch", these are the returned first few lines:
G
hib
berGischhib isbert eischine: Sprache E,ine die al steich Spr ausache v,ielen die vers hechieduteen noench Spr leacbt
hen z
usGammhibensberetzisch istt e. Esine ist alte e Sprine Kacheomb,ination a die bisus he itutealienischen no,ch arab inisc ehenin, tigen Teürkiliscenhen der und and Weren Dialektenelt, die z gues eproiner echen winzigirdart. Esigen is Sprtache e verschine semolzen shr alindte.
Spr
After a few paragraphs, this is returned:
Ghibberisch ist eine sehr alte Sprache, die bis heute noch lebt und die viele verschiedene Kulturen verbindet. Es ist eine sehr interessante Sprache, die viele Geschichten und Traditionen beinhaltet und die Menschen, die sie sprechen, möchten sie auch weiterhin bewahren. Wenn Sie mehr über Ghibberisch erfahren möchten, gibt es viele Möglichkeiten, es zu lernen.
So it works, but unfortunately, too late. This is the code on the Frontend:
React.useEffect(() => {
let url = "/api/ai?";
url += Object.keys(request)
.map(key => `${key}=${request[key]}`)
.join("&");
const eventSource = new EventSource(url);
eventSource.addEventListener("message", e => {
try {
if (e.data == "[DONE]") {
eventSource.close();
setSubmitting(false);
} else {
const message = e.data.replace(/^data: /, "");
const messageObject = JSON.parse(message);
setArticle(
state => (state = state + messageObject?.choices[0]?.text)
);
}
} catch (error) {
console.log(error);
}
});
eventSource.addEventListener("close", e => {
console.log("Connection closed with the server");
setSubmitting(false);
});
eventSource.addEventListener("error", e => {
props.setError(e?.message || "Leider ist ein Fehler aufgetreten");
setSubmitting(false);
eventSource.close();
});
}, [request]);
there is a page which is updated every 5-7 seconds, and on it records from the base are updated, but moments these records are duplicated, Do not tell me why this bug can be?
is a ActiveCaller model
namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class ActiveCaller extends Model
{
protected $fillable = ['queue', 'employee_id', 'station', 'state', 'duration',
'client_id', 'last_call'];
public function Employee()
{
return $this->belongsTo(Employee::class);
}
/**
* Convert duration attribute to acceptable format
*
* #param $value
* #return string
*/
public function getDurationAttribute($value)
{
if (empty($value))
return $value;
return $this->sec2hms($value);
}
public function getStateAttribute($value)
{
if (!empty($value))
return trim($value);
return null;
}
/**
* Convert last call attribute to acceptable format
*
* #param $value
* #return string
*/
public function getLastCallAttribute($value)
{
$data = explode("\n", $value);
$result = "";
$i = 0;
$len = count($data) - 1;
foreach ($data as $item) {
$item = str_replace("\r", "", $item);
$delimiter = "</br>";
if ($i == $len)
$delimiter = "";
if (empty($item) || (trim($item) == "No calls yet")) {
$result .= "No calls yet$delimiter";
} else {
$result .= $this->sec2hms($item) . " min. ago $delimiter";
}
$i++;
}
return $result;
}
public function getStationAttribute($value)
{
return str_replace("\r\n", "</br>", $value);
}
private function sec2hms($sec, $padHours = FALSE)
{
$timeStart = Carbon::now();
$timeEnd = Carbon::now()->addSeconds(intval($sec));
return $timeStart->diff($timeEnd)->format('%H:%I:%S');
}
}
is a AmiApiController
class AmiApiController extends Controller
{
public function fetchDashboardData()
{
$this->updateQueueState();
$activeCallers = ActiveCaller::with('Employee')
->where('old', true)
->orderBy('queue')
->orderBy('employee_id')
->orderBy('station', 'asc')
->get();
$waitingList = WaitingList::where('old', false)->get();
$waitingList = $waitingList->unique('client_id');
$charts = Chart::all()->toArray();
$chartFormatData = [
'Total' => [],
'Callers' => [],
'Queues' => [],
];
foreach ($charts as $key => $chart) {
$charts[$key]['data'] = json_decode($chart['data'], 1);
$chartFormatData[$chart['name']]['total'] = 0;
foreach ($charts[$key]['data']['statistic'] as $datum) {
// if ($datum[0] === 'Effort')
// continue;
$chartFormatData[$chart['name']]['label'][] = $datum[0];
$chartFormatData[$chart['name']]['data'][] = $datum[1];
$chartFormatData[$chart['name']]['name'] = $chart['name'];
}
$chartFormatData[$chart['name']]['total'] = array_sum($chartFormatData[$chart['name']]['data']);
// $chartFormatData[$chart['name']]['label'] = array_reverse($chartFormatData[$chart['name']]['label']);
}
return response()->json([
'activeCallers' => $activeCallers,
'charts' => $chartFormatData,
'waitingList' => $waitingList
], 200);
}
this is where we begin to check if we can update the database at this time
/**
* Check whether the database can be updated at this time
*
* - Returns True if no updates are currently being made to the database
* and the latest update was less than 5 seconds later
* -
Returns True if the update already occurs for more than 15 seconds
*
* - Returns False if an update is already in the database
* -
Returns False if the last update was within the last 5 seconds
*
* If the parameter in $ json is passed true (by default)
* the method returns the answer in JSON format
*
* If the parameter is passed false to $ json
* method returns a php-shne Boolean value
*
* #param bool $json
* #return bool|\Illuminate\Http\JsonResponse
*/
public function canWeUpdate($json = true)
{
$result = ['return' => null, 'msg' => null];
$isUpdating = Configuration::where('key', 'is_ami_data_updating')->first();
if (is_null($isUpdating)) {
Configuration::create(['key' => 'is_ami_data_updating', 'value' => 0]);
}
if ($isUpdating->value == true) {
// if an update is currently in progress
$checkingDate = Carbon::now()->addSeconds(-10);
if ($isUpdating->updated_at < $checkingDate) {
// if the update is longer than 15 seconds, we will cancel this update
$isUpdating->update(['value' => false]);
$result['return'] = true;
$result['msg'] = "Old update in database";
} else {
// if the update is less than 15 seconds, we cannot update again
$result['return'] = false;
$result['msg'] = "CURRENTLY UPDATE";
}
} else if ($isUpdating->updated_at > Carbon::now()->addSeconds(-3)) {
// if the last update was less than 5 seconds ago, we cannot update
$result['return'] = false;
$result['msg'] = "TOO EARLY";
} else {
//if the last update was more than 5 seconds ago, we allow the update
$result['return'] = true;
$result['msg'] = "OK";
}
if ($json)
return $this->simpleResponse($result['return'], $result['msg']);
return $result['return'];
}
is a method fot check if new data is in the database
/**
* A method to check if new data is in the database
*
* Returns True if validation time is less than database update time
* Returns False if validation time is longer than database update time
* Returns False if there is no data in the database
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\JsonResponse
*/
public function checkForNewData(Request $request)
{
$date = new Carbon($request->last_call);
$lastRecord = ActiveCaller::latest()->first();
if (is_null($lastRecord))
return $this->simpleResponse(false);
if ($date < $lastRecord->updated_at) {
return $this->simpleResponse(true);
} else
return $this->simpleResponse(false);
}
/**
* Method for loading table data
*
* Agents - information about active numbers in the PBX in all queues
* Waiting - information about numbers in standby mode
*
* #return \Illuminate\Http\JsonResponse
*/
public function renderAgentTable()
{
$agents = ActiveCaller::with('Employee')
->where('old', true)
->orderBy('queue')
->orderBy('station', 'asc')
->get();
$waitingList = WaitingList::all();
$agentsTable = View::make('dashboard.render.agent-table', ['agents' => $agents]);
$waitingTable = View::make('dashboard.render.waiting-list-table', ['waitingList' => $waitingList]);
$result =
[
'agents' => $agentsTable->render(),
'waiting' => $waitingTable->render(),
];
$result = array_merge($result, $this->renderDashboardChart(new Request()));
return response()->json($result);
}
/**
* Method for updating data from AMI
*
* updating data for ActiveCaller
* updating data for WaitingList
*/
public function updateQueueState()
{
if (!$this->canWeUpdate(false)) {
// dd("We can't update (large check)");
return;
}
$lastUpdateTime = ActiveCaller::latest()->first();
if ($lastUpdateTime != null)
if ($lastUpdateTime->created_at > Carbon::now()->addSeconds(-3)) {
// dd("We can't update (small check)");
return;
}
// we notice the launch of the update in the database
$isAmiDataUpdating = Configuration::where('key', 'is_ami_data_updating')->first();
$isAmiDataUpdating->update(['value' => true]);
$this->ClearOldRecords();
$queues = Queue::where('on_dashboard', '=', '1')->get()->toArray();
// we go through all the queues that are available in AMI
foreach ($queues as $queue) {
$command = new AMIQueueMemberState($queue['name']);
// we get a list of numbers and a waiting list of calls
$response = $command->handle();
$agents = $response['agents'];
$callers = $response['callers'];
//convert the waiting list to PeerList
$peerList = PeerInfo::hydrate($agents);
$employees = new Collection();
foreach ($callers as $caller) {
$caller['queue'] = $queue['name'];
WaitingList::create($caller);
}
$peerList->each(function (PeerInfo $peer) use ($employees) {
$record = Record
::where('phone', 'like', '%' . $peer->name . '%')
->where('end_date', null)
->get()->first();
$data = null;
if ($record != null) {
// check if this user already has an entry in active_callers (not old)
$active = ActiveCaller
::where('employee_id', $record['employee_id'])
->where('old', false)
->get()->first();
// if so, add him another number and
// we move on to the next iteration
if ($active != null) {
if ($this->HandleSingleActive($active, $peer->name, $peer->last_call))
return;
}
$peer->station = $record['station_name'];
$peer->employee_id = $record['employee_id'];
$a = collect($peer->toArray());
$data = $a->except(['name', 'pause'])->toArray();
$data['station'] = "$peer->station | $peer->name";
} else {
$peer->station = "- | $peer->name";
$a = collect($peer->toArray());
$data = $a->except(['name', 'pause'])->toArray();
}
ActiveCaller::create($data);
});
}
$this->updateDashboardChart();
$isAmiDataUpdating->update(['value' => false]);
}
I am having an error during the registration of a recruiter for the application I am working for
here is the error I am having in the network while sending the form information :
code:500
error: "Invalid view."
message: "Erreur lors de la création du compte"
here is the code
public function personnal(AccountCreateRequest $request)
{
try {
$http = new \GuzzleHttp\Client;
$exists = false;
$userData = $request->input('user');
$userData['password'] = bcrypt($userData['password']);
$userData['gender'] = ($userData['title'] === 'M.') ? 'm' : 'f';
if (array_get($userData, 'ref')) {
$user = User::where('ref', $userData['ref'])->firstOrFail();
$user->fill($userData);
$exists = true;
} else {
$userData['ref'] = User::generateId();
$user = new User($userData);
}
$user->source = 'website';
$user->optin_platform = 1;
if ($user->role === 'seeker') {
$user->is_active = 1;
$user->save();
$seeker = new UserSeeker([
'registration_date' => Carbon::now(),
'available_in' => 1,
'token' => bin2hex(uniqid(rand())),
'resume_path' => $request->input('seeker.resume_path'),
'resume_date' => Carbon::now(),
]);
$seeker = $user->seeker()->save($seeker);
$seeker->location()->associate(Address::create($request->input('location')))->save();
} else {
$user->is_active = 0;
$user->save();
// $size = $request->input('company.size', $request->session()->get('info'));
$companyData = $request->input('company');
$company = Company::create($companyData);
$recruiter = $user->recruiter()->save(new UserRecruiter([
'company_id' => $company->id,
]));
}
DB::commit();
$this->json['response'] = ['ref' => $user->ref];
$this->json['code'] = $this->code['created'];
dd($this->json);
} catch (MissingParamsException $e) {
DB::rollback();
$this->setError($e, $e->getMessage(), 'missing');
} catch (\Exception $e) {
DB::rollback();
$this->setError($e, 'Erreur lors de la création du compte');
} finally {
return ($this->response());
}
I resolve my issue by changing the is_active parameters to 1
I wrote a controller action that is supposed to add an element (meeting) to the database here it is:
public function newAction(Request $request){
$meeting = new Meeting();
$meetingUser = new MeetingUser();
$project = new Project();
$projectName = "SocialPro";//$request->get('projectName');
echo($projectName);
$users = $this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findProjectUser($projectName);
//$form = $this->createForm('SocialPro\MeetingBundle\Form\MeetingType', $meeting);
//$form->handleRequest($request);
//if ($form->isSubmitted() && $form->isValid()) {
$userconn = $this->container->get('security.token_storage')->getToken()->getUser();
echo($userconn->getId());
if ($request->isMethod('POST')) {
echo("message form");
$role = $this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findUserRole($userconn)[0]['role'];
$date = $request->get('date');
if ($role == "PROJECT_MASTER" || $role == "TEAM_MASTER") {
for ($i = 0; $i < count($users); $i++) {
$meetings = $this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findMeetingUser($users[$i]['id'], $date);
}
if ($meetings == null || count($meetings) == 0) {
$project = $this->getDoctrine()->getRepository('SocialProProjectBundle:Project')->findBy(array("name" = >$projectName));
$meeting->setDescription($request->get('description'));
$meeting->setDate(new \DateTime($request->get('date')));
$meeting->setTime($request->get('time'));
$meeting->setProjectName($request->get('projectName'));
$meeting->setProject($project[0]);
$meetingUser->setMeetings($meeting);
$meetingUser->setUsers($userconn);
var_dump($meetingUser);
$meeting->setMeetingUser(array($meetingUser));
//$project->setMeetings($meeting->getId());
$em = $this->getDoctrine()->getManager();
$em->persist($meeting);
$em->persist($meetingUser);
$em->flush();
// $meetingUser->setUsers($request->get(''));
return $this->redirectToRoute('reunion_show', array('id' = > $meeting->getId()));
}
else {
echo("Membre indisponible");
}
}
else {
echo("Must be MASTER to create meeting");
}
}
return $this->render('SocialProMeetingBundle::ajoutMeeting.html.twig', array('users' = >$users));
// $em = $this->getDoctrine()->getManager();
//$em->persist($meeting);
//$em->flush($meeting);
// return $this->redirectToRoute('meeting_show', array('id' => $meeting->getId()));
//}
//return $this->render('SocialProMeetingBundle:ajouMeeting', array(
// 'meeting' => $meeting,
//'form' => $form->createView(),
//));
}
When I submit the form it gives me a site not available page. I tested it line by line and everything is working perfectly. Turns out the problem is in the
$em->persist($meeting);
And I have no idea how to fix it.
You must call flush immediately after calling persist like so:
$em->persist( $meeting );
$em->flush();
$em->persist( $meetingUser );
$em->flush();
Then it will persist both.
I created a method to export AOT (application object tree) Objects.
It works, but when I export the Forms-Treenodes cant find it.
The method is a server method and it runs on a BatchServer.
My idea was to export the objects as xpo files every 2 hours.
By the backup I can track the Code changes.
void run(str Path)
{
List _ValueList = new List(Types::String);
Counter _ListCounter;
ListIterator _ListIterator;
str _RootFolder;
str _FileName;
str _FolderName;
TreeNode _TreeNode;
TreeNode _InnerTreeNode;
TreeNodeIterator _TreeNodeIt;
FileIoPermission _Perm;
#define.ExportMode("w")
;
_RootFolder = Path;
//Objektbaum definition
_ValueList.addEnd("Forms");
_ValueList.addEnd("Reports");
_ValueList.addEnd("Queries");
_ValueList.addEnd("Classes");
_ValueList.addEnd("Macros");
_ValueList.addEnd("Jobs");
_ValueList.addEnd(#"Data Dictionary\Tables");
_ValueList.addEnd(#"Data Dictionary\Maps");
_ValueList.addEnd(#"Data Dictionary\Views");
_ValueList.addEnd(#"Data Dictionary\Extended Data Types");
_ValueList.addEnd(#"Data Dictionary\Base Enums");
_ListIterator = new ListIterator(_ValueList);
info(strfmt("RootExportPath: %1",_RootFolder));
// durch die zuvor definierte Liste laufen
while(_ListIterator.more())
{
try
{
info(strfmt(#"\%1",_ListIterator.value()));
//Haupttreenode objekt laden
_TreeNode = TreeNode::findNode(strfmt(#"\%1",_ListIterator.value()));
if (_TreeNode != null)
{
//Splitten des HauptNodes
_TreeNodeIt = _TreeNode.AOTiterator();
_InnerTreeNode = _TreeNodeIt.next();
//Durchlaufen der SubNodes
info(strfmt("Object found in Node: %1 ",_TreeNode.AOTchildNodeCount()));
while(_InnerTreeNode)
{
//Pfad und Filename bereitstellen
_FolderName = strfmt(#"%1\%2",_RootFolder,strreplace(_ListIterator.value(),#" ","_"));
_FileName = strfmt(#"\%1.xpo",strreplace(_InnerTreeNode.AOTname(),#" ","_"));
//Fileperms setzen ("w") = Write (OverWrite)
_Perm = new FileIoPermission(_FolderName+_FileName , #ExportMode);
if (_Perm == null)
{
return;
}
_Perm.assert();
try
{
if(!WinApi::pathExists(_FolderName))
{
if(WinApi::createDirectory(_FolderName))
{
throw error(strfmt("Pfad konnte nicht erstellt werden %1\n",_FolderName));
}
if(!WinApi::pathExists(_FolderName))
{
throw error(strfmt("Fehler beim erstellen des Pfades %1\n",_FolderName));
}
}
//Export in definierten Filename
if(WinApi::fileLocked(_FolderName+_FileName))
{
throw error("File ist ReadOnly\n");
}
_InnerTreeNode.treeNodeExport(_Foldername+_FileName);
}
catch
{
error(strfmt(#"xpo File %1 konnte nicht geschrieben werden\n",_FolderName+_Filename));
throw error("Abbruch des Jobs\n");
}
CodeAccessPermission::revertAssert();
_InnerTreeNode = _TreeNodeIt.next();
}
// BP deviation documented.
_TreeNode.treeNodeExport(_FileName);
}
else
{
error(strfmt("TreeNode empty %1",_ListIterator.value()));
}
}
catch
{
throw error("Fehler in der Verarbeitungsroutine\n");
}
_ListIterator.next();
}
}
Does the Forms folder exist in your export location?
You are attempting to assert permissions on a folder BEFORE checking it exists and creating it.
Forms can no be exported by a batch-server because the form's ar not loadet.
This ist a litle bit strange but the batchserver calls only class layer in AOT... the Forms ar hirarchical top of it and so on not exportable.