content
stringlengths
228
999k
pred_label
stringclasses
1 value
pred_score
float64
0.5
1
Linked Questions 1 vote 1answer 41 views Is this a bug or a question? [duplicate] Possible Duplicate: What to do with questions that describe bugs? An user ask this 12.04 after latest update, no unity, no top bar, only wallpaper. Can you help? And I answer him. In that case, I ... 72 votes 11answers 3k views What prewritten Pro-forma (aka AutoReviewComments) userscript comments can we use and share? I'd like to gather a list of boilerplate comments (AKA canned responses) for Ask Ubuntu which can be used in combination with the awesome Pro-forma comments userscript. Post suggestions too, you are ... 27 votes 7answers 418 views Are bugs necessarily off-topic? Jorge Castro recently commented on one of my questions that it should be filed as a bug instead. And I've seen here that the general view is that questions about bugs should be considered off-topic ... 22 votes 5answers 467 views Why is Ask Ubuntu being linked to from Apport? When I was using Apport I got the following messages: If you select I don't know what to do or Please point me to a good place to get support you get another pop-up window directing you to Ask Ubuntu:... 31 votes 4answers 754 views What are common canonical questions for our site? So according to the Gospel of Spolsky 13:4, a core mission of Stack Exchange communities is to stop re-answering the same questions, and instead build a library of canonical answers. When general ... 16 votes 6answers 333 views How can we refocus on being a Q+A, not a support forum or bug tracker? [closed] After doing some investigation on issues brought up doing these questions I've found something that I'm embarrassed that we have let get out of control, see these questions for some background. What ... -9 votes 2answers 351 views Hi, how can i remove this account? This particular site of stack exchange is not amusing me, has no function and has over zealous moderators who deleted every single one of my posts, two of which because i mentioned that unity is a bug ... 8 votes 4answers 278 views What are Ask Ubuntu's current problems, if any, as of early 2012? The following question was posed to me on my moderator nomination Is there any concrete issues you would like to focus on as a moderator? My answer is what amounts to janitorial work, but I'd like ... 12 votes 3answers 146 views Why should I close 54422? Someone has suggested I delete/close Is there a way to disable or limit system xrandr probes? because I am no longer experiencing the bug that prompted me to ask it. Personally, I think it's still an ... -2 votes 2answers 335 views Why do valid questions get closed without providing any help? I run into this problem often. Case in point: 19.10 seems to have broken suspend on my MB Pro This user has a reputation of 111, appears to be an active contributor, and actually has the same ... 8 votes 2answers 169 views When is a bug a bug? Inspired by this question Would creating a Q&A question to cover specific 14.04 sound issues be okay here? we may want to better define which bug reports merit being a close reason for a ... 5 votes 2answers 93 views Do we need a linked report to close bug questions? In a recent question about problems with Ask Ubuntu, the topic of low-quality, incomplete, pseudo-bug-report questions came up. From What to do with questions that describe known bugs?, I was under ... 5 votes 2answers 114 views Why is this question on using Ubuntu with Nvidia drivers off-topic? I am utterly surprised that this question is considered off-topic: https://askubuntu.com/questions/400044/nvidia-x-server-flickers-hangs-and-segfaults-on-start-up . It represents a genuine ... 3 votes 1answer 67 views What should we do with a question discovered to be related to a bug with a fix? Let's suppose your system behaves strangely, but you can't tell if it is a bug. As a matter of fact, you think that it is a misconfiguration. You ask then a question in Ask Ubuntu and get some (... 2 votes 1answer 47 views Question closed as off topic, months later, with generic hint to read the FAQ My question firefox addon "Deutsches Wörterbuch 2.0.2" full of errors was closed and downvoted recently. Reason given: Off topic/RTFM. In the faq I read: We welcome questions ... 15 30 50 per page
__label__pos
0.754958
dc2ae19cccf02bae9a04c9f857823671d8505679 [reactos.git] / reactos / dll / win32 / rpcrt4 / rpc_transport.c 1 /* 2 * RPC transport layer 3 * 4 * Copyright 2001 Ove Kåven, TransGaming Technologies 5 * Copyright 2003 Mike Hearn 6 * Copyright 2004 Filip Navara 7 * Copyright 2006 Mike McCormack 8 * Copyright 2006 Damjan Jovanovic 9 * 10 * This library is free software; you can redistribute it and/or 11 * modify it under the terms of the GNU Lesser General Public 12 * License as published by the Free Software Foundation; either 13 * version 2.1 of the License, or (at your option) any later version. 14 * 15 * This library is distributed in the hope that it will be useful, 16 * but WITHOUT ANY WARRANTY; without even the implied warranty of 17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 18 * Lesser General Public License for more details. 19 * 20 * You should have received a copy of the GNU Lesser General Public 21 * License along with this library; if not, write to the Free Software 22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA 23 * 24 */ 25 26 #include "config.h" 27 28 #include <stdarg.h> 29 #include <stdio.h> 30 #include <string.h> 31 #include <assert.h> 32 #include <stdlib.h> 33 #include <sys/types.h> 34 35 #if defined(__MINGW32__) || defined (_MSC_VER) 36 # include <ws2tcpip.h> 37 # ifndef EADDRINUSE 38 # define EADDRINUSE WSAEADDRINUSE 39 # endif 40 # ifndef EAGAIN 41 # define EAGAIN WSAEWOULDBLOCK 42 # endif 43 # undef errno 44 # define errno WSAGetLastError() 45 #else 46 # include <errno.h> 47 # ifdef HAVE_UNISTD_H 48 # include <unistd.h> 49 # endif 50 # include <fcntl.h> 51 # ifdef HAVE_SYS_SOCKET_H 52 # include <sys/socket.h> 53 # endif 54 # ifdef HAVE_NETINET_IN_H 55 # include <netinet/in.h> 56 # endif 57 # ifdef HAVE_NETINET_TCP_H 58 # include <netinet/tcp.h> 59 # endif 60 # ifdef HAVE_ARPA_INET_H 61 # include <arpa/inet.h> 62 # endif 63 # ifdef HAVE_NETDB_H 64 # include <netdb.h> 65 # endif 66 # ifdef HAVE_SYS_POLL_H 67 # include <sys/poll.h> 68 # endif 69 # ifdef HAVE_SYS_FILIO_H 70 # include <sys/filio.h> 71 # endif 72 # ifdef HAVE_SYS_IOCTL_H 73 # include <sys/ioctl.h> 74 # endif 75 # define closesocket close 76 # define ioctlsocket ioctl 77 #endif /* defined(__MINGW32__) || defined (_MSC_VER) */ 78 79 #include "windef.h" 80 #include "winbase.h" 81 #include "winnls.h" 82 #include "winerror.h" 83 #include "wininet.h" 84 #include "winternl.h" 85 #include "wine/unicode.h" 86 87 #include "rpc.h" 88 #include "rpcndr.h" 89 90 #include "wine/debug.h" 91 92 #include "rpc_binding.h" 93 #include "rpc_assoc.h" 94 #include "rpc_message.h" 95 #include "rpc_server.h" 96 #include "epm_towers.h" 97 98 #ifndef SOL_TCP 99 # define SOL_TCP IPPROTO_TCP 100 #endif 101 102 #define DEFAULT_NCACN_HTTP_TIMEOUT (60 * 1000) 103 104 WINE_DEFAULT_DEBUG_CHANNEL(rpc); 105 106 static RPC_STATUS RPCRT4_SpawnConnection(RpcConnection** Connection, RpcConnection* OldConnection); 107 108 /**** ncacn_np support ****/ 109 110 typedef struct _RpcConnection_np 111 { 112 RpcConnection common; 113 HANDLE pipe; 114 OVERLAPPED ovl; 115 BOOL listening; 116 } RpcConnection_np; 117 118 static RpcConnection *rpcrt4_conn_np_alloc(void) 119 { 120 RpcConnection_np *npc = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcConnection_np)); 121 if (npc) 122 { 123 npc->pipe = NULL; 124 memset(&npc->ovl, 0, sizeof(npc->ovl)); 125 npc->listening = FALSE; 126 } 127 return &npc->common; 128 } 129 130 static RPC_STATUS rpcrt4_conn_listen_pipe(RpcConnection_np *npc) 131 { 132 if (npc->listening) 133 return RPC_S_OK; 134 135 npc->listening = TRUE; 136 for (;;) 137 { 138 if (ConnectNamedPipe(npc->pipe, &npc->ovl)) 139 return RPC_S_OK; 140 141 switch(GetLastError()) 142 { 143 case ERROR_PIPE_CONNECTED: 144 SetEvent(npc->ovl.hEvent); 145 return RPC_S_OK; 146 case ERROR_IO_PENDING: 147 /* will be completed in rpcrt4_protseq_np_wait_for_new_connection */ 148 return RPC_S_OK; 149 case ERROR_NO_DATA_DETECTED: 150 /* client has disconnected, retry */ 151 DisconnectNamedPipe( npc->pipe ); 152 break; 153 default: 154 npc->listening = FALSE; 155 WARN("Couldn't ConnectNamedPipe (error was %d)\n", GetLastError()); 156 return RPC_S_OUT_OF_RESOURCES; 157 } 158 } 159 } 160 161 static RPC_STATUS rpcrt4_conn_create_pipe(RpcConnection *Connection, LPCSTR pname) 162 { 163 RpcConnection_np *npc = (RpcConnection_np *) Connection; 164 TRACE("listening on %s\n", pname); 165 166 npc->pipe = CreateNamedPipeA(pname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 167 PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE, 168 PIPE_UNLIMITED_INSTANCES, 169 RPC_MAX_PACKET_SIZE, RPC_MAX_PACKET_SIZE, 5000, NULL); 170 if (npc->pipe == INVALID_HANDLE_VALUE) { 171 WARN("CreateNamedPipe failed with error %d\n", GetLastError()); 172 if (GetLastError() == ERROR_FILE_EXISTS) 173 return RPC_S_DUPLICATE_ENDPOINT; 174 else 175 return RPC_S_CANT_CREATE_ENDPOINT; 176 } 177 178 memset(&npc->ovl, 0, sizeof(npc->ovl)); 179 npc->ovl.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL); 180 181 /* Note: we don't call ConnectNamedPipe here because it must be done in the 182 * server thread as the thread must be alertable */ 183 return RPC_S_OK; 184 } 185 186 static RPC_STATUS rpcrt4_conn_open_pipe(RpcConnection *Connection, LPCSTR pname, BOOL wait) 187 { 188 RpcConnection_np *npc = (RpcConnection_np *) Connection; 189 HANDLE pipe; 190 DWORD err, dwMode; 191 192 TRACE("connecting to %s\n", pname); 193 194 while (TRUE) { 195 DWORD dwFlags = 0; 196 if (Connection->QOS) 197 { 198 dwFlags = SECURITY_SQOS_PRESENT; 199 switch (Connection->QOS->qos->ImpersonationType) 200 { 201 case RPC_C_IMP_LEVEL_DEFAULT: 202 /* FIXME: what to do here? */ 203 break; 204 case RPC_C_IMP_LEVEL_ANONYMOUS: 205 dwFlags |= SECURITY_ANONYMOUS; 206 break; 207 case RPC_C_IMP_LEVEL_IDENTIFY: 208 dwFlags |= SECURITY_IDENTIFICATION; 209 break; 210 case RPC_C_IMP_LEVEL_IMPERSONATE: 211 dwFlags |= SECURITY_IMPERSONATION; 212 break; 213 case RPC_C_IMP_LEVEL_DELEGATE: 214 dwFlags |= SECURITY_DELEGATION; 215 break; 216 } 217 if (Connection->QOS->qos->IdentityTracking == RPC_C_QOS_IDENTITY_DYNAMIC) 218 dwFlags |= SECURITY_CONTEXT_TRACKING; 219 } 220 pipe = CreateFileA(pname, GENERIC_READ|GENERIC_WRITE, 0, NULL, 221 OPEN_EXISTING, dwFlags, 0); 222 if (pipe != INVALID_HANDLE_VALUE) break; 223 err = GetLastError(); 224 if (err == ERROR_PIPE_BUSY) { 225 TRACE("connection failed, error=%x\n", err); 226 return RPC_S_SERVER_TOO_BUSY; 227 } 228 if (!wait || !WaitNamedPipeA(pname, NMPWAIT_WAIT_FOREVER)) { 229 err = GetLastError(); 230 WARN("connection failed, error=%x\n", err); 231 return RPC_S_SERVER_UNAVAILABLE; 232 } 233 } 234 235 /* success */ 236 memset(&npc->ovl, 0, sizeof(npc->ovl)); 237 /* pipe is connected; change to message-read mode. */ 238 dwMode = PIPE_READMODE_MESSAGE; 239 SetNamedPipeHandleState(pipe, &dwMode, NULL, NULL); 240 npc->ovl.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL); 241 npc->pipe = pipe; 242 243 return RPC_S_OK; 244 } 245 246 static RPC_STATUS rpcrt4_ncalrpc_open(RpcConnection* Connection) 247 { 248 RpcConnection_np *npc = (RpcConnection_np *) Connection; 249 static const char prefix[] = "\\\\.\\pipe\\lrpc\\"; 250 RPC_STATUS r; 251 LPSTR pname; 252 253 /* already connected? */ 254 if (npc->pipe) 255 return RPC_S_OK; 256 257 /* protseq=ncalrpc: supposed to use NT LPC ports, 258 * but we'll implement it with named pipes for now */ 259 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1); 260 strcat(strcpy(pname, prefix), Connection->Endpoint); 261 r = rpcrt4_conn_open_pipe(Connection, pname, TRUE); 262 I_RpcFree(pname); 263 264 return r; 265 } 266 267 static RPC_STATUS rpcrt4_protseq_ncalrpc_open_endpoint(RpcServerProtseq* protseq, const char *endpoint) 268 { 269 static const char prefix[] = "\\\\.\\pipe\\lrpc\\"; 270 RPC_STATUS r; 271 LPSTR pname; 272 RpcConnection *Connection; 273 char generated_endpoint[22]; 274 275 if (!endpoint) 276 { 277 static LONG lrpc_nameless_id; 278 DWORD process_id = GetCurrentProcessId(); 279 ULONG id = InterlockedIncrement(&lrpc_nameless_id); 280 snprintf(generated_endpoint, sizeof(generated_endpoint), 281 "LRPC%08x.%08x", process_id, id); 282 endpoint = generated_endpoint; 283 } 284 285 r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL, 286 endpoint, NULL, NULL, NULL); 287 if (r != RPC_S_OK) 288 return r; 289 290 /* protseq=ncalrpc: supposed to use NT LPC ports, 291 * but we'll implement it with named pipes for now */ 292 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1); 293 strcat(strcpy(pname, prefix), Connection->Endpoint); 294 r = rpcrt4_conn_create_pipe(Connection, pname); 295 I_RpcFree(pname); 296 297 EnterCriticalSection(&protseq->cs); 298 Connection->Next = protseq->conn; 299 protseq->conn = Connection; 300 LeaveCriticalSection(&protseq->cs); 301 302 return r; 303 } 304 305 static RPC_STATUS rpcrt4_ncacn_np_open(RpcConnection* Connection) 306 { 307 RpcConnection_np *npc = (RpcConnection_np *) Connection; 308 static const char prefix[] = "\\\\."; 309 RPC_STATUS r; 310 LPSTR pname; 311 312 /* already connected? */ 313 if (npc->pipe) 314 return RPC_S_OK; 315 316 /* protseq=ncacn_np: named pipes */ 317 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1); 318 strcat(strcpy(pname, prefix), Connection->Endpoint); 319 r = rpcrt4_conn_open_pipe(Connection, pname, TRUE); 320 I_RpcFree(pname); 321 322 return r; 323 } 324 325 static RPC_STATUS rpcrt4_protseq_ncacn_np_open_endpoint(RpcServerProtseq *protseq, const char *endpoint) 326 { 327 static const char prefix[] = "\\\\."; 328 RPC_STATUS r; 329 LPSTR pname; 330 RpcConnection *Connection; 331 char generated_endpoint[21]; 332 333 if (!endpoint) 334 { 335 static LONG np_nameless_id; 336 DWORD process_id = GetCurrentProcessId(); 337 ULONG id = InterlockedExchangeAdd(&np_nameless_id, 1 ); 338 snprintf(generated_endpoint, sizeof(generated_endpoint), 339 "\\\\pipe\\\\%08x.%03x", process_id, id); 340 endpoint = generated_endpoint; 341 } 342 343 r = RPCRT4_CreateConnection(&Connection, TRUE, protseq->Protseq, NULL, 344 endpoint, NULL, NULL, NULL); 345 if (r != RPC_S_OK) 346 return r; 347 348 /* protseq=ncacn_np: named pipes */ 349 pname = I_RpcAllocate(strlen(prefix) + strlen(Connection->Endpoint) + 1); 350 strcat(strcpy(pname, prefix), Connection->Endpoint); 351 r = rpcrt4_conn_create_pipe(Connection, pname); 352 I_RpcFree(pname); 353 354 EnterCriticalSection(&protseq->cs); 355 Connection->Next = protseq->conn; 356 protseq->conn = Connection; 357 LeaveCriticalSection(&protseq->cs); 358 359 return r; 360 } 361 362 static void rpcrt4_conn_np_handoff(RpcConnection_np *old_npc, RpcConnection_np *new_npc) 363 { 364 /* because of the way named pipes work, we'll transfer the connected pipe 365 * to the child, then reopen the server binding to continue listening */ 366 367 new_npc->pipe = old_npc->pipe; 368 new_npc->ovl = old_npc->ovl; 369 old_npc->pipe = 0; 370 memset(&old_npc->ovl, 0, sizeof(old_npc->ovl)); 371 old_npc->listening = FALSE; 372 } 373 374 static RPC_STATUS rpcrt4_ncacn_np_handoff(RpcConnection *old_conn, RpcConnection *new_conn) 375 { 376 RPC_STATUS status; 377 LPSTR pname; 378 static const char prefix[] = "\\\\."; 379 380 rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn); 381 382 pname = I_RpcAllocate(strlen(prefix) + strlen(old_conn->Endpoint) + 1); 383 strcat(strcpy(pname, prefix), old_conn->Endpoint); 384 status = rpcrt4_conn_create_pipe(old_conn, pname); 385 I_RpcFree(pname); 386 387 return status; 388 } 389 390 static RPC_STATUS rpcrt4_ncalrpc_handoff(RpcConnection *old_conn, RpcConnection *new_conn) 391 { 392 RPC_STATUS status; 393 LPSTR pname; 394 static const char prefix[] = "\\\\.\\pipe\\lrpc\\"; 395 396 TRACE("%s\n", old_conn->Endpoint); 397 398 rpcrt4_conn_np_handoff((RpcConnection_np *)old_conn, (RpcConnection_np *)new_conn); 399 400 pname = I_RpcAllocate(strlen(prefix) + strlen(old_conn->Endpoint) + 1); 401 strcat(strcpy(pname, prefix), old_conn->Endpoint); 402 status = rpcrt4_conn_create_pipe(old_conn, pname); 403 I_RpcFree(pname); 404 405 return status; 406 } 407 408 static int rpcrt4_conn_np_read(RpcConnection *Connection, 409 void *buffer, unsigned int count) 410 { 411 RpcConnection_np *npc = (RpcConnection_np *) Connection; 412 char *buf = buffer; 413 BOOL ret = TRUE; 414 unsigned int bytes_left = count; 415 OVERLAPPED ovl; 416 417 ZeroMemory(&ovl, sizeof(ovl)); 418 ovl.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL); 419 420 while (bytes_left) 421 { 422 DWORD bytes_read; 423 ret = ReadFile(npc->pipe, buf, bytes_left, &bytes_read, &ovl); 424 if ((!ret || !bytes_read) && (GetLastError() != ERROR_IO_PENDING)) 425 break; 426 ret = GetOverlappedResult(npc->pipe, &ovl, &bytes_read, TRUE); 427 if (!ret && (GetLastError() != ERROR_MORE_DATA)) 428 break; 429 bytes_left -= bytes_read; 430 buf += bytes_read; 431 } 432 CloseHandle(ovl.hEvent); 433 return ret ? count : -1; 434 } 435 436 static int rpcrt4_conn_np_write(RpcConnection *Connection, 437 const void *buffer, unsigned int count) 438 { 439 RpcConnection_np *npc = (RpcConnection_np *) Connection; 440 const char *buf = buffer; 441 BOOL ret = TRUE; 442 unsigned int bytes_left = count; 443 OVERLAPPED ovl; 444 445 ZeroMemory(&ovl, sizeof(ovl)); 446 ovl.hEvent = CreateEventW(NULL, TRUE, FALSE, NULL); 447 448 while (bytes_left) 449 { 450 DWORD bytes_written; 451 ret = WriteFile(npc->pipe, buf, bytes_left, &bytes_written, &ovl); 452 if ((!ret || !bytes_written) && (GetLastError() != ERROR_IO_PENDING)) 453 break; 454 455 ret = GetOverlappedResult(npc->pipe, &ovl, &bytes_written, TRUE); 456 if (!ret && (GetLastError() != ERROR_MORE_DATA)) 457 break; 458 bytes_left -= bytes_written; 459 buf += bytes_written; 460 } 461 CloseHandle(ovl.hEvent); 462 return ret ? count : -1; 463 } 464 465 static int rpcrt4_conn_np_close(RpcConnection *Connection) 466 { 467 RpcConnection_np *npc = (RpcConnection_np *) Connection; 468 if (npc->pipe) { 469 FlushFileBuffers(npc->pipe); 470 CloseHandle(npc->pipe); 471 npc->pipe = 0; 472 } 473 if (npc->ovl.hEvent) { 474 CloseHandle(npc->ovl.hEvent); 475 npc->ovl.hEvent = 0; 476 } 477 return 0; 478 } 479 480 static void rpcrt4_conn_np_cancel_call(RpcConnection *Connection) 481 { 482 /* FIXME: implement when named pipe writes use overlapped I/O */ 483 } 484 485 static int rpcrt4_conn_np_wait_for_incoming_data(RpcConnection *Connection) 486 { 487 /* FIXME: implement when named pipe writes use overlapped I/O */ 488 return -1; 489 } 490 491 static size_t rpcrt4_ncacn_np_get_top_of_tower(unsigned char *tower_data, 492 const char *networkaddr, 493 const char *endpoint) 494 { 495 twr_empty_floor_t *smb_floor; 496 twr_empty_floor_t *nb_floor; 497 size_t size; 498 size_t networkaddr_size; 499 size_t endpoint_size; 500 501 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint); 502 503 networkaddr_size = networkaddr ? strlen(networkaddr) + 1 : 1; 504 endpoint_size = endpoint ? strlen(endpoint) + 1 : 1; 505 size = sizeof(*smb_floor) + endpoint_size + sizeof(*nb_floor) + networkaddr_size; 506 507 if (!tower_data) 508 return size; 509 510 smb_floor = (twr_empty_floor_t *)tower_data; 511 512 tower_data += sizeof(*smb_floor); 513 514 smb_floor->count_lhs = sizeof(smb_floor->protid); 515 smb_floor->protid = EPM_PROTOCOL_SMB; 516 smb_floor->count_rhs = endpoint_size; 517 518 if (endpoint) 519 memcpy(tower_data, endpoint, endpoint_size); 520 else 521 tower_data[0] = 0; 522 tower_data += endpoint_size; 523 524 nb_floor = (twr_empty_floor_t *)tower_data; 525 526 tower_data += sizeof(*nb_floor); 527 528 nb_floor->count_lhs = sizeof(nb_floor->protid); 529 nb_floor->protid = EPM_PROTOCOL_NETBIOS; 530 nb_floor->count_rhs = networkaddr_size; 531 532 if (networkaddr) 533 memcpy(tower_data, networkaddr, networkaddr_size); 534 else 535 tower_data[0] = 0; 536 537 return size; 538 } 539 540 static RPC_STATUS rpcrt4_ncacn_np_parse_top_of_tower(const unsigned char *tower_data, 541 size_t tower_size, 542 char **networkaddr, 543 char **endpoint) 544 { 545 const twr_empty_floor_t *smb_floor = (const twr_empty_floor_t *)tower_data; 546 const twr_empty_floor_t *nb_floor; 547 548 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint); 549 550 if (tower_size < sizeof(*smb_floor)) 551 return EPT_S_NOT_REGISTERED; 552 553 tower_data += sizeof(*smb_floor); 554 tower_size -= sizeof(*smb_floor); 555 556 if ((smb_floor->count_lhs != sizeof(smb_floor->protid)) || 557 (smb_floor->protid != EPM_PROTOCOL_SMB) || 558 (smb_floor->count_rhs > tower_size) || 559 (tower_data[smb_floor->count_rhs - 1] != '\0')) 560 return EPT_S_NOT_REGISTERED; 561 562 if (endpoint) 563 { 564 *endpoint = I_RpcAllocate(smb_floor->count_rhs); 565 if (!*endpoint) 566 return RPC_S_OUT_OF_RESOURCES; 567 memcpy(*endpoint, tower_data, smb_floor->count_rhs); 568 } 569 tower_data += smb_floor->count_rhs; 570 tower_size -= smb_floor->count_rhs; 571 572 if (tower_size < sizeof(*nb_floor)) 573 return EPT_S_NOT_REGISTERED; 574 575 nb_floor = (const twr_empty_floor_t *)tower_data; 576 577 tower_data += sizeof(*nb_floor); 578 tower_size -= sizeof(*nb_floor); 579 580 if ((nb_floor->count_lhs != sizeof(nb_floor->protid)) || 581 (nb_floor->protid != EPM_PROTOCOL_NETBIOS) || 582 (nb_floor->count_rhs > tower_size) || 583 (tower_data[nb_floor->count_rhs - 1] != '\0')) 584 return EPT_S_NOT_REGISTERED; 585 586 if (networkaddr) 587 { 588 *networkaddr = I_RpcAllocate(nb_floor->count_rhs); 589 if (!*networkaddr) 590 { 591 if (endpoint) 592 { 593 I_RpcFree(*endpoint); 594 *endpoint = NULL; 595 } 596 return RPC_S_OUT_OF_RESOURCES; 597 } 598 memcpy(*networkaddr, tower_data, nb_floor->count_rhs); 599 } 600 601 return RPC_S_OK; 602 } 603 604 static RPC_STATUS rpcrt4_conn_np_impersonate_client(RpcConnection *conn) 605 { 606 RpcConnection_np *npc = (RpcConnection_np *)conn; 607 BOOL ret; 608 609 TRACE("(%p)\n", conn); 610 611 if (conn->AuthInfo && SecIsValidHandle(&conn->ctx)) 612 return RPCRT4_default_impersonate_client(conn); 613 614 ret = ImpersonateNamedPipeClient(npc->pipe); 615 if (!ret) 616 { 617 DWORD error = GetLastError(); 618 WARN("ImpersonateNamedPipeClient failed with error %u\n", error); 619 switch (error) 620 { 621 case ERROR_CANNOT_IMPERSONATE: 622 return RPC_S_NO_CONTEXT_AVAILABLE; 623 } 624 } 625 return RPC_S_OK; 626 } 627 628 static RPC_STATUS rpcrt4_conn_np_revert_to_self(RpcConnection *conn) 629 { 630 BOOL ret; 631 632 TRACE("(%p)\n", conn); 633 634 if (conn->AuthInfo && SecIsValidHandle(&conn->ctx)) 635 return RPCRT4_default_revert_to_self(conn); 636 637 ret = RevertToSelf(); 638 if (!ret) 639 { 640 WARN("RevertToSelf failed with error %u\n", GetLastError()); 641 return RPC_S_NO_CONTEXT_AVAILABLE; 642 } 643 return RPC_S_OK; 644 } 645 646 typedef struct _RpcServerProtseq_np 647 { 648 RpcServerProtseq common; 649 HANDLE mgr_event; 650 } RpcServerProtseq_np; 651 652 static RpcServerProtseq *rpcrt4_protseq_np_alloc(void) 653 { 654 RpcServerProtseq_np *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps)); 655 if (ps) 656 ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL); 657 return &ps->common; 658 } 659 660 static void rpcrt4_protseq_np_signal_state_changed(RpcServerProtseq *protseq) 661 { 662 RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common); 663 SetEvent(npps->mgr_event); 664 } 665 666 static void *rpcrt4_protseq_np_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count) 667 { 668 HANDLE *objs = prev_array; 669 RpcConnection_np *conn; 670 RpcServerProtseq_np *npps = CONTAINING_RECORD(protseq, RpcServerProtseq_np, common); 671 672 EnterCriticalSection(&protseq->cs); 673 674 /* open and count connections */ 675 *count = 1; 676 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common); 677 while (conn) { 678 rpcrt4_conn_listen_pipe(conn); 679 if (conn->ovl.hEvent) 680 (*count)++; 681 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common); 682 } 683 684 /* make array of connections */ 685 if (objs) 686 objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE)); 687 else 688 objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE)); 689 if (!objs) 690 { 691 ERR("couldn't allocate objs\n"); 692 LeaveCriticalSection(&protseq->cs); 693 return NULL; 694 } 695 696 objs[0] = npps->mgr_event; 697 *count = 1; 698 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common); 699 while (conn) { 700 if ((objs[*count] = conn->ovl.hEvent)) 701 (*count)++; 702 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common); 703 } 704 LeaveCriticalSection(&protseq->cs); 705 return objs; 706 } 707 708 static void rpcrt4_protseq_np_free_wait_array(RpcServerProtseq *protseq, void *array) 709 { 710 HeapFree(GetProcessHeap(), 0, array); 711 } 712 713 static int rpcrt4_protseq_np_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array) 714 { 715 HANDLE b_handle; 716 HANDLE *objs = wait_array; 717 DWORD res; 718 RpcConnection *cconn; 719 RpcConnection_np *conn; 720 721 if (!objs) 722 return -1; 723 724 do 725 { 726 /* an alertable wait isn't strictly necessary, but due to our 727 * overlapped I/O implementation in Wine we need to free some memory 728 * by the file user APC being called, even if no completion routine was 729 * specified at the time of starting the async operation */ 730 res = WaitForMultipleObjectsEx(count, objs, FALSE, INFINITE, TRUE); 731 } while (res == WAIT_IO_COMPLETION); 732 733 if (res == WAIT_OBJECT_0) 734 return 0; 735 else if (res == WAIT_FAILED) 736 { 737 ERR("wait failed with error %d\n", GetLastError()); 738 return -1; 739 } 740 else 741 { 742 b_handle = objs[res - WAIT_OBJECT_0]; 743 /* find which connection got a RPC */ 744 EnterCriticalSection(&protseq->cs); 745 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_np, common); 746 while (conn) { 747 if (b_handle == conn->ovl.hEvent) break; 748 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_np, common); 749 } 750 cconn = NULL; 751 if (conn) 752 RPCRT4_SpawnConnection(&cconn, &conn->common); 753 else 754 ERR("failed to locate connection for handle %p\n", b_handle); 755 LeaveCriticalSection(&protseq->cs); 756 if (cconn) 757 { 758 RPCRT4_new_client(cconn); 759 return 1; 760 } 761 else return -1; 762 } 763 } 764 765 static size_t rpcrt4_ncalrpc_get_top_of_tower(unsigned char *tower_data, 766 const char *networkaddr, 767 const char *endpoint) 768 { 769 twr_empty_floor_t *pipe_floor; 770 size_t size; 771 size_t endpoint_size; 772 773 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint); 774 775 endpoint_size = strlen(endpoint) + 1; 776 size = sizeof(*pipe_floor) + endpoint_size; 777 778 if (!tower_data) 779 return size; 780 781 pipe_floor = (twr_empty_floor_t *)tower_data; 782 783 tower_data += sizeof(*pipe_floor); 784 785 pipe_floor->count_lhs = sizeof(pipe_floor->protid); 786 pipe_floor->protid = EPM_PROTOCOL_PIPE; 787 pipe_floor->count_rhs = endpoint_size; 788 789 memcpy(tower_data, endpoint, endpoint_size); 790 791 return size; 792 } 793 794 static RPC_STATUS rpcrt4_ncalrpc_parse_top_of_tower(const unsigned char *tower_data, 795 size_t tower_size, 796 char **networkaddr, 797 char **endpoint) 798 { 799 const twr_empty_floor_t *pipe_floor = (const twr_empty_floor_t *)tower_data; 800 801 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint); 802 803 if (tower_size < sizeof(*pipe_floor)) 804 return EPT_S_NOT_REGISTERED; 805 806 tower_data += sizeof(*pipe_floor); 807 tower_size -= sizeof(*pipe_floor); 808 809 if ((pipe_floor->count_lhs != sizeof(pipe_floor->protid)) || 810 (pipe_floor->protid != EPM_PROTOCOL_PIPE) || 811 (pipe_floor->count_rhs > tower_size) || 812 (tower_data[pipe_floor->count_rhs - 1] != '\0')) 813 return EPT_S_NOT_REGISTERED; 814 815 if (networkaddr) 816 *networkaddr = NULL; 817 818 if (endpoint) 819 { 820 *endpoint = I_RpcAllocate(pipe_floor->count_rhs); 821 if (!*endpoint) 822 return RPC_S_OUT_OF_RESOURCES; 823 memcpy(*endpoint, tower_data, pipe_floor->count_rhs); 824 } 825 826 return RPC_S_OK; 827 } 828 829 static BOOL rpcrt4_ncalrpc_is_authorized(RpcConnection *conn) 830 { 831 return FALSE; 832 } 833 834 static RPC_STATUS rpcrt4_ncalrpc_authorize(RpcConnection *conn, BOOL first_time, 835 unsigned char *in_buffer, 836 unsigned int in_size, 837 unsigned char *out_buffer, 838 unsigned int *out_size) 839 { 840 /* since this protocol is local to the machine there is no need to 841 * authenticate the caller */ 842 *out_size = 0; 843 return RPC_S_OK; 844 } 845 846 static RPC_STATUS rpcrt4_ncalrpc_secure_packet(RpcConnection *conn, 847 enum secure_packet_direction dir, 848 RpcPktHdr *hdr, unsigned int hdr_size, 849 unsigned char *stub_data, unsigned int stub_data_size, 850 RpcAuthVerifier *auth_hdr, 851 unsigned char *auth_value, unsigned int auth_value_size) 852 { 853 /* since this protocol is local to the machine there is no need to secure 854 * the packet */ 855 return RPC_S_OK; 856 } 857 858 static RPC_STATUS rpcrt4_ncalrpc_inquire_auth_client( 859 RpcConnection *conn, RPC_AUTHZ_HANDLE *privs, RPC_WSTR *server_princ_name, 860 ULONG *authn_level, ULONG *authn_svc, ULONG *authz_svc, ULONG flags) 861 { 862 TRACE("(%p, %p, %p, %p, %p, %p, 0x%x)\n", conn, privs, 863 server_princ_name, authn_level, authn_svc, authz_svc, flags); 864 865 if (privs) 866 { 867 FIXME("privs not implemented\n"); 868 *privs = NULL; 869 } 870 if (server_princ_name) 871 { 872 FIXME("server_princ_name not implemented\n"); 873 *server_princ_name = NULL; 874 } 875 if (authn_level) *authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY; 876 if (authn_svc) *authn_svc = RPC_C_AUTHN_WINNT; 877 if (authz_svc) 878 { 879 FIXME("authorization service not implemented\n"); 880 *authz_svc = RPC_C_AUTHZ_NONE; 881 } 882 if (flags) 883 FIXME("flags 0x%x not implemented\n", flags); 884 885 return RPC_S_OK; 886 } 887 888 /**** ncacn_ip_tcp support ****/ 889 890 static size_t rpcrt4_ip_tcp_get_top_of_tower(unsigned char *tower_data, 891 const char *networkaddr, 892 unsigned char tcp_protid, 893 const char *endpoint) 894 { 895 twr_tcp_floor_t *tcp_floor; 896 twr_ipv4_floor_t *ipv4_floor; 897 struct addrinfo *ai; 898 struct addrinfo hints; 899 int ret; 900 size_t size = sizeof(*tcp_floor) + sizeof(*ipv4_floor); 901 902 TRACE("(%p, %s, %s)\n", tower_data, networkaddr, endpoint); 903 904 if (!tower_data) 905 return size; 906 907 tcp_floor = (twr_tcp_floor_t *)tower_data; 908 tower_data += sizeof(*tcp_floor); 909 910 ipv4_floor = (twr_ipv4_floor_t *)tower_data; 911 912 tcp_floor->count_lhs = sizeof(tcp_floor->protid); 913 tcp_floor->protid = tcp_protid; 914 tcp_floor->count_rhs = sizeof(tcp_floor->port); 915 916 ipv4_floor->count_lhs = sizeof(ipv4_floor->protid); 917 ipv4_floor->protid = EPM_PROTOCOL_IP; 918 ipv4_floor->count_rhs = sizeof(ipv4_floor->ipv4addr); 919 920 hints.ai_flags = AI_NUMERICHOST; 921 /* FIXME: only support IPv4 at the moment. how is IPv6 represented by the EPM? */ 922 hints.ai_family = PF_INET; 923 hints.ai_socktype = SOCK_STREAM; 924 hints.ai_protocol = IPPROTO_TCP; 925 hints.ai_addrlen = 0; 926 hints.ai_addr = NULL; 927 hints.ai_canonname = NULL; 928 hints.ai_next = NULL; 929 930 ret = getaddrinfo(networkaddr, endpoint, &hints, &ai); 931 if (ret) 932 { 933 ret = getaddrinfo("0.0.0.0", endpoint, &hints, &ai); 934 if (ret) 935 { 936 ERR("getaddrinfo failed: %s\n", gai_strerror(ret)); 937 return 0; 938 } 939 } 940 941 if (ai->ai_family == PF_INET) 942 { 943 const struct sockaddr_in *sin = (const struct sockaddr_in *)ai->ai_addr; 944 tcp_floor->port = sin->sin_port; 945 ipv4_floor->ipv4addr = sin->sin_addr.s_addr; 946 } 947 else 948 { 949 ERR("unexpected protocol family %d\n", ai->ai_family); 950 return 0; 951 } 952 953 freeaddrinfo(ai); 954 955 return size; 956 } 957 958 static RPC_STATUS rpcrt4_ip_tcp_parse_top_of_tower(const unsigned char *tower_data, 959 size_t tower_size, 960 char **networkaddr, 961 unsigned char tcp_protid, 962 char **endpoint) 963 { 964 const twr_tcp_floor_t *tcp_floor = (const twr_tcp_floor_t *)tower_data; 965 const twr_ipv4_floor_t *ipv4_floor; 966 struct in_addr in_addr; 967 968 TRACE("(%p, %d, %p, %p)\n", tower_data, (int)tower_size, networkaddr, endpoint); 969 970 if (tower_size < sizeof(*tcp_floor)) 971 return EPT_S_NOT_REGISTERED; 972 973 tower_data += sizeof(*tcp_floor); 974 tower_size -= sizeof(*tcp_floor); 975 976 if (tower_size < sizeof(*ipv4_floor)) 977 return EPT_S_NOT_REGISTERED; 978 979 ipv4_floor = (const twr_ipv4_floor_t *)tower_data; 980 981 if ((tcp_floor->count_lhs != sizeof(tcp_floor->protid)) || 982 (tcp_floor->protid != tcp_protid) || 983 (tcp_floor->count_rhs != sizeof(tcp_floor->port)) || 984 (ipv4_floor->count_lhs != sizeof(ipv4_floor->protid)) || 985 (ipv4_floor->protid != EPM_PROTOCOL_IP) || 986 (ipv4_floor->count_rhs != sizeof(ipv4_floor->ipv4addr))) 987 return EPT_S_NOT_REGISTERED; 988 989 if (endpoint) 990 { 991 *endpoint = I_RpcAllocate(6 /* sizeof("65535") + 1 */); 992 if (!*endpoint) 993 return RPC_S_OUT_OF_RESOURCES; 994 sprintf(*endpoint, "%u", ntohs(tcp_floor->port)); 995 } 996 997 if (networkaddr) 998 { 999 *networkaddr = I_RpcAllocate(INET_ADDRSTRLEN); 1000 if (!*networkaddr) 1001 { 1002 if (endpoint) 1003 { 1004 I_RpcFree(*endpoint); 1005 *endpoint = NULL; 1006 } 1007 return RPC_S_OUT_OF_RESOURCES; 1008 } 1009 in_addr.s_addr = ipv4_floor->ipv4addr; 1010 if (!inet_ntop(AF_INET, &in_addr, *networkaddr, INET_ADDRSTRLEN)) 1011 { 1012 ERR("inet_ntop: %s\n", strerror(errno)); 1013 I_RpcFree(*networkaddr); 1014 *networkaddr = NULL; 1015 if (endpoint) 1016 { 1017 I_RpcFree(*endpoint); 1018 *endpoint = NULL; 1019 } 1020 return EPT_S_NOT_REGISTERED; 1021 } 1022 } 1023 1024 return RPC_S_OK; 1025 } 1026 1027 typedef struct _RpcConnection_tcp 1028 { 1029 RpcConnection common; 1030 int sock; 1031 #ifdef HAVE_SOCKETPAIR 1032 int cancel_fds[2]; 1033 #else 1034 HANDLE sock_event; 1035 HANDLE cancel_event; 1036 #endif 1037 } RpcConnection_tcp; 1038 1039 #ifdef HAVE_SOCKETPAIR 1040 1041 static BOOL rpcrt4_sock_wait_init(RpcConnection_tcp *tcpc) 1042 { 1043 if (socketpair(PF_UNIX, SOCK_STREAM, 0, tcpc->cancel_fds) < 0) 1044 { 1045 ERR("socketpair() failed: %s\n", strerror(errno)); 1046 return FALSE; 1047 } 1048 return TRUE; 1049 } 1050 1051 static BOOL rpcrt4_sock_wait_for_recv(RpcConnection_tcp *tcpc) 1052 { 1053 struct pollfd pfds[2]; 1054 pfds[0].fd = tcpc->sock; 1055 pfds[0].events = POLLIN; 1056 pfds[1].fd = tcpc->cancel_fds[0]; 1057 pfds[1].events = POLLIN; 1058 if (poll(pfds, 2, -1 /* infinite */) == -1 && errno != EINTR) 1059 { 1060 ERR("poll() failed: %s\n", strerror(errno)); 1061 return FALSE; 1062 } 1063 if (pfds[1].revents & POLLIN) /* canceled */ 1064 { 1065 char dummy; 1066 read(pfds[1].fd, &dummy, sizeof(dummy)); 1067 return FALSE; 1068 } 1069 return TRUE; 1070 } 1071 1072 static BOOL rpcrt4_sock_wait_for_send(RpcConnection_tcp *tcpc) 1073 { 1074 struct pollfd pfd; 1075 pfd.fd = tcpc->sock; 1076 pfd.events = POLLOUT; 1077 if (poll(&pfd, 1, -1 /* infinite */) == -1 && errno != EINTR) 1078 { 1079 ERR("poll() failed: %s\n", strerror(errno)); 1080 return FALSE; 1081 } 1082 return TRUE; 1083 } 1084 1085 static void rpcrt4_sock_wait_cancel(RpcConnection_tcp *tcpc) 1086 { 1087 char dummy = 1; 1088 1089 write(tcpc->cancel_fds[1], &dummy, 1); 1090 } 1091 1092 static void rpcrt4_sock_wait_destroy(RpcConnection_tcp *tcpc) 1093 { 1094 close(tcpc->cancel_fds[0]); 1095 close(tcpc->cancel_fds[1]); 1096 } 1097 1098 #else /* HAVE_SOCKETPAIR */ 1099 1100 static BOOL rpcrt4_sock_wait_init(RpcConnection_tcp *tcpc) 1101 { 1102 static BOOL wsa_inited; 1103 if (!wsa_inited) 1104 { 1105 WSADATA wsadata; 1106 WSAStartup(MAKEWORD(2, 2), &wsadata); 1107 /* Note: WSAStartup can be called more than once so we don't bother with 1108 * making accesses to wsa_inited thread-safe */ 1109 wsa_inited = TRUE; 1110 } 1111 tcpc->sock_event = CreateEventW(NULL, FALSE, FALSE, NULL); 1112 tcpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL); 1113 if (!tcpc->sock_event || !tcpc->cancel_event) 1114 { 1115 ERR("event creation failed\n"); 1116 if (tcpc->sock_event) CloseHandle(tcpc->sock_event); 1117 return FALSE; 1118 } 1119 return TRUE; 1120 } 1121 1122 static BOOL rpcrt4_sock_wait_for_recv(RpcConnection_tcp *tcpc) 1123 { 1124 HANDLE wait_handles[2]; 1125 DWORD res; 1126 if (WSAEventSelect(tcpc->sock, tcpc->sock_event, FD_READ | FD_CLOSE) == SOCKET_ERROR) 1127 { 1128 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError()); 1129 return FALSE; 1130 } 1131 wait_handles[0] = tcpc->sock_event; 1132 wait_handles[1] = tcpc->cancel_event; 1133 res = WaitForMultipleObjects(2, wait_handles, FALSE, INFINITE); 1134 switch (res) 1135 { 1136 case WAIT_OBJECT_0: 1137 return TRUE; 1138 case WAIT_OBJECT_0 + 1: 1139 return FALSE; 1140 default: 1141 ERR("WaitForMultipleObjects() failed with error %d\n", GetLastError()); 1142 return FALSE; 1143 } 1144 } 1145 1146 static BOOL rpcrt4_sock_wait_for_send(RpcConnection_tcp *tcpc) 1147 { 1148 DWORD res; 1149 if (WSAEventSelect(tcpc->sock, tcpc->sock_event, FD_WRITE | FD_CLOSE) == SOCKET_ERROR) 1150 { 1151 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError()); 1152 return FALSE; 1153 } 1154 res = WaitForSingleObject(tcpc->sock_event, INFINITE); 1155 switch (res) 1156 { 1157 case WAIT_OBJECT_0: 1158 return TRUE; 1159 default: 1160 ERR("WaitForMultipleObjects() failed with error %d\n", GetLastError()); 1161 return FALSE; 1162 } 1163 } 1164 1165 static void rpcrt4_sock_wait_cancel(RpcConnection_tcp *tcpc) 1166 { 1167 SetEvent(tcpc->cancel_event); 1168 } 1169 1170 static void rpcrt4_sock_wait_destroy(RpcConnection_tcp *tcpc) 1171 { 1172 CloseHandle(tcpc->sock_event); 1173 CloseHandle(tcpc->cancel_event); 1174 } 1175 1176 #endif 1177 1178 static RpcConnection *rpcrt4_conn_tcp_alloc(void) 1179 { 1180 RpcConnection_tcp *tcpc; 1181 tcpc = HeapAlloc(GetProcessHeap(), 0, sizeof(RpcConnection_tcp)); 1182 if (tcpc == NULL) 1183 return NULL; 1184 tcpc->sock = -1; 1185 if (!rpcrt4_sock_wait_init(tcpc)) 1186 { 1187 HeapFree(GetProcessHeap(), 0, tcpc); 1188 return NULL; 1189 } 1190 return &tcpc->common; 1191 } 1192 1193 static RPC_STATUS rpcrt4_ncacn_ip_tcp_open(RpcConnection* Connection) 1194 { 1195 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection; 1196 int sock; 1197 int ret; 1198 struct addrinfo *ai; 1199 struct addrinfo *ai_cur; 1200 struct addrinfo hints; 1201 1202 TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint); 1203 1204 if (tcpc->sock != -1) 1205 return RPC_S_OK; 1206 1207 hints.ai_flags = 0; 1208 hints.ai_family = PF_UNSPEC; 1209 hints.ai_socktype = SOCK_STREAM; 1210 hints.ai_protocol = IPPROTO_TCP; 1211 hints.ai_addrlen = 0; 1212 hints.ai_addr = NULL; 1213 hints.ai_canonname = NULL; 1214 hints.ai_next = NULL; 1215 1216 ret = getaddrinfo(Connection->NetworkAddr, Connection->Endpoint, &hints, &ai); 1217 if (ret) 1218 { 1219 ERR("getaddrinfo for %s:%s failed: %s\n", Connection->NetworkAddr, 1220 Connection->Endpoint, gai_strerror(ret)); 1221 return RPC_S_SERVER_UNAVAILABLE; 1222 } 1223 1224 for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next) 1225 { 1226 int val; 1227 u_long nonblocking; 1228 1229 if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6) 1230 { 1231 TRACE("skipping non-IP/IPv6 address family\n"); 1232 continue; 1233 } 1234 1235 if (TRACE_ON(rpc)) 1236 { 1237 char host[256]; 1238 char service[256]; 1239 getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen, 1240 host, sizeof(host), service, sizeof(service), 1241 NI_NUMERICHOST | NI_NUMERICSERV); 1242 TRACE("trying %s:%s\n", host, service); 1243 } 1244 1245 sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol); 1246 if (sock == -1) 1247 { 1248 WARN("socket() failed: %s\n", strerror(errno)); 1249 continue; 1250 } 1251 1252 if (0>connect(sock, ai_cur->ai_addr, ai_cur->ai_addrlen)) 1253 { 1254 WARN("connect() failed: %s\n", strerror(errno)); 1255 closesocket(sock); 1256 continue; 1257 } 1258 1259 /* RPC depends on having minimal latency so disable the Nagle algorithm */ 1260 val = 1; 1261 setsockopt(sock, SOL_TCP, TCP_NODELAY, (char *)&val, sizeof(val)); 1262 nonblocking = 1; 1263 ioctlsocket(sock, FIONBIO, &nonblocking); 1264 1265 tcpc->sock = sock; 1266 1267 freeaddrinfo(ai); 1268 TRACE("connected\n"); 1269 return RPC_S_OK; 1270 } 1271 1272 freeaddrinfo(ai); 1273 ERR("couldn't connect to %s:%s\n", Connection->NetworkAddr, Connection->Endpoint); 1274 return RPC_S_SERVER_UNAVAILABLE; 1275 } 1276 1277 static RPC_STATUS rpcrt4_protseq_ncacn_ip_tcp_open_endpoint(RpcServerProtseq *protseq, const char *endpoint) 1278 { 1279 RPC_STATUS status = RPC_S_CANT_CREATE_ENDPOINT; 1280 int sock; 1281 int ret; 1282 struct addrinfo *ai; 1283 struct addrinfo *ai_cur; 1284 struct addrinfo hints; 1285 RpcConnection *first_connection = NULL; 1286 1287 TRACE("(%p, %s)\n", protseq, endpoint); 1288 1289 hints.ai_flags = AI_PASSIVE /* for non-localhost addresses */; 1290 hints.ai_family = PF_UNSPEC; 1291 hints.ai_socktype = SOCK_STREAM; 1292 hints.ai_protocol = IPPROTO_TCP; 1293 hints.ai_addrlen = 0; 1294 hints.ai_addr = NULL; 1295 hints.ai_canonname = NULL; 1296 hints.ai_next = NULL; 1297 1298 ret = getaddrinfo(NULL, endpoint ? endpoint : "0", &hints, &ai); 1299 if (ret) 1300 { 1301 ERR("getaddrinfo for port %s failed: %s\n", endpoint, 1302 gai_strerror(ret)); 1303 if ((ret == EAI_SERVICE) || (ret == EAI_NONAME)) 1304 return RPC_S_INVALID_ENDPOINT_FORMAT; 1305 return RPC_S_CANT_CREATE_ENDPOINT; 1306 } 1307 1308 for (ai_cur = ai; ai_cur; ai_cur = ai_cur->ai_next) 1309 { 1310 RpcConnection_tcp *tcpc; 1311 RPC_STATUS create_status; 1312 struct sockaddr_storage sa; 1313 socklen_t sa_len; 1314 char service[NI_MAXSERV]; 1315 u_long nonblocking; 1316 1317 if (ai_cur->ai_family != AF_INET && ai_cur->ai_family != AF_INET6) 1318 { 1319 TRACE("skipping non-IP/IPv6 address family\n"); 1320 continue; 1321 } 1322 1323 if (TRACE_ON(rpc)) 1324 { 1325 char host[256]; 1326 getnameinfo(ai_cur->ai_addr, ai_cur->ai_addrlen, 1327 host, sizeof(host), service, sizeof(service), 1328 NI_NUMERICHOST | NI_NUMERICSERV); 1329 TRACE("trying %s:%s\n", host, service); 1330 } 1331 1332 sock = socket(ai_cur->ai_family, ai_cur->ai_socktype, ai_cur->ai_protocol); 1333 if (sock == -1) 1334 { 1335 WARN("socket() failed: %s\n", strerror(errno)); 1336 status = RPC_S_CANT_CREATE_ENDPOINT; 1337 continue; 1338 } 1339 1340 ret = bind(sock, ai_cur->ai_addr, ai_cur->ai_addrlen); 1341 if (ret < 0) 1342 { 1343 WARN("bind failed: %s\n", strerror(errno)); 1344 closesocket(sock); 1345 if (errno == EADDRINUSE) 1346 status = RPC_S_DUPLICATE_ENDPOINT; 1347 else 1348 status = RPC_S_CANT_CREATE_ENDPOINT; 1349 continue; 1350 } 1351 1352 sa_len = sizeof(sa); 1353 if (getsockname(sock, (struct sockaddr *)&sa, &sa_len)) 1354 { 1355 WARN("getsockname() failed: %s\n", strerror(errno)); 1356 status = RPC_S_CANT_CREATE_ENDPOINT; 1357 continue; 1358 } 1359 1360 ret = getnameinfo((struct sockaddr *)&sa, sa_len, 1361 NULL, 0, service, sizeof(service), 1362 NI_NUMERICSERV); 1363 if (ret) 1364 { 1365 WARN("getnameinfo failed: %s\n", gai_strerror(ret)); 1366 status = RPC_S_CANT_CREATE_ENDPOINT; 1367 continue; 1368 } 1369 1370 create_status = RPCRT4_CreateConnection((RpcConnection **)&tcpc, TRUE, 1371 protseq->Protseq, NULL, 1372 service, NULL, NULL, NULL); 1373 if (create_status != RPC_S_OK) 1374 { 1375 closesocket(sock); 1376 status = create_status; 1377 continue; 1378 } 1379 1380 tcpc->sock = sock; 1381 ret = listen(sock, protseq->MaxCalls); 1382 if (ret < 0) 1383 { 1384 WARN("listen failed: %s\n", strerror(errno)); 1385 RPCRT4_DestroyConnection(&tcpc->common); 1386 status = RPC_S_OUT_OF_RESOURCES; 1387 continue; 1388 } 1389 /* need a non-blocking socket, otherwise accept() has a potential 1390 * race-condition (poll() says it is readable, connection drops, 1391 * and accept() blocks until the next connection comes...) 1392 */ 1393 nonblocking = 1; 1394 ret = ioctlsocket(sock, FIONBIO, &nonblocking); 1395 if (ret < 0) 1396 { 1397 WARN("couldn't make socket non-blocking, error %d\n", ret); 1398 RPCRT4_DestroyConnection(&tcpc->common); 1399 status = RPC_S_OUT_OF_RESOURCES; 1400 continue; 1401 } 1402 1403 tcpc->common.Next = first_connection; 1404 first_connection = &tcpc->common; 1405 1406 /* since IPv4 and IPv6 share the same port space, we only need one 1407 * successful bind to listen for both */ 1408 break; 1409 } 1410 1411 freeaddrinfo(ai); 1412 1413 /* if at least one connection was created for an endpoint then 1414 * return success */ 1415 if (first_connection) 1416 { 1417 RpcConnection *conn; 1418 1419 /* find last element in list */ 1420 for (conn = first_connection; conn->Next; conn = conn->Next) 1421 ; 1422 1423 EnterCriticalSection(&protseq->cs); 1424 conn->Next = protseq->conn; 1425 protseq->conn = first_connection; 1426 LeaveCriticalSection(&protseq->cs); 1427 1428 TRACE("listening on %s\n", endpoint); 1429 return RPC_S_OK; 1430 } 1431 1432 ERR("couldn't listen on port %s\n", endpoint); 1433 return status; 1434 } 1435 1436 static RPC_STATUS rpcrt4_conn_tcp_handoff(RpcConnection *old_conn, RpcConnection *new_conn) 1437 { 1438 int ret; 1439 struct sockaddr_in address; 1440 socklen_t addrsize; 1441 RpcConnection_tcp *server = (RpcConnection_tcp*) old_conn; 1442 RpcConnection_tcp *client = (RpcConnection_tcp*) new_conn; 1443 u_long nonblocking; 1444 1445 addrsize = sizeof(address); 1446 ret = accept(server->sock, (struct sockaddr*) &address, &addrsize); 1447 if (ret < 0) 1448 { 1449 ERR("Failed to accept a TCP connection: error %d\n", ret); 1450 return RPC_S_OUT_OF_RESOURCES; 1451 } 1452 nonblocking = 1; 1453 ioctlsocket(ret, FIONBIO, &nonblocking); 1454 client->sock = ret; 1455 TRACE("Accepted a new TCP connection\n"); 1456 return RPC_S_OK; 1457 } 1458 1459 static int rpcrt4_conn_tcp_read(RpcConnection *Connection, 1460 void *buffer, unsigned int count) 1461 { 1462 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection; 1463 int bytes_read = 0; 1464 while (bytes_read != count) 1465 { 1466 int r = recv(tcpc->sock, (char *)buffer + bytes_read, count - bytes_read, 0); 1467 if (!r) 1468 return -1; 1469 else if (r > 0) 1470 bytes_read += r; 1471 else if (errno != EAGAIN) 1472 { 1473 WARN("recv() failed: %s\n", strerror(errno)); 1474 return -1; 1475 } 1476 else 1477 { 1478 if (!rpcrt4_sock_wait_for_recv(tcpc)) 1479 return -1; 1480 } 1481 } 1482 TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_read); 1483 return bytes_read; 1484 } 1485 1486 static int rpcrt4_conn_tcp_write(RpcConnection *Connection, 1487 const void *buffer, unsigned int count) 1488 { 1489 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection; 1490 int bytes_written = 0; 1491 while (bytes_written != count) 1492 { 1493 int r = send(tcpc->sock, (const char *)buffer + bytes_written, count - bytes_written, 0); 1494 if (r >= 0) 1495 bytes_written += r; 1496 else if (errno != EAGAIN) 1497 return -1; 1498 else 1499 { 1500 if (!rpcrt4_sock_wait_for_send(tcpc)) 1501 return -1; 1502 } 1503 } 1504 TRACE("%d %p %u -> %d\n", tcpc->sock, buffer, count, bytes_written); 1505 return bytes_written; 1506 } 1507 1508 static int rpcrt4_conn_tcp_close(RpcConnection *Connection) 1509 { 1510 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection; 1511 1512 TRACE("%d\n", tcpc->sock); 1513 1514 if (tcpc->sock != -1) 1515 closesocket(tcpc->sock); 1516 tcpc->sock = -1; 1517 rpcrt4_sock_wait_destroy(tcpc); 1518 return 0; 1519 } 1520 1521 static void rpcrt4_conn_tcp_cancel_call(RpcConnection *Connection) 1522 { 1523 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection; 1524 TRACE("%p\n", Connection); 1525 rpcrt4_sock_wait_cancel(tcpc); 1526 } 1527 1528 static int rpcrt4_conn_tcp_wait_for_incoming_data(RpcConnection *Connection) 1529 { 1530 RpcConnection_tcp *tcpc = (RpcConnection_tcp *) Connection; 1531 1532 TRACE("%p\n", Connection); 1533 1534 if (!rpcrt4_sock_wait_for_recv(tcpc)) 1535 return -1; 1536 return 0; 1537 } 1538 1539 static size_t rpcrt4_ncacn_ip_tcp_get_top_of_tower(unsigned char *tower_data, 1540 const char *networkaddr, 1541 const char *endpoint) 1542 { 1543 return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr, 1544 EPM_PROTOCOL_TCP, endpoint); 1545 } 1546 1547 #ifdef HAVE_SOCKETPAIR 1548 1549 typedef struct _RpcServerProtseq_sock 1550 { 1551 RpcServerProtseq common; 1552 int mgr_event_rcv; 1553 int mgr_event_snd; 1554 } RpcServerProtseq_sock; 1555 1556 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void) 1557 { 1558 RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps)); 1559 if (ps) 1560 { 1561 int fds[2]; 1562 if (!socketpair(PF_UNIX, SOCK_DGRAM, 0, fds)) 1563 { 1564 fcntl(fds[0], F_SETFL, O_NONBLOCK); 1565 fcntl(fds[1], F_SETFL, O_NONBLOCK); 1566 ps->mgr_event_rcv = fds[0]; 1567 ps->mgr_event_snd = fds[1]; 1568 } 1569 else 1570 { 1571 ERR("socketpair failed with error %s\n", strerror(errno)); 1572 HeapFree(GetProcessHeap(), 0, ps); 1573 return NULL; 1574 } 1575 } 1576 return &ps->common; 1577 } 1578 1579 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq) 1580 { 1581 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common); 1582 char dummy = 1; 1583 write(sockps->mgr_event_snd, &dummy, sizeof(dummy)); 1584 } 1585 1586 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count) 1587 { 1588 struct pollfd *poll_info = prev_array; 1589 RpcConnection_tcp *conn; 1590 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common); 1591 1592 EnterCriticalSection(&protseq->cs); 1593 1594 /* open and count connections */ 1595 *count = 1; 1596 conn = (RpcConnection_tcp *)protseq->conn; 1597 while (conn) { 1598 if (conn->sock != -1) 1599 (*count)++; 1600 conn = (RpcConnection_tcp *)conn->common.Next; 1601 } 1602 1603 /* make array of connections */ 1604 if (poll_info) 1605 poll_info = HeapReAlloc(GetProcessHeap(), 0, poll_info, *count*sizeof(*poll_info)); 1606 else 1607 poll_info = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(*poll_info)); 1608 if (!poll_info) 1609 { 1610 ERR("couldn't allocate poll_info\n"); 1611 LeaveCriticalSection(&protseq->cs); 1612 return NULL; 1613 } 1614 1615 poll_info[0].fd = sockps->mgr_event_rcv; 1616 poll_info[0].events = POLLIN; 1617 *count = 1; 1618 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common); 1619 while (conn) { 1620 if (conn->sock != -1) 1621 { 1622 poll_info[*count].fd = conn->sock; 1623 poll_info[*count].events = POLLIN; 1624 (*count)++; 1625 } 1626 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common); 1627 } 1628 LeaveCriticalSection(&protseq->cs); 1629 return poll_info; 1630 } 1631 1632 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array) 1633 { 1634 HeapFree(GetProcessHeap(), 0, array); 1635 } 1636 1637 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array) 1638 { 1639 struct pollfd *poll_info = wait_array; 1640 int ret; 1641 unsigned int i; 1642 RpcConnection *cconn; 1643 RpcConnection_tcp *conn; 1644 1645 if (!poll_info) 1646 return -1; 1647 1648 ret = poll(poll_info, count, -1); 1649 if (ret < 0) 1650 { 1651 ERR("poll failed with error %d\n", ret); 1652 return -1; 1653 } 1654 1655 for (i = 0; i < count; i++) 1656 if (poll_info[i].revents & POLLIN) 1657 { 1658 /* RPC server event */ 1659 if (i == 0) 1660 { 1661 char dummy; 1662 read(poll_info[0].fd, &dummy, sizeof(dummy)); 1663 return 0; 1664 } 1665 1666 /* find which connection got a RPC */ 1667 EnterCriticalSection(&protseq->cs); 1668 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common); 1669 while (conn) { 1670 if (poll_info[i].fd == conn->sock) break; 1671 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common); 1672 } 1673 cconn = NULL; 1674 if (conn) 1675 RPCRT4_SpawnConnection(&cconn, &conn->common); 1676 else 1677 ERR("failed to locate connection for fd %d\n", poll_info[i].fd); 1678 LeaveCriticalSection(&protseq->cs); 1679 if (cconn) 1680 RPCRT4_new_client(cconn); 1681 else 1682 return -1; 1683 } 1684 1685 return 1; 1686 } 1687 1688 #else /* HAVE_SOCKETPAIR */ 1689 1690 typedef struct _RpcServerProtseq_sock 1691 { 1692 RpcServerProtseq common; 1693 HANDLE mgr_event; 1694 } RpcServerProtseq_sock; 1695 1696 static RpcServerProtseq *rpcrt4_protseq_sock_alloc(void) 1697 { 1698 RpcServerProtseq_sock *ps = HeapAlloc(GetProcessHeap(), 0, sizeof(*ps)); 1699 if (ps) 1700 { 1701 static BOOL wsa_inited; 1702 if (!wsa_inited) 1703 { 1704 WSADATA wsadata; 1705 WSAStartup(MAKEWORD(2, 2), &wsadata); 1706 /* Note: WSAStartup can be called more than once so we don't bother with 1707 * making accesses to wsa_inited thread-safe */ 1708 wsa_inited = TRUE; 1709 } 1710 ps->mgr_event = CreateEventW(NULL, FALSE, FALSE, NULL); 1711 } 1712 return &ps->common; 1713 } 1714 1715 static void rpcrt4_protseq_sock_signal_state_changed(RpcServerProtseq *protseq) 1716 { 1717 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common); 1718 SetEvent(sockps->mgr_event); 1719 } 1720 1721 static void *rpcrt4_protseq_sock_get_wait_array(RpcServerProtseq *protseq, void *prev_array, unsigned int *count) 1722 { 1723 HANDLE *objs = prev_array; 1724 RpcConnection_tcp *conn; 1725 RpcServerProtseq_sock *sockps = CONTAINING_RECORD(protseq, RpcServerProtseq_sock, common); 1726 1727 EnterCriticalSection(&protseq->cs); 1728 1729 /* open and count connections */ 1730 *count = 1; 1731 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common); 1732 while (conn) 1733 { 1734 if (conn->sock != -1) 1735 (*count)++; 1736 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common); 1737 } 1738 1739 /* make array of connections */ 1740 if (objs) 1741 objs = HeapReAlloc(GetProcessHeap(), 0, objs, *count*sizeof(HANDLE)); 1742 else 1743 objs = HeapAlloc(GetProcessHeap(), 0, *count*sizeof(HANDLE)); 1744 if (!objs) 1745 { 1746 ERR("couldn't allocate objs\n"); 1747 LeaveCriticalSection(&protseq->cs); 1748 return NULL; 1749 } 1750 1751 objs[0] = sockps->mgr_event; 1752 *count = 1; 1753 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common); 1754 while (conn) 1755 { 1756 if (conn->sock != -1) 1757 { 1758 int res = WSAEventSelect(conn->sock, conn->sock_event, FD_ACCEPT); 1759 if (res == SOCKET_ERROR) 1760 ERR("WSAEventSelect() failed with error %d\n", WSAGetLastError()); 1761 else 1762 { 1763 objs[*count] = conn->sock_event; 1764 (*count)++; 1765 } 1766 } 1767 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common); 1768 } 1769 LeaveCriticalSection(&protseq->cs); 1770 return objs; 1771 } 1772 1773 static void rpcrt4_protseq_sock_free_wait_array(RpcServerProtseq *protseq, void *array) 1774 { 1775 HeapFree(GetProcessHeap(), 0, array); 1776 } 1777 1778 static int rpcrt4_protseq_sock_wait_for_new_connection(RpcServerProtseq *protseq, unsigned int count, void *wait_array) 1779 { 1780 HANDLE b_handle; 1781 HANDLE *objs = wait_array; 1782 DWORD res; 1783 RpcConnection *cconn; 1784 RpcConnection_tcp *conn; 1785 1786 if (!objs) 1787 return -1; 1788 1789 do 1790 { 1791 /* an alertable wait isn't strictly necessary, but due to our 1792 * overlapped I/O implementation in Wine we need to free some memory 1793 * by the file user APC being called, even if no completion routine was 1794 * specified at the time of starting the async operation */ 1795 res = WaitForMultipleObjectsEx(count, objs, FALSE, INFINITE, TRUE); 1796 } while (res == WAIT_IO_COMPLETION); 1797 1798 if (res == WAIT_OBJECT_0) 1799 return 0; 1800 else if (res == WAIT_FAILED) 1801 { 1802 ERR("wait failed with error %d\n", GetLastError()); 1803 return -1; 1804 } 1805 else 1806 { 1807 b_handle = objs[res - WAIT_OBJECT_0]; 1808 /* find which connection got a RPC */ 1809 EnterCriticalSection(&protseq->cs); 1810 conn = CONTAINING_RECORD(protseq->conn, RpcConnection_tcp, common); 1811 while (conn) 1812 { 1813 if (b_handle == conn->sock_event) break; 1814 conn = CONTAINING_RECORD(conn->common.Next, RpcConnection_tcp, common); 1815 } 1816 cconn = NULL; 1817 if (conn) 1818 RPCRT4_SpawnConnection(&cconn, &conn->common); 1819 else 1820 ERR("failed to locate connection for handle %p\n", b_handle); 1821 LeaveCriticalSection(&protseq->cs); 1822 if (cconn) 1823 { 1824 RPCRT4_new_client(cconn); 1825 return 1; 1826 } 1827 else return -1; 1828 } 1829 } 1830 1831 #endif /* HAVE_SOCKETPAIR */ 1832 1833 static RPC_STATUS rpcrt4_ncacn_ip_tcp_parse_top_of_tower(const unsigned char *tower_data, 1834 size_t tower_size, 1835 char **networkaddr, 1836 char **endpoint) 1837 { 1838 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size, 1839 networkaddr, EPM_PROTOCOL_TCP, 1840 endpoint); 1841 } 1842 1843 /**** ncacn_http support ****/ 1844 1845 /* 60 seconds is the period native uses */ 1846 #define HTTP_IDLE_TIME 60000 1847 1848 /* reference counted to avoid a race between a cancelled call's connection 1849 * being destroyed and the asynchronous InternetReadFileEx call being 1850 * completed */ 1851 typedef struct _RpcHttpAsyncData 1852 { 1853 LONG refs; 1854 HANDLE completion_event; 1855 INTERNET_BUFFERSA inet_buffers; 1856 void *destination_buffer; /* the address that inet_buffers.lpvBuffer will be 1857 * copied into when the call completes */ 1858 CRITICAL_SECTION cs; 1859 } RpcHttpAsyncData; 1860 1861 static ULONG RpcHttpAsyncData_AddRef(RpcHttpAsyncData *data) 1862 { 1863 return InterlockedIncrement(&data->refs); 1864 } 1865 1866 static ULONG RpcHttpAsyncData_Release(RpcHttpAsyncData *data) 1867 { 1868 ULONG refs = InterlockedDecrement(&data->refs); 1869 if (!refs) 1870 { 1871 TRACE("destroying async data %p\n", data); 1872 CloseHandle(data->completion_event); 1873 HeapFree(GetProcessHeap(), 0, data->inet_buffers.lpvBuffer); 1874 DeleteCriticalSection(&data->cs); 1875 HeapFree(GetProcessHeap(), 0, data); 1876 } 1877 return refs; 1878 } 1879 1880 typedef struct _RpcConnection_http 1881 { 1882 RpcConnection common; 1883 HINTERNET app_info; 1884 HINTERNET session; 1885 HINTERNET in_request; 1886 HINTERNET out_request; 1887 HANDLE timer_cancelled; 1888 HANDLE cancel_event; 1889 DWORD last_sent_time; 1890 ULONG bytes_received; 1891 ULONG flow_control_mark; /* send a control packet to the server when this many bytes received */ 1892 ULONG flow_control_increment; /* number of bytes to increment flow_control_mark by */ 1893 UUID connection_uuid; 1894 UUID in_pipe_uuid; 1895 UUID out_pipe_uuid; 1896 RpcHttpAsyncData *async_data; 1897 } RpcConnection_http; 1898 1899 static RpcConnection *rpcrt4_ncacn_http_alloc(void) 1900 { 1901 RpcConnection_http *httpc; 1902 httpc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*httpc)); 1903 if (!httpc) return NULL; 1904 httpc->async_data = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(RpcHttpAsyncData)); 1905 if (!httpc->async_data) 1906 { 1907 HeapFree(GetProcessHeap(), 0, httpc); 1908 return NULL; 1909 } 1910 TRACE("async data = %p\n", httpc->async_data); 1911 httpc->cancel_event = CreateEventW(NULL, FALSE, FALSE, NULL); 1912 httpc->async_data->refs = 1; 1913 httpc->async_data->inet_buffers.dwStructSize = sizeof(INTERNET_BUFFERSA); 1914 httpc->async_data->inet_buffers.lpvBuffer = NULL; 1915 httpc->async_data->destination_buffer = NULL; 1916 InitializeCriticalSection(&httpc->async_data->cs); 1917 return &httpc->common; 1918 } 1919 1920 typedef struct _HttpTimerThreadData 1921 { 1922 PVOID timer_param; 1923 DWORD *last_sent_time; 1924 HANDLE timer_cancelled; 1925 } HttpTimerThreadData; 1926 1927 static VOID rpcrt4_http_keep_connection_active_timer_proc(PVOID param, BOOLEAN dummy) 1928 { 1929 HINTERNET in_request = param; 1930 RpcPktHdr *idle_pkt; 1931 1932 idle_pkt = RPCRT4_BuildHttpHeader(NDR_LOCAL_DATA_REPRESENTATION, 0x0001, 1933 0, 0); 1934 if (idle_pkt) 1935 { 1936 DWORD bytes_written; 1937 InternetWriteFile(in_request, idle_pkt, idle_pkt->common.frag_len, &bytes_written); 1938 RPCRT4_FreeHeader(idle_pkt); 1939 } 1940 } 1941 1942 static inline DWORD rpcrt4_http_timer_calc_timeout(DWORD *last_sent_time) 1943 { 1944 DWORD cur_time = GetTickCount(); 1945 DWORD cached_last_sent_time = *last_sent_time; 1946 return HTTP_IDLE_TIME - (cur_time - cached_last_sent_time > HTTP_IDLE_TIME ? 0 : cur_time - cached_last_sent_time); 1947 } 1948 1949 static DWORD CALLBACK rpcrt4_http_timer_thread(PVOID param) 1950 { 1951 HttpTimerThreadData *data_in = param; 1952 HttpTimerThreadData data; 1953 DWORD timeout; 1954 1955 data = *data_in; 1956 HeapFree(GetProcessHeap(), 0, data_in); 1957 1958 for (timeout = HTTP_IDLE_TIME; 1959 WaitForSingleObject(data.timer_cancelled, timeout) == WAIT_TIMEOUT; 1960 timeout = rpcrt4_http_timer_calc_timeout(data.last_sent_time)) 1961 { 1962 /* are we too soon after last send? */ 1963 if (GetTickCount() - HTTP_IDLE_TIME < *data.last_sent_time) 1964 continue; 1965 rpcrt4_http_keep_connection_active_timer_proc(data.timer_param, TRUE); 1966 } 1967 1968 CloseHandle(data.timer_cancelled); 1969 return 0; 1970 } 1971 1972 static VOID WINAPI rpcrt4_http_internet_callback( 1973 HINTERNET hInternet, 1974 DWORD_PTR dwContext, 1975 DWORD dwInternetStatus, 1976 LPVOID lpvStatusInformation, 1977 DWORD dwStatusInformationLength) 1978 { 1979 RpcHttpAsyncData *async_data = (RpcHttpAsyncData *)dwContext; 1980 1981 switch (dwInternetStatus) 1982 { 1983 case INTERNET_STATUS_REQUEST_COMPLETE: 1984 TRACE("INTERNET_STATUS_REQUEST_COMPLETED\n"); 1985 if (async_data) 1986 { 1987 if (async_data->inet_buffers.lpvBuffer) 1988 { 1989 EnterCriticalSection(&async_data->cs); 1990 if (async_data->destination_buffer) 1991 { 1992 memcpy(async_data->destination_buffer, 1993 async_data->inet_buffers.lpvBuffer, 1994 async_data->inet_buffers.dwBufferLength); 1995 async_data->destination_buffer = NULL; 1996 } 1997 LeaveCriticalSection(&async_data->cs); 1998 } 1999 HeapFree(GetProcessHeap(), 0, async_data->inet_buffers.lpvBuffer); 2000 async_data->inet_buffers.lpvBuffer = NULL; 2001 SetEvent(async_data->completion_event); 2002 RpcHttpAsyncData_Release(async_data); 2003 } 2004 break; 2005 } 2006 } 2007 2008 static RPC_STATUS rpcrt4_http_check_response(HINTERNET hor) 2009 { 2010 BOOL ret; 2011 DWORD status_code; 2012 DWORD size; 2013 DWORD index; 2014 WCHAR buf[32]; 2015 WCHAR *status_text = buf; 2016 TRACE("\n"); 2017 2018 index = 0; 2019 size = sizeof(status_code); 2020 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, &status_code, &size, &index); 2021 if (!ret) 2022 return GetLastError(); 2023 if (status_code < 400) 2024 return RPC_S_OK; 2025 index = 0; 2026 size = sizeof(buf); 2027 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index); 2028 if (!ret && GetLastError() == ERROR_INSUFFICIENT_BUFFER) 2029 { 2030 status_text = HeapAlloc(GetProcessHeap(), 0, size); 2031 ret = HttpQueryInfoW(hor, HTTP_QUERY_STATUS_TEXT, status_text, &size, &index); 2032 } 2033 2034 ERR("server returned: %d %s\n", status_code, ret ? debugstr_w(status_text) : "<status text unavailable>"); 2035 if(status_text != buf) HeapFree(GetProcessHeap(), 0, status_text); 2036 2037 if (status_code == HTTP_STATUS_DENIED) 2038 return ERROR_ACCESS_DENIED; 2039 return RPC_S_SERVER_UNAVAILABLE; 2040 } 2041 2042 static RPC_STATUS rpcrt4_http_internet_connect(RpcConnection_http *httpc) 2043 { 2044 static const WCHAR wszUserAgent[] = {'M','S','R','P','C',0}; 2045 LPWSTR proxy = NULL; 2046 LPWSTR user = NULL; 2047 LPWSTR password = NULL; 2048 LPWSTR servername = NULL; 2049 const WCHAR *option; 2050 INTERNET_PORT port = INTERNET_INVALID_PORT_NUMBER; /* use default port */ 2051 2052 if (httpc->common.QOS && 2053 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP)) 2054 { 2055 const RPC_HTTP_TRANSPORT_CREDENTIALS_W *http_cred = httpc->common.QOS->qos->u.HttpCredentials; 2056 if (http_cred->TransportCredentials) 2057 { 2058 WCHAR *p; 2059 const SEC_WINNT_AUTH_IDENTITY_W *cred = http_cred->TransportCredentials; 2060 ULONG len = cred->DomainLength + 1 + cred->UserLength; 2061 user = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR)); 2062 if (!user) 2063 return RPC_S_OUT_OF_RESOURCES; 2064 p = user; 2065 if (cred->DomainLength) 2066 { 2067 memcpy(p, cred->Domain, cred->DomainLength * sizeof(WCHAR)); 2068 p += cred->DomainLength; 2069 *p = '\\'; 2070 p++; 2071 } 2072 memcpy(p, cred->User, cred->UserLength * sizeof(WCHAR)); 2073 p[cred->UserLength] = 0; 2074 2075 password = RPCRT4_strndupW(cred->Password, cred->PasswordLength); 2076 } 2077 } 2078 2079 for (option = httpc->common.NetworkOptions; option; 2080 option = (strchrW(option, ',') ? strchrW(option, ',')+1 : NULL)) 2081 { 2082 static const WCHAR wszRpcProxy[] = {'R','p','c','P','r','o','x','y','=',0}; 2083 static const WCHAR wszHttpProxy[] = {'H','t','t','p','P','r','o','x','y','=',0}; 2084 2085 if (!strncmpiW(option, wszRpcProxy, sizeof(wszRpcProxy)/sizeof(wszRpcProxy[0])-1)) 2086 { 2087 const WCHAR *value_start = option + sizeof(wszRpcProxy)/sizeof(wszRpcProxy[0])-1; 2088 const WCHAR *value_end; 2089 const WCHAR *p; 2090 2091 value_end = strchrW(option, ','); 2092 if (!value_end) 2093 value_end = value_start + strlenW(value_start); 2094 for (p = value_start; p < value_end; p++) 2095 if (*p == ':') 2096 { 2097 port = atoiW(p+1); 2098 value_end = p; 2099 break; 2100 } 2101 TRACE("RpcProxy value is %s\n", debugstr_wn(value_start, value_end-value_start)); 2102 servername = RPCRT4_strndupW(value_start, value_end-value_start); 2103 } 2104 else if (!strncmpiW(option, wszHttpProxy, sizeof(wszHttpProxy)/sizeof(wszHttpProxy[0])-1)) 2105 { 2106 const WCHAR *value_start = option + sizeof(wszHttpProxy)/sizeof(wszHttpProxy[0])-1; 2107 const WCHAR *value_end; 2108 2109 value_end = strchrW(option, ','); 2110 if (!value_end) 2111 value_end = value_start + strlenW(value_start); 2112 TRACE("HttpProxy value is %s\n", debugstr_wn(value_start, value_end-value_start)); 2113 proxy = RPCRT4_strndupW(value_start, value_end-value_start); 2114 } 2115 else 2116 FIXME("unhandled option %s\n", debugstr_w(option)); 2117 } 2118 2119 httpc->app_info = InternetOpenW(wszUserAgent, proxy ? INTERNET_OPEN_TYPE_PROXY : INTERNET_OPEN_TYPE_PRECONFIG, 2120 NULL, NULL, INTERNET_FLAG_ASYNC); 2121 if (!httpc->app_info) 2122 { 2123 HeapFree(GetProcessHeap(), 0, password); 2124 HeapFree(GetProcessHeap(), 0, user); 2125 ERR("InternetOpenW failed with error %d\n", GetLastError()); 2126 return RPC_S_SERVER_UNAVAILABLE; 2127 } 2128 InternetSetStatusCallbackW(httpc->app_info, rpcrt4_http_internet_callback); 2129 2130 /* if no RpcProxy option specified, set the HTTP server address to the 2131 * RPC server address */ 2132 if (!servername) 2133 { 2134 servername = HeapAlloc(GetProcessHeap(), 0, (strlen(httpc->common.NetworkAddr) + 1)*sizeof(WCHAR)); 2135 if (!servername) 2136 { 2137 HeapFree(GetProcessHeap(), 0, password); 2138 HeapFree(GetProcessHeap(), 0, user); 2139 return RPC_S_OUT_OF_RESOURCES; 2140 } 2141 MultiByteToWideChar(CP_ACP, 0, httpc->common.NetworkAddr, -1, servername, strlen(httpc->common.NetworkAddr) + 1); 2142 } 2143 2144 httpc->session = InternetConnectW(httpc->app_info, servername, port, user, password, 2145 INTERNET_SERVICE_HTTP, 0, 0); 2146 2147 HeapFree(GetProcessHeap(), 0, password); 2148 HeapFree(GetProcessHeap(), 0, user); 2149 HeapFree(GetProcessHeap(), 0, servername); 2150 2151 if (!httpc->session) 2152 { 2153 ERR("InternetConnectW failed with error %d\n", GetLastError()); 2154 return RPC_S_SERVER_UNAVAILABLE; 2155 } 2156 2157 return RPC_S_OK; 2158 } 2159 2160 /* prepare the in pipe for use by RPC packets */ 2161 static RPC_STATUS rpcrt4_http_prepare_in_pipe(HINTERNET in_request, RpcHttpAsyncData *async_data, 2162 const UUID *connection_uuid, 2163 const UUID *in_pipe_uuid, 2164 const UUID *association_uuid) 2165 { 2166 BYTE packet[44]; 2167 BOOL ret; 2168 RPC_STATUS status; 2169 RpcPktHdr *hdr; 2170 INTERNET_BUFFERSW buffers_in; 2171 DWORD bytes_read, bytes_written; 2172 2173 /* prepare in pipe */ 2174 ResetEvent(async_data->completion_event); 2175 RpcHttpAsyncData_AddRef(async_data); 2176 ret = HttpSendRequestW(in_request, NULL, 0, NULL, 0); 2177 if (!ret) 2178 { 2179 if (GetLastError() == ERROR_IO_PENDING) 2180 WaitForSingleObject(async_data->completion_event, INFINITE); 2181 else 2182 { 2183 RpcHttpAsyncData_Release(async_data); 2184 ERR("HttpSendRequestW failed with error %d\n", GetLastError()); 2185 return RPC_S_SERVER_UNAVAILABLE; 2186 } 2187 } 2188 status = rpcrt4_http_check_response(in_request); 2189 if (status != RPC_S_OK) return status; 2190 2191 InternetReadFile(in_request, packet, 20, &bytes_read); 2192 /* FIXME: do something with retrieved data */ 2193 2194 memset(&buffers_in, 0, sizeof(buffers_in)); 2195 buffers_in.dwStructSize = sizeof(buffers_in); 2196 /* FIXME: get this from the registry */ 2197 buffers_in.dwBufferTotal = 1024 * 1024 * 1024; /* 1Gb */ 2198 ResetEvent(async_data->completion_event); 2199 RpcHttpAsyncData_AddRef(async_data); 2200 ret = HttpSendRequestExW(in_request, &buffers_in, NULL, 0, 0); 2201 if (!ret) 2202 { 2203 if (GetLastError() == ERROR_IO_PENDING) 2204 WaitForSingleObject(async_data->completion_event, INFINITE); 2205 else 2206 { 2207 RpcHttpAsyncData_Release(async_data); 2208 ERR("HttpSendRequestExW failed with error %d\n", GetLastError()); 2209 return RPC_S_SERVER_UNAVAILABLE; 2210 } 2211 } 2212 2213 TRACE("sending HTTP connect header to server\n"); 2214 hdr = RPCRT4_BuildHttpConnectHeader(0, FALSE, connection_uuid, in_pipe_uuid, association_uuid); 2215 if (!hdr) return RPC_S_OUT_OF_RESOURCES; 2216 ret = InternetWriteFile(in_request, hdr, hdr->common.frag_len, &bytes_written); 2217 RPCRT4_FreeHeader(hdr); 2218 if (!ret) 2219 { 2220 ERR("InternetWriteFile failed with error %d\n", GetLastError()); 2221 return RPC_S_SERVER_UNAVAILABLE; 2222 } 2223 2224 return RPC_S_OK; 2225 } 2226 2227 static RPC_STATUS rpcrt4_http_read_http_packet(HINTERNET request, RpcPktHdr *hdr, BYTE **data) 2228 { 2229 BOOL ret; 2230 DWORD bytes_read; 2231 unsigned short data_len; 2232 2233 ret = InternetReadFile(request, hdr, sizeof(hdr->common), &bytes_read); 2234 if (!ret) 2235 return RPC_S_SERVER_UNAVAILABLE; 2236 if (hdr->common.ptype != PKT_HTTP || hdr->common.frag_len < sizeof(hdr->http)) 2237 { 2238 ERR("wrong packet type received %d or wrong frag_len %d\n", 2239 hdr->common.ptype, hdr->common.frag_len); 2240 return RPC_S_PROTOCOL_ERROR; 2241 } 2242 2243 ret = InternetReadFile(request, &hdr->common + 1, sizeof(hdr->http) - sizeof(hdr->common), &bytes_read); 2244 if (!ret) 2245 return RPC_S_SERVER_UNAVAILABLE; 2246 2247 data_len = hdr->common.frag_len - sizeof(hdr->http); 2248 if (data_len) 2249 { 2250 *data = HeapAlloc(GetProcessHeap(), 0, data_len); 2251 if (!*data) 2252 return RPC_S_OUT_OF_RESOURCES; 2253 ret = InternetReadFile(request, *data, data_len, &bytes_read); 2254 if (!ret) 2255 { 2256 HeapFree(GetProcessHeap(), 0, *data); 2257 return RPC_S_SERVER_UNAVAILABLE; 2258 } 2259 } 2260 else 2261 *data = NULL; 2262 2263 if (!RPCRT4_IsValidHttpPacket(hdr, *data, data_len)) 2264 { 2265 ERR("invalid http packet\n"); 2266 return RPC_S_PROTOCOL_ERROR; 2267 } 2268 2269 return RPC_S_OK; 2270 } 2271 2272 /* prepare the out pipe for use by RPC packets */ 2273 static RPC_STATUS rpcrt4_http_prepare_out_pipe(HINTERNET out_request, 2274 RpcHttpAsyncData *async_data, 2275 const UUID *connection_uuid, 2276 const UUID *out_pipe_uuid, 2277 ULONG *flow_control_increment) 2278 { 2279 BYTE packet[20]; 2280 BOOL ret; 2281 RPC_STATUS status; 2282 RpcPktHdr *hdr; 2283 DWORD bytes_read; 2284 BYTE *data_from_server; 2285 RpcPktHdr pkt_from_server; 2286 ULONG field1, field3; 2287 2288 ResetEvent(async_data->completion_event); 2289 RpcHttpAsyncData_AddRef(async_data); 2290 ret = HttpSendRequestW(out_request, NULL, 0, NULL, 0); 2291 if (!ret) 2292 { 2293 if (GetLastError() == ERROR_IO_PENDING) 2294 WaitForSingleObject(async_data->completion_event, INFINITE); 2295 else 2296 { 2297 RpcHttpAsyncData_Release(async_data); 2298 ERR("HttpSendRequestW failed with error %d\n", GetLastError()); 2299 return RPC_S_SERVER_UNAVAILABLE; 2300 } 2301 } 2302 status = rpcrt4_http_check_response(out_request); 2303 if (status != RPC_S_OK) return status; 2304 2305 InternetReadFile(out_request, packet, 20, &bytes_read); 2306 /* FIXME: do something with retrieved data */ 2307 2308 hdr = RPCRT4_BuildHttpConnectHeader(0, TRUE, connection_uuid, out_pipe_uuid, NULL); 2309 if (!hdr) return RPC_S_OUT_OF_RESOURCES; 2310 ResetEvent(async_data->completion_event); 2311 RpcHttpAsyncData_AddRef(async_data); 2312 ret = HttpSendRequestW(out_request, NULL, 0, hdr, hdr->common.frag_len); 2313 if (!ret) 2314 { 2315 if (GetLastError() == ERROR_IO_PENDING) 2316 WaitForSingleObject(async_data->completion_event, INFINITE); 2317 else 2318 { 2319 RpcHttpAsyncData_Release(async_data); 2320 ERR("HttpSendRequestW failed with error %d\n", GetLastError()); 2321 RPCRT4_FreeHeader(hdr); 2322 return RPC_S_SERVER_UNAVAILABLE; 2323 } 2324 } 2325 RPCRT4_FreeHeader(hdr); 2326 status = rpcrt4_http_check_response(out_request); 2327 if (status != RPC_S_OK) return status; 2328 2329 status = rpcrt4_http_read_http_packet(out_request, &pkt_from_server, 2330 &data_from_server); 2331 if (status != RPC_S_OK) return status; 2332 status = RPCRT4_ParseHttpPrepareHeader1(&pkt_from_server, data_from_server, 2333 &field1); 2334 HeapFree(GetProcessHeap(), 0, data_from_server); 2335 if (status != RPC_S_OK) return status; 2336 TRACE("received (%d) from first prepare header\n", field1); 2337 2338 status = rpcrt4_http_read_http_packet(out_request, &pkt_from_server, 2339 &data_from_server); 2340 if (status != RPC_S_OK) return status; 2341 status = RPCRT4_ParseHttpPrepareHeader2(&pkt_from_server, data_from_server, 2342 &field1, flow_control_increment, 2343 &field3); 2344 HeapFree(GetProcessHeap(), 0, data_from_server); 2345 if (status != RPC_S_OK) return status; 2346 TRACE("received (0x%08x 0x%08x %d) from second prepare header\n", field1, *flow_control_increment, field3); 2347 2348 return RPC_S_OK; 2349 } 2350 2351 static RPC_STATUS rpcrt4_ncacn_http_open(RpcConnection* Connection) 2352 { 2353 RpcConnection_http *httpc = (RpcConnection_http *)Connection; 2354 static const WCHAR wszVerbIn[] = {'R','P','C','_','I','N','_','D','A','T','A',0}; 2355 static const WCHAR wszVerbOut[] = {'R','P','C','_','O','U','T','_','D','A','T','A',0}; 2356 static const WCHAR wszRpcProxyPrefix[] = {'/','r','p','c','/','r','p','c','p','r','o','x','y','.','d','l','l','?',0}; 2357 static const WCHAR wszColon[] = {':',0}; 2358 static const WCHAR wszAcceptType[] = {'a','p','p','l','i','c','a','t','i','o','n','/','r','p','c',0}; 2359 LPCWSTR wszAcceptTypes[] = { wszAcceptType, NULL }; 2360 WCHAR *url; 2361 RPC_STATUS status; 2362 BOOL secure; 2363 HttpTimerThreadData *timer_data; 2364 HANDLE thread; 2365 2366 TRACE("(%s, %s)\n", Connection->NetworkAddr, Connection->Endpoint); 2367 2368 if (Connection->server) 2369 { 2370 ERR("ncacn_http servers not supported yet\n"); 2371 return RPC_S_SERVER_UNAVAILABLE; 2372 } 2373 2374 if (httpc->in_request) 2375 return RPC_S_OK; 2376 2377 httpc->async_data->completion_event = CreateEventW(NULL, FALSE, FALSE, NULL); 2378 2379 status = UuidCreate(&httpc->connection_uuid); 2380 status = UuidCreate(&httpc->in_pipe_uuid); 2381 status = UuidCreate(&httpc->out_pipe_uuid); 2382 2383 status = rpcrt4_http_internet_connect(httpc); 2384 if (status != RPC_S_OK) 2385 return status; 2386 2387 url = HeapAlloc(GetProcessHeap(), 0, sizeof(wszRpcProxyPrefix) + (strlen(Connection->NetworkAddr) + 1 + strlen(Connection->Endpoint))*sizeof(WCHAR)); 2388 if (!url) 2389 return RPC_S_OUT_OF_MEMORY; 2390 memcpy(url, wszRpcProxyPrefix, sizeof(wszRpcProxyPrefix)); 2391 MultiByteToWideChar(CP_ACP, 0, Connection->NetworkAddr, -1, url+sizeof(wszRpcProxyPrefix)/sizeof(wszRpcProxyPrefix[0])-1, strlen(Connection->NetworkAddr)+1); 2392 strcatW(url, wszColon); 2393 MultiByteToWideChar(CP_ACP, 0, Connection->Endpoint, -1, url+strlenW(url), strlen(Connection->Endpoint)+1); 2394 2395 secure = httpc->common.QOS && 2396 (httpc->common.QOS->qos->AdditionalSecurityInfoType == RPC_C_AUTHN_INFO_TYPE_HTTP) && 2397 (httpc->common.QOS->qos->u.HttpCredentials->Flags & RPC_C_HTTP_FLAG_USE_SSL); 2398 2399 httpc->in_request = HttpOpenRequestW(httpc->session, wszVerbIn, url, NULL, NULL, 2400 wszAcceptTypes, 2401 (secure ? INTERNET_FLAG_SECURE : 0)|INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_PRAGMA_NOCACHE, 2402 (DWORD_PTR)httpc->async_data); 2403 if (!httpc->in_request) 2404 { 2405 ERR("HttpOpenRequestW failed with error %d\n", GetLastError()); 2406 return RPC_S_SERVER_UNAVAILABLE; 2407 } 2408 httpc->out_request = HttpOpenRequestW(httpc->session, wszVerbOut, url, NULL, NULL, 2409 wszAcceptTypes, 2410 (secure ? INTERNET_FLAG_SECURE : 0)|INTERNET_FLAG_KEEP_CONNECTION|INTERNET_FLAG_PRAGMA_NOCACHE, 2411 (DWORD_PTR)httpc->async_data); 2412 if (!httpc->out_request) 2413 { 2414 ERR("HttpOpenRequestW failed with error %d\n", GetLastError()); 2415 return RPC_S_SERVER_UNAVAILABLE; 2416 } 2417 2418 status = rpcrt4_http_prepare_in_pipe(httpc->in_request, 2419 httpc->async_data, 2420 &httpc->connection_uuid, 2421 &httpc->in_pipe_uuid, 2422 &Connection->assoc->http_uuid); 2423 if (status != RPC_S_OK) 2424 return status; 2425 2426 status = rpcrt4_http_prepare_out_pipe(httpc->out_request, 2427 httpc->async_data, 2428 &httpc->connection_uuid, 2429 &httpc->out_pipe_uuid, 2430 &httpc->flow_control_increment); 2431 if (status != RPC_S_OK) 2432 return status; 2433 2434 httpc->flow_control_mark = httpc->flow_control_increment / 2; 2435 httpc->last_sent_time = GetTickCount(); 2436 httpc->timer_cancelled = CreateEventW(NULL, FALSE, FALSE, NULL); 2437 2438 timer_data = HeapAlloc(GetProcessHeap(), 0, sizeof(*timer_data)); 2439 if (!timer_data) 2440 return ERROR_OUTOFMEMORY; 2441 timer_data->timer_param = httpc->in_request; 2442 timer_data->last_sent_time = &httpc->last_sent_time; 2443 timer_data->timer_cancelled = httpc->timer_cancelled; 2444 /* FIXME: should use CreateTimerQueueTimer when implemented */ 2445 thread = CreateThread(NULL, 0, rpcrt4_http_timer_thread, timer_data, 0, NULL); 2446 if (!thread) 2447 { 2448 HeapFree(GetProcessHeap(), 0, timer_data); 2449 return GetLastError(); 2450 } 2451 CloseHandle(thread); 2452 2453 return RPC_S_OK; 2454 } 2455 2456 static RPC_STATUS rpcrt4_ncacn_http_handoff(RpcConnection *old_conn, RpcConnection *new_conn) 2457 { 2458 assert(0); 2459 return RPC_S_SERVER_UNAVAILABLE; 2460 } 2461 2462 static int rpcrt4_ncacn_http_read(RpcConnection *Connection, 2463 void *buffer, unsigned int count) 2464 { 2465 RpcConnection_http *httpc = (RpcConnection_http *) Connection; 2466 char *buf = buffer; 2467 BOOL ret = TRUE; 2468 unsigned int bytes_left = count; 2469 2470 ResetEvent(httpc->async_data->completion_event); 2471 while (bytes_left) 2472 { 2473 RpcHttpAsyncData_AddRef(httpc->async_data); 2474 httpc->async_data->inet_buffers.dwBufferLength = bytes_left; 2475 httpc->async_data->inet_buffers.lpvBuffer = HeapAlloc(GetProcessHeap(), 0, bytes_left); 2476 httpc->async_data->destination_buffer = buf; 2477 ret = InternetReadFileExA(httpc->out_request, &httpc->async_data->inet_buffers, IRF_ASYNC, 0); 2478 if (ret) 2479 { 2480 /* INTERNET_STATUS_REQUEST_COMPLETED won't be sent, so release our 2481 * async ref now */ 2482 RpcHttpAsyncData_Release(httpc->async_data); 2483 memcpy(buf, httpc->async_data->inet_buffers.lpvBuffer, 2484 httpc->async_data->inet_buffers.dwBufferLength); 2485 HeapFree(GetProcessHeap(), 0, httpc->async_data->inet_buffers.lpvBuffer); 2486 httpc->async_data->inet_buffers.lpvBuffer = NULL; 2487 httpc->async_data->destination_buffer = NULL; 2488 } 2489 else 2490 { 2491 if (GetLastError() == ERROR_IO_PENDING) 2492 { 2493 HANDLE handles[2] = { httpc->async_data->completion_event, httpc->cancel_event }; 2494 DWORD result = WaitForMultipleObjects(2, handles, FALSE, DEFAULT_NCACN_HTTP_TIMEOUT); 2495 if (result == WAIT_OBJECT_0) 2496 ret = TRUE; 2497 else 2498 { 2499 TRACE("call cancelled\n"); 2500 EnterCriticalSection(&httpc->async_data->cs); 2501 httpc->async_data->destination_buffer = NULL; 2502 LeaveCriticalSection(&httpc->async_data->cs); 2503 break; 2504 } 2505 } 2506 else 2507 { 2508 HeapFree(GetProcessHeap(), 0, httpc->async_data->inet_buffers.lpvBuffer); 2509 httpc->async_data->inet_buffers.lpvBuffer = NULL; 2510 httpc->async_data->destination_buffer = NULL; 2511 RpcHttpAsyncData_Release(httpc->async_data); 2512 break; 2513 } 2514 } 2515 if (!httpc->async_data->inet_buffers.dwBufferLength) 2516 break; 2517 bytes_left -= httpc->async_data->inet_buffers.dwBufferLength; 2518 buf += httpc->async_data->inet_buffers.dwBufferLength; 2519 } 2520 TRACE("%p %p %u -> %s\n", httpc->out_request, buffer, count, ret ? "TRUE" : "FALSE"); 2521 return ret ? count : -1; 2522 } 2523 2524 static RPC_STATUS rpcrt4_ncacn_http_receive_fragment(RpcConnection *Connection, RpcPktHdr **Header, void **Payload) 2525 { 2526 RpcConnection_http *httpc = (RpcConnection_http *) Connection; 2527 RPC_STATUS status; 2528 DWORD hdr_length; 2529 LONG dwRead; 2530 RpcPktCommonHdr common_hdr; 2531 2532 *Header = NULL; 2533 2534 TRACE("(%p, %p, %p)\n", Connection, Header, Payload); 2535 2536 again: 2537 /* read packet common header */ 2538 dwRead = rpcrt4_ncacn_http_read(Connection, &common_hdr, sizeof(common_hdr)); 2539 if (dwRead != sizeof(common_hdr)) { 2540 WARN("Short read of header, %d bytes\n", dwRead); 2541 status = RPC_S_PROTOCOL_ERROR; 2542 goto fail; 2543 } 2544 if (!memcmp(&common_hdr, "HTTP/1.1", sizeof("HTTP/1.1")) || 2545 !memcmp(&common_hdr, "HTTP/1.0", sizeof("HTTP/1.0"))) 2546 { 2547 FIXME("server returned %s\n", debugstr_a((const char *)&common_hdr)); 2548 status = RPC_S_PROTOCOL_ERROR; 2549 goto fail; 2550 } 2551 2552 status = RPCRT4_ValidateCommonHeader(&common_hdr); 2553 if (status != RPC_S_OK) goto fail; 2554 2555 hdr_length = RPCRT4_GetHeaderSize((RpcPktHdr*)&common_hdr); 2556 if (hdr_length == 0) { 2557 WARN("header length == 0\n"); 2558 status = RPC_S_PROTOCOL_ERROR; 2559 goto fail; 2560 } 2561 2562 *Header = HeapAlloc(GetProcessHeap(), 0, hdr_length); 2563 if (!*Header) 2564 { 2565 status = RPC_S_OUT_OF_RESOURCES; 2566 goto fail; 2567 } 2568 memcpy(*Header, &common_hdr, sizeof(common_hdr)); 2569 2570 /* read the rest of packet header */ 2571 dwRead = rpcrt4_ncacn_http_read(Connection, &(*Header)->common + 1, hdr_length - sizeof(common_hdr)); 2572 if (dwRead != hdr_length - sizeof(common_hdr)) { 2573 WARN("bad header length, %d bytes, hdr_length %d\n", dwRead, hdr_length); 2574 status = RPC_S_PROTOCOL_ERROR; 2575 goto fail; 2576 } 2577 2578 if (common_hdr.frag_len - hdr_length) 2579 { 2580 *Payload = HeapAlloc(GetProcessHeap(), 0, common_hdr.frag_len - hdr_length); 2581 if (!*Payload) 2582 { 2583 status = RPC_S_OUT_OF_RESOURCES; 2584 goto fail; 2585 } 2586 2587 dwRead = rpcrt4_ncacn_http_read(Connection, *Payload, common_hdr.frag_len - hdr_length); 2588 if (dwRead != common_hdr.frag_len - hdr_length) 2589 { 2590 WARN("bad data length, %d/%d\n", dwRead, common_hdr.frag_len - hdr_length); 2591 status = RPC_S_PROTOCOL_ERROR; 2592 goto fail; 2593 } 2594 } 2595 else 2596 *Payload = NULL; 2597 2598 if ((*Header)->common.ptype == PKT_HTTP) 2599 { 2600 if (!RPCRT4_IsValidHttpPacket(*Header, *Payload, common_hdr.frag_len - hdr_length)) 2601 { 2602 ERR("invalid http packet of length %d bytes\n", (*Header)->common.frag_len); 2603 status = RPC_S_PROTOCOL_ERROR; 2604 goto fail; 2605 } 2606 if ((*Header)->http.flags == 0x0001) 2607 { 2608 TRACE("http idle packet, waiting for real packet\n"); 2609 if ((*Header)->http.num_data_items != 0) 2610 { 2611 ERR("HTTP idle packet should have no data items instead of %d\n", (*Header)->http.num_data_items); 2612 status = RPC_S_PROTOCOL_ERROR; 2613 goto fail; 2614 } 2615 } 2616 else if ((*Header)->http.flags == 0x0002) 2617 { 2618 ULONG bytes_transmitted; 2619 ULONG flow_control_increment; 2620 UUID pipe_uuid; 2621 status = RPCRT4_ParseHttpFlowControlHeader(*Header, *Payload, 2622 Connection->server, 2623 &bytes_transmitted, 2624 &flow_control_increment, 2625 &pipe_uuid); 2626 if (status != RPC_S_OK) 2627 goto fail; 2628 TRACE("received http flow control header (0x%x, 0x%x, %s)\n", 2629 bytes_transmitted, flow_control_increment, debugstr_guid(&pipe_uuid)); 2630 /* FIXME: do something with parsed data */ 2631 } 2632 else 2633 { 2634 FIXME("unrecognised http packet with flags 0x%04x\n", (*Header)->http.flags); 2635 status = RPC_S_PROTOCOL_ERROR; 2636 goto fail; 2637 } 2638 RPCRT4_FreeHeader(*Header); 2639 *Header = NULL; 2640 HeapFree(GetProcessHeap(), 0, *Payload); 2641 *Payload = NULL; 2642 goto again; 2643 } 2644 2645 /* success */ 2646 status = RPC_S_OK; 2647 2648 httpc->bytes_received += common_hdr.frag_len; 2649 2650 TRACE("httpc->bytes_received = 0x%x\n", httpc->bytes_received); 2651 2652 if (httpc->bytes_received > httpc->flow_control_mark) 2653 { 2654 RpcPktHdr *hdr = RPCRT4_BuildHttpFlowControlHeader(httpc->common.server, 2655 httpc->bytes_received, 2656 httpc->flow_control_increment, 2657 &httpc->out_pipe_uuid); 2658 if (hdr) 2659 { 2660 DWORD bytes_written; 2661 BOOL ret2; 2662 TRACE("sending flow control packet at 0x%x\n", httpc->bytes_received); 2663 ret2 = InternetWriteFile(httpc->in_request, hdr, hdr->common.frag_len, &bytes_written); 2664 RPCRT4_FreeHeader(hdr); 2665 if (ret2) 2666 httpc->flow_control_mark = httpc->bytes_received + httpc->flow_control_increment / 2; 2667 } 2668 } 2669 2670 fail: 2671 if (status != RPC_S_OK) { 2672 RPCRT4_FreeHeader(*Header); 2673 *Header = NULL; 2674 HeapFree(GetProcessHeap(), 0, *Payload); 2675 *Payload = NULL; 2676 } 2677 return status; 2678 } 2679 2680 static int rpcrt4_ncacn_http_write(RpcConnection *Connection, 2681 const void *buffer, unsigned int count) 2682 { 2683 RpcConnection_http *httpc = (RpcConnection_http *) Connection; 2684 DWORD bytes_written; 2685 BOOL ret; 2686 2687 httpc->last_sent_time = ~0U; /* disable idle packet sending */ 2688 ret = InternetWriteFile(httpc->in_request, buffer, count, &bytes_written); 2689 httpc->last_sent_time = GetTickCount(); 2690 TRACE("%p %p %u -> %s\n", httpc->in_request, buffer, count, ret ? "TRUE" : "FALSE"); 2691 return ret ? bytes_written : -1; 2692 } 2693 2694 static int rpcrt4_ncacn_http_close(RpcConnection *Connection) 2695 { 2696 RpcConnection_http *httpc = (RpcConnection_http *) Connection; 2697 2698 TRACE("\n"); 2699 2700 SetEvent(httpc->timer_cancelled); 2701 if (httpc->in_request) 2702 InternetCloseHandle(httpc->in_request); 2703 httpc->in_request = NULL; 2704 if (httpc->out_request) 2705 InternetCloseHandle(httpc->out_request); 2706 httpc->out_request = NULL; 2707 if (httpc->app_info) 2708 InternetCloseHandle(httpc->app_info); 2709 httpc->app_info = NULL; 2710 if (httpc->session) 2711 InternetCloseHandle(httpc->session); 2712 httpc->session = NULL; 2713 RpcHttpAsyncData_Release(httpc->async_data); 2714 if (httpc->cancel_event) 2715 CloseHandle(httpc->cancel_event); 2716 2717 return 0; 2718 } 2719 2720 static void rpcrt4_ncacn_http_cancel_call(RpcConnection *Connection) 2721 { 2722 RpcConnection_http *httpc = (RpcConnection_http *) Connection; 2723 2724 SetEvent(httpc->cancel_event); 2725 } 2726 2727 static int rpcrt4_ncacn_http_wait_for_incoming_data(RpcConnection *Connection) 2728 { 2729 BOOL ret; 2730 RpcConnection_http *httpc = (RpcConnection_http *) Connection; 2731 2732 RpcHttpAsyncData_AddRef(httpc->async_data); 2733 ret = InternetQueryDataAvailable(httpc->out_request, 2734 &httpc->async_data->inet_buffers.dwBufferLength, IRF_ASYNC, 0); 2735 if (ret) 2736 { 2737 /* INTERNET_STATUS_REQUEST_COMPLETED won't be sent, so release our 2738 * async ref now */ 2739 RpcHttpAsyncData_Release(httpc->async_data); 2740 } 2741 else 2742 { 2743 if (GetLastError() == ERROR_IO_PENDING) 2744 { 2745 HANDLE handles[2] = { httpc->async_data->completion_event, httpc->cancel_event }; 2746 DWORD result = WaitForMultipleObjects(2, handles, FALSE, DEFAULT_NCACN_HTTP_TIMEOUT); 2747 if (result != WAIT_OBJECT_0) 2748 { 2749 TRACE("call cancelled\n"); 2750 return -1; 2751 } 2752 } 2753 else 2754 { 2755 RpcHttpAsyncData_Release(httpc->async_data); 2756 return -1; 2757 } 2758 } 2759 2760 /* success */ 2761 return 0; 2762 } 2763 2764 static size_t rpcrt4_ncacn_http_get_top_of_tower(unsigned char *tower_data, 2765 const char *networkaddr, 2766 const char *endpoint) 2767 { 2768 return rpcrt4_ip_tcp_get_top_of_tower(tower_data, networkaddr, 2769 EPM_PROTOCOL_HTTP, endpoint); 2770 } 2771 2772 static RPC_STATUS rpcrt4_ncacn_http_parse_top_of_tower(const unsigned char *tower_data, 2773 size_t tower_size, 2774 char **networkaddr, 2775 char **endpoint) 2776 { 2777 return rpcrt4_ip_tcp_parse_top_of_tower(tower_data, tower_size, 2778 networkaddr, EPM_PROTOCOL_HTTP, 2779 endpoint); 2780 } 2781 2782 static const struct connection_ops conn_protseq_list[] = { 2783 { "ncacn_np", 2784 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_SMB }, 2785 rpcrt4_conn_np_alloc, 2786 rpcrt4_ncacn_np_open, 2787 rpcrt4_ncacn_np_handoff, 2788 rpcrt4_conn_np_read, 2789 rpcrt4_conn_np_write, 2790 rpcrt4_conn_np_close, 2791 rpcrt4_conn_np_cancel_call, 2792 rpcrt4_conn_np_wait_for_incoming_data, 2793 rpcrt4_ncacn_np_get_top_of_tower, 2794 rpcrt4_ncacn_np_parse_top_of_tower, 2795 NULL, 2796 RPCRT4_default_is_authorized, 2797 RPCRT4_default_authorize, 2798 RPCRT4_default_secure_packet, 2799 rpcrt4_conn_np_impersonate_client, 2800 rpcrt4_conn_np_revert_to_self, 2801 RPCRT4_default_inquire_auth_client, 2802 }, 2803 { "ncalrpc", 2804 { EPM_PROTOCOL_NCALRPC, EPM_PROTOCOL_PIPE }, 2805 rpcrt4_conn_np_alloc, 2806 rpcrt4_ncalrpc_open, 2807 rpcrt4_ncalrpc_handoff, 2808 rpcrt4_conn_np_read, 2809 rpcrt4_conn_np_write, 2810 rpcrt4_conn_np_close, 2811 rpcrt4_conn_np_cancel_call, 2812 rpcrt4_conn_np_wait_for_incoming_data, 2813 rpcrt4_ncalrpc_get_top_of_tower, 2814 rpcrt4_ncalrpc_parse_top_of_tower, 2815 NULL, 2816 rpcrt4_ncalrpc_is_authorized, 2817 rpcrt4_ncalrpc_authorize, 2818 rpcrt4_ncalrpc_secure_packet, 2819 rpcrt4_conn_np_impersonate_client, 2820 rpcrt4_conn_np_revert_to_self, 2821 rpcrt4_ncalrpc_inquire_auth_client, 2822 }, 2823 { "ncacn_ip_tcp", 2824 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_TCP }, 2825 rpcrt4_conn_tcp_alloc, 2826 rpcrt4_ncacn_ip_tcp_open, 2827 rpcrt4_conn_tcp_handoff, 2828 rpcrt4_conn_tcp_read, 2829 rpcrt4_conn_tcp_write, 2830 rpcrt4_conn_tcp_close, 2831 rpcrt4_conn_tcp_cancel_call, 2832 rpcrt4_conn_tcp_wait_for_incoming_data, 2833 rpcrt4_ncacn_ip_tcp_get_top_of_tower, 2834 rpcrt4_ncacn_ip_tcp_parse_top_of_tower, 2835 NULL, 2836 RPCRT4_default_is_authorized, 2837 RPCRT4_default_authorize, 2838 RPCRT4_default_secure_packet, 2839 RPCRT4_default_impersonate_client, 2840 RPCRT4_default_revert_to_self, 2841 RPCRT4_default_inquire_auth_client, 2842 }, 2843 { "ncacn_http", 2844 { EPM_PROTOCOL_NCACN, EPM_PROTOCOL_HTTP }, 2845 rpcrt4_ncacn_http_alloc, 2846 rpcrt4_ncacn_http_open, 2847 rpcrt4_ncacn_http_handoff, 2848 rpcrt4_ncacn_http_read, 2849 rpcrt4_ncacn_http_write, 2850 rpcrt4_ncacn_http_close, 2851 rpcrt4_ncacn_http_cancel_call, 2852 rpcrt4_ncacn_http_wait_for_incoming_data, 2853 rpcrt4_ncacn_http_get_top_of_tower, 2854 rpcrt4_ncacn_http_parse_top_of_tower, 2855 rpcrt4_ncacn_http_receive_fragment, 2856 RPCRT4_default_is_authorized, 2857 RPCRT4_default_authorize, 2858 RPCRT4_default_secure_packet, 2859 RPCRT4_default_impersonate_client, 2860 RPCRT4_default_revert_to_self, 2861 RPCRT4_default_inquire_auth_client, 2862 }, 2863 }; 2864 2865 2866 static const struct protseq_ops protseq_list[] = 2867 { 2868 { 2869 "ncacn_np", 2870 rpcrt4_protseq_np_alloc, 2871 rpcrt4_protseq_np_signal_state_changed, 2872 rpcrt4_protseq_np_get_wait_array, 2873 rpcrt4_protseq_np_free_wait_array, 2874 rpcrt4_protseq_np_wait_for_new_connection, 2875 rpcrt4_protseq_ncacn_np_open_endpoint, 2876 }, 2877 { 2878 "ncalrpc", 2879 rpcrt4_protseq_np_alloc, 2880 rpcrt4_protseq_np_signal_state_changed, 2881 rpcrt4_protseq_np_get_wait_array, 2882 rpcrt4_protseq_np_free_wait_array, 2883 rpcrt4_protseq_np_wait_for_new_connection, 2884 rpcrt4_protseq_ncalrpc_open_endpoint, 2885 }, 2886 { 2887 "ncacn_ip_tcp", 2888 rpcrt4_protseq_sock_alloc, 2889 rpcrt4_protseq_sock_signal_state_changed, 2890 rpcrt4_protseq_sock_get_wait_array, 2891 rpcrt4_protseq_sock_free_wait_array, 2892 rpcrt4_protseq_sock_wait_for_new_connection, 2893 rpcrt4_protseq_ncacn_ip_tcp_open_endpoint, 2894 }, 2895 }; 2896 2897 #define ARRAYSIZE(a) (sizeof((a)) / sizeof((a)[0])) 2898 2899 const struct protseq_ops *rpcrt4_get_protseq_ops(const char *protseq) 2900 { 2901 unsigned int i; 2902 for(i=0; i<ARRAYSIZE(protseq_list); i++) 2903 if (!strcmp(protseq_list[i].name, protseq)) 2904 return &protseq_list[i]; 2905 return NULL; 2906 } 2907 2908 static const struct connection_ops *rpcrt4_get_conn_protseq_ops(const char *protseq) 2909 { 2910 unsigned int i; 2911 for(i=0; i<ARRAYSIZE(conn_protseq_list); i++) 2912 if (!strcmp(conn_protseq_list[i].name, protseq)) 2913 return &conn_protseq_list[i]; 2914 return NULL; 2915 } 2916 2917 /**** interface to rest of code ****/ 2918 2919 RPC_STATUS RPCRT4_OpenClientConnection(RpcConnection* Connection) 2920 { 2921 TRACE("(Connection == ^%p)\n", Connection); 2922 2923 assert(!Connection->server); 2924 return Connection->ops->open_connection_client(Connection); 2925 } 2926 2927 RPC_STATUS RPCRT4_CloseConnection(RpcConnection* Connection) 2928 { 2929 TRACE("(Connection == ^%p)\n", Connection); 2930 if (SecIsValidHandle(&Connection->ctx)) 2931 { 2932 DeleteSecurityContext(&Connection->ctx); 2933 SecInvalidateHandle(&Connection->ctx); 2934 } 2935 rpcrt4_conn_close(Connection); 2936 return RPC_S_OK; 2937 } 2938 2939 RPC_STATUS RPCRT4_CreateConnection(RpcConnection** Connection, BOOL server, 2940 LPCSTR Protseq, LPCSTR NetworkAddr, LPCSTR Endpoint, 2941 LPCWSTR NetworkOptions, RpcAuthInfo* AuthInfo, RpcQualityOfService *QOS) 2942 { 2943 static LONG next_id; 2944 const struct connection_ops *ops; 2945 RpcConnection* NewConnection; 2946 2947 ops = rpcrt4_get_conn_protseq_ops(Protseq); 2948 if (!ops) 2949 { 2950 FIXME("not supported for protseq %s\n", Protseq); 2951 return RPC_S_PROTSEQ_NOT_SUPPORTED; 2952 } 2953 2954 NewConnection = ops->alloc(); 2955 NewConnection->Next = NULL; 2956 NewConnection->server_binding = NULL; 2957 NewConnection->server = server; 2958 NewConnection->ops = ops; 2959 NewConnection->NetworkAddr = RPCRT4_strdupA(NetworkAddr); 2960 NewConnection->Endpoint = RPCRT4_strdupA(Endpoint); 2961 NewConnection->NetworkOptions = RPCRT4_strdupW(NetworkOptions); 2962 NewConnection->MaxTransmissionSize = RPC_MAX_PACKET_SIZE; 2963 memset(&NewConnection->ActiveInterface, 0, sizeof(NewConnection->ActiveInterface)); 2964 NewConnection->NextCallId = 1; 2965 2966 SecInvalidateHandle(&NewConnection->ctx); 2967 memset(&NewConnection->exp, 0, sizeof(NewConnection->exp)); 2968 NewConnection->attr = 0; 2969 if (AuthInfo) RpcAuthInfo_AddRef(AuthInfo); 2970 NewConnection->AuthInfo = AuthInfo; 2971 NewConnection->auth_context_id = InterlockedIncrement( &next_id ); 2972 NewConnection->encryption_auth_len = 0; 2973 NewConnection->signature_auth_len = 0; 2974 if (QOS) RpcQualityOfService_AddRef(QOS); 2975 NewConnection->QOS = QOS; 2976 2977 list_init(&NewConnection->conn_pool_entry); 2978 NewConnection->async_state = NULL; 2979 2980 TRACE("connection: %p\n", NewConnection); 2981 *Connection = NewConnection; 2982 2983 return RPC_S_OK; 2984 } 2985 2986 static RPC_STATUS RPCRT4_SpawnConnection(RpcConnection** Connection, RpcConnection* OldConnection) 2987 { 2988 RPC_STATUS err; 2989 2990 err = RPCRT4_CreateConnection(Connection, OldConnection->server, 2991 rpcrt4_conn_get_name(OldConnection), 2992 OldConnection->NetworkAddr, 2993 OldConnection->Endpoint, NULL, 2994 OldConnection->AuthInfo, OldConnection->QOS); 2995 if (err == RPC_S_OK) 2996 rpcrt4_conn_handoff(OldConnection, *Connection); 2997 return err; 2998 } 2999 3000 RPC_STATUS RPCRT4_DestroyConnection(RpcConnection* Connection) 3001 { 3002 TRACE("connection: %p\n", Connection); 3003 3004 RPCRT4_CloseConnection(Connection); 3005 RPCRT4_strfree(Connection->Endpoint); 3006 RPCRT4_strfree(Connection->NetworkAddr); 3007 HeapFree(GetProcessHeap(), 0, Connection->NetworkOptions); 3008 if (Connection->AuthInfo) RpcAuthInfo_Release(Connection->AuthInfo); 3009 if (Connection->QOS) RpcQualityOfService_Release(Connection->QOS); 3010 3011 /* server-only */ 3012 if (Connection->server_binding) RPCRT4_ReleaseBinding(Connection->server_binding); 3013 3014 HeapFree(GetProcessHeap(), 0, Connection); 3015 return RPC_S_OK; 3016 } 3017 3018 RPC_STATUS RpcTransport_GetTopOfTower(unsigned char *tower_data, 3019 size_t *tower_size, 3020 const char *protseq, 3021 const char *networkaddr, 3022 const char *endpoint) 3023 { 3024 twr_empty_floor_t *protocol_floor; 3025 const struct connection_ops *protseq_ops = rpcrt4_get_conn_protseq_ops(protseq); 3026 3027 *tower_size = 0; 3028 3029 if (!protseq_ops) 3030 return RPC_S_INVALID_RPC_PROTSEQ; 3031 3032 if (!tower_data) 3033 { 3034 *tower_size = sizeof(*protocol_floor); 3035 *tower_size += protseq_ops->get_top_of_tower(NULL, networkaddr, endpoint); 3036 return RPC_S_OK; 3037 } 3038 3039 protocol_floor = (twr_empty_floor_t *)tower_data; 3040 protocol_floor->count_lhs = sizeof(protocol_floor->protid); 3041 protocol_floor->protid = protseq_ops->epm_protocols[0]; 3042 protocol_floor->count_rhs = 0; 3043 3044 tower_data += sizeof(*protocol_floor); 3045 3046 *tower_size = protseq_ops->get_top_of_tower(tower_data, networkaddr, endpoint); 3047 if (!*tower_size) 3048 return EPT_S_NOT_REGISTERED; 3049 3050 *tower_size += sizeof(*protocol_floor); 3051 3052 return RPC_S_OK; 3053 } 3054 3055 RPC_STATUS RpcTransport_ParseTopOfTower(const unsigned char *tower_data, 3056 size_t tower_size, 3057 char **protseq, 3058 char **networkaddr, 3059 char **endpoint) 3060 { 3061 const twr_empty_floor_t *protocol_floor; 3062 const twr_empty_floor_t *floor4; 3063 const struct connection_ops *protseq_ops = NULL; 3064 RPC_STATUS status; 3065 unsigned int i; 3066 3067 if (tower_size < sizeof(*protocol_floor)) 3068 return EPT_S_NOT_REGISTERED; 3069 3070 protocol_floor = (const twr_empty_floor_t *)tower_data; 3071 tower_data += sizeof(*protocol_floor); 3072 tower_size -= sizeof(*protocol_floor); 3073 if ((protocol_floor->count_lhs != sizeof(protocol_floor->protid)) || 3074 (protocol_floor->count_rhs > tower_size)) 3075 return EPT_S_NOT_REGISTERED; 3076 tower_data += protocol_floor->count_rhs; 3077 tower_size -= protocol_floor->count_rhs; 3078 3079 floor4 = (const twr_empty_floor_t *)tower_data; 3080 if ((tower_size < sizeof(*floor4)) || 3081 (floor4->count_lhs != sizeof(floor4->protid))) 3082 return EPT_S_NOT_REGISTERED; 3083 3084 for(i = 0; i < ARRAYSIZE(conn_protseq_list); i++) 3085 if ((protocol_floor->protid == conn_protseq_list[i].epm_protocols[0]) && 3086 (floor4->protid == conn_protseq_list[i].epm_protocols[1])) 3087 { 3088 protseq_ops = &conn_protseq_list[i]; 3089 break; 3090 } 3091 3092 if (!protseq_ops) 3093 return EPT_S_NOT_REGISTERED; 3094 3095 status = protseq_ops->parse_top_of_tower(tower_data, tower_size, networkaddr, endpoint); 3096 3097 if ((status == RPC_S_OK) && protseq) 3098 { 3099 *protseq = I_RpcAllocate(strlen(protseq_ops->name) + 1); 3100 strcpy(*protseq, protseq_ops->name); 3101 } 3102 3103 return status; 3104 } 3105 3106 /*********************************************************************** 3107 * RpcNetworkIsProtseqValidW (RPCRT4.@) 3108 * 3109 * Checks if the given protocol sequence is known by the RPC system. 3110 * If it is, returns RPC_S_OK, otherwise RPC_S_PROTSEQ_NOT_SUPPORTED. 3111 * 3112 */ 3113 RPC_STATUS WINAPI RpcNetworkIsProtseqValidW(RPC_WSTR protseq) 3114 { 3115 char ps[0x10]; 3116 3117 WideCharToMultiByte(CP_ACP, 0, protseq, -1, 3118 ps, sizeof ps, NULL, NULL); 3119 if (rpcrt4_get_conn_protseq_ops(ps)) 3120 return RPC_S_OK; 3121 3122 FIXME("Unknown protseq %s\n", debugstr_w(protseq)); 3123 3124 return RPC_S_INVALID_RPC_PROTSEQ; 3125 } 3126 3127 /*********************************************************************** 3128 * RpcNetworkIsProtseqValidA (RPCRT4.@) 3129 */ 3130 RPC_STATUS WINAPI RpcNetworkIsProtseqValidA(RPC_CSTR protseq) 3131 { 3132 UNICODE_STRING protseqW; 3133 3134 if (RtlCreateUnicodeStringFromAsciiz(&protseqW, (char*)protseq)) 3135 { 3136 RPC_STATUS ret = RpcNetworkIsProtseqValidW(protseqW.Buffer); 3137 RtlFreeUnicodeString(&protseqW); 3138 return ret; 3139 } 3140 return RPC_S_OUT_OF_MEMORY; 3141 } 3142 3143 /*********************************************************************** 3144 * RpcProtseqVectorFreeA (RPCRT4.@) 3145 */ 3146 RPC_STATUS WINAPI RpcProtseqVectorFreeA(RPC_PROTSEQ_VECTORA **protseqs) 3147 { 3148 TRACE("(%p)\n", protseqs); 3149 3150 if (*protseqs) 3151 { 3152 int i; 3153 for (i = 0; i < (*protseqs)->Count; i++) 3154 HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]); 3155 HeapFree(GetProcessHeap(), 0, *protseqs); 3156 *protseqs = NULL; 3157 } 3158 return RPC_S_OK; 3159 } 3160 3161 /*********************************************************************** 3162 * RpcProtseqVectorFreeW (RPCRT4.@) 3163 */ 3164 RPC_STATUS WINAPI RpcProtseqVectorFreeW(RPC_PROTSEQ_VECTORW **protseqs) 3165 { 3166 TRACE("(%p)\n", protseqs); 3167 3168 if (*protseqs) 3169 { 3170 int i; 3171 for (i = 0; i < (*protseqs)->Count; i++) 3172 HeapFree(GetProcessHeap(), 0, (*protseqs)->Protseq[i]); 3173 HeapFree(GetProcessHeap(), 0, *protseqs); 3174 *protseqs = NULL; 3175 } 3176 return RPC_S_OK; 3177 } 3178 3179 /*********************************************************************** 3180 * RpcNetworkInqProtseqsW (RPCRT4.@) 3181 */ 3182 RPC_STATUS WINAPI RpcNetworkInqProtseqsW( RPC_PROTSEQ_VECTORW** protseqs ) 3183 { 3184 RPC_PROTSEQ_VECTORW *pvector; 3185 int i = 0; 3186 RPC_STATUS status = RPC_S_OUT_OF_MEMORY; 3187 3188 TRACE("(%p)\n", protseqs); 3189 3190 *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned short*)*ARRAYSIZE(protseq_list))); 3191 if (!*protseqs) 3192 goto end; 3193 pvector = *protseqs; 3194 pvector->Count = 0; 3195 for (i = 0; i < ARRAYSIZE(protseq_list); i++) 3196 { 3197 pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, (strlen(protseq_list[i].name)+1)*sizeof(unsigned short)); 3198 if (pvector->Protseq[i] == NULL) 3199 goto end; 3200 MultiByteToWideChar(CP_ACP, 0, (CHAR*)protseq_list[i].name, -1, 3201 (WCHAR*)pvector->Protseq[i], strlen(protseq_list[i].name) + 1); 3202 pvector->Count++; 3203 } 3204 status = RPC_S_OK; 3205 3206 end: 3207 if (status != RPC_S_OK) 3208 RpcProtseqVectorFreeW(protseqs); 3209 return status; 3210 } 3211 3212 /*********************************************************************** 3213 * RpcNetworkInqProtseqsA (RPCRT4.@) 3214 */ 3215 RPC_STATUS WINAPI RpcNetworkInqProtseqsA(RPC_PROTSEQ_VECTORA** protseqs) 3216 { 3217 RPC_PROTSEQ_VECTORA *pvector; 3218 int i = 0; 3219 RPC_STATUS status = RPC_S_OUT_OF_MEMORY; 3220 3221 TRACE("(%p)\n", protseqs); 3222 3223 *protseqs = HeapAlloc(GetProcessHeap(), 0, sizeof(RPC_PROTSEQ_VECTORW)+(sizeof(unsigned char*)*ARRAYSIZE(protseq_list))); 3224 if (!*protseqs) 3225 goto end; 3226 pvector = *protseqs; 3227 pvector->Count = 0; 3228 for (i = 0; i < ARRAYSIZE(protseq_list); i++) 3229 { 3230 pvector->Protseq[i] = HeapAlloc(GetProcessHeap(), 0, strlen(protseq_list[i].name)+1); 3231 if (pvector->Protseq[i] == NULL) 3232 goto end; 3233 strcpy((char*)pvector->Protseq[i], protseq_list[i].name); 3234 pvector->Count++; 3235 } 3236 status = RPC_S_OK; 3237 3238 end: 3239 if (status != RPC_S_OK) 3240 RpcProtseqVectorFreeA(protseqs); 3241 return status; 3242 }
__label__pos
0.989783
The Essential Guide to UX Research: Methods, Best Practices, and Benefits The Essential Guide to UX Research: Methods, Best Practices, and Benefits in Articles 3 comments Advertisements 7 Shares User Experience (UX) research is a crucial step in designing digital products and services that are user-centered, intuitive, and effective. It involves understanding users’ behaviors, preferences, and needs to inform the design process and create experiences that resonate with the target audience. In this article, we will delve into the world of UX research, covering its key methods, best practices, and benefits. • Save What is UX Research? UX research is a systematic process of collecting and analyzing data about users and their interactions with digital products or services. It aims to uncover insights about users’ behaviors, attitudes, and needs to inform the design process and create user-centered solutions. UX research provides valuable information that helps designers and product teams make informed decisions, validate design assumptions, and identify areas of improvement. Key Methods of UX Research Key Methods of UX Research • Save There are various methods available in UX research, and the choice of method depends on the research goals, resources, and stage of the design process. Here are some common methods used in UX research: 1. Interviews: Interviews involve one-on-one conversations with users to gather qualitative data about their experiences, opinions, and preferences. Interviews can be conducted in-person or remotely and can provide valuable insights into users’ motivations, behaviors, and pain points. 2. Surveys: Surveys involve collecting data from a large number of users through questionnaires or online forms. Surveys can provide quantitative data, such as demographics, preferences, and satisfaction levels, and are useful for gathering data from a wide range of users. 3. Usability Testing: Usability testing involves observing users as they interact with a prototype or a live product to identify usability issues, evaluate the effectiveness of the design, and gather feedback for improvements. 4. Card Sorting: Card sorting involves asking users to organize and categorize content or features into groups. Card sorting helps understand users’ mental models, information architecture, and navigation preferences. 5. Analytics and Metrics: Analytics and metrics involve collecting quantitative data from digital analytics tools, such as website traffic, user engagement, and conversion rates. Analytics and metrics provide insights into how users are interacting with a product or service in a real-world setting. Best Practices in UX Research Best Practices in UX Research • Save To conduct effective UX research, it’s important to follow best practices that ensure the validity and reliability of the findings. Here are some best practices in UX research: 1. Define Clear Research Goals: Clearly define your research goals and objectives before starting the research process. What are you trying to achieve? What questions are you trying to answer? Setting clear research goals helps keep the research focused and ensures that the findings are aligned with the overall project objectives. 2. Use a Mix of Research Methods: Different research methods provide different types of data and insights. It’s important to use a mix of research methods that are appropriate for your research goals and resources. Triangulation, or using multiple methods, can help validate findings and provide a more comprehensive understanding of users. 3. Recruit Diverse Participants: Ensure that your participant sample is diverse and represents the characteristics of your target audience. This includes factors such as age, gender, location, and expertise. A diverse sample helps capture a wide range of perspectives and behaviors, leading to more robust and reliable findings. 4. Practice Active Listening and Empathy: During interviews or usability testing sessions, practice active listening and empathy. Pay attention to users’ verbal and non-verbal cues, and try to understand their emotions, motivations, and behaviors. This helps uncover valuable insights and ensures that users’ voices are heard in the research process. 5. Collaborate with Stakeholders: UX research is a collaborative effort that involves working with cross-functional teams, including designers, developers, product managers, and other stakeholders. Collaborate with your team and involve. UX Research Benefits UX Research Benefits • Save UX research offers numerous benefits that contribute to the overall success of a digital product or service. Here are some key benefits of UX research: 1. User-Centered Design: UX research puts users at the center of the design process by gaining insights into their behaviors, preferences, and needs. This helps designers create products that are tailored to users’ requirements, resulting in improved user satisfaction and engagement. 2. Informed Decision Making: UX research provides data-driven insights that help inform decision-making throughout the design process. It helps designers and product teams make informed choices about features, functionalities, and interactions, based on user feedback and preferences. 3. Improved Usability and Accessibility: UX research helps identify usability issues, accessibility barriers, and other pain points in the user experience. This allows designers to make necessary improvements to create products that are easy to use, accessible to a wide range of users, and meet their needs effectively. 4. Reduced Development Costs and Risks: UX research helps identify design issues and user frustrations early in the design process, reducing the risks of costly redesigns and post-launch fixes. By addressing usability issues and gathering user feedback, UX research minimizes the risks associated with product failure and enhances its chances of success in the market. 5. Competitive Advantage: UX research provides valuable insights into users’ needs, preferences, and behaviors, which can give a competitive edge to a digital product or service. By creating a user-centered design that meets users’ expectations, products are more likely to stand out in a competitive market and attract loyal users. 6. Increased User Satisfaction and Loyalty: A well-designed product that caters to users’ needs and preferences leads to higher user satisfaction and loyalty. UX research helps understand user preferences, expectations, and pain points, resulting in products that meet user expectations and create a positive user experience. 7. Enhanced Brand Reputation: A user-centered design that prioritizes usability, accessibility, and user satisfaction contributes to a positive brand reputation. Users are more likely to recommend a product or service that provides a seamless and enjoyable experience, leading to enhanced brand reputation and word-of-mouth marketing. Conclusion UX research plays a critical role in designing digital products and services that are user-centered, effective, and successful in the market. It helps inform decision-making, improve usability, reduce risks, and create products that meet user needs and expectations. By incorporating UX research into the design process, businesses can gain a competitive advantage, enhance user satisfaction, and build a positive brand reputation. • Save Author: I'm Muhammad Faisal founder of GDJ and co-founder of FPD. I love all things having to do with WordPress, PHP, HTML5, CSS, or jQuery. And really enjoying to writing articles on web design and typography. You can catch me on Twitter, Facebook and Pinterest. Comments to The Essential Guide to UX Research: Methods, Best Practices, and Benefits Anthony Webb May 10, 2023 Nice read! thank you for gathering all UX related information in a single article. I like to share few pros and cons of UX Research: Pro: User-Centered Design: UX research ensures products meet user needs. Improved Usability: Identifies and resolves usability issues. Enhanced Conversion: Optimizes user experience, increasing conversions. Cost Efficiency: Prevents costly design changes later in the process. Competitive Advantage: Differentiates products with tailored experiences. Evidence-Based Decision Making: Relies on real user feedback for informed choices. Customer Satisfaction: Delivers products that truly satisfy users. Cons: Time and Resources: Conducting UX research can be time-consuming and resource-intensive. Expertise Requirement: It requires skilled researchers to conduct effective studies. Balancing User Needs and Business Goals: Finding a balance between user needs and business objectives can be challenging. Subjectivity: Interpreting user data may involve some level of subjectivity and bias. Limited Generalization: Findings may not always apply universally due to diverse user populations. Cost: Investing in UX research can be costly, especially for small businesses. Potential Conflict with Designers: Findings may challenge designers’ preconceptions, leading to conflicts. M Dev May 10, 2023 As i designer! I know how important is UX research. It provides valuable insights into user needs, behaviors, and preferences, guiding the design process and ensuring the creation of user-centered products. By incorporating research findings, designers can make informed decisions that lead to improved usability, engagement, and customer satisfaction. Thank you Author Muhammad Faisal May 10, 2023 Thank you for your appreciation and tips about UX Research. Leave a Reply Previous Post « Next Post » © 2010 - 2023 Graphic Design Junction. Powered by Wordpress. 7 Shares Share via Copy link
__label__pos
0.984667
ROC632: Construction of diagnostic or prognostic scoring system and internal validation of its discriminative capacities based on ROC curve and 0.633+ boostrap resampling This package computes traditional ROC curves and time-dependent ROC curves using the cross-validation, the 0.632 and the 0.632+ estimators. The 0.632+ estimator of time-dependent ROC curve is useful to estimate the predictive accuracy of prognostic signature based on high-dimensional data. For instance, it outperforms the other approaches, especially the cross-validation solution which is often used. The 0.632+ estimators correct the area under the curve in order to adequately estimate the prognostic capacities regardless of the overfitting level. This package also allows for the construction of diagnostic or prognostic scoring systems (penalized regressions). The methodology is adapted to complete data (penalized logistic regression associated with ROC curve) or incomplete time-to-event data (penalized Cox model associated with time-dependent ROC curve). Version: 0.6 Depends: R (≥ 2.10), splines, survival, penalized, survivalROC Published: 2013-12-27 Author: Y. Foucher Maintainer: Y. Foucher <Yohann.Foucher at univ-nantes.fr> License: GPL-2 | GPL-3 [expanded from: GPL (≥ 2)] URL: www.r-project.org, www.divat.fr NeedsCompilation: no CRAN checks: ROC632 results Downloads: Reference manual: ROC632.pdf Package source: ROC632_0.6.tar.gz Windows binaries: r-devel: ROC632_0.6.zip, r-release: ROC632_0.6.zip, r-oldrel: ROC632_0.6.zip OS X Mavericks binaries: r-release: ROC632_0.6.tgz, r-oldrel: ROC632_0.6.tgz Old sources: ROC632 archive
__label__pos
0.655599
Generics Invariance In Java FILE : JavaInvariance.java First let's look at one example written in java to have a base for further experiments. In Java collections are invariant what means that List is not a supertype of List List<String> strings= new LinkedList<>(); strings.add("aaa"); strings.add("bbb"); List<Object> object=new LinkedList<>(); object.add("aaa"); object.add(2); // ILLEGAL IN JAVA // object=strings; However Java has a mechanism called use site variance which allows programmer to use wildcards in assignment and declare different relation between types. List<? extends Object> parent=strings; This mechanism however moves responsibility for defining correct relationship to developer in each assignment thus gives more chances to introduce a bug. Scala uses declaration site variance which solves this problem. Arrays - bug by design In Java you can actually assign String[] to Object[] which allow you to store integer in an array of strings. This is by design and results in ArrayStroeException in runtime. (Why this is by design -> search on the internet) String[] stringsArray={"aaa","bbb"}; Object[] objectsArray=stringsArray; objectsArray[1]=55; Generics In Scala FILE : GenericsDemo.scala First difference form Java - generics in scala are declared in square brackets. var map:Map[String,Int]=Map() def genericToString[T](arg : T) : String = arg.toString You can add generic directly to a class definition and also another one to method definition so it will be resolved each time a method is called class Wrapper[A](element:A){ def modify[B](f:A=>B):Wrapper[B] = new Wrapper[B](f(element)) } Invariance and covariance Scala has two sets of collections : scala.collections.mutable and scala.collections.immutable. By default you are using immutable collections which are covariant - this means that List[Any] is a supertype of List[String] val s:List[String] = List("aaa","bbb") val i:List[Int]=List(1,2) val o1:List[AnyRef] = s val o2:List[Any] = i This is legal because it is impossible to add an element to immutable list so you can not add integer to a collection of strings. If you want to declare covariant structure you need to add + before generic declaration class CovariantWrapper[+A](element:A){ def modify[B](f:A=>B):Wrapper[B] = new Wrapper[B](f(element)) } Nothing Nothing type becomes really useful when working with covariant types. Becuase Nothing is a subtype of every other type then we can always do a substitution val v:Type[Whatever] = Type[Nothing]() so for example when working with either and defining one side we can easily set other side as Nothing def createRight:Either[Nothing,Int]=Right(500) Arrays Arrays are invariant so no "java bugs by design". val arrayString=Array("aaa","bbb") // val arrayAny:Array[Any]=arrayString //error Exercises FILE TEST : jug.lodz.workshops.starter.generics.exercises. GenericsExercisesSpec 1. Create typed Pair[A,B] 2. Method which displays patch of any class 3. Create Invariant option with proper implementation of getOrElse in None and Some 4. Implement Covariant Option - in this exercise uncomment only part of code. Leave getOrElse for exercise 5. results matching "" No results matching ""
__label__pos
0.886148
Share Notifications View all notifications NCERT solutions for Class 8 Mathematics Textbook chapter 15 - Introduction to Graphs [Latest edition] Login Create free account       Forgot password? Textbook page Chapters Chapter 15: Introduction to Graphs Ex. 15.1Ex. 15.2Ex. 15.3 NCERT solutions for Class 8 Mathematics Textbook Chapter 15 Introduction to Graphs Exercise 15.1 [Pages 236 - 239] Ex. 15.1 | Q 1 | Page 236 The following graph shows the temperature of a patient in a hospital, recorded every hour. 1) What was the patient’s temperature at 1 p.m.? 2) When was the patient’s temperature 38.5°C? 3) The patient’s temperature was the same two times during the period given. What were these two times? 4) What was the temperature at 1.30 p.m.? How did you arrive at your answer? 5) During which periods did the patients’ temperature showed an upward trend? Ex. 15.1 | Q 2 | Page 237 The following line graph shows the yearly sales figures for a manufacturing company. 1) What were the sales in (a) 2002 (b) 2006? 2) What were the sales in (a) 2003 (b) 2005? 3) Compute the difference between the sales in 2002 and 2006. 4) In which year was there the greatest difference between the sales as compared to its previous year? Ex. 15.1 | Q 3 | Page 237 For an experiment in Botany, two different plants, plant A and plant B were grown under similar laboratory conditions. Their heights were measured at the end of each week for 3 weeks. The results are shown by the following graph. 1) How high was Plant A after (a) 2 weeks (b) 3weeks? 2) How high was Plant B after (a) 2 weeks (b) 3weeks? 3) How much did Plant A grow during the 3rd week? 4) How much did Plant B grow from the end of the 2nd week to the end of the 3rd week? 5) During which week did Plant A grow most? 6) During which week did Plant B grow least? 7) Were the two plants of the same height during any week shown here? Specify. Ex. 15.1 | Q 4 | Page 238 The following graph shows the temperature forecast and the actual temperature for each day of a week. 1) On which days was the forecast temperature the same as the actual temperature? 2) What was the maximum forecast temperature during the week? 3) What was the minimum actual temperature during the week? 4) On which day did the actual temperature differ the most from the forecast temperature? Ex. 15.1 | Q 5.1 | Page 238 Use the tables below to draw linear graphs The number of days a hill side city received snow in different years. Year 2003 2004 2005 2006 Days 8 10 5 12  Ex. 15.1 | Q 5.2 | Page 238 Use the tables below to draw linear graphs. Population (in thousands) of men and women in a village in different years. Year 2003 2004 2005 2006 2007 Number of men 12 12.5 13 13.2 13.5 Number of women 11.3 11.9 13 13.6 12.8  Ex. 15.1 | Q 6 | Page 239 A courier-person cycles from a town to a neighboring suburban area to deliver a parcel to a merchant. His distance from the town at different times is shown by the following graph. 1) What is the scale taken for the time axis? 2) How much time did the person take for the travel? 3) How far is the place of the merchant from the town? 4) Did the person stop on his way? Explain. 5) During which period did he ride fastest? Ex. 15.1 | Q 7.1 | Page 239 Can there be a time temperature graph as follows? Justify you’re answer: Ex. 15.1 | Q 7.2 | Page 239 Can there be a time-temperature graph as follows? Justify your answer Ex. 15.1 | Q 7.3 | Page 239 Can there be a time-temperature graph as follows? Justify your answer Ex. 15.1 | Q 7.4 | Page 239 Can there be a time temperature graph as follows? Justify you’re answer: NCERT solutions for Class 8 Mathematics Textbook Chapter 15 Introduction to Graphs Exercise 15.2 [Page 243] Ex. 15.2 | Q 1.1 | Page 243 Plot the following points on a graph sheet. Verify if they lie on a line A(4, 0), B(4, 2), C(4, 6), D(4, 2.5) Ex. 15.2 | Q 1.2 | Page 243 Plot the following points on a graph sheet. Verify if they lie on a line P(1, 1), Q(2, 2), R(3, 3), S(4, 4) Ex. 15.2 | Q 1.3 | Page 243 Plot the following points on a graph sheet. Verify if they lie on a line K(2, 3), L(5, 3), M(5, 5), N(2, 5) Ex. 15.2 | Q 2 | Page 243 Draw the line passing through (2, 3) and (3, 2). Find the coordinates of the points at which this line meets the x-axis and y-axis. Ex. 15.2 | Q 3 | Page 243 Write the coordinates of the vertices of each of these adjoining figures. Ex. 15.2 | Q 4.1 | Page 243 State whether True or False. Correct those are false. A point whose x coordinate is zero and y-coordinate is non-zero will lie on the y-axis. • True • False Ex. 15.2 | Q 4.2 | Page 243 State whether True or False. Correct those are false. A point whose y coordinate is zero and x-coordinate is 5 will lie on y-axis. • True • False Ex. 15.2 | Q 4.3 | Page 243 State whether True or False. Correct those are false. The coordinates of the origin are (0, 0). • True • False NCERT solutions for Class 8 Mathematics Textbook Chapter 15 Introduction to Graphs Exercise 15.3 [Pages 247 - 248] Ex. 15.3 | Q 1.1 | Page 247 Draw the graphs for the following tables of values, with suitable scales on the axes. Cost of apples Number of apples 1 2 3 4 5 Cost (in Rs) 5 10 15 20 25 Ex. 15.3 | Q 1.2 | Page 247 Draw the graphs for the following tables of values, with suitable scales on the axes. Distance travelled by a car Time (in hours) 6 a.m 7 a.m 8 a.m 9 a.m Distance (in km) 40 80 120 160  1)  How much distance did the car cover during the period 7.30 a.m. to 8 a.m.? 2) What was the time when the car had covered a distance of 100 km since its start? Ex. 15.3 | Q 1.3 | Page 247 Draw the graphs for the following tables of values, with suitable scales on the axes.  Interest on deposits for a year: Deposit (in Rs) 1000 2000 3000 4000 5000 Simple interest (in Rs) 80 160 240 320 400 1) Does the graph pass through the origin? 2) Use the graph to find the interest on Rs 2500 for a year: 3) To get an interest of Rs 280 per year, how much money should be deposited? Ex. 15.3 | Q 2.1 | Page 248 Draw a graph for the following. Side of square (in cm) 2 3 3.5 5 5 Perimeter (in cm) 8 12 14 20 24 Is it a linear graph?   Ex. 15.3 | Q 2.2 | Page 248 Draw a graph for the following. Side of square (in cm) 2 3 4 5 6 Area (in cm2) 4 9 16 25 36 Is it a linear graph?   Chapter 15: Introduction to Graphs Ex. 15.1Ex. 15.2Ex. 15.3 NCERT solutions for Class 8 Mathematics Textbook chapter 15 - Introduction to Graphs NCERT solutions for Class 8 Mathematics Textbook chapter 15 (Introduction to Graphs) include all questions with solution and detail explanation. This will clear students doubts about any question and improve application skills while preparing for board exams. The detailed, step-by-step solutions will help you understand the concepts better and clear your confusions, if any. Shaalaa.com has the CBSE Class 8 Mathematics Textbook solutions in a manner that help students grasp basic concepts better and faster. Further, we at Shaalaa.com provide such solutions so that students can prepare for written exams. NCERT textbook solutions can be a core help for self-study and acts as a perfect self-help guidance for students. Concepts covered in Class 8 Mathematics Textbook chapter 15 Introduction to Graphs are Concept of Bar Graph, Concept of Pie Graph (Or a Circle-graph), Concept of Histogram, Concept of a Line Graph, Some Applications, Linear Graphs - Location of a Point, Linear Graphs - Coordinates. Using NCERT Class 8 solutions Introduction to Graphs exercise by students are an easy way to prepare for the exams, as they involve solutions arranged chapter-wise also page wise. The questions involved in NCERT Solutions are important questions that can be asked in the final exam. Maximum students of CBSE Class 8 prefer NCERT Textbook Solutions to score more in exam. Get the free view of chapter 15 Introduction to Graphs Class 8 extra questions for Class 8 Mathematics Textbook and can use Shaalaa.com to keep it handy for your exam preparation S View in app×
__label__pos
0.999815
Fix output sanitatizing for options and xhtml-fixes. [squirrelmail.git] / functions / display_messages.php CommitLineData 59177427 1<?php 2ba13803 2 35586184 3/** 4 * display_messages.php 5 * 82d304a0 6 * Copyright (c) 1999-2004 The SquirrelMail Project Team 35586184 7 * Licensed under the GNU GPL. For full terms see the file COPYING. 8 * 9 * This contains all messages, including information, error, and just 10 * about any other message you can think of. 11 * 31841a9e 12 * @version $Id$ d6c32258 13 * @package squirrelmail 35586184 14 */ 3302d0d4 15 5100f68f 16/** 17 * including plugin functions 18 */ ebb9eaaf 19require_once(SM_PATH . 'functions/plugin.php'); 20 c94b297c 21/** 22 * Find out where squirrelmail lives and try to be smart about it. 23 * The only problem would be when squirrelmail lives in directories 24 * called "src", "functions", or "plugins", but people who do that need 25 * to be beaten with a steel pipe anyway. 26 * d6c32258 27 * @return string the base uri of squirrelmail installation. c94b297c 28 */ 399846ea 29function sqm_baseuri(){ 30 global $base_uri, $PHP_SELF; c94b297c 31 /** 32 * If it is in the session, just return it. 33 */ 399846ea 34 if (isset($base_uri)){ 35 return $base_uri; 36 } 7e156b3d 37 $dirs = array('|src/.*|', '|plugins/.*|', '|functions/.*|'); 38 $repl = array('', '', ''); 399846ea 39 $base_uri = preg_replace($dirs, $repl, $PHP_SELF); 40 return $base_uri; 41} 42 ec5b189b 43function error_message($message, $mailbox, $sort, $startMessage, $color) { 44 $urlMailbox = urlencode($mailbox); fd2611e9 45 $string = '<tr><td ALIGN="center">' . $message . '</td></tr>'."\n". 46 '<tr><td ALIGN="center">'. 47 '<A HREF="' . sqm_baseuri() 90d3887e 48 . "src/right_main.php?sort=$sort&amp;startMessage=$startMessage" fd2611e9 49 . "&amp;mailbox=$urlMailbox\">" . 42c2281a 50 sprintf (_("Click here to return to %s"), strtoupper($mailbox) == 'INBOX' ? _("INBOX") : imap_utf7_decode_local($mailbox)) . fd2611e9 51 '</A></td></tr>'; 52 error_box($string, $color); ec5b189b 53} aa4c3749 54 ec5b189b 55function plain_error_message($message, $color) { fd2611e9 56 error_box($message, $color); ec5b189b 57} b6d8d08d 58 9be8198d 59function logout_error( $errString, $errTitle = '' ) { 1f05436e 60 global $frame_top, $org_logo, $org_name, $org_logo_width, $org_logo_height, 35185c82 61 $hide_sm_attributions, $version, $squirrelmail_language; 62 399846ea 63 $base_uri = sqm_baseuri(); 26f9a94a 64 65 include_once( SM_PATH . 'functions/page_header.php' ); 9be8198d 66 if ( !isset( $org_logo ) ) { 67 // Don't know yet why, but in some accesses $org_logo is not set. 26f9a94a 68 include( SM_PATH . 'config/config.php' ); 9be8198d 69 } 70 /* Display width and height like good little people */ 71 $width_and_height = ''; e16cb07b 72 if (isset($org_logo_width) && is_numeric($org_logo_width) && $org_logo_width>0) { 9be8198d 73 $width_and_height = " WIDTH=\"$org_logo_width\""; 74 } e16cb07b 75 if (isset($org_logo_height) && is_numeric($org_logo_height) && $org_logo_height>0) { 9be8198d 76 $width_and_height .= " HEIGHT=\"$org_logo_height\""; 77 } 78 79 if (!isset($frame_top) || $frame_top == '' ) { 80 $frame_top = '_top'; 81 } 82 83 if ( !isset( $color ) ) { 84 $color = array(); 85 $color[0] = '#DCDCDC'; /* light gray TitleBar */ 86 $color[1] = '#800000'; /* red */ 87 $color[2] = '#CC0000'; /* light red Warning/Error Messages */ 9be8198d 88 $color[4] = '#FFFFFF'; /* white Normal Background */ 9be8198d 89 $color[7] = '#0000CC'; /* blue Links */ 90 $color[8] = '#000000'; /* black Normal text */ 9be8198d 91 } 92 8d42e09a 93 list($junk, $errString, $errTitle) = do_hook('logout_error', $errString, $errTitle); 94 9be8198d 95 if ( $errTitle == '' ) { 96 $errTitle = $errString; 97 } 98 set_up_language($squirrelmail_language, true); 1f05436e 99 100 displayHtmlHeader( $errTitle, '', false ); 101 9be8198d 102 echo "<BODY TEXT=\"$color[8]\" BGCOLOR=\"$color[4]\" LINK=\"$color[7]\" VLINK=\"$color[7]\" ALINK=\"$color[7]\">\n\n" . 4cbcaebd 103 '<CENTER>'; 104 105 if (isset($org_logo) && ($org_logo != '')) { 106 echo "<IMG SRC=\"$org_logo\" ALT=\"" . sprintf(_("%s Logo"), $org_name) . 107 "\"$width_and_height><BR>\n"; 108 } 109 echo ( $hide_sm_attributions ? '' : 9be8198d 110 '<SMALL>' . sprintf (_("SquirrelMail version %s"), $version) . "<BR>\n". 111 ' ' . _("By the SquirrelMail Development Team") . "<BR></SMALL>\n" ) . 112 "<table cellspacing=1 cellpadding=0 bgcolor=\"$color[1]\" width=\"70%\"><tr><td>". c9062c05 113 "<TABLE WIDTH=\"100%\" BORDER=\"0\" BGCOLOR=\"$color[4]\" ALIGN=CENTER>". 114 "<TR><TD BGCOLOR=\"$color[0]\" ALIGN=\"center\">". 115 "<FONT COLOR=\"$color[2]\"><B>" . _("ERROR") . 116 '</B></FONT></TD></TR>'. 117 '<TR><TD ALIGN="center">' . $errString . '</TD></TR>'. 118 "<TR><TD BGCOLOR=\"$color[0]\" ALIGN=\"center\">". 119 "<FONT COLOR=\"$color[2]\"><B>". c94b297c 120 '<a href="' . $base_uri . 'src/login.php" target="' . 121 $frame_top . '">' . c9062c05 122 _("Go to the login page") . "</a></B></FONT>". 9be8198d 123 '</TD></TR>'. 1f05436e 124 '</TABLE></td></tr></table></center></body></html>'; 9be8198d 125} 126 fd2611e9 127function error_box($string, $color) { b6c283c4 128 global $pageheader_sent; 129 a429618b 130 if ( !isset( $color ) ) { 131 $color = array(); 132 $color[0] = '#DCDCDC'; /* light gray TitleBar */ 133 $color[1] = '#800000'; /* red */ 134 $color[2] = '#CC0000'; /* light red Warning/Error Messages */ 135 $color[4] = '#FFFFFF'; /* white Normal Background */ 136 $color[7] = '#0000CC'; /* blue Links */ 137 $color[8] = '#000000'; /* black Normal text */ 138 } 139 b6c283c4 140 $err = _("ERROR"); 141 7753dac4 142 $ret = concat_hook_function('error_box', $string); 143 if($ret != '') { 144 $string = $ret; 145 } 8d42e09a 146 b6c283c4 147 /* check if the page header has been sent; if not, send it! */ 148 if(!isset($pageheader_sent) && !$pageheader_sent) { 149 /* include this just to be sure */ 150 include_once( SM_PATH . 'functions/page_header.php' ); 151 displayHtmlHeader('SquirrelMail: '.$err); 152 $pageheader_sent = TRUE; 153 echo "<body text=\"$color[8]\" bgcolor=\"$color[4]\" link=\"$color[7]\" vlink=\"$color[7]\" alink=\"$color[7]\">\n\n"; 154 } 155 36ec6865 156 echo ' <table width="100%" cellpadding="1" cellspacing="0" align="center"'.' border="0" bgcolor="'.$color[9].'">'; 157 echo ' <tr><td>'; 158 echo ' <table width="100%" cellpadding="0" cellspacing="0" align="center" border="0" bgcolor="'.$color[4].'">'; 159 echo ' <tr><td ALIGN="center" bgcolor="'.$color[0].'">'; 472e7acb 160 echo ' <font color="' . $color[2].'"><b>' . $err . ':</b></font>'; 36ec6865 161 echo ' </td></tr>'; 162 echo ' <tr><td>'; 163 echo ' <table cellpadding="1" cellspacing="5" align="center" border="0">'; 164 echo ' <tr>' . html_tag( 'td', $string."\n", 'left') 165 . '</tr>'; 166 echo ' </table>'; bbc2c67d 167 echo ' </td></tr>'; 36ec6865 168 echo ' </table></td></tr>'; 169 echo ' </table>'; fd2611e9 170} 6a6ce0a3 171?>
__label__pos
0.736844
chservice.exe Process Information Process Name: Cyberhawk Service Author: Novatix Corporation Download PC Repair Tool & fix chservice.exe Windows errors automatically System Process: No Uses network: No Hardware related: No Background Process: Yes Spyware: No Trojan: No Virus: No Security risk 0-5: 0 What is chservice exe? chservice.exe is a process associated with NovatixCyberhawk (tm) from Novatix Corporation. The “.exe” file extension stands for Windows executable file. Any program that is executable has the .exe file extension. Find out if chservice.exe is a virus and sould be removed, how to fix chservice.exe error, if chservice exe is CPU intensive and slowing down your Windows PC. Any process has four stages of the lifecycle including start, ready, running, waiting, terminated or exit. Should You Remove chservice exe? If you are asking yourself if it is safe to remove chservice.exe from your Windows system then it is understandable that it is causing trouble. chservice.exe is not a critical component and a non-system process. Any process that is not managed by the system is known as non-system processes. It is safe to terminate the non-system process as they do not affect the general functionality of the operating system. However, the program using the non-system processes will be either terminated or halted. Download PC Repair Tool & fix chservice.exe Windows errors automatically Fix chservice.exe Error? There are many reasons why you are seeing chservice.exe error in your Windows system including: Malicious software Malicious software infects the system with malware, keyloggers, spyware, and other malicious actors. They slow down the whole system and also cause .exe errors. This occurs because they modify the registry which is very important in the proper functioning of processes. Incomplete installation Another common reason behind chservice.exe error is an incomplete installation. It can happen because of errors during installation, lack of hard disk space, and crash during install. This also leads to a corrupted registry causing the error. Application conflicts and Missing or corrupt windows drivers can also lead to chservice.exe error. The solution to fixing chservice.exe error include any one of the following • Make sure your PC is protected with proper anti-virus software program. • Run a registry cleaner to repair and remove the Windows registry that is causing chservice.exe error. • Make sure the system’s device drivers are updated properly. It is also recommended that you run a performance scan to automatically optimize memory and CPU settings. Download PC Repair Tool & fix chservice.exe Windows errors automatically Is a chservice.exe CPU intensive? Windows process requires three resource types to function properly including CPU, Memory, and Network. CPU cycles to do computational tasks, memory to store information and network to communicate with the required services. If any of the resources are not available, it will either get interrupted or stopped. Any given process has a process identification number(PID) associated with it. A user can easily identify and track a process using its PID. Task Manager is a great way to learn how much resources chservice.exe process is allocating to itself. It showcases process resource usage in CPU/Memory/Disk and Network. If you have a GPU, it will also showcase the percentage of GPU it is using to run the process.
__label__pos
0.897914
Locks in Java A few examples and notes Nicholas Duchon, Jan 5, 2015. Outline Externals General The problem is controlled and efficient access to shared resources. Java support Type Class or Package Links to API - SE 8 Threads java.lang.Thread Thread - start, run, sleep, join, yield Monitor java.lang.Object Object - wait, notify, notifyAll Chapter 8. Classes - synchronized reference in Language Specification Lock interface java.util.concurrent.locks locks Atomic single variable updates java.util.concurrent.atomic atomic Thread-safe data structures java.util.concurrent concurrent Low level machine interface sun.misc.Unsafe FAQ - Sun Packages - Unsafe is exactly what its name implies Understanding sun.misc.Unsafe | Javalobby some of its features Download Slides - Oracle - 2014 pdf presentation on ideas for locks Object class Each object in Java (including instances of Class class) has ONE lock, called a monitor, which is handled through the synchronized(Object) keyword and the wait/notify/notifyAll methods. Here is a typical approach to using these locks: 1. synchronized (X) { 2.   while (X.busyFlag) { 3.     try { 4.       X.wait(); 5.     } 6.     catch (InterruptedException e) { 7.     } // end try/catch block 8.   } // end while waiting for worker to be free 9.   X.busyFlag = true; 10. } // end synchronized on X 11. // do stuff, not needing synchronization 12. // later: 13. synchronized (X) { 14.   X.busyFlag = false; 15.   X.notifyAll (); 16. } // end synchronized on X Comments: 1. This code can be used to make sure that only one thread has access to X at a time, while minimizing the resources used by threads that don't have access to X. 2. In this example, the entire focus is on the control of access to the variable X.busyFlag in a multi-threaded environment. 3. (lines 1-10 and 13-16): Request lock on object X (may be an instance of a class or the class definition). This will block if some other thread is holding this lock - the monitor for this object. 4. (lines 2-8) Check some condition, only proceed if condition is not met. In this case, the X class has a boolean variable busyFlag. 5. (lines 3-8) try/catch block related to the wait() method call on line 4. 6. (line 4) Since the object X was not available (the condition on line 2 was true), this thread will go into a wait state, taking it off the thread scheduler's processes ready to run list. 1. The wait() operation RELEASES the monitor lock, and blocks until this thread receives a notify() call, or a notifyAll() is executed by another thread. 2. When this thread is awoken by the O/S, the thread first tries to acquire the monitor lock on the object X. 1. If acquiring the lock fails, this thread will block waiting for the lock to be released through an end of some other synchronize block on this object. In other words, this thread re-executes the wait() method. 2. If acquiring the lock succeeds, this code will exit the try/catch block, to line 8, which returns the execution to line 2. 7. (line 9) if the code gets here, THIS thread has sole access to X, and now is the time to mark this object as owned by this thread 8. (line 10) The end of the synchronize block, which will release the monitor lock on the object X. 9. (line 11) This is the time to do something that may be long and complicated, but will not impact any other thread. 10. (lines 13-16) Again request the lock on object X. 11. (line 14) Change the condition variable used by X. 12. (line 15) Notify other threads that the condition of X has changed, and let the other threads try their luck in obtaining sole protected access to X. 13. The monitor lock is held for very short times. 14. The monitor methods (wait, notify and notifyAll) MUST be inside a synchronized block of the corresponding object - in this example, that object is X. Locks Locks interface ReentrantLock Class Condition interface Required & common Specialized Methods lock () lockInterruptibly () newCondition () tryLock () tryLock (long, TimeUnit) unlock () lock () lockInterruptibly () newCondition () tryLock () tryLock (long, TimeUnit) unlock () isLocked () toString () getHoldCount () getOwner () getQueuedThreads () getQueueLength () getWaitingThreads (Condition) getWaitQueueLength (Condition) hasQueuedThread (Thread) hasQueuedThreads () hasWaiters (Condition) isFair () isHeldByCurrentThread () await () await (long, TimeUnit) awaitNanos (long) awaitUninterruptibly () awaitUntil (Date) signal () signalAll () Lock Trace Example Here's a trace of the methods called when a myLock.lock() call is made on the ReentrantLock myLock. Locking Examples public class TaskThreadDemo {   public static void main (String args []) {     String [] sa = {"a", "X", "+", "."};     for (String s: sa) {       Runnable ps = new PrintChar (s, 200);       Thread ts = new Thread (ps, s);       ts.start ();     } // end for each character   } // end main } // end class TaskThreadDemo class PrintChar implements Runnable {   String ch;   int times;     public PrintChar (String c, int n) {     ch = c;     times = n;   } // end constructor     public void run () {     for (int i = 0; i < times; i++) {       System.out.print (ch);       if (i%30 == 29) System.out.println ();     } // end for loop   } // end method run } // end class PrintChar public class TaskThreadDemo2 {   public static void main (String args []) {     String [] sa = {"a", "X", "+", "."};     Thread ts;     for (String s: sa) {       Runnable ps = new PrintChar2 (10_000_000);       ts = new Thread (ps, s);       ts.start (); // start () vs run() !     } // end for each character   } // end main } // end class TaskThreadDemo class PrintChar2 implements Runnable {   static int sum; // try without static !   int times;     public PrintChar2 (int n) {     times = n;   } // end constructor     // try synchronized : method, this, class   public void run () {     for (int i = 0; i < times; i++) {       sum = sum + 1; //       synchronized (PrintChar2.class) { sum = sum + 1;} //       synchronized (this) { sum = sum + 1;}     } // end for loop     System.out.printf ("%s: %,d\n",       Thread.currentThread().getName(),       sum);   } // end method run } // end class PrintChar import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class TaskThreadDemo3 {   public static void main (String args []) {     String [] sa = {"a", "X", "+", "."};     Thread ts;     for (String s: sa) {       Runnable ps = new PrintChar3 (10_000_000);       ts = new Thread (ps, s);       ts.start (); // start () vs run() !     } // end for each character   } // end main } // end class TaskThreadDemo3 class PrintChar3 implements Runnable {   static Lock myLock = new ReentrantLock ();   static int sum; // try without static !   int times;     public PrintChar3 (int n) {     times = n;   } // end constructor     // try locking : method, this, class   public void run () {     for (int i = 0; i < times; i++) { //       sum = sum + 1;       {myLock.lock(); sum = sum + 1; myLock.unlock();}     } // end for loop     System.out.printf ("%s: %,d\n",       Thread.currentThread().getName(),       sum);   } // end method run } // end class PrintChar3 import java.util.concurrent.atomic.LongAdder; public class TaskThreadDemo4 {   public static void main (String args []) {     String [] sa = {"a", "X", "+", "."};     Thread [] ts = new Thread [sa.length];     for (int i = 0; i < ts.length; i++) {       Runnable ps = new PrintChar4 (10_000_000);       ts[i] = new Thread (ps, sa[i]);       ts[i].start ();     } // end start a thread for each character     for (int i = 0; i < ts.length; i++) {       try {ts[i].join ();}       catch (InterruptedException e) {}     } // end for i - wait until all threads are done     System.out.printf ("Final sum: %,d\n", PrintChar4.sum.intValue());   } // end main } // end class TaskThreadDemo4 class PrintChar4 implements Runnable {   static LongAdder sum = new LongAdder ();   int times;     public PrintChar4 (int n) {     times = n;   } // end constructor      public void run () {     for (int i = 0; i < times; i++) {       sum.add(1);     } // end for loop     System.out.printf ("%s: %,d\n",       Thread.currentThread().getName(),       sum.intValue());   } // end method run } // end class PrintChar4 More Comments As for why locks might be better than synchronized methods, and vs synchronized blocks - let me give it a try. First, a synchronized method is actually synchronizing on "this" - in an instance method, the object that was the context of the method call. In a static method, the class (as an object). A synchronized block will explicitly synchronize on some object: synchronize (this) or synchronize (X), where X is some object in scope. In this context, a lock creates a completely different object and synchronizes on that object. Even more to the point - Java currently provides only THREE classes that implement the Lock interface: And they all are based on the idea of a queue holding the threads that attempt to assert this lock - which gives a kind of fairness to the system. And then there's the substitute for the wait/notify/notifyAll protocol of synchronize, based on conditions - but again Condition is an interface, with only two current implementations: And writing your own implementations of these interfaces seems amazingly daunting. SO: Instead of creating one's own conditions, like I did in the following example using the X.busy boolean flag: With locks, one can define conditions in a more intuitive and integral way - notice the two conditions defined in the example and how they are used - and that the conditions are tied to the lock: I know this is rather long, but the issues take quite a bit of time to explain and they are rather subtle. I hope thus helps, Summaries Locks package Atomic package Interfaces Classes Classes Condition Lock ReadWriteLock AtomicBoolean AtomicInteger AtomicIntegerArray AtomicIntegerFieldUpdater AtomicLong AtomicLongArray AtomicLongFieldUpdater AtomicMarkableReference AtomicReference AtomicReferenceArray AtomicReferenceFieldUpdater AtomicStampedReference DoubleAccumulator DoubleAdder LongAccumulator LongAdder Concurrent Package Interfaces Classes Enums Exceptions BlockingDeque BlockingQueue Callable CompletableFuture.AsynchronousCompletionTask CompletionService CompletionStage ConcurrentMap ConcurrentNavigableMap Delayed Executor ExecutorService ForkJoinPool.ForkJoinWorkerThreadFactory ForkJoinPool.ManagedBlocker Future RejectedExecutionHandler RunnableFuture RunnableScheduledFuture ScheduledExecutorService ScheduledFuture ThreadFactory TransferQueue AbstractExecutorService ArrayBlockingQueue CompletableFuture ConcurrentHashMap ConcurrentHashMap.KeySetView ConcurrentLinkedDeque ConcurrentLinkedQueue ConcurrentSkipListMap ConcurrentSkipListSet CopyOnWriteArrayList CopyOnWriteArraySet CountDownLatch CountedCompleter CyclicBarrier DelayQueue Exchanger ExecutorCompletionService Executors ForkJoinPool ForkJoinTask ForkJoinWorkerThread FutureTask LinkedBlockingDeque LinkedBlockingQueue LinkedTransferQueue Phaser PriorityBlockingQueue RecursiveAction RecursiveTask ScheduledThreadPoolExecutor Semaphore SynchronousQueue ThreadLocalRandom ThreadPoolExecutor ThreadPoolExecutor.AbortPolicy ThreadPoolExecutor.CallerRunsPolicy ThreadPoolExecutor.DiscardOldestPolicy ThreadPoolExecutor.DiscardPolicy TimeUnit BrokenBarrierException CancellationException CompletionException ExecutionException RejectedExecutionException TimeoutException
__label__pos
0.965201
0 Hi, I would like to search one field in database with multiple words. Also i will allow searches for example : a or cs....(one,two characters). My code: <cfparam name="URL.NAME" default="1" type="Any"> <cfquery name="search" datasource="datasource"> SELECT * FROM search WHERE NAME LIKE ="%#URL.NAME#%" ORDER BY DATE DESC </cfquery> this code works fine but only with one word or if there is exact match with multiple words. Example: database rows: 1.adobe photohop 2.adobe photoshop cs4 search string adobe(my code) will display both results,but search string adobe cs4 will not display results. I want if user type one,two, three words to match any of these words and to display all results like google. What am I doing wrong? I also tried to replace characters and add + but no results. Any idea or example i would appreciate. 5 Contributors 5 Replies 7 Views 8 Years Discussion Span Last Post by samaru 0 You don't explain enough about what the data looks like and the result you are trying to get. But couldn't you break the url.name into pieces based on spaces and then select LIKE for each piece? 0 i was tired to think when i posted question. You can use and i am using cfif and cfloop tags in cfqueries. Just loop url.name, that is simple explanation and for advanced one you will need a couple of cfif,cfset and cfloop's in cfqueries. 0 you have to break your input into 2 elements separated by a delimiter(I did it with a space) and put them into an array <cfparam name="strSearch" default=""> <cfparam name="myArrayList" default=""> <cfset myArrayList=ArrayNew(1)> <cfif isdefined("form.searchMeals") AND form.searchMeals neq ""> <cfset strSearch = #trim(form.searchMeals)#> <cfset strSearch = #lcase(strSearch)#> <cfif strSearch contains ""> <cfset strSearch = Replace(strSearch," ",",")> <cfset myArrayList = ListToArray(strSearch)> <cfif myArrayList[1] neq ""> <cfset element1 = #myArrayList[1]#> </cfif> <cfif strSearch contains ","> <cfset element2 = #myArrayList[2]#> </cfif> </cfif> </cfif> now you can easily pass both or either one into your query. Hope this helps. Edited by peter_budo: Keep It Organized - For easy readability, always wrap programming code within posts in [code] (code blocks) 0 You can try to find some Capitalization method from the database that you are using and search it like. In postgreSQL they have initcap() method for capitalizing the first letters of the words. I don't really know but I did not find any method in coldfusion that converts the first letter of a set of words in uppercase. so that's how I did manage it. and initcap(column_name) LIKE initcap('%#url.name#%') Hope that helps. Edited by grungy coder: n/a 0 Word order I assume counts? (For example "Adobe ColdFusion" vs "ColdFusion Adobe.") Also, you may want to use <cfqueryparam> to help against SQL Injections. <cfset searchString = "Immigration Law" /> <cfquery name="Info" datasource="YourDB"> SELECT * FROM Areas WHERE <cfloop list="#searchString#" delimiters=" " index="word"> ShortName LIKE <cfqueryparam cfsqltype="cf_sql_varchar" value="%#Trim(word)#%" /> OR </cfloop> (1 <> 1) </cfquery> <cfdump var="#Info#" /> If you have to search a lot of text, I suggest you use your database's FTS services or Verity. This topic has been dead for over six months. Start a new discussion instead. Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.
__label__pos
0.849363
Consistently print program Name and __func__ in debug messages. [thirdparty/mdadm.git] / managemon.c CommitLineData a54d5262 DW 1/* 2 * mdmon - monitor external metadata arrays 3 * e736b623 N 4 * Copyright (C) 2007-2009 Neil Brown <[email protected]> 5 * Copyright (C) 2007-2009 Intel Corporation a54d5262 DW 6 * 7 * This program is free software; you can redistribute it and/or modify it 8 * under the terms and conditions of the GNU General Public License, 9 * version 2, as published by the Free Software Foundation. 10 * 11 * This program is distributed in the hope it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for 14 * more details. 15 * 16 * You should have received a copy of the GNU General Public License along with 17 * this program; if not, write to the Free Software Foundation, Inc., 18 * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. 19 */ 549e9569 NB 20 21/* 22 * The management thread for monitoring active md arrays. 23 * This thread does things which might block such as memory 24 * allocation. 25 * In particular: 26 * 27 * - Find out about new arrays in this container. 28 * Allocate the data structures and open the files. 29 * 30 * For this we watch /proc/mdstat and find new arrays with 31 * metadata type that confirms sharing. e.g. "md4" 32 * When we find a new array we slip it into the list of 33 * arrays and signal 'monitor' by writing to a pipe. 34 * 35 * - Respond to reshape requests by allocating new data structures 36 * and opening new files. 37 * 38 * These come as a change to raid_disks. We allocate a new 39 * version of the data structures and slip it into the list. 40 * 'monitor' will notice and release the old version. 41 * Changes to level, chunksize, layout.. do not need re-allocation. 42 * Reductions in raid_disks don't really either, but we handle 43 * them the same way for consistency. 44 * 45 * - When a device is added to the container, we add it to the metadata 46 * as a spare. 47 * 6c3fb95c NB 48 * - Deal with degraded array 49 * We only do this when first noticing the array is degraded. 50 * This can be when we first see the array, when sync completes or 51 * when recovery completes. 52 * 53 * Check if number of failed devices suggests recovery is needed, and 54 * skip if not. 55 * Ask metadata to allocate a spare device 56 * Add device as not in_sync and give a role 57 * Update metadata. 58 * Open sysfs files and pass to monitor. 59 * Make sure that monitor Starts recovery.... 549e9569 NB 60 * 61 * - Pass on metadata updates from external programs such as 62 * mdadm creating a new array. 63 * 64 * This is most-messy. 65 * It might involve adding a new array or changing the status of 66 * a spare, or any reconfig that the kernel doesn't get involved in. 67 * 68 * The required updates are received via a named pipe. There will 69 * be one named pipe for each container. Each message contains a 70 * sync marker: 0x5a5aa5a5, A byte count, and the message. This is 71 * passed to the metadata handler which will interpret and process it. 72 * For 'DDF' messages are internal data blocks with the leading 73 * 'magic number' signifying what sort of data it is. 74 * 75 */ 76 77/* 78 * We select on /proc/mdstat and the named pipe. 79 * We create new arrays or updated version of arrays and slip 80 * them into the head of the list, then signal 'monitor' via a pipe write. 81 * 'monitor' will notice and place the old array on a return list. 82 * Metadata updates are placed on a queue just like they arrive 83 * from the named pipe. 84 * 85 * When new arrays are found based on correct metadata string, we 86 * need to identify them with an entry in the metadata. Maybe we require 87 * the metadata to be mdX/NN when NN is the index into an appropriate table. 88 * 89 */ 90 91/* 92 * List of tasks: 93 * - Watch for spares to be added to the container, and write updated 94 * metadata to them. 95 * - Watch for new arrays using this container, confirm they match metadata 96 * and if so, start monitoring them 97 * - Watch for spares being added to monitored arrays. This shouldn't 98 * happen, as we should do all the adding. Just remove them. 99 * - Watch for change in raid-disks, chunk-size, etc. Update metadata and 100 * start a reshape. 101 */ 102#ifndef _GNU_SOURCE 103#define _GNU_SOURCE 104#endif 105#include "mdadm.h" 106#include "mdmon.h" 4d43913c 107#include <sys/syscall.h> 549e9569 108#include <sys/socket.h> 1ed3f387 109#include <signal.h> 549e9569 110 2a0bb19e DW 111static void close_aa(struct active_array *aa) 112{ 113 struct mdinfo *d; 114 e1516be1 DW 115 for (d = aa->info.devs; d; d = d->next) { 116 close(d->recovery_fd); 2a0bb19e 117 close(d->state_fd); e1516be1 118 } 2a0bb19e 119 c2047875 JS 120 if (aa->action_fd >= 0) 121 close(aa->action_fd); 122 if (aa->info.state_fd >= 0) 123 close(aa->info.state_fd); 124 if (aa->resync_start_fd >= 0) 125 close(aa->resync_start_fd); 126 if (aa->metadata_fd >= 0) 127 close(aa->metadata_fd); 128 if (aa->sync_completed_fd >= 0) 129 close(aa->sync_completed_fd); 2a0bb19e DW 130} 131 549e9569 NB 132static void free_aa(struct active_array *aa) 133{ 2a0bb19e DW 134 /* Note that this doesn't close fds if they are being used 135 * by a clone. ->container will be set for a clone 549e9569 136 */ 1ade5cc1 137 dprintf("sys_name: %s\n", aa->info.sys_name); 2a0bb19e DW 138 if (!aa->container) 139 close_aa(aa); 549e9569 NB 140 while (aa->info.devs) { 141 struct mdinfo *d = aa->info.devs; 142 aa->info.devs = d->next; 143 free(d); 144 } 145 free(aa); 146} 147 6c3fb95c NB 148static struct active_array *duplicate_aa(struct active_array *aa) 149{ 503975b9 150 struct active_array *newa = xmalloc(sizeof(*newa)); 6c3fb95c NB 151 struct mdinfo **dp1, **dp2; 152 153 *newa = *aa; 154 newa->next = NULL; 155 newa->replaces = NULL; 156 newa->info.next = NULL; 157 158 dp2 = &newa->info.devs; 159 160 for (dp1 = &aa->info.devs; *dp1; dp1 = &(*dp1)->next) { 161 struct mdinfo *d; 162 if ((*dp1)->state_fd < 0) 163 continue; 164 503975b9 165 d = xmalloc(sizeof(*d)); 6c3fb95c NB 166 *d = **dp1; 167 *dp2 = d; 168 dp2 = & d->next; 169 } 7e1432fb 170 *dp2 = NULL; 6c3fb95c NB 171 172 return newa; 173} 174 4d43913c 175static void wakeup_monitor(void) 2a0bb19e 176{ 4d43913c NB 177 /* tgkill(getpid(), mon_tid, SIGUSR1); */ 178 int pid = getpid(); 179 syscall(SYS_tgkill, pid, mon_tid, SIGUSR1); 2a0bb19e DW 180} 181 1ed3f387 NB 182static void remove_old(void) 183{ 184 if (discard_this) { 185 discard_this->next = NULL; 186 free_aa(discard_this); 187 if (pending_discard == discard_this) 188 pending_discard = NULL; 189 discard_this = NULL; 48561b01 190 wakeup_monitor(); 1ed3f387 NB 191 } 192} 193 549e9569 NB 194static void replace_array(struct supertype *container, 195 struct active_array *old, 196 struct active_array *new) 197{ 198 /* To replace an array, we add it to the top of the list 199 * marked with ->replaces to point to the original. 200 * 'monitor' will take the original out of the list 201 * and put it on 'discard_this'. We take it from there 202 * and discard it. 203 */ 1ed3f387 204 remove_old(); 549e9569 NB 205 while (pending_discard) { 206 while (discard_this == NULL) 207 sleep(1); 1ed3f387 208 remove_old(); 549e9569 NB 209 } 210 pending_discard = old; 211 new->replaces = old; 212 new->next = container->arrays; 213 container->arrays = new; 4d43913c 214 wakeup_monitor(); 549e9569 NB 215} 216 2e735d19 NB 217struct metadata_update *update_queue = NULL; 218struct metadata_update *update_queue_handled = NULL; 219struct metadata_update *update_queue_pending = NULL; 220 071cfc42 221static void free_updates(struct metadata_update **update) 2e735d19 222{ 071cfc42 DW 223 while (*update) { 224 struct metadata_update *this = *update; cb23f1f4 225 void **space_list = this->space_list; 071cfc42 DW 226 227 *update = this->next; 904c1ef7 228 free(this->buf); 071cfc42 229 free(this->space); cb23f1f4 N 230 while (space_list) { 231 void *space = space_list; 232 space_list = *space_list; 233 free(space); 234 } 2e735d19 NB 235 free(this); 236 } 071cfc42 DW 237} 238 239void check_update_queue(struct supertype *container) 240{ 241 free_updates(&update_queue_handled); 242 2e735d19 NB 243 if (update_queue == NULL && 244 update_queue_pending) { 245 update_queue = update_queue_pending; 246 update_queue_pending = NULL; 4d43913c 247 wakeup_monitor(); 2e735d19 NB 248 } 249} 250 6c3fb95c 251static void queue_metadata_update(struct metadata_update *mu) 2e735d19 NB 252{ 253 struct metadata_update **qp; 254 255 qp = &update_queue_pending; 256 while (*qp) 257 qp = & ((*qp)->next); 258 *qp = mu; 259} 260 43dad3d6 DW 261static void add_disk_to_container(struct supertype *st, struct mdinfo *sd) 262{ 263 int dfd; 264 char nm[20]; 661dce36 265 struct supertype *st2; 43dad3d6 266 struct metadata_update *update = NULL; 661dce36 267 struct mdinfo info; 43dad3d6 DW 268 mdu_disk_info_t dk = { 269 .number = -1, 270 .major = sd->disk.major, 271 .minor = sd->disk.minor, 272 .raid_disk = -1, 273 .state = 0, 274 }; 275 1ade5cc1 276 dprintf("add %d:%d to container\n", sd->disk.major, sd->disk.minor); 43dad3d6 277 04a8ac08 DW 278 sd->next = st->devs; 279 st->devs = sd; 280 43dad3d6 DW 281 sprintf(nm, "%d:%d", sd->disk.major, sd->disk.minor); 282 dfd = dev_open(nm, O_RDWR); 283 if (dfd < 0) 284 return; 285 661dce36 N 286 /* Check the metadata and see if it is already part of this 287 * array 288 */ 289 st2 = dup_super(st); 290 if (st2->ss->load_super(st2, dfd, NULL) == 0) { 4389b648 291 st2->ss->getinfo_super(st2, &info, NULL); 661dce36 N 292 if (st->ss->compare_super(st, st2) == 0 && 293 info.disk.raid_disk >= 0) { 294 /* Looks like a good member of array. 295 * Just accept it. 296 * mdadm will incorporate any parts into 297 * active arrays. 298 */ 299 st2->ss->free_super(st2); 300 return; 301 } 302 } 303 st2->ss->free_super(st2); 304 43dad3d6 305 st->update_tail = &update; 72ca9bcf 306 st->ss->add_to_super(st, &dk, dfd, NULL, INVALID_SECTORS); 43dad3d6 DW 307 st->ss->write_init_super(st); 308 queue_metadata_update(update); 309 st->update_tail = NULL; 310} 311 1a64be56 LM 312/* 313 * Create and queue update structure about the removed disks. 314 * The update is prepared by super type handler and passed to the monitor 315 * thread. 316 */ 317static void remove_disk_from_container(struct supertype *st, struct mdinfo *sd) 318{ 319 struct metadata_update *update = NULL; 320 mdu_disk_info_t dk = { 321 .number = -1, 322 .major = sd->disk.major, 323 .minor = sd->disk.minor, 324 .raid_disk = -1, 325 .state = 0, 326 }; 1ade5cc1 N 327 dprintf("remove %d:%d from container\n", 328 sd->disk.major, sd->disk.minor); 1a64be56 LM 329 330 st->update_tail = &update; 331 st->ss->remove_from_super(st, &dk); 4dd968cc N 332 /* FIXME this write_init_super shouldn't be here. 333 * We have it after add_to_super to write to new device, 334 * but with 'remove' we don't ant to write to that device! 335 */ 1a64be56 LM 336 st->ss->write_init_super(st); 337 queue_metadata_update(update); 338 st->update_tail = NULL; 339} 340 549e9569 NB 341static void manage_container(struct mdstat_ent *mdstat, 342 struct supertype *container) 343{ 1a64be56 344 /* Of interest here are: 1011e834 345 * - if a new device has been added to the container, we 1a64be56 LM 346 * add it to the array ignoring any metadata on it. 347 * - if a device has been removed from the container, we 348 * remove it from the device list and update the metadata. 549e9569 NB 349 * FIXME should we look for compatible metadata and take hints 350 * about spare assignment.... probably not. 549e9569 NB 351 */ 352 if (mdstat->devcnt != container->devcnt) { 7bc1962f DW 353 struct mdinfo **cdp, *cd, *di, *mdi; 354 int found; 355 549e9569 NB 356 /* read /sys/block/NAME/md/dev-??/block/dev to find out 357 * what is there, and compare with container->info.devs 358 * To see what is removed and what is added. 359 * These need to be remove from, or added to, the array 360 */ 4dd2df09 361 mdi = sysfs_read(-1, mdstat->devnm, GET_DEVS); 313a4a82 DW 362 if (!mdi) { 363 /* invalidate the current count so we can try again */ 364 container->devcnt = -1; 7bc1962f 365 return; 313a4a82 366 } 7bc1962f DW 367 368 /* check for removals */ 369 for (cdp = &container->devs; *cdp; ) { 370 found = 0; 371 for (di = mdi->devs; di; di = di->next) 372 if (di->disk.major == (*cdp)->disk.major && 373 di->disk.minor == (*cdp)->disk.minor) { 374 found = 1; 375 break; 376 } 377 if (!found) { 378 cd = *cdp; 379 *cdp = (*cdp)->next; 1a64be56 380 remove_disk_from_container(container, cd); 7bc1962f DW 381 free(cd); 382 } else 383 cdp = &(*cdp)->next; 384 } 43dad3d6 DW 385 386 /* check for additions */ 387 for (di = mdi->devs; di; di = di->next) { 388 for (cd = container->devs; cd; cd = cd->next) 389 if (di->disk.major == cd->disk.major && 390 di->disk.minor == cd->disk.minor) 391 break; 04a8ac08 392 if (!cd) { 503975b9 393 struct mdinfo *newd = xmalloc(sizeof(*newd)); 04a8ac08 394 04a8ac08 DW 395 *newd = *di; 396 add_disk_to_container(container, newd); 397 } 43dad3d6 398 } 7bc1962f 399 sysfs_free(mdi); 549e9569 NB 400 container->devcnt = mdstat->devcnt; 401 } 402} 403 da5a36fa N 404static int sysfs_open2(char *devnum, char *name, char *attr) 405{ 406 int fd = sysfs_open(devnum, name, attr); 407 if (fd >= 0) { 408 /* seq_file in the kernel allocates buffer space 409 * on the first read. Do that now so 'monitor' 410 * never needs too. 411 */ 412 char buf[200]; 413 read(fd, buf, sizeof(buf)); 414 } 415 return fd; 416} 417 63b4aae3 DW 418static int disk_init_and_add(struct mdinfo *disk, struct mdinfo *clone, 419 struct active_array *aa) 420{ 421 if (!disk || !clone) 422 return -1; 423 424 *disk = *clone; da5a36fa N 425 disk->recovery_fd = sysfs_open2(aa->info.sys_name, disk->sys_name, 426 "recovery_start"); 3e1d79b2 JS 427 if (disk->recovery_fd < 0) 428 return -1; da5a36fa 429 disk->state_fd = sysfs_open2(aa->info.sys_name, disk->sys_name, "state"); 3e1d79b2 JS 430 if (disk->state_fd < 0) { 431 close(disk->recovery_fd); 432 return -1; 433 } 63b4aae3 DW 434 disk->prev_state = read_dev_state(disk->state_fd); 435 disk->curr_state = disk->prev_state; 436 disk->next = aa->info.devs; 437 aa->info.devs = disk; 438 439 return 0; 440} 441 549e9569 NB 442static void manage_member(struct mdstat_ent *mdstat, 443 struct active_array *a) 444{ 445 /* Compare mdstat info with known state of member array. 446 * We do not need to look for device state changes here, that 447 * is dealt with by the monitor. 448 * 0f99b4bd N 449 * If a reshape is being requested, monitor will have noticed 450 * that sync_action changed and will have set check_reshape. 451 * We just need to see if new devices have appeared. All metadata 452 * updates will already have been processed. 6c3fb95c 453 * 0f99b4bd 454 * We also want to handle degraded arrays here by 6c3fb95c NB 455 * trying to find and assign a spare. 456 * We do that whenever the monitor tells us too. 549e9569 457 */ bc77ed53 DW 458 char buf[64]; 459 int frozen; 4e2c1a9a 460 struct supertype *container = a->container; 4edb8530 461 unsigned long long int component_size = 0; 4e2c1a9a N 462 463 if (container == NULL) 464 /* Raced with something */ 465 return; bc77ed53 466 e49a8a80 N 467 if (mdstat->active) { 468 // FIXME 469 a->info.array.raid_disks = mdstat->raid_disks; 470 // MORE 471 } 549e9569 472 4edb8530 PB 473 if (sysfs_get_ll(&a->info, NULL, "component_size", &component_size) >= 0) 474 a->info.component_size = component_size << 1; 475 bc77ed53 DW 476 /* honor 'frozen' */ 477 if (sysfs_get_str(&a->info, NULL, "metadata_version", buf, sizeof(buf)) > 0) 478 frozen = buf[9] == '-'; 479 else 480 frozen = 1; /* can't read metadata_version assume the worst */ 481 f54a6742 N 482 /* If sync_action is not 'idle' then don't try recovery now */ 483 if (!frozen 484 && sysfs_get_str(&a->info, NULL, "sync_action", buf, sizeof(buf)) > 0 485 && strncmp(buf, "idle", 4) != 0) 486 frozen = 1; 487 57f8c769 AK 488 if (mdstat->level) { 489 int level = map_name(pers, mdstat->level); 7023e0b8 490 if (level == 0 || level == LEVEL_LINEAR) { ba714450 491 a->to_remove = 1; 84f3857f 492 wakeup_monitor(); 7023e0b8 N 493 return; 494 } 495 else if (a->info.array.level != level && level > 0) { 57f8c769 AK 496 struct active_array *newa = duplicate_aa(a); 497 if (newa) { 498 newa->info.array.level = level; 4e2c1a9a 499 replace_array(container, a, newa); 57f8c769 AK 500 a = newa; 501 } 502 } 503 } 504 50927b13 AK 505 /* we are after monitor kick, 506 * so container field can be cleared - check it again 507 */ 508 if (a->container == NULL) 509 return; 510 4e5e54cf 511 if (sigterm && a->info.safe_mode_delay != 1) { 2ef21963 N 512 sysfs_set_safemode(&a->info, 1); 513 a->info.safe_mode_delay = 1; 514 } 515 0c4f6e37 516 /* We don't check the array while any update is pending, as it 88b496c2 517 * might container a change (such as a spare assignment) which 0c4f6e37 N 518 * could affect our decisions. 519 */ 88b496c2 520 if (a->check_degraded && !frozen && 0c4f6e37 521 update_queue == NULL && update_queue_pending == NULL) { 6c3fb95c 522 struct metadata_update *updates = NULL; 071cfc42 523 struct mdinfo *newdev = NULL; 6c3fb95c 524 struct active_array *newa; 071cfc42 525 struct mdinfo *d; 3c00ffbe 526 6c3fb95c NB 527 a->check_degraded = 0; 528 529 /* The array may not be degraded, this is just a good time 530 * to check. 531 */ 4e2c1a9a 532 newdev = container->ss->activate_spare(a, &updates); 071cfc42 DW 533 if (!newdev) 534 return; 535 536 newa = duplicate_aa(a); 537 if (!newa) 538 goto out; 1d446d52 DW 539 /* prevent the kernel from activating the disk(s) before we 540 * finish adding them 541 */ 1ade5cc1 542 dprintf("freezing %s\n", a->info.sys_name); 1d446d52 543 sysfs_set_str(&a->info, NULL, "sync_action", "frozen"); 071cfc42 DW 544 545 /* Add device to array and set offset/size/slot. 546 * and open files for each newdev */ 547 for (d = newdev; d ; d = d->next) { 548 struct mdinfo *newd; 549 503975b9 550 newd = xmalloc(sizeof(*newd)); 2904b26f 551 if (sysfs_add_disk(&newa->info, d, 0) < 0) { 071cfc42 DW 552 free(newd); 553 continue; 6c3fb95c 554 } 63b4aae3 555 disk_init_and_add(newd, d, newa); 071cfc42 DW 556 } 557 queue_metadata_update(updates); 558 updates = NULL; 6ca1e6ec MW 559 while (update_queue_pending || update_queue) { 560 check_update_queue(container); 561 usleep(15*1000); 562 } 4e2c1a9a 563 replace_array(container, a, newa); 6ca1e6ec MW 564 if (sysfs_set_str(&a->info, NULL, "sync_action", "recover") 565 == 0) 566 newa->prev_action = recover; 1ade5cc1 567 dprintf("recovery started on %s\n", a->info.sys_name); 071cfc42 DW 568 out: 569 while (newdev) { 570 d = newdev->next; 571 free(newdev); 572 newdev = d; 6c3fb95c 573 } 071cfc42 574 free_updates(&updates); 6c3fb95c 575 } 0f99b4bd N 576 577 if (a->check_reshape) { 578 /* mdadm might have added some devices to the array. 579 * We want to disk_init_and_add any such device to a 580 * duplicate_aa and replace a with that. 581 * mdstat doesn't have enough info so we sysfs_read 582 * and look for new stuff. 583 */ 584 struct mdinfo *info, *d, *d2, *newd; aad6f216 585 unsigned long long array_size; 0f99b4bd N 586 struct active_array *newa = NULL; 587 a->check_reshape = 0; 4dd2df09 588 info = sysfs_read(-1, mdstat->devnm, 0f99b4bd N 589 GET_DEVS|GET_OFFSET|GET_SIZE|GET_STATE); 590 if (!info) 591 goto out2; 592 for (d = info->devs; d; d = d->next) { 593 if (d->disk.raid_disk < 0) 594 continue; 595 for (d2 = a->info.devs; d2; d2 = d2->next) 596 if (d2->disk.raid_disk == 597 d->disk.raid_disk) 598 break; 599 if (d2) 600 /* already have this one */ 601 continue; 602 if (!newa) { 603 newa = duplicate_aa(a); 604 if (!newa) 605 break; 606 } 503975b9 607 newd = xmalloc(sizeof(*newd)); 0f99b4bd N 608 disk_init_and_add(newd, d, newa); 609 } aad6f216 610 if (sysfs_get_ll(info, NULL, "array_size", &array_size) == 0 02eedb57 611 && a->info.custom_array_size > array_size*2) { aad6f216 612 sysfs_set_num(info, NULL, "array_size", 02eedb57 613 a->info.custom_array_size/2); aad6f216 614 } 0f99b4bd N 615 out2: 616 sysfs_free(info); 617 if (newa) 4e2c1a9a 618 replace_array(container, a, newa); 0f99b4bd 619 } 549e9569 NB 620} 621 836759d5 DW 622static int aa_ready(struct active_array *aa) 623{ 624 struct mdinfo *d; 625 int level = aa->info.array.level; 626 627 for (d = aa->info.devs; d; d = d->next) 628 if (d->state_fd < 0) 629 return 0; 630 631 if (aa->info.state_fd < 0) 632 return 0; 633 634 if (level > 0 && (aa->action_fd < 0 || aa->resync_start_fd < 0)) 635 return 0; 636 637 if (!aa->container) 638 return 0; 639 640 return 1; 641} 642 549e9569 643static void manage_new(struct mdstat_ent *mdstat, 2a0bb19e DW 644 struct supertype *container, 645 struct active_array *victim) 549e9569 NB 646{ 647 /* A new array has appeared in this container. 648 * Hopefully it is already recorded in the metadata. 649 * Check, then create the new array to report it to 650 * the monitor. 651 */ 652 653 struct active_array *new; 654 struct mdinfo *mdi, *di; cba0191b 655 char *inst; 549e9569 656 int i; f1d26766 657 int failed = 0; 138477db 658 char buf[40]; 549e9569 659 836759d5 660 /* check if array is ready to be monitored */ 7023e0b8 N 661 if (!mdstat->active || !mdstat->level) 662 return; 663 if (strcmp(mdstat->level, "raid0") == 0 || 664 strcmp(mdstat->level, "linear") == 0) 836759d5 DW 665 return; 666 4dd2df09 667 mdi = sysfs_read(-1, mdstat->devnm, 836759d5 668 GET_LEVEL|GET_CHUNK|GET_DISKS|GET_COMPONENT| 2ef21963 669 GET_DEGRADED|GET_SAFEMODE| 0c5d6054 670 GET_DEVS|GET_OFFSET|GET_SIZE|GET_STATE|GET_LAYOUT); 836759d5 671 503975b9 672 if (!mdi) 836759d5 673 return; 503975b9 674 new = xcalloc(1, sizeof(*new)); d52690ac 675 4dd2df09 676 strcpy(new->info.sys_name, mdstat->devnm); 549e9569 NB 677 678 new->prev_state = new->curr_state = new->next_state = inactive; 679 new->prev_action= new->curr_action= new->next_action= idle; 680 681 new->container = container; 682 4dd2df09 683 inst = to_subarray(mdstat, container->devnm); 549e9569 684 549e9569 685 new->info.array = mdi->array; 272bcc48 686 new->info.component_size = mdi->component_size; 549e9569 NB 687 688 for (i = 0; i < new->info.array.raid_disks; i++) { 503975b9 689 struct mdinfo *newd = xmalloc(sizeof(*newd)); 549e9569 NB 690 691 for (di = mdi->devs; di; di = di->next) 692 if (i == di->disk.raid_disk) 693 break; 694 63b4aae3 695 if (disk_init_and_add(newd, di, new) != 0) { 7da80e6f DW 696 if (newd) 697 free(newd); 698 f1d26766 699 failed++; 7da80e6f DW 700 if (failed > new->info.array.failed_disks) { 701 /* we cannot properly monitor without all working disks */ 702 new->container = NULL; 703 break; 704 } 549e9569 705 } 549e9569 706 } 836759d5 707 da5a36fa N 708 new->action_fd = sysfs_open2(new->info.sys_name, NULL, "sync_action"); 709 new->info.state_fd = sysfs_open2(new->info.sys_name, NULL, "array_state"); 710 new->resync_start_fd = sysfs_open2(new->info.sys_name, NULL, "resync_start"); 711 new->metadata_fd = sysfs_open2(new->info.sys_name, NULL, "metadata_version"); 712 new->sync_completed_fd = sysfs_open2(new->info.sys_name, NULL, "sync_completed"); 713 1ade5cc1 714 dprintf("inst: %s action: %d state: %d\n", inst, 4e6e574a 715 new->action_fd, new->info.state_fd); 549e9569 716 2ef21963 N 717 if (sigterm) 718 new->info.safe_mode_delay = 1; 719 else if (mdi->safe_mode_delay >= 50) 720 /* Normal start, mdadm set this. */ 721 new->info.safe_mode_delay = mdi->safe_mode_delay; 722 else 723 /* Restart, just pick a number */ 724 new->info.safe_mode_delay = 5000; 725 sysfs_set_safemode(&new->info, new->info.safe_mode_delay); 726 138477db AK 727 /* reshape_position is set by mdadm in sysfs 728 * read this information for new arrays only (empty victim) 729 */ 730 if ((victim == NULL) && 731 (sysfs_get_str(mdi, NULL, "sync_action", buf, 40) > 0) && 732 (strncmp(buf, "reshape", 7) == 0)) { 733 if (sysfs_get_ll(mdi, NULL, "reshape_position", 734 &new->last_checkpoint) != 0) 735 new->last_checkpoint = 0; 0d51bfa2 AK 736 else { 737 int data_disks = mdi->array.raid_disks; 738 if (mdi->array.level == 4 || mdi->array.level == 5) 739 data_disks--; 740 if (mdi->array.level == 6) 741 data_disks -= 2; 742 743 new->last_checkpoint /= data_disks; 744 } 138477db AK 745 dprintf("mdmon: New monitored array is under reshape.\n" 746 " Last checkpoint is: %llu\n", 747 new->last_checkpoint); 748 } 749 4fa5aef9 750 sysfs_free(mdi); 836759d5 DW 751 752 /* if everything checks out tell the metadata handler we want to 753 * manage this instance 754 */ 755 if (!aa_ready(new) || container->ss->open_new(container, new, inst) < 0) { a88e119f 756 pr_err("failed to monitor %s\n", 836759d5 757 mdstat->metadata_version); 549e9569 758 new->container = NULL; 836759d5 759 free_aa(new); 93f7caca 760 } else { 2a0bb19e 761 replace_array(container, victim, new); 93f7caca DW 762 if (failed) { 763 new->check_degraded = 1; 764 manage_member(mdstat, new); 765 } 766 } 549e9569 NB 767} 768 5d19760d 769void manage(struct mdstat_ent *mdstat, struct supertype *container) 549e9569 NB 770{ 771 /* We have just read mdstat and need to compare it with 772 * the known active arrays. 773 * Arrays with the wrong metadata are ignored. 774 */ 775 776 for ( ; mdstat ; mdstat = mdstat->next) { 777 struct active_array *a; 4dd2df09 778 if (strcmp(mdstat->devnm, container->devnm) == 0) { 549e9569 NB 779 manage_container(mdstat, container); 780 continue; 781 } 4dd2df09 782 if (!is_container_member(mdstat, container->devnm)) 549e9569 NB 783 /* Not for this array */ 784 continue; 785 /* Looks like a member of this container */ 5d19760d 786 for (a = container->arrays; a; a = a->next) { 4dd2df09 787 if (strcmp(mdstat->devnm, a->info.sys_name) == 0) { ba714450 788 if (a->container && a->to_remove == 0) 549e9569 NB 789 manage_member(mdstat, a); 790 break; 791 } 792 } 2a0bb19e DW 793 if (a == NULL || !a->container) 794 manage_new(mdstat, container, a); 549e9569 NB 795 } 796} 797 edd8d13c 798static void handle_message(struct supertype *container, struct metadata_update *msg) 3e70c845 799{ edd8d13c NB 800 /* queue this metadata update through to the monitor */ 801 802 struct metadata_update *mu; 803 313a4a82 804 if (msg->len <= 0) 3c00ffbe N 805 while (update_queue_pending || update_queue) { 806 check_update_queue(container); 807 usleep(15*1000); 808 } 809 313a4a82 DW 810 if (msg->len == 0) { /* ping_monitor */ 811 int cnt; 1011e834 812 3c00ffbe 813 cnt = monitor_loop_cnt; 1eb252b8 N 814 if (cnt & 1) 815 cnt += 2; /* wait until next pselect */ 816 else 817 cnt += 3; /* wait for 2 pselects */ 818 wakeup_monitor(); 3c00ffbe 819 1eb252b8 N 820 while (monitor_loop_cnt - cnt < 0) 821 usleep(10 * 1000); 313a4a82 DW 822 } else if (msg->len == -1) { /* ping_manager */ 823 struct mdstat_ent *mdstat = mdstat_read(1, 0); 824 825 manage(mdstat, container); 826 free_mdstat(mdstat); 6144ed44 827 } else if (!sigterm) { 503975b9 828 mu = xmalloc(sizeof(*mu)); edd8d13c NB 829 mu->len = msg->len; 830 mu->buf = msg->buf; 831 msg->buf = NULL; 832 mu->space = NULL; cb23f1f4 833 mu->space_list = NULL; edd8d13c NB 834 mu->next = NULL; 835 if (container->ss->prepare_update) 5fe6f031 N 836 if (!container->ss->prepare_update(container, mu)) 837 free_updates(&mu); edd8d13c NB 838 queue_metadata_update(mu); 839 } 3e70c845 DW 840} 841 842void read_sock(struct supertype *container) 549e9569 NB 843{ 844 int fd; bfa44e2e 845 struct metadata_update msg; b109d928 DW 846 int terminate = 0; 847 long fl; 848 int tmo = 3; /* 3 second timeout before hanging up the socket */ 549e9569 849 3e70c845 850 fd = accept(container->sock, NULL, NULL); 549e9569 NB 851 if (fd < 0) 852 return; b109d928 DW 853 854 fl = fcntl(fd, F_GETFL, 0); 855 fl |= O_NONBLOCK; 856 fcntl(fd, F_SETFL, fl); 857 858 do { 859 msg.buf = NULL; 860 861 /* read and validate the message */ 862 if (receive_message(fd, &msg, tmo) == 0) { bfa44e2e 863 handle_message(container, &msg); bc77ed53 DW 864 if (msg.len == 0) { 865 /* ping reply with version */ 866 msg.buf = Version; 867 msg.len = strlen(Version) + 1; 868 if (send_message(fd, &msg, tmo) < 0) 869 terminate = 1; 870 } else if (ack(fd, tmo) < 0) bfa44e2e NB 871 terminate = 1; 872 } else b109d928 873 terminate = 1; b109d928 874 b109d928 DW 875 } while (!terminate); 876 549e9569 NB 877 close(fd); 878} 1ed3f387 879 e0d6609f NB 880int exit_now = 0; 881int manager_ready = 0; 549e9569 NB 882void do_manager(struct supertype *container) 883{ 884 struct mdstat_ent *mdstat; 4d43913c 885 sigset_t set; 1ed3f387 886 4d43913c NB 887 sigprocmask(SIG_UNBLOCK, NULL, &set); 888 sigdelset(&set, SIGUSR1); 6144ed44 889 sigdelset(&set, SIGTERM); 549e9569 NB 890 891 do { 1ed3f387 892 e0d6609f NB 893 if (exit_now) 894 exit(0); 895 3c00ffbe N 896 /* Can only 'manage' things if 'monitor' is not making 897 * structural changes to metadata, so need to check 898 * update_queue 899 */ 900 if (update_queue == NULL) { 901 mdstat = mdstat_read(1, 0); 549e9569 902 3c00ffbe 903 manage(mdstat, container); 549e9569 904 3c00ffbe 905 read_sock(container); 4fa5aef9 906 3c00ffbe N 907 free_mdstat(mdstat); 908 } 1ed3f387 NB 909 remove_old(); 910 2e735d19 NB 911 check_update_queue(container); 912 e0d6609f 913 manager_ready = 1; 4d43913c 914 6144ed44 DW 915 if (sigterm) 916 wakeup_monitor(); 917 5d4d1b26 918 if (update_queue == NULL) 58a4ba2a 919 mdstat_wait_fd(container->sock, &set); 5d4d1b26 920 else 3c00ffbe N 921 /* If an update is happening, just wait for signal */ 922 pselect(0, NULL, NULL, NULL, NULL, &set); 549e9569 NB 923 } while(1); 924}
__label__pos
0.937306
JBoss Community Archive (Read Only) Infinispan 6.0 Can I run my own Infinispan cache within JBoss Application Server 5 or 4? Yes, you can, but since Infinispan uses different JGroups jar libraries to the ones shipped by these application servers, you need to make sure that the code using Infinispan, and the Infinispan libraries, are deployed in an isolated WAR/EAR. Information on how to isolate deployments can be found in: Apart from isolating your deployment, you can use Maven's Shade plugin to build Infinispan and all its dependencies in a single jar, and then shade the library that might clash with the one in the app server. For example, to shade org.jgroups, you'd build Infinispan with: <plugin>   <groupId>org.apache.maven.plugins</groupId>   <artifactId>maven-shade-plugin</artifactId>   <version>1.4</version>   <executions>     <execution>       <phase>package</phase>       <goals>         <goal>shade</goal>       </goals>       <configuration>         <relocations>           <relocation>             <pattern>org.jgroups</pattern>             <shadedPattern>org.shaded.jgroups</shadedPattern>           </relocation>         </relocations>       </configuration>     </execution>   </executions> </plugin> JBoss.org Content Archive (Read Only), exported from JBoss Community Documentation Editor at 2020-03-11 09:41:26 UTC, last content change 2011-07-18 18:23:17 UTC.
__label__pos
0.502825
Beefy Boxes and Bandwidth Generously Provided by pair Networks Just another Perl shrine   PerlMonks   Re: Perl 5.10: switch statement demo by LighthouseJ (Sexton) on Dec 20, 2007 at 13:42 UTC ( #658114=note: print w/ replies, xml ) Need Help?? in reply to Perl 5.10: switch statement demo I don't know why people want a verbatim 'switch' statement when you can use a for-statement. #!/usr/bin/perl -w use strict; { for (1..40) { print; ($_ % 3 == 0) && print q! fizz!; ($_ % 5 == 0) && print q! buzz!; ($_ % 7 == 0) && print q! sausage!; print "\n"; } } I generally use a for loop in conjunction with regular expression matches, like this trivial example: #!/usr/bin/perl -w use strict; { my @items = qw/The three principal virtues of a programmer are Laz +iness, Impatience, and Hubris. See the Camel Book for why/; for (@items) { /^[A-Z]/ && do { print "Found a proper noun? $_\n"; next; }; /[,.]/ && do { print "This word has punctuation: $_\n"; next; }; print "This word seems uninteresting: $_\n"; } } It has a lot of flexibility where you can mix and match parts and get real nice uses out of it. I've always used it fully and got very good results --without waiting for a proper switch statement. "The three principal virtues of a programmer are Laziness, Impatience, and Hubris. See the Camel Book for why." -- `man perl` Replies are listed 'Best First'. Re^2: Perl 5.10: switch statement demo by robin (Chaplain) on Dec 20, 2007 at 18:20 UTC You can use when in a for loop: for (@items) { when (/^[A-Z]/) { say "Found a proper noun? $_"; } when (/[,.]/) { say "This word has punctuation: $_"; } say "This word seems uninteresting: $_"; } I guess that's kind of my point. The really useful and powerful things in todays computing industry like Perl, UNIX, even RISC processors all merely provide you with a basic set of tools and rely on you (the user) to put the simple tools together to make a useful mechanism. Stuff like adding a named "switch" statement or needing a "when" keyword just complicates it unnecessarily IMO. I had a discussion about this with an Oracle DBA. Needless to say we maintained our differences of opinion. "The three principal virtues of a programmer are Laziness, Impatience, and Hubris. See the Camel Book for why." -- `man perl` Well, I wasn't really trying to make a polemical point. You just gave me a convenient excuse to draw attention to a feature of the switch implementation that I thought people might be interested in hearing about. :-) Needless to say, though, I don't agree with you. If I did, then I wouldn't have implemented the switch feature, presumably! It sounds odd to me to hear Perl described as a "simple tool". What I like about it is precisely the opposite: the fact that it's rich and interesting, and usually has More Than One Way To Do It. Java is a simple language, but it's difficult to write a useful Java program that is simple. Perl is not a simple language, but it is a language in which it's possible to write simple programs. Log In? Username: Password: What's my password? Create A New User Node Status? node history Node Type: note [id://658114] help Chatterbox? and the web crawler heard nothing... How do I use this? | Other CB clients Other Users? Others examining the Monastery: (16) As of 2016-07-27 16:06 GMT Sections? Information? Find Nodes? Leftovers? Voting Booth? What is your favorite alternate name for a (specific) keyboard key? Results (245 votes). Check out past polls.
__label__pos
0.833712
Как получить значение справочника, выбранное для записи Есть справочник, унаследованный от базового справочника, со стандартными полями Id, Name, Description. Есть раздел, в котором есть поле, принимающее значения из этого справочника (UsrYesNo), а также ряд других полей, содержащих значения INTEGER (UsrIntValue), TEXT (UsrTextValue) и т.п. Есть необходимость извлечь значение соответствующего поля в коде клиентской части. Примерно так:   // Возвращает целочиcленное значение, работает корректно var a = this.get("UsrIntValue"); // Возвращает строковое значение, работает тоже корректно var b = this.get("UsrTextValue"); // По идее, должно возвращать значение из справочника, выбранное для записи раздела. // Но по факту выдает undefined. var c = this.get("UsrYesNo.Name"); Что я делаю не так? Нравится 4 комментария Лучший ответ Генин Юрий пишет: var c = this.get("UsrYesNo").Name; Да, верно. Мы берём поле и читаем его атрибуты.  Указать эту колонку в attributes attributes: { "UsrYesNo": { "dataValueType": Terrasoft.DataValueType.LOOKUP, "lookupListConfig": { "columns": ["Name"] } } } Или в данном случае достаточно взять this.get("UsrYesNo").displayValue Владимир Соколов, Вариант с this.get("UsrYesNo").displayValue сработал, спасибо. Но добавление атрибута (в схему страницы редактирования) ничего не поменяло:  this.get("UsrYesNo.Name") все равно возвращает undefined.  Владимир Соколов, А вот так, кстати, сработало: attributes: { "UsrYesNo": { lookupListConfig: { columns: ["Name"] } } } и var c = this.get("UsrYesNo").Name; Интересно, почему... Генин Юрий пишет: var c = this.get("UsrYesNo").Name; Да, верно. Мы берём поле и читаем его атрибуты.  Показать все комментарии
__label__pos
0.974619
The Packageho.me is deemed as a browser hijacker or redirection virus for the reason that it gets web traffics in evil ways. It can be triggered by PUP or Adware packed into free software, which is the most common way that computer infections spread. As long as it enters a computer, the major web browser of users such as Edge, Chrome or Firefox can be affected seriously and users cannot do normal web-surfing due to this virus. When a user opens the homepage, search Google, or click links on websites, Packageho.me may pop up as a new tab to harass the user. Packageho.me Packageho.me Packageho.me Is Packageho.me just annoying and will not damage the computer? It is not so simple. Though you just see that Packageho.me only interrupts your web page, it may bring more severe problems to your computer. The adware or malware connected with Packageho.me can harm your system by dropping more computer infections. Besides, redirect virus such as Packageho.me usually use cookies to collect private data of your system, that means your personal information may be at risk as well. What is the worst situation? In case it related virus download ransomware to your system, your file may be encrypted and you will be forced to pay lots of money to recover them. In short, if Packageho.me cannot be removed completely, your computer may suffer from all possible damages. You must understand now that keeping Packageho.me infections inside of your computer may seriously damage your system and lead to severe consequences. In order to remove Packageho.me and prevent future infections, we advise you to follow the steps from the removal guide below. Packageho.me – how dangerous is it? It doesn`t matter if Packageho.me malicious or not, if program is considered as potentially unwanted it may cause a lot of problems for you and your computer. Some programs are able to add many various extensions to most popular browsers such as Google Chrome, Mozilla Firefox, Microsoft Edge and so on. This way it may store some information on its users – for example, search queries, to show thousands of ads based on these preferences, though they are not relevant. Also, this behavior can provide other malicious programs and viruses a way inside of your computer. Moreover, it may generate adverts and pop-ups that will annoy you a lot! Such programs can be installed along with other programs, so probably the Packageho.me would lead a lot of unwanted guests on your PC – malicious programs, adware, CoinMiners or even Ransomware! Don’t waste your time and wait for your computer`s death – follow the simple removal guide below and get rid of this Packageho.me in a few minutes! Packageho.me automatic remover: Loaris Trojan Remover aids in the removal of various malicious and unwanted stuff – Trojan Horses, Worms, Adware, Spyware, Malware, Ransomware Traces – when standard anti-virus software either fails to detect them or fails to effectively eliminate them. Standard anti-virus programs may be good at detecting threats like Packageho.me, but not always good at effectively removing it… Also, Loaris Trojan Remover can be considered as a simple cleaner – it removes not only infected files, but also other junk files that were brought by viruses and unwanted programs. NOTE: Loaris Trojan Remover is absolutely free! You can use it for 30 days without any restrictions! Follow the removal guide below to know how to get the key. Download now Learn More Packageho.me removal steps: 1. 1) Download and install Loaris Trojan Remover. 2. 2) When you open the program for the first time, you will see next window with a suggestion to start a free trial: 3. Loaris Trojan Remover software 4. 3) Enter your Name and E-mail address – press “Get Now 5. 4) Loaris will send a needed credentials on this e-mail. Open the message and you will see this: 6. Loaris Trojan Remover software 7. 5) Click on “MEMBER AREA” and enter you profile using login\password from the e-mail: 8. Loaris Trojan Remover software 9. 6) In your profile you will find a key, copy it in your buffer: 10. Loaris Trojan Remover software 11. 7) Open Loaris Trojan remover and paste the key in it: 12. Loaris Trojan Remover software 13. 8) Your program is activated! Now that you can use it completely free, you need to remove Packageho.me completely. The scanning process should start right after the activations. If not, just click on “Scan” tab and choose “Standard Scan“: 14. Loaris Trojan Remover software 15. 9) When the scanning process is over click “Apply” to remove all infections found after the scan is completed: 16. Loaris Trojan Remover software (OPTIONAL) Reset browser settings to remove Packageho.me traces: 1. 1) It is advices to shut down browsers for this one. 2. 2) In Loaris Trojan Remover click on “Tools” and then on “Reset browser settings“: 3. Loaris Trojan Remover software 4. 3) Follow the instructions and click on “Yes” button. NOTE: You may lose some of your browser data, so we advise you to backup your bookmarks or addons: 5. Loaris Trojan Remover software 6. 4) Finally, restart your computer to apply all made changes. If all these steps didn’t help and you still have to deal with Packageho.me on your PC, just contact us and we will help to set your computer free from this annoying ads! (Visited 130 times, 1 visits today)
__label__pos
0.775384
James James - 5 months ago 29 jQuery Question jQuery change input type Trying to change input type attribute from password to text . $('.form').find('input:password').attr({type:"text"}); Why this doesn't work? Answer You can't do this with jQuery, it explicitly forbids it because IE doesn't support it (check your console you'll see an error. You have to remove the input and create a new one if that's what you're after, for example: $('.form').find('input:password').each(function() { $("<input type='text' />").attr({ name: this.name, value: this.value }).insertBefore(this); }).remove(); You can give it a try here To be clear on the restriction, jQuery will not allow changing type on a <button> or <input> so the behavior is cross-browser consistent (since IE doens't allow it, they decided it's disallowed everywhere). When trying you'll get this error in the console: Error: type property can't be changed Comments
__label__pos
0.998354
Awesome Open Source Awesome Open Source promise-fun I intend to use this space to document my promise modules, useful promise patterns, and how to solve common problems. For now though, you can see all my promise modules below. Contents Packages Not accepting additions, but happy to take requests. • pify: Promisify a callback-style function • delay: Delay a promise a specified amount of time • yoctodelay: Delay a promise a specified amount of time • p-map: Map over promises concurrently • p-all: Run promise-returning & async functions concurrently with optional limited concurrency • p-queue: Promise queue with concurrency control • p-catch-if: Conditional promise catch handler • p-if: Conditional promise chains • p-tap: Tap into a promise chain without affecting its value or state • p-log: Log the value/error of a promise • p-event: Promisify an event by waiting for it to be emitted • p-debounce: Debounce promise-returning & async functions • p-throttle: Throttle promise-returning & async functions • p-timeout: Timeout a promise after a specified amount of time • p-finally: Promise#finally() ponyfill - Invoked when the promise is settled regardless of outcome • p-retry: Retry a promise-returning or async function • p-any: Wait for any promise to be fulfilled • p-some: Wait for a specified number of promises to be fulfilled • p-locate: Get the first fulfilled promise that satisfies the provided testing function • p-limit: Run multiple promise-returning & async functions with limited concurrency • p-series: Run promise-returning & async functions in series • p-memoize: Memoize promise-returning & async functions • p-pipe: Compose promise-returning & async functions into a reusable pipeline • p-props: Like Promise.all() but for Map and Object • p-waterfall: Run promise-returning & async functions in series, each passing its result to the next • p-cancelable: Create a promise that can be canceled • p-progress: Create a promise that reports progress • p-reflect: Make a promise always fulfill with its actual fulfillment value or rejection reason • p-filter: Filter promises concurrently • p-reduce: Reduce a list of values using promises into a promise for a value • p-settle: Settle promises concurrently and get their fulfillment value or rejection reason • p-every: Test whether all promises passes a testing function • p-one: Test whether some promise passes a testing function • p-map-series: Map over promises serially • p-each-series: Iterate over promises serially • p-times: Run promise-returning & async functions a specific number of times concurrently • p-lazy: Create a lazy promise that defers execution until .then() or .catch() is called • p-whilst: While a condition returns true, calls a function repeatedly, and then resolves the promise • p-do-whilst: Calls a function repeatedly while a condition returns true and then resolves the promise • p-forever: Run promise-returning & async functions repeatedly until you end it • p-wait-for: Wait for a condition to be true • p-min-delay: Delay a promise a minimum amount of time • p-try: Promise.try() ponyfill - Starts a promise chain • p-race: A better Promise.race() • p-immediate: Returns a promise resolved in the next event loop - think setImmediate() • p-time: Measure the time a promise takes to resolve • p-defer: Create a deferred promise • p-break: Break out of a promise chain • p-is-promise: Check if something is a promise • p-state: Inspect the state of a promise • make-synchronous: Make an asynchronous function synchronous FAQ How can I run 100 async/promise-returning functions with only 5 running at once? This is a good use-case for p-map. You might ask why you can't just specify an array of promises. Promises represent values of a computation and not the computation itself - they are eager. So by the time p-map starts reading the array, all the actions creating those promises have already started running. p-map works by executing a promise-returning function in a mapper function. This way the promises are created lazily and can be concurrency limited. Check out p-all instead if you're using different functions to get each promise. const pMap = require('p-map'); const urls = [ 'https://sindresorhus.com', 'https://avajs.dev', 'https://github.com', ]; console.log(urls.length); //=> 100 const mapper = url => { return fetchStats(url); //=> Promise }; pMap(urls, mapper, {concurrency: 5}).then(result => { console.log(result); //=> [{url: 'https://sindresorhus.com', stats: {…}}, …] }); How can I reduce nesting? Let's say you want to fetch some data, process it, and return both the data and the processed data. The common approach would be to nest the promises: const getData = id => Storage .find(id) .then(data => { return process(data).then(result => { return prepare(data, result); }); }); But we can take advantage of Promise.all: const getData = id => Storage .find(id) .then(data => Promise.all([data, process(data)]) .then(([data, result]) => prepare(data, result)); And even simpler with async functions: (Requires Babel or Node.js 8) const getData = async id => { const data = await Storage.find(id); return prepare(data, await process(data)); }; What about something like Bluebird#spread()? Bluebird: Promise.resolve([1, 2]).spread((one, two) => { console.log(one, two); //=> 1 2 }); Instead, use destructuring: Promise.resolve([1, 2]).then(([one, two]) => { console.log(one, two); //=> 1 2 }); What about something like Bluebird.join()? Bluebird: Promise.join(p1, p2, p3, (r1, r2, r3) => { // … }); Instead, use an async function and destructuring: const [r1, r2, r3] = await Promise.all([p1, p2, p3]); // … How do I break out of a promise chain? You might think you want to break out ("return early") when doing conditional logic in promise chains. Here you would like to only run the onlyRunConditional promises if conditional is truthy. alwaysRun1() .then(() => alwaysRun2()) .then(conditional => conditional || somehowBreakTheChain()) .then(() => onlyRunConditional1()) .then(() => onlyRunConditional2()) .then(() => onlyRunConditional3()) .then(() => onlyRunConditional4()) .then(() => alwaysRun3()); You could implement the above by abusing the promise rejection mechanism. However, it would be better to branch out the chain instead. Promises can not only be chained, but also nested and unnested. const runConditional = () => onlyRunConditional1() .then(() => onlyRunConditional2()) .then(() => onlyRunConditional3()) .then(() => onlyRunConditional4()); alwaysRun1() .then(() => alwaysRun2()) .then(conditional => conditional && runConditional()) .then(() => alwaysRun3()); Get A Weekly Email With Trending Projects For These Topics No Spam. Unsubscribe easily at any time. javascript (68,136 nodejs (3,639 awesome (1,319 awesome-list (1,234 async (465 list (364 promise (200 concurrency (193 resources (187 polyfill (115 async-await (86 promises (65 unicorns (16 ponyfill (15 Find Open Source By Browsing 7,000 Topics Across 59 Categories
__label__pos
0.943103
Quadratic regression calculator: definition, formula and calculation Survey Sparrow Alternatives Quadratic Regression Calculator: Deciphering (r) SHARE THE ARTICLE ON Table of Contents What is quadratic regression? Quadratic regression is the process of finding the equation of a parabola, that best fits your dataset.  You can identify a quadratic regression by the plotting of your scatterplots. If the scatterplots are in a shape looking like a “U” (concave up), or the scatterplot are plotted in a shape like an up-side down U like “∩” (concave down), then you can say that you have a Quadratic regression at your hand which is best fitting your data. The shape of the scatterplots are not always complete. So you might see a half U or just a 3/4th of it.  Quadratic regression calculator: definition, formula and calculation Survey Sparrow Alternatives As being an extension of simple linear regression, we can say that the major difference between the both is that in linear regression, a straight line can be drawn using only two points too. But when it comes to Quadratic regression, as it is a parabolic curve, you need as much points as possible to plot a perfect curve. Due to this disadvantage of Quadratic regression, it is generally more costly than simple linear regression. Transform your insight generation process Create an actionable feedback collection process. online survey Quadratic regression formula y = ax2 + bx + c a = { [ Σ x2 y * Σ xx ] – [Σ xy * Σ xx2 ] } / { [ Σ xx * Σ x2 x2] – [Σ xx2 ]2 } b = { [ Σ xy * Σ x2 x2 ] – [Σ x2y * Σ xx2 ] } / { [ Σ xx * Σ x2x 2] – [Σ xx2 ]2 } c = [ Σ y / n ] – { b * [ Σ x / n ] } – { a * [ Σ x 2 / n ] } Where,  a, b, c are the coefficients of Quadratic regression. Σ x x = [ Σ x 2 ] – [ ( Σ x )2 / n ] Σ x y = [ Σ x y ] – [ ( Σ x * Σ y ) / n ] Σ x x2 = [ Σ x 3 ] – [ ( Σ x 2 * Σ x ) / n ] Σ x2 y = [ Σ x 2 y] – [ ( Σ x 2 * Σ y ) / n ] Σ x2 x2 = [ Σ x 4 ] – [ ( Σ x 2 )2 / n ]  a, b, c are the coefficients of Quadratic regression. How to calculate Quadratic regression? Let’s take an example to understand how the formula works around the give data. Example: draw a second degree polynomial with polynomial regression for the given dataset. x values y values 5 3 6 2 4 4 Step 1: Count the total given numbers. In our case, n=3. Step 2: Find all the values needed for our formula. x y x2 x3 x4 xy x2y 5 3 25 125 625 15 75 6 2 36 216 1296 12 72 4 4 16 64 256 16 64 ∑x ∑y ∑x2 ∑x3 ∑x4 ∑xy ∑x2y 15 9 77 405 2177 43 211 Download Market Research Toolkit Get market research trends guide, Online Surveys guide, Agile Market Research Guide & 5 Market research Template Making the most of your B2B market research in 2021 PDF 3 s 1.png Step 3: Substitute the values in the formula Σ x x = [ Σ x 2 ] – [ ( Σ x )2 / n ] ∑xx = [77] – [(15)2 / 3] ∑xx = 77 – [225/3] ∑xx = 77 – 75 ∑xx = 2 Σ x y = [ Σ x y ] – [ ( Σ x * Σ y ) / n ] ∑xy = [43] – [(15 x 9) /3] ∑xy = 43 – [135/3] ∑xy = 43 – 45 ∑xy = -2 Σ x x2 = [ Σ x 3 ] – [ ( Σ x 2 * Σ x ) / n ] ∑xx2 = [405] – [(77 x 15) / 3] ∑xx2 = 405 – [1155 / 3] ∑xx2 = 405 – 385  ∑xx2 = 20 Σ x2 y = [ Σ x 2 y] – [ ( Σ x 2 * Σ y ) / n ] ∑x2y = [211] – [(77 x 9) / 3] ∑x2y = 211 – [693 / 3] ∑x2y = 211 – 231 ∑x2y = -20 Σ x2 x2 = [ Σ x 4 ] – [ ( Σ x 2 )2 / n ]  ∑x2x2 = [2177] – [(77)2 / 3] ∑x2x2 = 2177 – [5929 / 3] ∑x2x2 = 2177 – 1976 ∑x2x2 = 201 Step 4: Calculate a a = { [ Σ x2 y * Σ xx ] – [Σ xy * Σ xx2 ] } / { [ Σ xx * Σ x2 x2] – [Σ xx2 ]2 } a = {[-20 * 2] – [-2 * 20]} / {[2 * 201] – [20]2} a = {(-40) – (40)} / {(402) – (400)} a = -80 / 2 a = -40 See Voxco survey software in action with a Free demo. Step 5: Calculate b b = { [ Σ xy * Σ x2 x2 ] – [Σ x2y * Σ xx2 ] } / { [ Σ xx * Σ x2x 2] – [Σ xx2 ]2 } b = {[-2 * 201] – [-20 * 20]} / {[2 * 201] – [20]2} b = {[-402] – [-400]} / {(402) – (400)} b = -2 / 2 b = -1 Step 6: Calculate c c = [ Σ y / n ] – { b * [ Σ x / n ] } – { a * [ Σ x 2 / n ] } c = [9 / 3] – {-1 * (15 / 3)} – {-40 * (77 / 3)} c = 3 – [-1 * 5] – [-40 * 25.66] c = 3 – (-5) – (-1026.4) c = 1034.4 Step 7: Substitute the value of a, b, c in the Quadratic regression equation y = ax2 + bx + c y = -40x2 + (-1x) + 1034.4 y = -40x2 – x + 1034.4 Hence, the Quadratic regression equation of your parabola is y = -40x2 – x + 1034.4  Apart from this, there are various online Quadratic regression calculators that make your task easy and save all these steps and give the Quadratic regression equation straight away.  Explore all the survey question types possible on Voxco Read more Phone Surveys cvr Phone Surveys Phone Surveys Book a Demo Voxco is trusted by 450+ Global Brands in 40+ countries What are Phone Surveys? Phone surveying is a method of Read More »
__label__pos
0.996069
package WebService::Idonethis; use v5.010; use strict; use warnings; use autodie; use Moo; use WWW::Mechanize; use JSON::Any; use Carp qw(croak); use POSIX qw(strftime); use HTTP::Request; use File::XDG; use File::Spec; use HTTP::Cookies; use HTML::Entities qw(decode_entities); use Try::Tiny; my $json = JSON::Any->new; # ABSTRACT: WebScraping pseudo-API for iDoneThis our $VERSION = '0.18'; # VERSION: Generated by DZP::OurPkg:Version has agent => ( is => 'rw' ); has user_url => ( is => 'rw' ); has user => ( is => 'rw' ); has xdg => ( is => 'rw' ); sub BUILD { my ($self, $args) = @_; my $agent = $self->agent; if (not $self->xdg) { # XDG is used to figure out where to store cache and config # files. If not provided at initialisation time, we'll # mae our own. $self->xdg(File::XDG->new(name => 'webservice-idonethis-perl')); } # Theoretically these may get changed after login. $self->user ( $args->{user} ); $self->user_url( "https://idonethis.com/cal/$args->{user}/" ); if (not $agent) { # Initialise user-agent if none provided, storing cookies in # the xdg cache. my $xdg = $self->xdg; if (not -e $xdg->cache_home) { mkdir($xdg->cache_home); } my $user_cache = File::Spec->catfile( $xdg->cache_home, $self->user ); if (not -e $user_cache) { mkdir($user_cache); } $agent = WWW::Mechanize->new( agent => "perl/$], WebService::Idonethis/" . $self->VERSION, cookie_jar => HTTP::Cookies->new( file => File::Spec->catfile( $user_cache , "cookies") ), ); $self->agent( $agent ); } # Ping idonethis to see if we even need to login. # We're going to guess our user URL so we can do a get_day. try { $self->get_today; # Throws on failure } catch { # Our ping failed, so login instead. $agent->get( "https://idonethis.com/accounts/login/" ); $agent->submit_form( form_id => 'register', fields => { username => $args->{user}, password => $args->{pass}, } ); my $url = $agent->uri; if ($url !~ m{/cal/$args->{user}/?$}i) { croak "Login to idonethis failed (unexpected URL $url)"; } $self->user_url( $url ); $self->user( $args->{user} ); # We used to save the cookie jar on destruction, but that # caused a hiccup with Moo. Now we save immediately after # login. $self->agent->cookie_jar->save(); }; return; } sub get_day { my ($self, $date) = @_; return $self->get_range($date, $date); } sub get_today { my ($self) = @_; my $today = strftime("%Y-%m-%d",localtime); return $self->get_day( $today ); } sub get_range { my ($self, $start, $end) = @_; my $url = $self->user_url . "dailydone?"; $url .= "start=$start&end=$end"; $self->agent->get($url); # Decode JSON my $data = $json->decode( $self->agent->content ); # Decode HTML entities. foreach my $record (@$data) { $record->{text} = decode_entities($record->{text}) if $record->{text}; } return $data; } sub set_done { my ($self, %args) = @_; # TODO: Use real date objects. # TODO: Allow more arguments to be passed. my $now = time(); my $timestamp = strftime("%Y-%m-%dT%H:%M:%SZ", gmtime($now)); my $date = $args{date} || strftime("%Y-%m-%d", localtime($now)); my $text = $args{text} or croak "set_done requires a 'text' argument"; my $done_json = $json->encode({ calendar => $self->user, owner => $self->user, created => $timestamp, modified => $timestamp, done_date => $date, text => $text, total_comments => undef, total_likes => undef, url => undef, }); # TODO: There's got to be a better way of doing JSON posts than this... my $req = HTTP::Request->new( 'POST', $self->user_url . "dailydone?" ); $req->header ( 'Content-Type' => 'application/json' ); $req->header ( 'Accept' => 'application/json, text/javascript, */*; q0.01' ); $req->content( $done_json ); # NOTE: This is wrong, and you should never do it, but it looks like # we have to send this header for idonethis to accept the request. $req->header ( 'X-CSRFToken' => $self->agent->cookie_jar->{COOKIES}{'idonethis.com'}{'/'}{csrftoken}[1] ); my $response = $self->agent->request( $req ); # TODO: Check we die automatically on failed submission. return; } __PACKAGE__->meta->make_immutable; 1; __END__ =pod =head1 NAME WebService::Idonethis - WebScraping pseudo-API for iDoneThis =head1 VERSION version 0.18 =head1 SYNOPSIS use WebService::Idonethis; my $idt = WebService::Idonethis->new( user => 'someuser', pass => 'somepass', ); my $dones = $idt->get_day("2012-01-01"); foreach my $item (@$dones) { say "* $item->{text}"; } # Get items done today my $dones = $idt->get_today; # Submit a new done item. $idt->set_done(text => "Drank ALL the coffee!"); =head1 DESCRIPTION This is an extremely bare-bones wrapper around the L website that allows retrieving of what was done on a particular day. It's only been tested with personal calendars. Patches are extremely welcome. This code was motivated by I's most excellent (but now defunct) memory service, which would send reminders as to what one was doing a year ago by email. The L command included in this distribution is a simple proof-of-concept that reimplements this service, and is suitable for running as a cron job. The L command included with this distribution allows you to submit new done items from the command line. Patches are extremely welcome. L =head1 METHODS =head2 get_day my $dones = $idt->get_day("2012-01-01"); Gets the data for a given day. An array will be returned which is a conversation from the JSON data structure used by idonethis. The structure at the time of writing looks like this: The 'text' field (and currently only the 'text' field) will have HTML entities converted before it is returned. (eg, '>' -> '>') [ { owner => 'some_user', avatar_url => '/site_media/blahblah/foo.png', modified => '2012-01-01T15:22:33.12345', calendar => { short_name => 'some_short_name', # usually owner name name => 'personal', type => 'PERSONAL', }, created => '2012-01-01T15:22:33.12345', done_date => '2012-01-01', text => 'Wrote code to frobinate the foobar', nicest_name => 'some_user', type => 'dailydone', id => 12345 }, ... ] =head2 get_today my $dones = $idt->get_today; This is a convenience method that calls L using the current (localtime) date as an argument. =head2 get_range my $done = $idt->get_range('2012-01-01', 2012-01-31'); Gets everything done in a range of dates. Returns in the same format at L above. =head2 set_done $idt->set_done( text => "Installed WebService::Idonethis" ); $idt->set_done( date => '2013-01-01', text => "Drank coffee." ); Submits a done item to I. The C field is optional, but the C field is mandatory. The current date (localtime) will be used if no date is specified. Returns nothing on success. Throws an exception on failure. =head1 FILES Sessions are cached in your XDG cache directory as 'webservice-idonethis-perl'. =for Pod::Coverage BUILD DEMOLISH =for Pod::Coverage agent user_url user xdg =head1 BUGS If a suitable cache location cannot be created on the filesystem, this class dies with an error. See L for more details. Other bugs may be present that are not listed in this documentation. See L for a full list, or to submit your own. =head1 SEE ALSO L =head1 AUTHOR Paul Fenwick =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2013 by Paul Fenwick. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut
__label__pos
0.91981
Get a free application, infrastructure and malware scan report - Scan Your Website Now Subscribe to our Newsletter Try AppTrana WAAP (WAF) OWASP API1: 2019 – Broken Object Level Authorization Posted DateFebruary 9, 2023 Posted Time 8   min Read Are you leaving your APIs vulnerable to attacks? OWASP revealed that Broken Object Level Authorization is among the top 10 most critical API security risks list. It is number 1 on OWASP API Top 10, 2019. Even large companies like Facebook, Uber, and Verizon, with thousands of engineers and dedicated security teams, have experienced BOLA attacks. Before diving into Broken Object Level Authorization, here are a few terms you’ll need to be familiar with. Data Objects are collections of related data points that create meaning together. Objects are assigned unique data types such as string, real, char, integer, etc. Data objects could be database records or files. Let us consider an example from online retail. Your profile associated with your account is a data object. It contains your name, username, address, customer ID, etc. Developers use profile objects in their APIs to access information on different customers. Object Identifiers: These are unique names that are assigned to objects. They are identifiers of the variable that contains the data object. Object identifiers are how objects are referenced within the code. They are used to access resources. APIs often tend to expose object identifiers. Object Level Authorization is an access control mechanism. This essentially defines whether users have access to the data objects. If they have access, the difference is read-only, edit, and add/delete access to those objects. For instance, a user may view objects but not modify them. These permissions will differ based on user groups and roles. Object-level authorization adds a layer of security to data objects. It ensures that only validated users view and access data objects. What is Broken Object Level Authorization? API12019 Broken Object Level AuthorizationBOLA is a common and severe API vulnerability. It is also referred to as Insecure Direct Object Reference (IDOR). Broken Object Level Authorization vulnerabilities allow attackers to access data objects that should be restricted. So attackers can request and access other users’ data/ resources. The API doesn’t correctly validate the identity and privileges of the user performing the request. This is due to authorization flaws. Some examples of authorization flaws: • API not checking permissions and allowing access to resources • APIs include resource ID in the URI, request header, or body • Resource ID has a clear structure that can be easily substituted • No checks in place to determine ownership • Not validating user-supplied inputs • Misconfigured authorization checks • Human errors – some requests have authorization checks while others don’t Types of Broken Object Level Authorization   Based on the User ID: API endpoints receive user IDs to access user objects. For example: /example.com/get_users_search_history?userID=1089  The BOLA flaw allows attackers to change the user ID to something else. Thus, they can view other users’ search history. This flaw, however, is easier to solve for developers. This is because the authorization mechanism is straightforward here. A simple check must be included to ensure the user can access the objects. In our example, the check must compare the user ID from the GET parameter to the current user ID. If it doesn’t match, the query must return an error message. Based on Object ID In this BOLA flaw type, the API endpoint receives an Object identifier that doesn’t belong to the user object. For instance, example.com/receipts/download_as_pdf?receipt_id=1089 The attacker can switch the receipt id to download the receipts of different users. api/shop/ {shop name}/revenue_data.json The attacker can change the shop name to gain access to the revenue data of other shops on an eCommerce platform. Here again, the flaw exists because the server doesn’t properly validate the request for the object ID. Developers may not have properly secured all objects. They may have missed an object that must be secured. Securing this BOLA vulnerability is more complex than those based on user IDs. How Do BOLA Attacks Work? BOLA exploits are possible in any API endpoint that allows user inputs. Attackers tend to test APIs for BOLA flaws. They try changing the user or object ID to see how the API responds.They would then go ahead with the attack if the API returns objects instead of an error message. The attack usually enumerates more user/ object IDs to access large volumes of restricted resources. Let us take an example from the banking industry. An attacker uses a credential-stuffing attack to breach a banking system. Suppose they identify a Broken Object Level Authorization vulnerability. Using this flaw, they keep changing the identifier in their request. They don’t have to reauthenticate every request. So, they end up accessing any number of user accounts. Or they may even transfer money. Why is Broken Object Level Authorization OWASP API1: 2019? BOLA Exploitability  As per OWASP API, BOLA has an exploitability score of 3. This means it is easily exploitable by attackers. And why wouldn’t it be? Attackers must replace their resource’s user or object IDs with other values. It is even simpler with modern apps that widely use APIs. Why so? The server in traditional apps would know what buttons a user clicked or which objects they viewed. Modern apps are much less aware of the user state as it is managed on the client side. The server components in API-based apps don’t completely track the user state. They rely on object IDs given by the client to decide access. Widespread Prevalence  Broken Object Level Authorization, as per OWASP, has a prevalence score of 3. It is found in all kinds of modern apps and across domains. Further, enterprises use hundreds of APIs today. There are several shadow and rogue APIs that developers aren’t aware of. Developers cannot test for BOLA or rectify the problem without centralized visibility. So, enterprises end up having one or more APIs vulnerable to BOLA. Impact of BOLA on APIs The technical impact score for BOLA is 3. This means the impact is severe and business specific. Here are some possible impacts of successful BOLA exploits. • Exposure to sensitive information • Attackers can view, modify, or delete data • Full takeover of admin accounts • Privilege escalation • Using stolen data for identity thefts, financial fraud, etc. Successful BOLA exploits are costly. You will lose customer trust and loyalty. There will be customer attrition. You’ll also have to invest time and money in acquiring new customers. And this will be challenging, given the damage to your brand reputation. Broken Object Level Authorization Attack Examples Parler’s Data Breach70TB of Parler, a social network, got scarped through insecure APIs. Hackers scarped millions of posts, photos, and videos before the network was offline after Amazon, Apple, and Google booted the site. How did it happen? Experts confirmed that Parler lacked the basic security measures. The insecure direct object reference is Parler’s major security flaw, says Kenneth White, the co-director of the Open Crypto Audit Project. Facebook Vulnerability The vulnerability in Facebook’s API allowed the unauthorized creation of posts on other users’ pages.  Although not appearing in newsfeeds, the posts could be viewed as legitimate by accessing through a direct link. The root cause was insufficient authorization checks for unlisted posts. How to Detect BOLA Vulnerabilities?  Despite its severity and prevalence, BOLA has average detectability (score 2). Regular API scanning and testing are the best ways to detect BOLA flaws. • Evaluate all API endpoints and the identifiers they use • Write test cases to implement across the API lifecycle. The tests are straightforward. Tests simply require object IDs to be replaced. If they don’t return an error message, you must act • Test all objects. Check them for read, update, modify and delete actions • Check all functionalities that access objects through secondary routes, including those that access objects • Automate the testing process to find all BOLA flaws quickly and accurately to uncover business logic flaws • Leverage API-specific, comprehensive testing solutions for the effective detection of BOLA flaws • Follow a regular cadence of manual pen testing for uncovering BOLA flaws that often reside in the business logic layer of APIs How to Prevent BOLA Risks? Traditional Tools Don’t Work   Enterprises often rely on traditional tools like WAFs and API gateways to prevent BOLA risks. And these tools cannot offer adequate protection. Why so? • API gateways are good for implementing authorization. However, they can’t inspect requests and check for malicious requests. After all, barring DDoS requests, most malicious requests could be deciphered by analyzing the request object • These tools rely on signatures. It is difficult for them to differentiate good from bad API behaviour • They can’t look or don’t know where to look for APIs and API flaws. So, they aren’t equipped to know the unknown • Traditional tools offer only the least common denominator protection. And that is inadequate for today’s complex, modern architecture Implement Proper Authorization Mechanisms You must implement a well-defined authorization mechanism. It must be based on user policies, roles, and hierarchies. The mechanism must validate every user. It must ensure that the user has permission to perform any actions that they do. This should be the case for every user using any functionality to fetch data. This must be a centralized mechanism that can be deployed for every sensitive object. This helps ensure that codes are not messed up by varying authorization mechanisms. You must regularly test and update your authorization policies. This helps ensure that your policies are free of logical flaws and loopholes. This is the most effective way to combat Broken Object Level Authorization. Using GUIDs instead of Numeric IDs Most guides on BOLA protection will tell you to use GUIDs instead of numeric IDs. GUID (Globally Unique Identifier) is also known as UUID (Universally Unique Identifiers). GUIDs are long, random, unpredictable strings of alphanumeric values. It minimizes the risk of tampering by attackers. Remember that GUIDs make it challenging for attackers to guess object identifiers. However, it is not impossible. Employ GUIDs as an added security layer and not the only solution. Real-Time Threat Monitoring Deploy an API security solution that detects and neutralizes BOLA threats in real-time. It must maintain an updated inventory of all APIs, endpoints, and dependencies. The solution should use behavioral and pattern analysis to detect malicious API behaviour and stop it. In addition, attackers use bots to evade traditional defences. So, behaviour-based protection and self-learning AI are key to combat BOLA attacks. If possible, the solution should also have an API discovery module, where the solution will keep updating the inventory of APIs automatically as and when they are created. Prevent BOLA Through AppTrana API Protection AppTrana can help both detect the vulnerability and stop its exploitation. With behavioural analytics, AppTrana can monitor, flag, and block behaviour that indicates BOLA attempts. How Our API Protection Is Unique? Infinite API Scanner The AppTrana solution bundles an API scanner that is infinitely expandable through the usage of plugins. Hence the name Infinite. There is also an added capability of penetration testing on the APIs. The infinite API scanner with built-in pen testing license will help you detect all the OWASP API Top 10 vulnerabilities, including detects BOLA / IDOR. The automated scanner helps detect gaps in access control and server validation. It performs a comprehensive scan of API to ensure no loopholes for BOLA attacks. Few tests are dependent on the particular API and can’t be generalized. In such cases, the plug-in-based architecture enables pen-testers to write an automated test case. It extends testing capabilities infinitely. Infinite API scanner providers visibility on vulnerable API endpoints. It continuously scans each endpoint and compares observed requests with expected usage. Then it analyses the failed resources for various error conditions, which reveals potential BOLA weakness. False Positives Sometimes legitimate users who forget their password appears like attackers. In other cases, attackers attempt through legitimate user credentials. With threat intelligence, AppTrana can find the difference. It is designed to block malicious requests from attacking the APIs while allowing legitimate traffic. Enhanced Bot Protection BOLA significantly widens the attack surface. Hackers can target multi-step attacks. Once they exploit BOLA, they will string together a series of attacks, including bot attacks. Also, they hide their attempt to exploit BOLA with high traffic using bots. AppTrana counter this approach with advanced bot management. It also relates malicious traffic across multiple events to detect techniques associated with a unique attacker. Behaviour-Based Monitoring AppTrana continuously monitors each user and detects activity targeting BOLA vulnerability. It not only monitors for resources that attempt to exploit this vulnerability. It also looks for other suspicious activities like repeated error responses. If these behaviours exceed the risk threshold, it blocks the attacker immediately. Visibility It displays all results graphically on a dashboard with actionable insights. It enables fingertip access to details like: • Attack source/response codes that leak the data • Underlying IP address details Broken Object Level Authorization is the top API vulnerability today. The damage caused by the exploitation of BOLA is catastrophic. Don’t let a broken object-level authorization vulnerability be the downfall of your business. Leverage a fully managed and reliable API security solution like AppTrana. To protect your APIs and reduce the risk of BOLA, start your free trial today! Stay tuned for more relevant and interesting security updates. Follow Indusface on FacebookTwitter, and LinkedIn AppTrana API Protection Spread the love Join 47000+ Security Leaders Get weekly tips on blocking ransomware, DDoS and bot attacks and Zero-day threats. We're committed to your privacy. indusface uses the information you provide to us to contact you about our relevant content, products, and services. You may unsubscribe from these communications at any time. For more information, check out our Privacy Policy. Related Posts API-Discovery API Discovery: Definition, Importance, and Step-by-Step Guide on AppTrana WAAP By identifying & cataloging in-use APIs, API discovery enables organizations to assess security risks associated with each API upon inventory creation. Spread the love Read More What is new in OWASP API Top 10 2023 What’s New in OWASP API Top 10 2023: The Latest Changes and Enhancements The OWASP API Top 10 2023 list has quite a few changes from the 2019 Top 10 API security risks. Here is updated OWASP API Top 10 2023 RC List. Spread the love Read More OWASP API7 2019 Security Misconfiguration API7:2019 Security Misconfiguration: The What, Sample Exploits, and Prevention Methods Security misconfigurations are very common security risks, not just in web applications but also in APIs. They have been consistently part of the OWASP Top 10 Web Application Vulnerabilities. They. Spread the love Read More AppTrana Fully Managed SaaS-Based Web Application Security Solution Get free access to Integrated Application Scanner, Web Application Firewall, DDoS & Bot Mitigation, and CDN for 14 days Know More Take Free Trial Gartner Indusface is the only cloud WAAP (WAF) vendor with 100% Customer Recommendation for 3 consecutive years. A Customers’ Choice for 2022 and 2023 - Gartner® Peer Insights™ The reviews and ratings are in!
__label__pos
0.768075
[Python-ideas] New scope for exception handlers Steven D'Aprano steve at pearwood.info Sat Apr 9 03:44:44 EDT 2016 On Fri, Apr 08, 2016 at 05:03:05PM -0400, Joseph Jevnik wrote: > I would like to propose a change to exception handlers to make it harder to > accidently leak names defined only in the exception handler blocks. This > change follows from the decision to delete the name of an exception at the > end of a handler. The goal of this change is to prevent people from relying > on names that are defined only in a handler. An interesting proposal, but you're missing one critical point: why is it harmful to create names inside an except block? There is a concrete reason why Python 3, and not Python 2, deletes the "except Exception as err" name when the except block leaves: because exceptions now hold on to a lot more call info, which can prevent objects from being garbage-collected. But the same doesn't apply to arbitrary names. At the moment, only a few block statements create a new scope: def and class mostly. In particular, no flow control statement does: if, elif, else, for, while, try, except all use the existing scope. This is a nice clean design, and in my opinion must better than the rule that any indented block is a new scope. I would certainly object to making "except" the only exception (pun intended) and I would object even more to making *all* the block statements create a new scope. Here is an example of how your proposal would bite people. Nearly all by code is hybrid 2+3 code, so I often have a construct like this at the start of modules: try: import builtins # Python 3.x except ImportError: # Python 2.x import __builtin__ as builtins Nice and clean. But what if try and except introduced a new scope? I would have to write: builtins = None try: global builtins import builtins except ImportError: global builtins import __builtin__ as builtins assert builtins is not None Since try and except are different scopes, I need a separate global declaration in each. If you think this second version is an improvement over the first, then our ideas of what makes good looking code are so far apart that I don't think its worth discussing this further :-) If only except is a different scope, then I have this shorter version: try: # global scope import builtins except ImportError: # local scope global builtins import __builtin__ as builtins > As an example, let's looks at a function with a try except: > > > def f(): > try: > ... > except: > a = 1 > return a > > > This function will only work if the body raises some exception, otherwise > we will get an UnBoundLocalError. Not necessary. It depends on what is hidden by the ... dots. For example: def f(): try: a = sequence.pop() except AttributeError: a = -1 return a It might not be the most Pythonic code around, but it works, and your proposal will break it. Bottom line is, there's nothing fundamentally wrong with except blocks *not* starting a new scope. I'm not sure if there's any real benefit to the proposal, but even if there is, I doubt it's worth the cost of breaking existing working code. So if you still want to champion your proposal, it's not enough to demonstrate that it could be done. You're going to have to demonstrate not only a benefit from the change, but that the benefit is worth breaking other people's code. -- Steve More information about the Python-ideas mailing list
__label__pos
0.59874
MINLPLib A Library of Mixed-Integer and Continuous Nonlinear Programming Instances Home // Instances // Documentation // Download // Statistics Instance st_rv2 Formats ams gms lp mod nl osil pip py Primal Bounds (infeas ≤ 1e-08) -64.48069510 p1 ( gdx sol ) (infeas: 0) Other points (infeas > 1e-08)   Dual Bounds -64.48069517 (ANTIGONE) -64.48069519 (BARON) -64.48069511 (COUENNE) -64.48069510 (CPLEX) -64.48069511 (GUROBI) -64.48069511 (LINDO) -64.48069510 (SCIP) References Tawarmalani, M and Sahinidis, N V, Convexification and Global Optimization in Continuous and Mixed-Integer Nonlinear Programming: Theory, Algorithms, Software, and Applications, Kluwer, 2002. Shectman, J P and Sahinidis, N V, A finite algorithm for global minimization of separable concave programs, Journal of Global Optimization, 12:1, 1998, 1-36. Shectman, J P, Finite Algorithms for Global Optimization of Concave Programs and General Quadratic Programs, PhD thesis, Department of Mechanical and Industrial Engineering, University of Illinois, Urbana Champagne, 1999. Added to library 03 Sep 2002 Problem type QP #Variables 20 #Binary Variables 0 #Integer Variables 0 #Nonlinear Variables 20 #Nonlinear Binary Variables 0 #Nonlinear Integer Variables 0 Objective Sense min Objective type quadratic Objective curvature concave #Nonzeros in Objective 20 #Nonlinear Nonzeros in Objective 20 #Constraints 10 #Linear Constraints 10 #Quadratic Constraints 0 #Polynomial Constraints 0 #Signomial Constraints 0 #General Nonlinear Constraints 0 Operands in Gen. Nonlin. Functions   Constraints curvature linear #Nonzeros in Jacobian 160 #Nonlinear Nonzeros in Jacobian 0 #Nonzeros in (Upper-Left) Hessian of Lagrangian 20 #Nonzeros in Diagonal of Hessian of Lagrangian 20 #Blocks in Hessian of Lagrangian 20 Minimal blocksize in Hessian of Lagrangian 1 Maximal blocksize in Hessian of Lagrangian 1 Average blocksize in Hessian of Lagrangian 1.0 #Semicontinuities 0 #Nonlinear Semicontinuities 0 #SOS type 1 0 #SOS type 2 0 Minimal coefficient 1.5000e-04 Maximal coefficient 9.0000e+00 Infeasibility of initial point 0 Sparsity Jacobian Sparsity of Objective Gradient and Jacobian Sparsity Hessian of Lagrangian Sparsity of Hessian of Lagrangian $offlisting * * Equation counts * Total E G L N X C B * 11 1 0 10 0 0 0 0 * * Variable counts * x b i s1s s2s sc si * Total cont binary integer sos1 sos2 scont sint * 21 21 0 0 0 0 0 0 * FX 0 * * Nonzero counts * Total const NL DLL * 181 161 20 0 * * Solve m using NLP minimizing objvar; Variables x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17,x18,x19 ,x20,objvar; Positive Variables x1,x2,x3,x4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15,x16,x17 ,x18,x19,x20; Equations e1,e2,e3,e4,e5,e6,e7,e8,e9,e10,e11; e1.. 6*x1 + 2*x2 + 4*x3 + 3*x5 + 4*x6 + 9*x7 + 5*x9 + x10 + 9*x11 + 6*x12 + 7*x14 + 9*x15 + 2*x16 + 8*x18 + 2*x19 + 4*x20 =L= 405; e2.. 6*x1 + 5*x2 + x3 + 8*x4 + 4*x6 + 3*x7 + 9*x8 + 6*x10 + 4*x11 + 7*x12 + 5*x13 + 2*x15 + 5*x16 + 8*x17 + 9*x19 + 8*x20 =L= 450; e3.. 8*x2 + 6*x3 + 2*x4 + 6*x5 + 4*x7 + 4*x8 + 6*x9 + 9*x11 + 4*x12 + 6*x13 + 9*x14 + 9*x16 + 9*x17 + 3*x18 + x20 =L= 430; e4.. 8*x1 + 7*x3 + 3*x4 + 2*x5 + x6 + 7*x8 + 4*x9 + 7*x10 + 3*x12 + 4*x13 + x14 + 6*x15 + 2*x17 + 8*x18 + 9*x19 =L= 360; e5.. x1 + 5*x2 + 5*x4 + 5*x5 + x6 + 3*x7 + 5*x9 + 7*x10 + 4*x11 + 6*x13 + x14 + 3*x15 + 4*x16 + 3*x18 + 5*x19 + 5*x20 =L= 315; e6.. x1 + 8*x2 + 7*x3 + x5 + 6*x6 + x7 + 6*x8 + 7*x10 + 3*x11 + 6*x12 + 4*x14 + 6*x15 + x16 + 4*x17 + x19 + 4*x20 =L= 330; e7.. 5*x2 + 8*x3 + 7*x4 + 3*x6 + 3*x7 + 8*x8 + 6*x9 + 6*x11 + 4*x12 + 3*x13 + 4*x15 + 2*x16 + 5*x17 + 2*x18 + 4*x20 =L= 350; e8.. x1 + 3*x3 + 2*x4 + 7*x5 + 2*x7 + x8 + x9 + 7*x10 + 4*x12 + 3*x13 + 5*x14 + 3*x16 + 6*x17 + 3*x18 + x19 =L= 245; e9.. 5*x1 + 5*x2 + 2*x4 + x5 + 9*x6 + 7*x8 + 4*x9 + 8*x10 + 5*x11 + 2*x13 + 4*x14 + 4*x15 + 4*x17 + 8*x18 + 9*x19 + x20 =L= 390; e10.. x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 + x12 + x13 + x14 + x15 + x16 + x17 + x18 + x19 + x20 =L= 200; e11.. -(-0.00015*sqr(x1) - 0.0051*x1 - 0.00245*sqr(x2) - 0.2205*x2 - 0.00095* sqr(x3) - 0.0171*x3 - 0.0038*sqr(x4) - 0.6384*x4 - 0.0029*sqr(x5) - 0.435 *x5 - 0.0024*sqr(x6) - 0.4704*x6 - 0.0034*sqr(x7) - 0.4556*x7 - 0.0018* sqr(x8) - 0.2916*x8 - 0.00305*sqr(x9) - 0.0549*x9 - 0.00025*sqr(x10) - 0.0245*x10 - 0.00195*sqr(x11) - 0.3588*x11 - 0.0008*sqr(x12) - 0.1456*x12 - 0.0035*sqr(x13) - 0.672*x13 - 0.0027*sqr(x14) - 0.5184*x14 - 0.002* sqr(x15) - 0.016*x15 - 0.0026*sqr(x16) - 0.1404*x16 - 0.0048*sqr(x17) - 0.2592*x17 - 0.00275*sqr(x18) - 0.418*x18 - 0.00235*sqr(x19) - 0.1081*x19 - 0.00275*sqr(x20) - 0.264*x20) + objvar =E= 0; Model m / all /; m.limrow=0; m.limcol=0; m.tolproj=0.0; $if NOT '%gams.u1%' == '' $include '%gams.u1%' $if not set NLP $set NLP NLP Solve m using %NLP% minimizing objvar; Last updated: 2024-04-02 Git hash: 1dd5fb9b Imprint / Privacy Policy / License: CC-BY 4.0
__label__pos
0.984542
HP Printer In Error State Hp Printer Support How to Fix HP Printer In Error State Windows 10? You were busy printing out the document required for your presentation tomorrow, and out of the blue the message “Printer is in error state”. Can be pretty vexatious, right? Fret not, the printer in an error state HP can be easily resolved by just executing a few methods. You can also mitigate this issue while chatting with HP Printer Technical Support. If you want to try your hands and resolve the issue by yourself, read on to know more. What does the HP printer in an error state mean? HP is a world-renowned brand, making some prolific printers that are in the market. Although HP printers are sturdy, they might encounter some issues. The HP Printer in an error state can spring up owing to myriad reasons like driver being corrupted, an issue with ink, printer being disconnected, the printer being jammed or the printer lead being open. When the HP Printer in an error state message sprouts, it hinders the print commands to reach the printer. The unfastened USB or some error in OS are the main propellants of the HP printer error state. To fix HP Printer in Error State Method 1: Uninstalling and reinstalling the drivers Usually uninstalling and reinstalling the HP printer drivers can be efficacious in removing the HP printer in error state message. The steps for it are 1. Open control panel. 2. Select Devices and Printer. 3. Right-click on the HP printer you are using> select Remove Device and confirm it. 4. Restart the PC. 5. After the system reboots, it would detect the printer and install it. If the printer is not detectable, remove the cable, and fasten it again. Method 2: HP printer Troubleshooting To evoke the HP printer Troubleshooting function, do as follows: • Verify the power supply to the printer is fastened properly. • Ensure the USB connection (for wired printers) and Wi-fi connection (for wireless printers) is adequate. • If the above criteria are met, download the HP printer troubleshooting program and install it. • Thereafter, if the issue persists, the probable reason is Driver. To tackle the issue related to a driver, • Click on start. • Select ‘, Device Manager’. • Expand the printer’s option and locate the printer in use. • Right-click on the located printer, and select ‘Update Drivers’. Method 3: The printer is in Offline State The HP printer error state might emerge due to the printer being in an offline state. To make the printer online, 1. Select Start> Control Panel. 2. Choose Devices and Printer 3. Check whether the printer you are making use of us shows Ready. If so, it means the printer is online. 4. If not, then right-click the printer you are using, and select ‘Use printer online’. Method 5: Using Print Spooler • Press Windows + R. • Type services.msc and click enter. • Scroll down and choose the print spooler service by double-clicking on it. • Confirm whether the services are started and the default setting is Automatic. • If not, then make the setting to automatic, and start the service. • Click on Recovery Tab, modify the first failure option to “Restart the service”. • Choose the apply option. The above-mentioned methods are some effortless procedures that can be utilized to resolve the HP printer in error state. Even after going through these steps, the printer is in error state HP persists, feel free to contact HP Printer Technical Support. I hope the article helped provide some fixes to the printer in error state hp. Leave a Reply Your email address will not be published. Required fields are marked *
__label__pos
0.6048
Solved How do program installation keys work? Posted on 2003-12-04 1 185 Views Last Modified: 2010-04-05 Hi, Can someone give me an explanation (or point me to a useful link) as to how  program installation keys work? This is my difficulty: Assuming the keys (each software package has a different key) all decrypt to one value, how is it possible that numerous values decrypt to one value? (I have a basic knowledge of rsa, hashes etc but try to keep it simple :) ) Conversely, how are the different key generated? Thanks, Joe 0 Comment Question by:SafariJoe [X] Welcome to Experts Exchange Add your voice to the tech community where 5M+ people just like you are talking about what matters. • Help others & share knowledge • Earn cash & points • Learn & ask questions 1 Comment   LVL 8 Accepted Solution by: gmayo earned 250 total points ID: 9881495 You mean the code you usually have to enter whilst installing software? They rarely degenerate down to a single value. Rather, a *set* of values are allowed. One Microsoft one from a few years ago had the format something like XXX-XXXXXX. As long as you entered a set of digits that added up to a multiple of 9 you were okay - which meant that 111-111111 worked! Since then, they've got a little more complex and MS are obviously not going to tell you how to calculate that value. I used a key once for my own software which was also pretty simple. Anybody with an hour to spare could probably have cracked it. All it was was the program name letters added up (their ASCII values), a couple of magic number additions later and then you have a key! The source follows: To generate a key (different each time): program SimSigRegister; uses       Dialogs, SysUtils; var       sim, reg : string;       i, key, total, count : integer;       found : boolean; begin       Randomize;       if InputQuery('Create registration number', 'Enter simulation ID (data directory name)', sim) = true then begin             sim := UpperCase(sim);             key := 0;             for i := 1 to Length(sim) do begin                   key := key + Ord(sim[i]);             end;             key := key mod 1000;             total := (key * (500 + Random(500)));             reg := Format('%x (key %d)', [total, key]);             ShowMessage('Registration code is ' + reg);       end; end. To validate a key: function ValidateRegistration(s : string) : boolean; var       sim : string;       code, i, key : integer;       vi : integer;       vr : single; begin       if s = '' then begin             Result := false;       end else begin             sim := UpperCase(MiscData.SimData.SimulationID);             key := 0;             for i := 1 to Length(sim) do begin                   key := key + Ord(sim[i]);             end;             key := key mod 1000;             try                   code := StrToInt('$' + s);                   vi := code div key;                   vr := code / key;                   Result := (vi = vr) and (code > 999);             except                   Result := false;             end;       end; end; Geoff M. 0 Featured Post Enroll in June's Course of the Month June's Course of the Month is now available! Every 10 seconds, a consumer gets hit with ransomware. Refresh your knowledge of ransomware best practices by enrolling in this month's complimentary course for Premium Members, Team Accounts, and Qualified Experts. Question has a verified solution. If you are experiencing a similar issue, please ask a related question A lot of questions regard threads in Delphi.   One of the more specific questions is how to show progress of the thread.   Updating a progressbar from inside a thread is a mistake. A solution to this would be to send a synchronized message to the… Creating an auto free TStringList The TStringList is a basic and frequently used object in Delphi. On many occasions, you may want to create a temporary list, process some items in the list and be done with the list. In such cases, you have to… There's a multitude of different network monitoring solutions out there, and you're probably wondering what makes NetCrunch so special. It's completely agentless, but does let you create an agent, if you desire. It offers powerful scalability … Michael from AdRem Software outlines event notifications and Automatic Corrective Actions in network monitoring. Automatic Corrective Actions are scripts, which can automatically run upon discovery of a certain undesirable condition in your network.… 690 members asked questions and received personalized solutions in the past 7 days. Join the community of 500,000 technology professionals and ask your questions. Join & Ask a Question
__label__pos
0.813207
[SOLVED] Dynamic batching doesn't work when using "Standard" shader. Can someone explain why ? Hi, I tried to dynamically batch some objects that have less than 300 verts and tris and the objects do not batch when they have the standard shader on them. When using unlit mobile shader dynamic batching works fine. Why is this happening ? If you know why please reply. Thank you, Gerald. With the Standard shader, you’ve got yet another set of verts involved for the lighting data so the actual limit drops even further to 225 verts. Unlit and the old legacy Diffuse don’t have the extra set, which is why they still work okay. As I recall, the hard limit is something like 900 verts, but that gets divided by how many sets (i.e. mesh verts, UV, lighting, etc) you’re using. So for 3 sets of verts it’s 300, and for 4 sets which Standard uses it’s 225.
__label__pos
0.999916
Прошу помочь составить задачу в ABC Pascal!!! Долго болел и пропустил много важных теорий, а теперь нужно подготовиться к зачету :С Прошу, помогите составить алгоритм, суть такова: 1.Нужно использовать только целые числа 2.Определить тип треугольника (равносторонний, равнобедренный, прямой и т.д.) 3.Существует ли этот треугольник (ну то, что каждая сторона меньше суммы двух других) 4.Вид треугольника 5.Найти по формулам: Периметр (P), площадь (S), медиану и бессикриссу 6.И по возможности синусы и косинусы Заранее благодарю за помощь! 1 Ответы и объяснения Лучший Ответ! 2013-12-09T04:33:42+04:00 Опущу все прелюдии. WriteLn('Введите длины сторон треугольника'); ReadLn(x, y, z); If x = y and y = z and z = x  then   WriteLn('Данный треугольник - равносторонний')  else   If (x = y and y = z) or (x = y and x = z) or (x = z and y = z)    then     WriteLn('Данный треугольник - равнобедренный')    else     If (Sqrt(x) = Sqrt(y) + Sqrt(z)) or (Sqrt(y) = Sqrt(x) + Sqrt(z)) or (Sqrt(z) = Sqrt(x) + Sqrt(y))      then       WriteLn('Данный треугольник - прямоугольный')      else       If (x < (y + z)) and (y < (x + z)) and (z < (x + y))        then         WriteLn('Данный треугольник является обыкновенным')        else         WriteLn('Данный треугольник не существует'); p := div((x + y + z) / 2); {Полупериметр} WriteLn('Периметр треугольника Р =', x + y + z); WriteLn('Площадь треугольника S =', div(Sqrt(p*(p-x)*(p-y)*(p-z)))); WriteLn('Медиана к стороне x -', div(Sqrt(2*Sqr(y) + 2*Sqr(z) - Sqr(x))/2)); WriteLn('Биссектриса стороны х -', div(Sqrt(y*z*(x+y+z)*(y+z-x))/(y+z))); С синусами/косинусами особая история, напиши мне в лс, чтоб я не забыл потом помочь. Все отлично, но почему то ругается на операцию "div"? Вот выдает ошибку: Program1.pas(21) : Встречено 'div', а ожидалось выражение
__label__pos
0.959246
Sunday, January 30, 2011 Managing Coupling (This post has also been posted to http://altdevblogaday.com/.) The only way of staying sane while writing a large complex software system is to regard it as a collection of smaller, simpler systems. And this is only possible if the systems are properly decoupled. Ideally, each system should be completely isolated. The effect system should be the only system manipulating effects and it shouldn’t do anything else. It should have its own update() call just for updating effects. No other system should care how the effects are stored in memory or what parts of the update happen on the CPU, SPU or GPU. A new programmer wanting to understand the system should only have to look at the files in the effect_system directory. It should be possible to optimize, rewrite or drop the entire system without affecting any other code. Of course, complete isolation is not possible. If anything interesting is going to happen, different systems will at some point have to talk to one another, whether we like it or not. The main challenge in keeping an engine “healthy” is to keep the systems as decoupled as possible while still allowing the necessary interactions to take place. If a system is properly decoupled, adding features is simple. Want a wind effect in your particle system? Just write it. It’s just code. It shouldn’t take more than a day. But if you are working in a tightly coupled project, such seemingly simple changes can stretch out into nightmarish day-long debugging marathons. If you ever get the feeling that you would prefer to test an idea out in a simple toy project rather than in “the real engine”, that’s a clear sign that you have too much coupling. Sometimes, engines start out decoupled, but then as deadlines approach and features are requested that don’t fit the well-designed APIs, programmers get tempted to open back doors between systems and introduce couplings that shouldn’t really be there. Slowly, through this “coupling creep” the quality of the code deteriorates and the engine becomes less and less pleasant to work with. Still, programmers cannot lock themselves in their ivory towers. “That feature doesn’t fit my API,” is never an acceptable answer to give a budding artist. Instead, we need to find ways of handling the challenges of coupling without destroying our engines. Here are four quick ideas to begin with: 1. Be wary of “frameworks”. By a “framework” I mean any kind of system that requires all your other code to conform to a specific world view. For example, a scripting system that requires you to add a specific set of macro tags to all your class declarations. Other common culprits are: • Root classes that every object must inherit from • RTTI/reflection systems • Serialization systems • Reference counting systems Such global systems introduce a coupling across the entire engine. They rudely enforce certain design choices on all subsystems, design choices which might not be appropriate for them. Sometimes the consequences are serious. A badly thought out reference system may prevent subsystems from multithreading. A less than stellar serialization system can make linear loading impossible. Often, the motivation given for such global systems is that they increase maintainability. With a global serialization system, we just have to make changes at a single place. So refactoring is much easier, it is claimed. But in practice, the reverse is often true. After a while, the global system has infested so much of the code base that making any significant change to it is virtually impossible. There are just too many things that would have to be changed, all at the same time. You would be much better off if each system just defined its own save() and load() functions. 2. Use high level systems to mediate between low level systems. Instead of directly coupling low level systems, use a high level system to shuffle data between them. For example, handling footstep sounds might involve the animation system, the sound system and the material system. But none of these systems should know about the others. So instead of directly coupling them, let the gameplay system handle their interactions. Since the gameplay system knows about all three systems, it can poll the animation system for events defined in the animation data, sample the ground material from the material system and then ask the sound system to play the appropriate sound. Make sure that you have a clear separation between this messy gameplay layer, that can poke around in all other systems, and your clean engine code that is isolated and decoupled. Otherwise there is always a risk that the mess propagates downwards and infects your clean systems. In the BitSquid Tech we put the messy stuff either in Lua or in Flow (our visual scripting tool, similar to Unreal’s Kismet). The language barrier acts as a firewall, preventing the spread of the messiness. 3. Duplicating code is sometimes OK! Avoiding duplicated code is one of the fundamentals of software design. Entities should not be needlessly multiplied. But there are instances when you are better off breaking this rule. I’m not advocating copy-paste-programming or writing complicated algorithms twice. I’m saying that sometimes people can get a little overzealous with their code reuse. Code sharing has a price that is not always recognized, in that it increases system coupling. Sometimes a little judiciously applied code duplication can be a better solution. An typical example is the String class (or std::string if you are thusly inclined). In some projects you see the String class used almost everywhere. If something is a string, it should use the Stringclass, the reasoning seems to be. But many systems that handle strings do not need all the features that you find in your typical String class: locales, find_first_of(), etc. They are fine with just aconst char *strcmp() and maybe one custom written (potentially duplicated) three-line function. So why not use that, the code will be much simpler and easier to move to SPUs. Another culprit is FixedArray a. Sure, if you write int a[5] instead you will have to duplicate the code for bounds checking if you want that. But your code can be understood and compiled without fixed_array.h and template instantiation. And if you have any method that takes a const Vector &v as argument you should probably take const T *begin, const T *end instead. Now you don’t need the vector.h header, and the caller is not forced to use a particular Vector class for storage. A final example: I just wrote a patching tool that manipulates our bundles (aka pak-files). That tool duplicates the code for parsing the bundle headers, which is already in the engine. Why? Well, the tool is written in C# and the engine in C++, but in this case that is kind of beside the point. The point is that sharing that code would have been a significant effort. First, it would have had to be broken out into a separate library, together with the related parts of the engine. Then, since the tool requires some functionality that the engine doesn’t (to parse bundles with foreign endianness) I would have to add a special function for the tool, and probably a #define TOOL_COMPILE since I don’t want that function in the regular builds. This means I need a special build configuration for the tool. And the engine code would forever be dirtied with the TOOL_COMPILE flag. And I wouldn’t be able to rearrange the engine code as I wanted in the future, since that might break the tool compile. In contrast, rewriting the code for parsing the headers was only 10 minutes of work. It just reads a vector of string hashes. It's not rocket science. Sure, if I ever decide to change the bundle format, I might have to spend another 10 minutes rewriting that code. I think I can live with that. Writing code is not the problem. The messy, complicated couplings that prevent you from writing code is the problem. 4. Use IDs to refer to external objects. At some point one of your systems will have to refer to objects belonging to another system. For example, the gameplay layer may have to move an effect around or change its parameters. I find that the most decoupled way of doing that is by using an ID. Let’s consider the alternatives. Effect *, shared_ptr A direct pointer is no good, because it will become invalid if the target object is deleted and the effect system should have full control over when and how its objects are deleted. A standardshared_ptr won’t work for the same reason, it puts the life time of Effect objects out of the control of the effect system. Weak_ptr, handle By this I mean some kind of reference-counted, indirect pointer to the object. This is better, but still too strongly coupled for my taste. The indirect pointer will be accessed both by the external system (for dereferencing and changing the reference count) and by the effect system (for deleting the Effect object or moving it in memory). This has the potential for creating threading problems. Also, this construct kind of implies that external systems can dereference and use the Effectwhenever they want to. Perhaps the effect system only allows that when its update() loop is not running and want to assert() that. Or perhaps the effect system doesn’t want to allow direct access to its objects at all, but instead double buffer all changes. So, in order to allow the effect system to freely reorganize its data and processing in any way it likes, I use IDs to identify objects externally. The IDs are just an integers uniquely identifying an object, that the user can throw away when she is done with them. They don’t have to be “released” like aweak_ptr, which removes a point of interaction between the systems. It also means that the IDs are PODs. We can copy and move them freely in memory, juggle them in Lua and DMA them back-and-forth to our heart’s content. All of this would be a lot more complicated if we had to keep reference counts. In the system we need a fast way of mapping IDs back to objects. Note that std::map is not a fast way! But there are a number of possibilities. The simplest is to just use a fixed size array with object pointers: Object *lookup[MAX_OBJECTS]; If your system has a maximum of 4096 objects, use 12 bits from the key to store an index into this array and the remaining 20 bits as a unique identifier (i.e., to detect the case when the original object has been deleted and a new object has been created at the same index). If you need lots of objects, you can go to a 64 bit ID. That's it for today, but this post really just scratches the surface of decoupling. There are a lot of other interesting techniques to look at, such as events, callbacks and “duck typing”. Maybe something for a future entry... 20 comments: 1. Using IDs for external references, wouldn't that possibly incur a rather large cost for function calls on that object? For example, refering to an object in a scene graph, to change a property (like local transform) on that object you would have to call something like _scenegraph->set_object_transform( object_id, transform ); which would in effect translate to a lookup in the object table, a check to make sure the unique id is valid, and then a call to set the actual property data. I guess you would use this with a design where external access to objects in a subsystem is restricted to higher level functions where the overhead costs are small in comparison with the actual function implementation? I.e not for get/set properties-like functions. ReplyDelete 2. Love this. From the perspective of being the guy writing the messy gameplay-code, a sound structure is key to being able to work efficiently and in somewhat harmony with the engine, love it! I'm looking forward for future entries. ReplyDelete 3. @Mattias - I'm guessing in that case, the graph would consume a stream of set_transform events. http://bitsquid.blogspot.com/2009/12/events.html Regarding the cost of ID validation -- on the bright side, this means you wont ever crash because of a bad pointer ;) You could even reserve object #0 in each system as a "null struct", and conditionally select offset '0' instead of 'ID' if 'ID' is invalid -- meaning you don't even have to branch to deal with bad pointers (they just read/write these pre-reserved junk "null structs"). ReplyDelete 4. @Mattias - As I said in the post, the cost is one extra pointer access (the test is nearly free, since you can branch hint that the object still exists). So not too bad. And the IDs don't necessarily have to be indirect references. Since the external system just treats them as opaque data, they could be something else if you like. For example, our scene graph is essentially just: struct { Vector local_transform; Vector world_transform; Vector parent; } And the object_id for the scene graph is just an integer index into these arrays. ReplyDelete 5. @Action Man - I like your idea about a "null struct". Haven't thought about that. It is a nice way of getting rid of a lot of "does the object exist?" tests. ReplyDelete 6. @Action Man - Nice idea, I like it. But wouldn't that possibly lead to other hard-to-track strange behaviour if random readers of the null struct data get stuff from other random writers? Basically anything could be present in the null struct, which is as bad as reading from random memory (except for not getting a potential access violation). @Niklas - Ah, right, good point. I guess I'm still stuck a bit in my object oriented thinking, but seeing your example of a more data-oriented approach of the system the ideas fall in to place and makes a lot of sense. Cheers. ReplyDelete 7. Great post, I was just wondering how you would add/delete data to the simple arrays of objects? ReplyDelete 8. @Amir You can use an "in-place free list". I.e. you keep a linked list of the free slots in the lookup[] array. But you store the linked list in the lookup[] array itself. So in each free slot in lookup[] you store the index of the next free slot in the linked list. And then you use a variable first_free_slot to point to the first free slot. To add an object to the array, allocating it from the free list: int slot = first_free_slot; first_free_slot = (int)lookup[slot]; To remove an object from the array, adding it to the free list: lookup[slot] = (Object *)first_free_slot; first_free_slot = slot; To make this a complete system, you also need an index value to mark the end of the list (such as 0xffffffff) and a way of allocating a slot when the free list is empty (just keep a count of the number of slots you have used and allocate from the end of the array in that case). ReplyDelete 9. Nice, very minimal and interesting. Now I am wondering how the list of objects can be traversed. How can we know if an element in the array is actually containing an object pointer or represents the next free index? Any specific bits reserved maybe? ReplyDelete 10. Yes you would need some kind of flag for that. You could go to a struct {} with room for both the flag and the Object *. Or you could try to be clever with bit twiddling. For example, assuming that all allocations are 4-byte aligned, bit 0 of the pointers is never actually used, so you could use that to mark free or occupied nodes. ReplyDelete 11. Niklas, how do you handle the case when several subsystems trying to access the entity by its ID? For example, Scripting subsystem may be working with Foo* entity acquired by some ID, while at the same time this entity gets somehow removed from the World by another subsystem(say Physics). How do you handler this case? In shared/weak ptrs schema this is handled by "locking" the weak_ptr thus turning it into a shared_ptr. In your case the most obvious way is to access the entity by ID only and never cache the pointer to it. Right? Or you also "lock" the entity explicitly somehow? ReplyDelete 12. No, I solve this at a higher level, by structuring the code so that object deletes cannot happen at the same time as objects are processed. When objects are processed in a background thread, I typically do this by delaying deletes. I. e., object deletes are delayed and put in a queue and only executed by the system when it "knows" it is safe. (When it is in sync with the background processing threads.) ReplyDelete 13. Sorry for waking a sleeping thread but while I'm really enjoying this series I'm a bit confused as to how this works for a system like a scene graph. For example: 1) Children How do child nodes know when the parent node has been deleted or moved? Is the idea that higher level objects are responsible for aggregating transforms and then deleting/updating them as necessary (e.g. the Car object takes care of telling the wheel transforms that the chassis transform has been deleted)? 2) Updating How do you keep the various arrays that represent the transforms laid out in the proper order for updating sequentially? Seems like you would have to sort your arrays every time you added or removed a node in the transform hierarchy which looks like a lot of copying of data for such a frequent event. ReplyDelete 14. We don't have a complete graph for the entire scene, instead we have local scene graphs in each of our units/entities. Each node in the graph has a dirty flag that is set if its local matrix has been modified. When we process the graph we check each node in order and compute the new world matrix if its local matrix or its parent's world matrix has been modified. For units we keep track of which units are linked to other units. Most units are not linked and we update all of those in parallel. The linked units are sorted by link depth and then updated in that order. That guarantees that parents are updated before children. The transform graphs within units are never resorted. We could do that, but we have not yet found any reason to "re-root" a unit's scene graph. ReplyDelete 15. Great article but it's left me with a few questions. 1.) Where are the systems? By this I mean, do you keep an instance of each active system in some kind of World/Engine object or do higher level systems actually own an instance of the lower level systems they depend upon? 2.) Where are the components? Does each system own an array of components or are they to kept in arrays elsewhere? e.g. A number of systems need to access world transforms, do those systems need to query the "SceneGraph" system to access a world transform or can they directly reference a pool of components? ReplyDelete Replies 1. 1) Systems are owned at the level where it makes sense. Globally shared stuff, like MemoryManager and ThreadManager are owned by the Application. Stuff local to a World (there can be multiple worlds) like ParticleWorld, SoundWorld, etc are owned by the world. Lower level systems get passed references to the shared objects they need when created. 2) They query the scene graph. Delete 2. Thanks for the response, it's a lot clearer now. Delete 16. Really interesting article! I've been struggling with coupling recently. Question: how do you decouple behaviour tree actions? Specifically with disaggregating state into smaller bits to feed into the functions. Everything I've seen seems to pass in the same matching state into every behaviour even if the behaviour only requires a small subset of that state. This isn't scaling for me well though! Any thoughts? ReplyDelete 17. Nice knowledge gaining article. This post is really the best on this valuable topic. norton.com/setup office.com/setup norton.com/setup ReplyDelete 18. such a great information. I like this article.Gas Turbine Labyrinths ReplyDelete
__label__pos
0.740106
Dismiss Notice Join Physics Forums Today! The friendliest, high quality science and math community on the planet! Everyone who loves science is here! Mathematica: Animate multiple sets of XY data 1. Oct 11, 2015 #1 I have nine sets of data with x,y coords that are the position of a particle. I can ListPlot the particle positions on a single plot, but, I want to animate this. ListPlot[{mydata1, mydata2, mydata3, mydata4, mydata5, mydata6, mydata7, mydata8, mydata9}, PlotRange -> {{-1, 20}, {-1, 20}}] I have been playing around with ListAnimate and I can get one particle to animate but I can not get the rest. ListAnimate[ ListPlot[{#, #}, PlotRange -> {{-1, 20}, {-1, 20}}] & /@ mydata1] Is there a way to get all nine particles in the same frame?   2. jcsd 3. Oct 16, 2015 #2 Thanks for the post! This is an automated courtesy bump. Sorry you aren't generating responses at the moment. Do you have any further information, come to any new conclusions or is it possible to reword the post?   Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook Similar Discussions: Mathematica: Animate multiple sets of XY data 1. Zeros in a data set (Replies: 4) Loading...
__label__pos
0.797912
Problem Express the results of the following calculations with the correct number of significant figures. (a) (( 3.41 - 0.23)/5.233) * 0.205 Relevant Solution clock 6m Play a video: Hey there. Welcome back. Alright, so here, how many significant figures does each arithmetic calculation have? So here we have three different calculations. We're going to take a look at the first one. Alright, so in the first one, what we're doing is we're adding. Right so whenever we're adding we're going to take a look at decimal places. We want our final answer to have the least number of decimal places as possible. So both of these numbers have one too. They have two decimal places which means our final answer should have two decimal places. Right? So let's go ahead and add this. Just put that into your calculator and see what we get. So we get 1, 0.55. Right? So here we actually have 12. We have two decimal places which is the correct um correct answer. So how many significant figures does this answer have? Well since here we have a decimal place, we're going to start from counting from the left and go to the right. The 1st 10 0 number is one. So let's just go ahead and count. We have 123456. So this one has six significant figures. Okay, so it looks like the only correct answer or the option here that we have for the first one to have six is the so that is most likely going to be our our answer but let's go ahead and actually do all of the work for the second and the third. So for the second and for the second one we're doing multiplication and division for that, we need to count the number of significant figures. Right? So in the first number we have three significant figures because we're starting to count from the left, going to the right, right. So this is three significant figures. The second number we have 12344 and then this one we have 1234 as well. Alright, so we know that our final answer should have three significant figures. And that actually makes sense with the with the answer option here. But let's let's see why it is three significant figures. So we're going to go ahead and do the multiplication first. So 8.00 times 12.67. When you put that into your calculator, you're going to get 101.36. Right? So if we were to get this as a final answer, this is actually the wrong number of significant figures. Because between these two numbers, three was the least number of significant figures. So this would actually we would drop this .36 and it would just be 1, 101. Alright, so just be 101. So that will give us a number of significant figures as three. Then when we divide that By 2.39, 2 again, So we're dividing we're looking at a number of significant figures. This one has three. This one has four. So we want our final answer to have three. Right, So we have we get 442.224. That's what my calculator gave us. But because we only want to three significant figures, here's 12 and three. So that's all we want. So the final answer for that. 2nd 1 would be 42.2. Right? And here we have three significant figures. Whoops! Alright, so for the 3rd 1 we're already kind of know there's going to be too. Probably Right, but let's go ahead and do that. So here we have it's a little bit different. Um All right, so we did the second one and now we're doing this third one. So here we actually have multiplication and addition. So obviously we usually do multiplication first. Right, And then addition. And here they are in parentheses. So parentheses do come first. So we're gonna go ahead and multiply these again. Here, we're gonna take a look at the number of significant figures. 28.12 has 1234. Right? It has four significant figures and 9.0, has two significant figures. So for the multiplication part, which should have two significant figures. So 28.12 times 9.0 What we get here is actually 253.08. Right, as the answer. Now, that's not the correct number of significant figures. Right, We want to because that's the least number of significant figures between those two numbers. So we're actually gonna go ahead and convert this number into scientific notation. So all we want is just two and five, right? Five is next to three. So actually we don't need to round up five, it can stay as to five. So we're gonna Uh do 2.5 Times 10. And then here has to be to the second power because we're moving this decimal place two times to the left, so 12, right, so that is the answer for the multiplication of those two numbers. Now we're going to go ahead and add 12.56. Now, whenever we're adding numbers and we have scientific notation we want them to have the same the same exponents. Right? So 12.56 if we were to write that and scientific notation with uh two as a coefficient, it would actually be .12 times tend to the second power. And of course we would put this in parentheses when we're putting this into the calculator because it's you know, it's a scientific notation number. Right? So now that they are in the same, obviously, I'm sorry, like you put both of those numbers in parentheses, so now that we have the same scientific notation or the same coefficient, We're just going to ignore the coefficient for now and we're just going to add 2.5, And that will give us an answer of two 6- 6. and of course the Times 10 to the second is still there. Now we do want how many significant figures? So we started with two from this one. Right? So this one has two Sig figs And this one has actually 1234. So we want our final answer to have to because that's the least number of significant figures. So we want to and six if you take a look at the number that's next to six, it's too So we do not need to round it up. So it would just be 2.6 Times to the second. Okay, so here again, we have two significant figures. So yes, we were correct. D is our final answer are correct. Final answer. Right, folks, thank you so much for watching. We'll see you in the next video.
__label__pos
0.96733
Exercise 8 - Reading and writing files Exercise 8 - Reading and writing files Andrew Valentine, Louis Moresi, [email protected] Up to this point, we have typed all the data for our programs in ‘by hand’. However, as you have no doubt noticed, this quickly gets tedious. It is useful to be able to read and write data files, allowing information to be stored and shared with other people. In order to read a data file, we need to understand what information it contains, and how this has been encoded. This is generally referred to as the ‘file format’. Different programs produce files in different formats - a photograph in .jpeg format cannot be read by a spreadsheet package, which might expect to receive files in .xlsx format. The simplest file format for storing and transferring scientific data is a plain text file in ‘ascii’ (‘American Standard Code for Information Exchange’) format. This is the sort of file that can be read and produced using a simple text editor such as ‘notepad’ (on Windows) or ‘TextEdit’ (on a Mac). Commonly, such files will have an extension such as .txt or .dat. Reading ascii files in Python is a four-step process: 1. Open the file; 2. Read each line from the file; 3. Parse each line (i.e., extract the required information from it); 4. Close the file. We assume that the file is already saved on your computer, and you know the ‘path’ to the file. To open the file, we use the open() function, which returns a file object. It is important to assign this to a variable (here, fp) so that we can continue to access the open file. filename = 'sample.dat' fp = open(filename, 'r') Here, filename is a variable holding the file name (or file path and name, if it is not in our current working directory), and the second argument, 'r', specifies that we want to open the file for reading only. Once the file is open, we can read from it. There are various ways of doing this, but for small files the simplest method is generally to call the readlines() function, which returns the entire file in the form of a list: lines = fp.readlines() Each element of the list lines is now a string, containing one of the lines from the file sample.dat. Since we have read all the information in the file, we can now close the file: fp.close() ➤ Try it out! # Try it here! Opening and closing files explicitly is useful to illustrate how Python handles reading and writing files. However, doing this in practice can get quite messy because these ‘connections’ to files stay open until you explicitly close them. With single files, this can lead to data corruption and data loss, with more complex scripts you might open 10,000 files and not close any of them, clogging up your computer! Luckily, Python has a really handy construct for dealing with this automatically, called ‘context managers’. They have a number of uses, but in the case of reading/writing files, you create a ‘context’ that contains a connection to a file, which is automatically closed when the code within the context is finished. This sounds complex… so an example: filename = 'sample.dat' with open(filename, 'r') as fp: lines = fp.readlines() The with statement tells python that the file you’re giving it is only used in the following indented code, and can be closed afterwards. This performs exactly the same as manually opening and closing the file, as above, but automatically cleans up after you. ➤ Try it out! # Try it here! Once you have a list of strings, you can use the list- and string-parsing tools we have already encountered to extract the necessary data and store it in appropriate data structures. The file sample.dat contains records of the mass and volume of twenty samples of a given material. ➤ Read the data from this file, compute the density of each sample and hence the average density of the material. # Try it here! To write data to file, we need to first open the file for writing. This can be done by using 'w' instead of 'r' when opening the file. Note that if a file already exists with the specified name, it will be immediately overwritten and lost. To avoid this, you can instead use 'x' when opening the file. This will throw an error if there is an existing file, rather than overwrite it. Again, when opening the file it is important to assign the result of open() to a variable, so we can write to it. outputfile = 'processed_samples.dat' fp = open(outputfile, 'w') Once the file is open, we can write any text strings to it by calling the write() function. Remember, to insert a new line, you use the symbol '\n', otherwise everything will be on a single line: fp.write("Hello!\n") fp.write("This is some text to store in a file... ") line = "The file has only two lines." fp.write(line) Once everything is written to the file, call close() to close it. fp.close() ➤ Create a new file, based on the data you read earlier. It should contain three columns: mass, sample volume and sample density. All quantities should be in SI units. Remember, you can use the string-formatting tools we encountered in the last exercise to control how your numbers are written out. You can open a text file by clicking its name in Jupyter’s file browser. Verify that the file has been correctly written. # Try it here! From the examples above, we just saw how to read and write data using Python built-in methods. These are good for simple files, but not for more complex information such as an Excel spreadsheet. Later in the course, we will encounter a number of more sophisticated tools that can help us with these kinds of files.
__label__pos
0.985759
File: block-stream.js package info (click to toggle) node-block-stream 0.0.9-2 • links: PTS, VCS • area: main • in suites: bookworm, bullseye, sid • size: 132 kB • sloc: makefile: 2 file content (209 lines) | stat: -rw-r--r-- 6,555 bytes parent folder | download | duplicates (3) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 // write data to it, and it'll emit data in 512 byte blocks. // if you .end() or .flush(), it'll emit whatever it's got, // padded with nulls to 512 bytes. module.exports = BlockStream var Stream = require("stream").Stream , inherits = require("inherits") , assert = require("assert").ok , debug = process.env.DEBUG ? console.error : function () {} function BlockStream (size, opt) { this.writable = this.readable = true this._opt = opt || {} this._chunkSize = size || 512 this._offset = 0 this._buffer = [] this._bufferLength = 0 if (this._opt.nopad) this._zeroes = false else { this._zeroes = new Buffer(this._chunkSize) for (var i = 0; i < this._chunkSize; i ++) { this._zeroes[i] = 0 } } } inherits(BlockStream, Stream) BlockStream.prototype.write = function (c) { // debug(" BS write", c) if (this._ended) throw new Error("BlockStream: write after end") if (c && !Buffer.isBuffer(c)) c = new Buffer(c + "") if (c.length) { this._buffer.push(c) this._bufferLength += c.length } // debug("pushed onto buffer", this._bufferLength) if (this._bufferLength >= this._chunkSize) { if (this._paused) { // debug(" BS paused, return false, need drain") this._needDrain = true return false } this._emitChunk() } return true } BlockStream.prototype.pause = function () { // debug(" BS pausing") this._paused = true } BlockStream.prototype.resume = function () { // debug(" BS resume") this._paused = false return this._emitChunk() } BlockStream.prototype.end = function (chunk) { // debug("end", chunk) if (typeof chunk === "function") cb = chunk, chunk = null if (chunk) this.write(chunk) this._ended = true this.flush() } BlockStream.prototype.flush = function () { this._emitChunk(true) } BlockStream.prototype._emitChunk = function (flush) { // debug("emitChunk flush=%j emitting=%j paused=%j", flush, this._emitting, this._paused) // emit a <chunkSize> chunk if (flush && this._zeroes) { // debug(" BS push zeroes", this._bufferLength) // push a chunk of zeroes var padBytes = (this._bufferLength % this._chunkSize) if (padBytes !== 0) padBytes = this._chunkSize - padBytes if (padBytes > 0) { // debug("padBytes", padBytes, this._zeroes.slice(0, padBytes)) this._buffer.push(this._zeroes.slice(0, padBytes)) this._bufferLength += padBytes // debug(this._buffer[this._buffer.length - 1].length, this._bufferLength) } } if (this._emitting || this._paused) return this._emitting = true // debug(" BS entering loops") var bufferIndex = 0 while (this._bufferLength >= this._chunkSize && (flush || !this._paused)) { // debug(" BS data emission loop", this._bufferLength) var out , outOffset = 0 , outHas = this._chunkSize while (outHas > 0 && (flush || !this._paused) ) { // debug(" BS data inner emit loop", this._bufferLength) var cur = this._buffer[bufferIndex] , curHas = cur.length - this._offset // debug("cur=", cur) // debug("curHas=%j", curHas) // If it's not big enough to fill the whole thing, then we'll need // to copy multiple buffers into one. However, if it is big enough, // then just slice out the part we want, to save unnecessary copying. // Also, need to copy if we've already done some copying, since buffers // can't be joined like cons strings. if (out || curHas < outHas) { out = out || new Buffer(this._chunkSize) cur.copy(out, outOffset, this._offset, this._offset + Math.min(curHas, outHas)) } else if (cur.length === outHas && this._offset === 0) { // shortcut -- cur is exactly long enough, and no offset. out = cur } else { // slice out the piece of cur that we need. out = cur.slice(this._offset, this._offset + outHas) } if (curHas > outHas) { // means that the current buffer couldn't be completely output // update this._offset to reflect how much WAS written this._offset += outHas outHas = 0 } else { // output the entire current chunk. // toss it away outHas -= curHas outOffset += curHas bufferIndex ++ this._offset = 0 } } this._bufferLength -= this._chunkSize assert(out.length === this._chunkSize) // debug("emitting data", out) // debug(" BS emitting, paused=%j", this._paused, this._bufferLength) this.emit("data", out) out = null } // debug(" BS out of loops", this._bufferLength) // whatever is left, it's not enough to fill up a block, or we're paused this._buffer = this._buffer.slice(bufferIndex) if (this._paused) { // debug(" BS paused, leaving", this._bufferLength) this._needsDrain = true this._emitting = false return } // if flushing, and not using null-padding, then need to emit the last // chunk(s) sitting in the queue. We know that it's not enough to // fill up a whole block, because otherwise it would have been emitted // above, but there may be some offset. var l = this._buffer.length if (flush && !this._zeroes && l) { if (l === 1) { if (this._offset) { this.emit("data", this._buffer[0].slice(this._offset)) } else { this.emit("data", this._buffer[0]) } } else { var outHas = this._bufferLength , out = new Buffer(outHas) , outOffset = 0 for (var i = 0; i < l; i ++) { var cur = this._buffer[i] , curHas = cur.length - this._offset cur.copy(out, outOffset, this._offset) this._offset = 0 outOffset += curHas this._bufferLength -= curHas } this.emit("data", out) } // truncate this._buffer.length = 0 this._bufferLength = 0 this._offset = 0 } // now either drained or ended // debug("either draining, or ended", this._bufferLength, this._ended) // means that we've flushed out all that we can so far. if (this._needDrain) { // debug("emitting drain", this._bufferLength) this._needDrain = false this.emit("drain") } if ((this._bufferLength === 0) && this._ended && !this._endEmitted) { // debug("emitting end", this._bufferLength) this._endEmitted = true this.emit("end") } this._emitting = false // debug(" BS no longer emitting", flush, this._paused, this._emitting, this._bufferLength, this._chunkSize) }
__label__pos
0.977889
Problem H. Heron statues Author:A. Klenin, I. Blinov   Time limit:1 sec Input file:Standard input   Memory limit:256 Mb Output file:Standard output   Statement Elephant Pakhom installed a row of n statues of herons, each statue is painted in its own color. Colors are represented by small Latin letters from 'a' to 'z'. The elephant is pleased with the result of his work, but now he wants to repaint some statues so that there are no three consecutive statues of the same color. Since Pakhom has tired during the construction of the statues, he wants to repaint as few herons as possible. Input format The first line of the input contains integer n. The second line contains n characters — description of statue colors. Output format Output must contain a string of length n — a new coloring of herons. If there are several optimal colorings, output any of them. Constraints 1 ≤ n ≤ 105 Sample tests No. Standard input Standard output 1 5 aaaaa aazaa 2 10 asdfghjklz asdfghjklz 0.039s 0.008s 15
__label__pos
0.804031
CameraIcon CameraIcon SearchIcon MyQuestionIcon MyQuestionIcon 1 You visited us 1 times! Enjoying our articles? Unlock Full Access! Question A tank with rectangular base and rectangular sides, open at the top is to be constructed so that its depth is 2 m and volume is 8 m3. If building of tank costs Rs. 70 per square metre for the base and Rs. 45 per square metre for the sides, what is the cost of least expensive tank ? Open in App Solution Let l,b,h be the length, breadth and height of the tank respectively. Then h=2 m And, volume of tank =8 m3 l×b×h=8l×b=4b=4l Now, area of the base =lb=4 And, area of the walls =2lh+2bh=2h(l+b) Therefore, total area is A=2h(l+b)+lbA=4(l+4l)+4 Differentiating A with respect to l, we get dAdl=4(14l2)+0 Now, putting dAdl=0, we get 4(14l2)=014l2=0l2=4 l=2 [Since length can't be negative] l=2b=4l=2 d2Adl2=32l3 At l=2,d2Adl2=328=4>0 Therefore, by second derivative test, area is minimum when l=2. So, we get l=b=h=2 Therefore, cost of building base =70×lb=70×4= Rs. 280 Cost of building walls =45×(2h(l+b))=45×4×4= Rs. 720 Therefore, least cost of tank is Rs. 280+720= Rs. 1000 flag Suggest Corrections thumbs-up 9 Join BYJU'S Learning Program similar_icon Related Videos thumbnail lock Rate of Change MATHEMATICS Watch in App Join BYJU'S Learning Program CrossIcon
__label__pos
0.993464
Sai Kiran Sai Kiran - 7 months ago 54 Android Question How to create empty constructor for data class in Kotlin Android I have 10+ parameter in a data class, I want initialize the data class with empty constructor and set the values only for few parameters using setter and pass the object to server. data class Activity( var updated_on: String, var tags: List<String>, var description: String, var user_id: List<Int>, var status_id: Int, var title: String, var created_at: String, var data: HashMap<*, *>, var id: Int, var counts: LinkedTreeMap<*, *>, ) //Something like this will be easy val activity = Activity(); //but it needs all the parameters activity.title = "New Computer" sendToServer(activity) //It requires all the paraments, How to avoid this and use something like above code val activity = Activity(null,null,null,null,null,"New Computer",null,null,null,null); sendToServer(activity) Answer You have 2 options here: 1. Assign a default value to each primary constructor parameter: data class Activity( var updated_on: String = "", var tags: List<String> = emptyList(), var description: String = "", var user_id: List<Int> = emptyList(), var status_id: Int = -1, var title: String = "", var created_at: String = "", var data: HashMap<*, *> = hashMapOf<Any, Any>(), var id: Int = -1, var counts: LinkedTreeMap<*, *> = LinkedTreeMap<Any, Any>() ) 2. Declare a secondary constructor that has no parameters: data class Activity( var updated_on: String, var tags: List<String>, var description: String, var user_id: List<Int>, var status_id: Int, var title: String, var created_at: String, var data: HashMap<*, *>, var id: Int, var counts: LinkedTreeMap<*, *> ) { constructor():this("", emptyList(), "", emptyList(), -1, "", "", hashMapOf<Any, Any>(), -1, LinkedTreeMap<Any, Any>()) } If you don't rely on copy or equals of the Activity class or don't use the autogenerated data class methods at all you could use regular class like so: class ActivityDto { var updated_on: String = "", var tags: List<String> = emptyList(), var description: String = "", var user_id: List<Int> = emptyList(), var status_id: Int = -1, var title: String = "", var created_at: String = "", var data: HashMap<*, *> = hashMapOf<Any, Any>(), var id: Int = -1, var counts: LinkedTreeMap<*, *> = LinkedTreeMap<Any, Any>() } Not every DTO needs to be a data class and vice versa. In fact in my experience I find data classes to be particularly useful in areas that involve some complex business logic.
__label__pos
0.997396
my first oop based program This is a discussion on my first oop based program within the C++ Programming forums, part of the General Programming Boards category; i'd like to know how to make the same pointer points to differents types of vars, if you read the ... 1. #1 Registered User Join Date Jul 2010 Posts 56 my first oop based program i'd like to know how to make the same pointer points to differents types of vars, if you read the code, you'll see the comment I NEED A SOLUTION FOR THIS, and thats where im stuck... Code: #include <iostream> using namespace std; class person { public: person(); string name; int age; bool sex; // true means male string country; string sexString() { string returnString; returnString = (this->sex == true) ? "guy" : "woman" ; return returnString; } }; person::person() { this->name = "Unnamed Person"; this->age = 50; this->sex = true; this->country = "United States"; } void introduce(person person) { cout<<"Hi, my name is "<<person.name<<". I'm a "<<person.age<<" years old "<<person.sexString()<<", and I live in "<<person.country<<"."<<endl; } void callMenu(person& person) { int option; string optionIdentifier; string input; string * pointer; cout<<"\n WHAT WOULD LIKE TO CHANGE?\n"; cout<<"1. NAME\n"; cout<<"2. AGE\n"; cout<<"3. SEX\n"; cout<<"4. COUNTRY\n"; cout<<"5. NOTHING\n"; cout<<"\nCOMMAND: "; cin>>option; switch(option) { case 1: optionIdentifier = "NAME"; pointer = &person.name; break; case 2: optionIdentifier = "AGE"; //pointer = &person.age; I NEED A SOLUTION FOR THIS break; case 3: optionIdentifier = "SEX"; //pointer = &person.sex; I NEED A SOLUTION FOR THIS break; case 4: optionIdentifier = "COUNTRY"; pointer = &person.country; break; } cout<<"TYPE YOUR NEW "<<optionIdentifier<<": "; cin>>input; *pointer = input; introduce(person); } int main() { person someone; introduce(someone); callMenu(someone); cin.get(); } btw, advices for making the code cleaner are welcome 2. #2 Registered User Join Date Sep 2004 Location California Posts 3,267 Just write directly to the variable you are attempting to change. For example: Code: case 2: optionIdentifier = "AGE"; cin >> person.age; break; Also, in general it's not a good idea to make a classes member variables have public access. Read up on "encapsulation" for the reasons why. bit∙hub [bit-huhb] n. A source and destination for information. 3. #3 Chi! whiteflags's Avatar Join Date Apr 2006 Location United States Posts 8,189 I think the program is neat but isn't really OOP. Using your current Person class I could make another program that introduces a person like this: Code: person myperson; int option; cout << "1 - Change name\n"; cout << "2 - Change age\n" cout << "3 - Change gender\n"; cout << "4 - Change country\n" cout << "5 - Change nothing\n"; cout << "Choose an option - "; cin >> option; switch (option) { case 1: { cout << "Enter a new name: "; cin >> myperson.name; } break; case 2: { cout << "Enter a new age: "; cin >> person.age; } break; case 3: { string gender; cout << "Enter a new gender ("guy" or "woman"); cin >> gender; myperson.sex = gender == "guy"; } break; case 4: { cout << "Enter a new country: "; cin >> myperson.country; } break; case 5: default: break; } introduce (myperson); cin.get (); // for a pause You'll get to change one thing about him before you meet him, which is exactly how your program seems to work now. There's nothing particularly object oriented about this, anyway, but it is rather strange that person is a class that exposes its data to the rest of the program. The code sample doesn't need to be found in a main() function. I could change the details of a person anywhere, and in any way I wanted. My advice for the program is to throw it away. My advise for you is to learn more about OOP. There are no shortage of tutorials (or entire books), just STFW. Last edited by whiteflags; 08-05-2010 at 03:54 PM. 4. #4 Registered User Join Date Jul 2010 Posts 56 I've upgraded my code, i'll read about encapsulation later, thanks. I still haven't managed to make the pointer work on multiple data types though... Code: #include <iostream> using namespace std; class person { public: person(); string name; int age; bool sex; // true means male string country; string sexString() { string returnString; returnString = (this->sex == true) ? "guy" : "woman" ; return returnString; } }; person::person() { this->name = "Unnamed Person"; this->age = 50; this->sex = true; this->country = "United States"; } void introduce(person person) { cout<<"\nHi, my name is "<<person.name<<". I'm a "<<person.age<<" years old "<<person.sexString()<<", and I live in "<<person.country<<"."<<endl; cin.get(); } void callMenu(person& person) { int option; string optionIdentifier; string input; string * pointer; int numberOfChanges = 0; do{ cout<<"\n WHAT WOULD YOU LIKE TO CHANGE?\n"; cout<<"1. NAME\n"; cout<<"2. AGE\n"; cout<<"3. SEX\n"; cout<<"4. COUNTRY\n"; cout<<"5. NOTHING\n"; cout<<"\nCOMMAND: "; cin>>option; switch(option) { case 1: optionIdentifier = "NAME"; pointer = &person.name; break; case 2: optionIdentifier = "AGE"; //pointer = &person.age; break; case 3: optionIdentifier = "SEX"; //pointer = &person.sex; break; case 4: optionIdentifier = "COUNTRY"; pointer = &person.country; break; } if(option != 5) { cout<<"TYPE YOUR NEW "<<optionIdentifier<<": "; cin>>input; *pointer = input; numberOfChanges++; } }while(option != 5); introduce(person); } int main() { person someone; introduce(someone); callMenu(someone); cin.get(); } 5. #5 Registered User Join Date Sep 2004 Location California Posts 3,267 Do what I suggested in my post... bit∙hub [bit-huhb] n. A source and destination for information. 6. #6 C++まいる!Cをこわせ! Join Date Oct 2007 Posts 23,934 You can't do it your way since the data aren't all the same type. You could do it your way with a more advanced technique, but then, what is the point? bithub's example is easier, so I'd suggest you use that instead. Quote Originally Posted by Adak View Post io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions. Quote Originally Posted by Salem View Post You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much. Outside of your DOS world, your header file is meaningless. 7. #7 Registered User hk_mp5kpdw's Avatar Join Date Jan 2002 Location Northern Virginia/Washington DC Metropolitan Area Posts 3,815 Other suggestions: #1. Code: #include <iostream> using namespace std; class person { ... string name; ... string country; ... Make sure you've also got #include <string> in addition to the <iostream> header. Your implementation may pull in the necessary header for the string object to work but you really do not want to rely on this. Since you're using string containers, include the string header. #2. Code: class person { public: person(); ... }; person::person() { this->name = "Unnamed Person"; this->age = 50; this->sex = true; this->country = "United States"; } For such a constructor, the preferred method of initialization is to use something a bit different, for example: Code: class person { public: person() : name("Unnamed Person"), age(50), sex(true), country("United States") {}; ... }; #3. Code: class person { ... string sexString() { string returnString; returnString = (this->sex == true) ? "guy" : "woman" ; return returnString; } }; Member functions that do not alter the class (change the value of any of its member variables) should be declared const. The function can also be simplified a bit: Code: class person { ... string sexString() const { return sex ? "guy" : "woman" ; } }; #4. Code: void introduce(person person) { cout<<"\nHi, my name is "<<person.name<<". I'm a "<<person.age<<" years old "<<person.sexString() <<", and I live in "<<person.country<<"."<<endl; cin.get(); } When passing objects into function, prefer to use a reference parameter. Also, since the function does not do anything to alter the member variables of the passed in object, it should be passed in as const: Code: void introduce(const person& person) { cout<<"\nHi, my name is "<<person.name<<". I'm a "<<person.age<<" years old "<<person.sexString() <<", and I live in "<<person.country<<"."<<endl; cin.get(); } "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods." -Christopher Hitchens Popular pages Recent additions subscribe to a feed Similar Threads 1. Help With Based Square Root Program... By matt.s in forum C Programming Replies: 11 Last Post: 11-09-2009, 04:19 PM 2. Data Mapping and Moving Relationships By Mario F. in forum Tech Board Replies: 7 Last Post: 12-14-2006, 09:32 AM 3. BOOKKEEPING PROGRAM, need help! By yabud in forum C Programming Replies: 3 Last Post: 11-16-2006, 10:17 PM 4. OOP program example By l2u in forum C++ Programming Replies: 1 Last Post: 11-06-2006, 05:53 AM 5. My program, anyhelp By @licomb in forum C Programming Replies: 14 Last Post: 08-14-2001, 10:04 PM 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
__label__pos
0.887854
Roku Developer Program Developers and content creators—a complete solution for growing an audience directly. cancel Showing results for  Search instead for  Did you mean:  305Stream Level 7 Which URL is it? Hi there, i have a roku and i have a tv channel, I was given 3 links, which link is it that i need to add to the roku for it to work? rtsp://stream2.livestreamingservices.com/tvcristo/tvcristo Thanks! 0 Kudos 4 Replies rockou Level 7 Re: Which URL is it? Nice try at getting someone to click the links. 4K HDR TV: Samsung UN60KS8000 4K HDR Receiver: Yamaha RX-V381 4K HDR blu ray: Samsung UBD-K8500 4K HDR streamer: Roku Ultra (2016 model) 4K HDR Gaming: Xbox One X 4K HDR DVR: Directv Genie HS17-500 w/ C61K mini client Cables: Amazon Basics 18Gbps HDMI 0 Kudos 305Stream Level 7 Re: Which URL is it? What do you mean? Those are my livestreaming links,  that's why there RTMP's genius. Now can i get some support please? Thanks. 0 Kudos belltown Level 7 Re: Which URL is it? As far as I know, the Roku does not support RTMP and RTSP (your first and third links), but does support HTTP Live Streaming (your second link). Whether that link will play on the Roku though depends on many other factors, however. https://github.com/belltown/ 0 Kudos renojim Level 8 Re: Which URL is it? If you're asking how you can share that with others, you'd pretty much have to create your own channel. If you just want to watch it yourself, I think there was an IPTV channel that would let you add HLS links. By the way, why is he YELLING so much?! -JT 0 Kudos
__label__pos
0.998174
Answers Solutions by everydaycalculation.com Answers.everydaycalculation.com » Multiply fractions Multiply 28/75 with 60/75 This multiplication involving fractions can also be rephrased as "What is 28/75 of 60/75?" 28/75 × 60/75 is 112/375. Steps for multiplying fractions 1. Simply multiply the numerators and denominators separately: 2. 28/75 × 60/75 = 28 × 60/75 × 75 = 1680/5625 3. After reducing the fraction, the answer is 112/375 MathStep (Works offline) Download our mobile app and learn to work with fractions in your own time: Android and iPhone/ iPad Related: © everydaycalculation.com
__label__pos
0.894076
Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute: Sign up Here's how it works: 1. Anybody can ask a question 2. Anybody can answer 3. The best answers are voted up and rise to the top Does anyone know how I can disable ETag on IIS 7? share|improve this question up vote 1 down vote accepted Microsoft doesn't make it easy. In fact, the only way I've found to do it requires installing a 3rd party plugin. At that point, the performance benefit of removing etags is questionable. share|improve this answer      never found a good solution for it so left it alone. – Chirag Mar 16 '11 at 5:57 As I answered here (different question, same answer): Open your IIS manager, click on the server, and go to HTTP Response Headers. Click the "Add..." button, and under name, enter: ETag (case sensitive). Under Value, enter "" (thats two double quotes) And ETags begone! share|improve this answer      Even after doing that it still writes ETag:·"9111cdf83dc3cb1:0","" – Chirag Feb 3 '11 at 1:03 Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.550574
Take the 2-minute tour × Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required. I have a pipe that filters an RSS feed and removes any item that contains "stopwords" that I've chosen. Currently I've manually created a filter for each stopword in the pipe editor, but the more logical way is to read these from a file. I've figured out how to read the stopwords out of the text file, but how do I apply the filter operator to the feed, once for every stopword? The documentation states explicitly that operators can't be applied within the loop construct, but hopefully I'm missing something here. share|improve this question 2 Answers 2 You're not missing anything - the filter operator can't go in a loop. Your best bet might be to generate a regex out of the stopwords and filter using that. e.g. generate a string like (word1|word2|word3|...|wordN). You may have to escape any odd characters. Also I'm not sure how long a regex can be so you might have to chunk it over multiple filter rules. share|improve this answer In addition to Gavin Brock's answer the following Yahoo Pipes filters the feed items (title, description, link and author) according to multiple stopwords: Inputs share|improve this answer Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.606992
2 $\begingroup$ I have a set of sequences with length 8,48,480,5760,.. and would like to do sequence analysis on them. I plugged the length 8 sequence into wolframalpha: https://www.wolframalpha.com/input/?i=11,+2,+1,+8,+7,+14,+13,+4 This gives the output: Diophantine relations: 11 - 2 - 1 + 8 + 7 - 14 - 13 + 4 = 0 11 - 2 + 1 - 8 - 7 + 14 - 13 + 4 = 0 11 + 2 - 1 - 8 - 7 - 14 + 13 + 4 = 0 11^2 + 2^2 - 1^2 - 8^2 - 7^2 - 14^2 + 13^2 + 4^2 = 0 11^3 + 2^3 - 1^3 - 8^3 - 7^3 - 14^3 + 13^3 + 4^3 = 0 I exceeded the free computation time for any more processing of the larger sequences, is there a way to do the same as Wolfram|Alpha does? I can send the longer sequences if someone is able to plug them into Wolfram|Alpha Pro. Thanks. cheers, Jamie $\endgroup$ closed as off-topic by Carl Lange, MarcoB, LCarvalho, MikeLimaOscar, Alex Trounev Jun 24 at 3:10 This question appears to be off-topic. The users who voted to close gave this specific reason: • "The question is out of scope for this site. The answer to this question requires either advice from Wolfram support or the services of a professional consultant." – Carl Lange, MarcoB, LCarvalho, MikeLimaOscar, Alex Trounev If this question can be reworded to fit the rules in the help center, please edit the question. • 1 $\begingroup$ The sequence lengths sequence is OEIS sequence 5867 and this not a coincidence. Even for length 48 there are too many possibilities for naive search to check in any reasonable time. I know that the sign patterns found have a number theoretic origin. $\endgroup$ – Somos Jun 7 at 23:52 • $\begingroup$ Hi, there is a draft for the sequence here: oeis.org/draft/A308121. These 48,480,5760 length sequences are on Primorial rows, ie rows 210,2310,30030. $\endgroup$ – Jamie M Jun 8 at 2:14 2 $\begingroup$ You can use Solve for this purpose. Let v be your vector: v = {11, 2, 1, 8, 7, 14, 13, 4}; Then, to find the linear Diophantine relations: linear = Solve[ v . a == 0 && a ∈ RegionProduct @@ Prepend[ Table[Point[{{-1},{1}}],7], Point[{{1}}] ], a ] {{a -> {1, -1, -1, 1, 1, -1, -1, 1}}, {a -> {1, -1, 1, -1, -1, 1, -1, 1}}, {a -> {1, 1, -1, -1, -1, -1, 1, 1}}} Comparison: v #& /@ (a /. linear) {{11, -2, -1, 8, 7, -14, -13, 4}, {11, -2, 1, -8, -7, 14, -13, 4}, {11, 2, -1, -8, -7, -14, 13, 4}} To find the quadratic Diophantine relations: Solve[ vec^2 . a == 0 && a ∈ RegionProduct @@ Prepend[ Table[Point[{{-1},{1}}],7], Point[{{1}}] ], a ] {{a -> {1, 1, -1, -1, -1, -1, 1, 1}}} etc. $\endgroup$ • $\begingroup$ Would you be able to analyze this sequence? 27, -18, 1, 4, 23, 26, 13, 32, 19, 22, 41, 44, 31, 18, 37, 24, 27, 46, 33, 36, 23, -6, -3, 16, 19, 38, 41, 12, -1, 2, -11, 8, 11, -2, 17, 4, -9, -6, 13, 16, 3, 22, 9, 12, 31, 34, 53, 8 $\endgroup$ – Jamie M Jun 8 at 14:23 1 $\begingroup$ Another approach using Solve Clear["Global`*"] diophantine[p_Integer?Positive] := Inner[Times, coef, If[p == 1, seq, Inactive[Power][#, p] & /@ seq], Inactive[Plus]] == 0 /. Union[ Solve[ seq^p.coef == 0 && And @@ (# == -1 || # == 1 & /@ coef), coef], SameTest -> ((coef /. #1) == -(coef /. #2) &)] seq = {11, 2, 1, 8, 7, 14, 13, 4}; coef = Array[c, Length@seq]; Column[d[1] = diophantine[1]] enter image description here Verifying, And @@ (d[1] // Activate) (* True *) Column[d[2] = diophantine[2]] enter image description here Verifying, And @@ (d[2] // Activate) (* True *) Column[d[3] = diophantine[3]] enter image description here Verifying, And @@ (d[3] // Activate) (* True *) $\endgroup$ • $\begingroup$ Thanks, is there any way to reduce the memory requirements? I tried it on seq={27, -18, 1, 4, 23, 26, 13, 32, 19, 22, 41, 44, 31, 18, 37, 24, 27, 46, 33, 36, 23, -6, -3, 16, 19, 38, 41, 12, -1, 2, -11, 8, 11, -2, 17, 4, -9, -6, 13, 16, 3, 22, 9, 12, 31, 34, 53, 8} But Mathematica exited after using 16GB ram. $\endgroup$ – Jamie M Jun 8 at 13:27 Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.630738
Bash Positional Parameters and Brace Expansion Tricks Bash, the powerful command-line interface for Linux and Unix systems, offers a wealth of features for handling command-line arguments and manipulating variables. In this post, we’ll delve into positional parameters, which represent arguments passed to your script, and explore how brace expansion can unlock advanced scripting capabilities. Understanding Positional Parameters When you run a Bash script, any words you type after the script name become positional parameters. These are numbered sequentially, starting with $1, $2, and so on. You can access these parameters within your script for dynamic behavior. Brace Expansion: Your Scripting Swiss Army Knife Brace expansion, denoted by curly braces {}, is a versatile tool for generating sequences, expanding variables, and performing manipulations. Let’s dive into some common use cases: 1. Multiple-Digit Parameters For positional parameters beyond $9, you need to use braces: echo "" # Access the 10th parameter 2. Indirection with ! Indirection allows you to access a variable whose name is stored in another variable: X=ABC ABC="Hello, world!" echo "${!X}" # Output: Hello, world! 3. Default Values and Parameter Checks echo "${VAR:-default}" # If VAR is unset or null, use "default" echo "${VAR:=default}" # If VAR is unset or null, set it to "default" and use it echo "${VAR:?Error: VAR is unset or null}" # Exit with an error if VAR is unset or null 4. String Manipulation STR="Hello, world!" echo "${STR:1:4}" # Output: ello (substring starting at index 1, length 4) echo "${STR#*, }" # Output: world! (remove everything up to the first comma and space) echo "${STR%.SH}" # Output: /usr/local/bin/hotdog (remove suffix ".SH") Example Script: Positional Parameter Handling #!/bin/bash echo "Arg 1 is $1" echo "Arg 11 is " shift # Shift parameters to the left echo "Now Arg 1 is $1" echo "Now Arg 11 is " echo "Script name: $0" Output Arg 1 is A Arg 11 is K Now Arg 1 is B Now Arg 11 is L Script name: ./script.sh Explanation: The script showcases the use of $1 (the first parameter) and ${11}. The shift command moves the parameters (Arg 1 is now B since A was shifted out). Example: String Manipulation #!/bin/bash filename=/usr/local/bin/example.sh basename=${filename##*/} # Remove everything up to the last slash echo "Basename: $basename" extension=${filename##*.} # Remove everything up to the last dot echo "Extension: $extension" Output: Basename: example.sh Extension: sh Why Use Positional Parameters and Brace Expansion? • Dynamic Scripts: Handle varying inputs and adapt script behavior accordingly. • Concise Code: Brace expansion offers shortcuts for common operations. • Robustness: Parameter checks prevent unexpected script failures. Feel free to experiment with these techniques and unlock the full potential of Bash scripting! Leave a Reply Your email address will not be published. Required fields are marked *
__label__pos
0.983206
3DES CBC Шифрование в PHP с 16-байтовым ключом Я пытался сделать алгоритм 3DES в PHP. Я сделал это на Java, и он работает хорошо, но версия PHP дает мне другой результат; вот мой код: function String2Hex($string){ $hex=''; for ($i=0; $i < strlen($string); $i++){ $hex .= dechex(ord($string[$i])); } return $hex; } function hexToAscii($inputHex) { $inputHex = str_replace(' ', '', $inputHex); $inputHex = str_replace('\x', '', $inputHex); $ascii = pack('H*', $inputHex); return $ascii; } $cipher = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, ''); $iv = '0000000000000000'; $key = '75ABFD405D018A9BD0E66D23DA3B6DC8'; printf("KEY: %s\n", String2Hex($key)); $cleartext = '0436A6BFFFFFFFA8'; printf("<br>TEXT: %s\n\n", $cleartext); if (mcrypt_generic_init($cipher, hexToAscii($key), $iv) != -1) { $cipherText = mcrypt_generic($cipher, hexToAscii($cleartext)); mcrypt_generic_deinit($cipher); printf("<br><br>3DES encrypted:\n%s\n\n", strtoupper(bin2hex($cipherText))); } Это должно дать мне: 76FB62FB3AFD6677 Но это дает мне: E01BD1085F0126A2 Что я могу сделать? 1 Решение Тройной DES определен для ключей размером 192 бит (168 бит без контроля четности). Это предполагает три независимых подраздела. Поскольку у вас есть только один 128-битный код, вам нужно разделить две клавиши на три подраздела. Поскольку 3DES обычно выполняется как схема Encrypt-Decrypt-Encrypt (EDE), первый и последний подразделы могут быть одинаковыми. Если ваш текущий ключ K1 || K2тогда вы можете попробовать K1 || K2 || K1 или же K2 || K1 || K2 как окончательный ключ. Я попробовал это для вас, и первое предложение работает. Кроме того, вы забыли декодировать IV из Hex. Вот полный код: function String2Hex($string){ $hex=''; for ($i=0; $i < strlen($string); $i++){ $hex .= dechex(ord($string[$i])); } return $hex; } function hexToAscii($inputHex) { $inputHex = str_replace(' ', '', $inputHex); $inputHex = str_replace('\x', '', $inputHex); $ascii = pack('H*', $inputHex); return $ascii; } $cipher = mcrypt_module_open(MCRYPT_3DES, '', MCRYPT_MODE_CBC, ''); $iv = '0000000000000000'; //$key = '75ABFD405D018A9BD0E66D23DA3B6DC8'; $key = '75ABFD405D018A9BD0E66D23DA3B6DC875ABFD405D018A9B'; printf("KEY: %s\n", $key); $cleartext = '0436A6BFFFFFFFA8'; printf("<br>TEXT: %s\n\n", $cleartext); if (mcrypt_generic_init($cipher, hexToAscii($key), hexToAscii($iv)) != -1) { $cipherText = mcrypt_generic($cipher, hexToAscii($cleartext)); mcrypt_generic_deinit($cipher); printf("<br>3DES encrypted:\n%s\n\n", strtoupper(bin2hex($cipherText))); } Выход: КЛЮЧ: 75ABFD405D018A9BD0E66D23DA3B6DC875ABFD405D018A9B ТЕКСТ: 0436A6BFFFFFFFA8 3DES в зашифрованном виде: 76FB62FB3AFD6677 1 Другие решения Других решений пока нет …
__label__pos
0.874294
Take the 2-minute tour × Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required. To run Word/Excel/PowerPoint 2003 or 2007 in Windows XP run box. Is there any way to do this? Furthermore, does it have any arguments? share|improve this question 3 Answers 3 up vote 3 down vote accepted You can use command-line switches with parameters to run MS Office programs. The following articles explain the details: For example, if you type the following command into Run box and hit Enter, it opens a specific Excel workbook as read-only: excel.exe /r "c:\My Folder\book1.xlsx" As another example, the following command forces Excel to bypass all files that are stored in startup directories, such as the default XLStart folder located in the directory where Excel or the 2007 Microsoft Office system is installed. excel.exe /s or excel.exe /safemode share|improve this answer You can launch Office word/excel/powerpoint using the following, Word - winword Excel - excel Powerpoint - powerpnt And you could use the arguments like @Mehper C. Palavuzlar mentioned/ for example, Powerpoint - powerpnt "C:\Users\admin\test.pptx" share|improve this answer • powerpnt.exe (or powerpnt) for launching MS Powerpoint • winword.exe (or winword) for launching MS Word • excel.exe (or excel) for launching MS Excel share|improve this answer Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.998057
记录–uniapp开发安卓APP视频通话模块初实践 • 记录–uniapp开发安卓APP视频通话模块初实践已关闭评论 • 8 次浏览 • A+ 所属分类:Web前端 摘要 代码中的masterSecret需要修改为极光后台的masterSecret,appKey需要修改为极光后台的appKey 这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助 记录--uniapp开发安卓APP视频通话模块初实践 视频通话SDK用的即构的,uniapp插件市场地址 推送用的极光的,uniapp插件市场地址 即构音视频SDK uniapp插件市场的貌似是有些问题,导入不进项目,直接去官网下载,然后放到项目下的 nativeplugins 目录下,在配置文件中填入即构后台的appID和AppSign,接下来就可以开干了 准备两个页面 首页:/pages/index/index // 新建一个按钮 <button @click="sendVideo">发送视频邀请</button> // 发送事件,主动发送直接进入下一个页面即可 sendVideo(){ uni.navigateTo({ url: '/pages/call/call' }) } 通话页:pages/call/call 这个页面会复杂一点 注意这个页面为 nvue 页面 先把所有代码都列出来,再一一做说明 <template> <view> <view v-if="status === 1" class="switch-bg" :style="{'height': pageH + 'px'}"> <view class="top-info u-flex" style="flex-direction: row;"> <image src="http://cdn.u2.huluxia.com/g3/M02/32/81/wKgBOVwN9CiARK1lAAFT4MSyQ3863.jpeg" class="avatar"> </image> <view class="info u-flex u-flex-col u-col-top"> <text class="text">值班中心</text> <text class="text" style="margin-top: 10rpx;">正在呼叫</text> </view> </view> <view class="switch-handle u-flex u-row-center" style="flex-direction: row; justify-content: center;"> <image src="/static/hang_up.png" alt="记录--uniapp开发安卓APP视频通话模块初实践" class="img" @click="hangUp"></image> </view> </view> <view v-if="status === 2" class="switch-bg" :style="{'height': pageH + 'px'}"> <view class="top-info u-flex" style="flex-direction: row;"> <image src="http://cdn.u2.huluxia.com/g3/M02/32/81/wKgBOVwN9CiARK1lAAFT4MSyQ3863.jpeg" class="avatar"> </image> <view class="info u-flex u-flex-col u-col-top"> <text class="text">值班中心</text> <text class="text" style="margin-top: 10rpx;">邀请您视频聊天</text> </view> </view> <view class="switch-handle"> <view class="u-flex" style="justify-content: flex-end; flex-direction: row; padding-right: 10rpx; padding-bottom: 30rpx;"> <text style="font-size: 26rpx; color: #fff; margin: 10rpx;">切到语音接听</text> <image src="/static/notice.png" alt="记录--uniapp开发安卓APP视频通话模块初实践" style="width: 64rpx; height: 52rpx;"></image> </view> <view class="u-flex u-row-center u-row-between" style="flex-direction: row; justify-content: space-between;"> <image src="/static/hang_up.png" alt="记录--uniapp开发安卓APP视频通话模块初实践" class="img" @click="hangUp"></image> <image src="/static/switch_on.png" alt="记录--uniapp开发安卓APP视频通话模块初实践" class="img" @click="switchOn"></image> </view> </view> </view> <view v-if="status === 3" style="background-color: #232323;" :style="{'height': pageH + 'px'}"> <view style="flex-direction: row; flex-wrap: wrap;"> <zego-preview-view class="face" style="width: 375rpx; height: 335rpx;"></zego-preview-view> <view v-for="(stream, index) in streamList" :key="index" style="flex-direction: row; flex-wrap: wrap;"> <zego-view :streamID="stream.streamID" style="width: 375rpx; height: 335rpx;"></zego-view> </view> </view> <view class="switch-handle"> <view style="flex-direction: row; justify-content: center; padding-bottom: 30rpx;"> <text style="font-size: 26rpx; color: #fff; margin: 10rpx;">{{minute}}:{{seconds}}</text> </view> <view style="flex-direction: row; justify-content: space-between;"> <view style="align-items: center;"> <view class="icon-round"> <image src="/static/notice.png" alt="记录--uniapp开发安卓APP视频通话模块初实践" class="icon1" mode=""></image> </view> <text class="h-text">切到语音通话</text> </view> <view style="align-items: center;"> <image src="/static/hang_up.png" alt="记录--uniapp开发安卓APP视频通话模块初实践" class="img" @click="hangUp"></image> <text class="h-text">挂断</text> </view> <view style="align-items: center;"> <view class="icon-round" @click="changeCamera"> <image src="/static/change_camera.png" alt="记录--uniapp开发安卓APP视频通话模块初实践" class="icon2" mode=""></image> </view> <text class="h-text">转换摄像头</text> </view> </view> </view> </view> </view> </template> <script> // #ifdef APP-PLUS var jpushModule = uni.requireNativePlugin("JG-JPush") import ZegoExpressEngine from '../../zego-express-video-uniapp/ZegoExpressEngine'; import {ZegoScenario} from '../../zego-express-video-uniapp/impl/ZegoExpressDefines' import {AppID,AppSign} from '../../zegoKey.js' var instance = ZegoExpressEngine.createEngine(AppID, AppSign, true, 0); // #endif export default { data() { return { status: 1, // 1: 主动呼叫;2: 被呼叫 pageH: '', // 页面高度 innerAudioContext: null, // 音乐对象 streamList: [], msg_id: '', // 推送消息id msg_cid: '', // 推送cid roomID: 'dfmily110001', publishStreamID: uni.getStorageSync('userinfo').nickname, userID: uni.getStorageSync('userinfo').nickname, userName: uni.getStorageSync('userinfo').nickname, camera_dir: 'before', // 摄像头 before 前置,after 后置 }; }, destroyed: () => { console.log('destroyed'); ZegoExpressEngine.destroyEngine(); }, mounted() { var client = uni.getSystemInfoSync() if (client.platform == 'android') { //安卓事先请求摄像头、麦克风权限 var nativeEngine = uni.requireNativePlugin('zego-ZegoExpressUniAppSDK_ZegoExpressUniAppEngine'); nativeEngine.requestCameraAndAudioPermission(); } }, onLoad(opt) { this.getSysInfo(); this.playAudio(); if(opt.status == 2){ // 带参数 status=2时代表被呼叫 this.status = parseInt(opt.status) } if(!opt.status){ // 主动呼叫、需要发推送消息 this.getPushCid(); } this.initZegoExpress(); }, onBackPress() { // return true; this.innerAudioContext.stop(); this.logout(); }, methods: { getSysInfo() { // 获取手机信息 let sys = uni.getSystemInfoSync() this.pageH = sys.windowHeight }, playAudio() { // 播放音乐 this.innerAudioContext = uni.createInnerAudioContext(); this.innerAudioContext.autoplay = true; this.innerAudioContext.src = '/static/message.mp3'; this.innerAudioContext.onPlay(() => { console.log('开始播放'); }); }, stopAudio(){ // 停止播放音乐 if (this.innerAudioContext) { this.innerAudioContext.stop() } }, hangUp() { // 挂断 this.stopAudio(); this.sendCustomCommand(500) this.revocationPushMsg(); this.logout(); uni.navigateBack({ delta:1 }) }, switchOn() { // 接通 this.stopAudio(); this.status = 3 this.sendCustomCommand(200) }, changeCamera() { // 切换摄像头 var instance = ZegoExpressEngine.getInstance(); if (this.camera_dir == 'before') { instance.useFrontCamera(false) this.camera_dir = 'after' } else if (this.camera_dir == 'after') { instance.useFrontCamera(true) this.camera_dir = 'before' } }, sendCustomCommand(msg){ // 发送自定义信令 var instance = ZegoExpressEngine.getInstance(); instance.sendCustomCommand(this.roomID, msg, [{ "userID": this.userID, "userName": this.userName }], res => { console.log(res) }); }, getPushCid(){ // 极光推送cid获取 uni.request({ url: 'https://api.jpush.cn/v3/push/cid', header: { 'Authorization': 'Basic ' + this.encode( 'appKey:masterSecret') }, success: (res) => { this.msg_cid = res.data.cidlist[0] this.sendPushMsg(); } }) }, revocationPushMsg(){ // 撤销推送 uni.request({ url: 'https://api.jpush.cn/v3/push/' + this.msg_id, method: 'DELETE', header: { 'Authorization': 'Basic ' + this.encode( 'appKey:masterSecret') }, success: (res) => { console.log(res) } }) }, sendPushMsg(idArr) { uni.request({ url: 'https://api.jpush.cn/v3/push', method: 'POST', header: { 'Authorization': 'Basic ' + this.encode( 'appKey:masterSecret') }, data: { "cid": this.msg_cid, "platform": "all", "audience": { "registration_id": ['160a3797c8ae473a331'] }, "notification": { "alert": "邀请通话", "android": {}, "ios": { "extras": { "newsid": 321 } } } }, success: (res) => { this.msg_id = res.data.msg_id } }) }, initZegoExpress(){ // 初始化 // instance.startPreview(); instance.on('roomStateUpdate', result => { console.log('From Native roomStateUpdate:' + JSON.stringify(result)); if (result['state'] == 0) { console.log('房间断开') } else if (result['state'] == 1) { console.log('房间连接中') } else if (result['state'] == 2) { console.log('房间连接成功') } }); instance.on('engineStateUpdate', result => { if (result == 0) { console.log('引擎启动') } else if (result['state'] == 1) { console.log('引擎停止') } }); instance.on('roomStreamUpdate', result => { var updateType = result['updateType']; if (updateType === 0) { var addedStreamList = result['streamList']; this.streamList = this.streamList.concat(addedStreamList); for (let i = 0; i < addedStreamList.length; i++) { console.log('***********&&&&', addedStreamList[i].streamID) var streamID = addedStreamList[i].streamID; var instance = ZegoExpressEngine.getInstance(); instance.startPlayingStream(streamID); } } else if (updateType === 1) { this.removeStreams(result['streamList']); } }); instance.on('roomUserUpdate', result => { var updateType = result['updateType']; if (updateType === 0) { this.userID = result.userList[0].userID this.userName = result.userList[0].userName // this.userList = this.userList.concat(result['userList']); } else if (updateType === 1) { // this.removeUsers(result['userList']); } }); instance.on('IMRecvCustomCommand', result => { var fromUser = result['fromUser']; var command = result['command']; // console.log(`收到${fromUser.userID}的消息:${JSON.stringify(result)}`) if(result.command == 200){ console.log('接听视频通话') this.status = 3 this.stopAudio(); }else if(result.command == 500){ console.log('拒绝通话') uni.navigateBack({ delta: 1 }) } }); this.login(); this.publish(); }, login() { // 登录房间 var instance = ZegoExpressEngine.getInstance(); instance.loginRoom(this.roomID, { 'userID': this.userID, 'userName': this.userName }); }, logout() { // 退出房间 var instance = ZegoExpressEngine.getInstance(); instance.logoutRoom(this.roomID); this.destroyEngine(); }, publish() { // 推流 var instance = ZegoExpressEngine.getInstance(); instance.startPublishingStream(this.publishStreamID); instance.setVideoConfig({ encodeWidth: 375, encodeHeight: 336 }) }, destroyEngine() { ZegoExpressEngine.destroyEngine(boolResult => { this.streamList = []; }); }, removeStreams(removedStreams) { // 删除流 let leg = this.streamList.length for (let i = leg - 1; i >= 0; i--) { for (let j = 0; j < removedStreams.length; j++) { if (this.streamList[i]) { if (this.streamList[i].streamID === removedStreams[j].streamID) { this.streamList.splice(i, 1) continue; //结束当前本轮循环,开始新的一轮循环 } } } } }, encode: function(str) { // 对字符串进行编码 var encode = encodeURI(str); // 对编码的字符串转化base64 var base64 = btoa(encode); return base64; }, } } </script> <style lang="scss"> .switch-bg { position: relative; background-color: #6B6B6B; } .top-info { padding: 150rpx 35rpx; flex-direction: row; align-items: center; .avatar { width: 150rpx; height: 150rpx; border-radius: 10rpx; } .info { padding-left: 18rpx; .text { color: #fff; font-size: 26rpx; } } } .switch-handle { position: absolute; bottom: 100rpx; left: 0; right: 0; padding: 0 85rpx; .img { width: 136rpx; height: 136rpx; } .icon-round { align-items: center; justify-content: center; width: 136rpx; height: 136rpx; border: 1rpx solid #fff; border-radius: 50%; .icon1 { width: 64rpx; height: 52rpx; } .icon2 { width: 60rpx; height: 60rpx; } } .h-text { margin-top: 10rpx; font-size: 26rpx; color: #fff; } } </style> 说明: 代码中的masterSecret需要修改为极光后台的masterSecretappKey需要修改为极光后台的appKey view 部分: status=1 中的为主动呼叫方进入页面是初始显示内容,最重要的是 hangUp 方法,用来挂断当前邀请 status=2 中的为被邀请者进入页面初始显示的内容,有两个按钮,一个hangUp挂断,一个switchOn 接听 status=3中为接听后显示的内容(显示自己与对方视频画面) script 部分: 最开始五行是引入相关SDK的。极光推送、即构音视频 onLoad 中有一个判断语句,这个就是用于判断进入页面时是主动呼叫方还是被动答应方的,显示不同内容 if(opt.status == 2){ // 带参数 status=2时代表被呼叫 this.status = parseInt(opt.status) } if(!opt.status){ // 主动呼叫、需要发推送消息 this.getPushCid(); } sendCustomCommand 是用来在房间内发送自定义信令的,用于通知另一个人是接听了还是挂断了通话 getPushCid 是获取极光推送的cid,避免重复发送推送消息(极光推送) changeCamera 切换摄像头 revocationPushMsg 撤销推送(主动呼叫方挂断通话) sendPushMsg 发推送消息 initZegoExpress 初始化即构音视频SDK相关,与官网demo,此处我做了小改动 login 登录即构房间 logout 退出即构房间 publish 推流 destroyEngine 销毁音视频实例 removeStreams 删除流 encode base64转码 在App.vue中进行极光推送的初始化 onLaunch: function() { console.log('App Launch') // #ifdef APP-PLUS if (uni.getSystemInfoSync().platform == "ios") { // 请求定位权限 let locationServicesEnabled = jpushModule.locationServicesEnabled() let locationAuthorizationStatus = jpushModule.getLocationAuthorizationStatus() console.log('locationAuthorizationStatus', locationAuthorizationStatus) if (locationServicesEnabled == true && locationAuthorizationStatus < 3) { jpushModule.requestLocationAuthorization((result) => { console.log('定位权限', result.status) }) } jpushModule.requestNotificationAuthorization((result) => { let status = result.status if (status < 2) { uni.showToast({ icon: 'none', title: '您还没有打开通知权限', duration: 3000 }) } }) jpushModule.addGeofenceListener(result => { let code = result.code let type = result.type let geofenceId = result.geofenceId let userInfo = result.userInfo uni.showToast({ icon: 'none', title: '触发地理围栏', duration: 3000 }) }) jpushModule.setIsAllowedInMessagePop(true) jpushModule.pullInMessage(result => { let code = result.code console.log(code) }) jpushModule.addInMessageListener(result => { let eventType = result.eventType let messageType = result.messageType let content = result.content console.log('inMessageListener', eventType, messageType, content) uni.showToast({ icon: 'none', title: JSON.stringify(result), duration: 3000 }) }) } jpushModule.initJPushService(); jpushModule.setLoggerEnable(true); jpushModule.addConnectEventListener(result => { let connectEnable = result.connectEnable uni.$emit('connectStatusChange', connectEnable) }); jpushModule.addNotificationListener(result => { let notificationEventType = result.notificationEventType let messageID = result.messageID let title = result.title let content = result.content let extras = result.extras console.log(result) this.$util.router(`/pages/public/answer?status=2`) }); jpushModule.addCustomMessageListener(result => { let type = result.type let messageType = result.messageType let content = result.content console.log(result) uni.showToast({ icon: 'none', title: JSON.stringify(result), duration: 3000 }) }) jpushModule.addLocalNotificationListener(result => { let messageID = result.messageID let title = result.title let content = result.content let extras = result.extras console.log(result) uni.showToast({ icon: 'none', title: JSON.stringify(result), duration: 3000 }) }) // #endif }, 不要忘了在最开始引入极光推送的插件 var jpushModule = uni.requireNativePlugin("JG-JPush") 官方demo的代码,直接拿过来了。。 其中最重要的就是下面这段,用来监听获取推送消息的,这里如果收到推送消息自动跳转至通话页面,也就是上面status=2的状态下 jpushModule.addNotificationListener(result => { let notificationEventType = result.notificationEventType let messageID = result.messageID let title = result.title let content = result.content let extras = result.extras console.log(result) this.$util.router(`/pages/call/call?status=2`) }); https://juejin.cn/post/6954172658195906567 如果对您有所帮助,欢迎您点个关注,我会定时更新技术文档,大家一起讨论学习,一起进步。  记录--uniapp开发安卓APP视频通话模块初实践
__label__pos
0.957041
h5fromtxt(1) convert text input to an HDF5 file SYNOPSIS h5fromtxt [OPTION]... [HDF5FILE] DESCRIPTION h5fromtxt takes a series of numbers from standard input and outputs a multi-dimensional numeric dataset in an HDF5 file. HDF5 is a free, portable binary format and supporting library developed by the National Center for Supercomputing Applications at the University of Illinois in Urbana-Champaign. A single h5 file can contain multiple data sets; by default, h5fromtxt creates a dataset called "data", but this can be changed via the -d option, or by using the syntax HDF5FILE:DATASET. The -a option can be used to append new datasets to an existing HDF5 file. All characters besides the numbers (and associated decimal points, etcetera) in the input are ignored. By default, the data is assumed to be a two-dimensional MxN dataset where M is the number of rows (delimited by newlines) and N is the number of columns. In this case, it is an error for the number of columns to vary between rows. If M or N is 1 then the data is written as a one-dimensional dataset. Alternatively, you can specify the dimensions of the data explicitly via the -n size option, where size is e.g. "2x2x2". In this case, newlines are ignored and the data is taken as an array of the given size stored in row-major ("C") order (where the last index varies most quickly as you step through the data). e.g. a 2x2x2 array would be have the elements listed in the order: (0,0,0), (0,0,1), (0,1,0), (0,1,1), (1,0,0), (1,0,1), (1,1,0), (1,1,1). A simple example is: h5fromtxt foo.h5 <<EOF 1 2 3 4 5 6 7 8 EOF which reads in a 2x4 space-delimited array from standard input. OPTIONS -h Display help on the command-line options and usage. -V Print the version number and copyright info for h5fromtxt. -v Verbose output. -a If the HDF5 output file already exists, append the data as a new dataset rather than overwriting the file (the default behavior). An existing dataset of the same name within the file is overwritten, however. -n size Instead of trying to infer the dimensions of the array from the rows and columns of the input, treat the data as a sequence of numbers in row-major order forming an array of dimensions size. size is of the form MxNxLx... (with M, N, L being numbers) and may be of any dimensionality. -T Transpose the input when it is written, reversing the dimensions. -d name Write to dataset name in the output; otherwise, the output dataset is called "data" by default. Alternatively, use the syntax HDF5FILE:DATASET. BUGS Send bug reports to S. G. Johnson, [email protected] AUTHORS Written by Steven G. Johnson. Copyright (c) 2005 by the Massachusetts Institute of Technology.
__label__pos
0.899737
Java. Calculating the elapsed years, months, and days between two dates Question: Good afternoon. Date intervals are given, for example: 01/28/2009 – 03/05/2013. The task is to calculate the exact number of full years, months and days in this interval. Tell me how to do this? I just find the number of days like this Date startDate = new SimpleDateFormat("dd.MM.yyyy").parse(s1); Date endDate = new SimpleDateFormat("dd.MM.yyyy").parse(s2); Calendar calendarStart = Calendar.getInstance(); calendarStart.setTimeInMillis(startDate.getTime()); Calendar calendarEnd = Calendar.getInstance(); calendarEnd.setTimeInMillis(endDate.getTime()); long difference = calendarEnd.getTimeInMillis() - calendarStart.getTimeInMillis(); long days = difference /(24* 60 * 60 * 1000); System.out.println(days); The result should be presented as: Years: 7, Months: 5, Days: 10 Answer: It's pretty straightforward using the classes in the java.time.* Package (in Java 8 and newer): DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy"); LocalDate startDate = LocalDate.parse("28.01.2009", formatter); LocalDate endDate = LocalDate.parse("05.03.2013", formatter); Period period = Period.between(startDate, endDate); System.out.println(period.getYears()); // 4 System.out.println(period.getMonths()); // 1 System.out.println(period.getDays()); // 5 Scroll to Top
__label__pos
0.995914
Guest evaluate ∫(5cos^3(x) + 6sin^3(x)) / 2sin^2(x) cos^2(x) dx evaluate ∫(5cos^3(x) + 6sin^3(x)) / 2sin^2(x) cos^2(x) dx Grade:12 1 Answers Jitender Singh IIT Delhi askIITians Faculty 158 Points 7 years ago Ans: Hello Student, Please find answer to your question below I = \int \frac{5cos^3x+6sin^3x}{2sin^2xcos^2x}dx I = \int (\frac{5cosx}{2sin^2x}+\frac{3sinx}{cos^{2}x})dx I = \int \frac{5cosx}{2sin^2x}dx+\int \frac{3sinx}{cos^{2}x}dx I_{1} = \int \frac{5cosx}{2sin^2x}dx sinx = t cosxdx = dt I_{1} = \int \frac{5}{2t^2}dt I_{1} = \frac{-5}{2t} + c I_{1} = \frac{-5}{2sinx} + c I_{2} = \int \frac{3sinx}{cos^{2}x}dx cosx = t -sinxdx = dt I_{2} = \int \frac{-3}{t^{2}}dt I_{2} = \frac{3}{t} + d I_{2} = \frac{3}{cosx} + d I = \frac{-5}{2sinx} + \frac{3}{cosx} + c + d I = \frac{-5}{2sinx} + \frac{3}{cosx} + e Think You Can Provide A Better Answer ? Provide a better Answer & Earn Cool Goodies See our forum point policy ASK QUESTION Get your questions answered by the expert for free
__label__pos
1
A literate program embeds source code in an essay documenting the program. learn more… | top users | synonyms 2 votes 1answer 79 views F# FSharp.Literate formatted code snippet does not display correctly (.css & .js?) I'm trying to use FSharp.Literate to produce html pages. I'm working in Xamarin using Mono 4.5. I want to turn basic *.fsx scripts into html. I am using the simple script example from the ... 2 votes 0answers 97 views Off-the-shelf Common Lisp literate programming setup for Emacs/SLIME with transparent tangle and weave? [closed] Is there one? What are some viable alternatives, if any? Ideally, I would like to be able to continue using the normal SLIME workflow without resorting to any build/reload procedures. 1 vote 1answer 50 views Control indentation with Org–Babel When writing literate Python with Org–Babel, I need to be able to control the indentation level (either explicitly with :indentation-level 3 or implicitly with some clever indication). Here's an ... 2 votes 1answer 32 views Unresolved Links in scribble/lp document I'm trying to write a small example program in Racket's scribble/lp. The source for the project is on Github. The problem I am experiencing is broken links in the woven html. I've provided it as a ... 1 vote 1answer 124 views How can I implicitly organize literate code with org-mode? I'm developing a Stack Exchange mode for Emacs and I'm trying to use literate programming (with org-mode) to organize the project. I'm finding myself repeating a lot of information. I'm taking a ... 3 votes 3answers 620 views org-mode with code example as html I'm trying to embed a literate code example as HTML in Emacs org-mode. The idea is that I can use something like #+BEGIN_SRC html :noweb-ref content :exports source <span>some content ... 1 vote 3answers 148 views Non-exhaustive pattern in function-Haskell I've written a function, that Inserts an Element into a binary Tree, but every time I try to run it, I get the a non-exhaustive pattern in function. type Eintrag = (Person, Anschrift, SozNr) data ... 1 vote 1answer 84 views Is there a way to do test-driven development with literate programming? I'm learning to do my first unit tests with R, and I write my code in R Markdown files to make delivering short research reports easy. At the same time, I would like to test the functions I use in ... 2 votes 1answer 140 views using scons for literate programming Using noweb, I would either like to generate a document file (or a source file) from a noweb input file **.nw From hand I would do something like that: notangle my_program.nw > my_program.cpp g++ ... 0 votes 0answers 37 views Print user defined filename and line number when an exception occurs in Python I am using noweb for literate programming in Python. The choice has already been made and there is no going back on noweb. Now the trouble is this, whenever some error occurs in code, python prints ... 0 votes 0answers 69 views Emacs org-babel auto-loading? I'm currently learning Clojure, and I'm evaluating sample code from the book in begin_src/end_src blocks. Works quite well, as org adds structure to otherwise unrelated pieces of code. The problem ... 3 votes 1answer 67 views How to use `typed/racket` in `scribble/lp` Is it possible to use other #langs in #lang scribble/lp for literate programming? For example, I want to use #lang typed/racket in #lang scribble/lp. How to realize that? 2 votes 2answers 60 views Natural Language Programming vs. Literate Programming I can't see a difference between natural language programming and literate programming. If anyone explains, I would be grateful. 4 votes 1answer 156 views How to set up vim's identation for literate Haskell programming? When I turn on autoindent for a regular *.hs file, the after pressing Enter the new line is indented as expected. However, this doesn't work with literate Haskell *.lhs files whose code lines start ... 0 votes 2answers 139 views Can org-mode babel tangle produce leiningen directories? We want to automate the production of a Leiningen project tree entirely from an org-mode babel file. We want to do this so that we can also create beautiful, typeset documentation via ... 0 votes 1answer 104 views Linking/importing externalized source code in org-mode This paper inspired me to check out Emac's org-mode a bit and currently I try to assess what's more suitable for writing my documents: knitr/Sweave (I'm mainly using R to do my programming) or ... 5 votes 2answers 310 views How to comment out lines in literate haskell I am having trouble commenting out lines of code in an lhs-style haskell program, so both haskell and Latex ignore the line. When I use -- then my lh2tex will try to render the haskell code as a ... 11 votes 1answer 352 views Is literate programming in Haskell really “literate programming”? I'm new to the concept of literate programming. I was reading Donald Knuth's paper (PDF) concerning this subject, and in the very beginning, in the Introduction, he says: Instead of imagining that ... 1 vote 1answer 121 views Marginalia / Docco / etc for Java Maven projects? Is it possible to run Marginalia on a Java (multi-module) project which uses Maven? Or is there any other alternative that's similar to Marginalia or Docco that can do this? What's important to me ... 4 votes 1answer 135 views Conditional Compilation inside Literate Haskell I have a literate haskell file and want to use conditional compilation. I use the bird style of literate programming. The following code does not work. > #if MIN_VERSION_base(4,6,0) > import ... 10 votes 1answer 153 views Put result of code right below the code in resulting PDF. Haskell Is there any way to execute code in a .lhs file and put the result right below the code itself in the resulting PDF? For example: [1,2,3] ++ [4,5,6] [1,2,3,4,5,6] 3 votes 1answer 209 views How to hide block of code [closed] I'm writing a program in a .lhs file which contains code in Haskell (I'm specifying this because I want it to be clear that it's not only for rendering a pdf but it's also for being execute with ... 0 votes 1answer 103 views MathJax scripts not being generated by knitr::spin I'm generating an html report from a knitr::spin marked up document 1) It works doing the following > spin("document.R") Process the resulting .md file in Rstudio by clicking the "Preview ... 1 vote 2answers 118 views How to import/expand noweb refs in evaluated (exported) source blocks in org-babel? I'm trying to do something like this: * Define some functions #+begin_src python :noweb_ref defs def f1(a,b,c): return True def f2(d,e,f): return False #+end_src * Use them in a ... 3 votes 2answers 109 views How can I retain the initial white space in a line when writing Rd documentation? In conjunction with trying to find a solution for myself in regards to this question, I find myself plunged into trying to write valid Rd markup. What I want is to add a section named Raw Function ... 0 votes 2answers 70 views Is there a global flag that can be set to provide code alongside ROxygen documentation? I have taught a class in which I have had students use a package I have written. Now that the class is ending, I'd like to provide them the code for each of those functions inline with the ... 6 votes 5answers 286 views Does any literate programming environment support on the fly results? I am currently writing lots of small reports. Most of them are just value dumps with some graphs and illustrative comments. Is there a literate programming environment that let's me write my reports ... 6 votes 2answers 375 views Setting HTML meta elements with knitr I'm generating HTML reports using knitr, and I'd like to include author and generation date meta tags. My Rhtml page looks something like this. <html> <head> <meta name="author" ... 1 vote 1answer 344 views Pdflatex error when using {-“ … ”-} inline TeX comments in lhs2TeX I have the following code block in my .lhs file which uses inline TeX comments: \begin{code} main = print 0 {-"$\langle$Link$\rangle$"-} \end{code} However, after compiling with lhs2TeX, I get the ... 5 votes 2answers 215 views Examples on Literate Programming with Racket scribble/lp In addition to learning Racket I'm trying to learn literate programming. Unfortunately the Racket documentation is sparse to say the least with regards to scribble/lp. Could someone point me to some ... 1 vote 3answers 665 views How to iterate over a changing vector in Matlab, not consecutive number? I am really a beginner level at matlab. Now I want to have a loop, such that it iterates over a vector (not consecutive numbers) which contains a decreasing number of elements through iteration. For ... 9 votes 3answers 271 views How can I hide code blocks in lhs2TeX? I want to document my code using latex, but it's really annoying having all those modules and compiler extensions show up at the beginning of the latex document. Is there some flag I can pass to ... 8 votes 1answer 597 views Is there a way to knitr and produce .rmd files using the external tools function of the StatET Eclipse plugin? I'm becoming a fan of reproducible analyses and of Sweave, Beamer and specially of the knitr package. RStudio allows to Sweave and knit documents with just one click, but although RStudio is easy to ... 4 votes 3answers 1k views How to autogenerate API documentation from Express route mappings? I am developing a REST API in nodejs + Express and I have been simultaneously documenting my API in the README file and I was wondering if it is possible to automate it. e.g. given: ... 4 votes 0answers 153 views HTML anchor in noweb style literate programming by org-mode This is my simple C source code in org-mode. #+name: hello_one.c #+begin_src C :noweb tangle :tangle hello_one.c #include <stdio.h> int main() { printf("Hello, world!\n"); reurn 0; } ... 3 votes 1answer 89 views How to pipe input to a src_block as stdin ? Consider the following snippet of perl in org-babel, which uses <STDIN>. ** Ans 2 #+begin_src perl :results output use Math::Trig; $rad = <STDIN>; $circumference = ... 2 votes 1answer 78 views How to diagnose emacs lisp problems involving indirect buffers? I am using Dave Love's noweb-mode to edit a file that is a mix of LaTeX and C code. Love's mode uses his multi-mode to switch back and forth between modes. This switching is accomplished via indirect ... 1 vote 1answer 94 views Chunk arguments for noweb In nuweb, I can do something like this @d Define the chunk with argument echo "Hello, @1"; Then I can use it in other chunks by passing arguments: @d Second chunk @<Define the chunk with ... 1 vote 1answer 425 views noweb style weaving in org-babel I'm using Emacs 23 with Org 7.8.04. My code structure is as follows: #+TITLE: hello, world! #+BEGIN_SRC python :tangle yes :noweb yes <<go_function>> if __name__ == "__main__": go() ... 2 votes 1answer 233 views Cryptic error message in emacs org-mode following attempted export of file containing image-generating block of R code I have an R code block that generates an image (see below). Executing the code is no problem (i.e., C-c C-c from within the block generates an image temp.png as expected). However, on export to PDF ... 5 votes 1answer 286 views Make the source code from one code block the input to another code block in Emacs org-mode I'm getting started with org-mode and there's something I'd like to do that seems like it should be possible, but I'm having trouble figuring out. Let me describe the scenario: I have some SQL code ... 1 vote 1answer 75 views Can noweb create traversable links in latex like it does in HTML? When you generate html documents with noweb each chunk of code can be clicked when referenced elsewhere and you can jump to this definition but I'm not able to get the same functionality with the ... 1 vote 2answers 233 views Can Pweave play nice with Ruffus? I am interested in developing self-documenting pipelines. Can I wrap Ruffus tasks in Pweave chunks? Pweave and Ruffus ============================================================== **Let's see if ... 0 votes 2answers 98 views Macro in Literate programming I found that some tool such as Noweb doesn't support macro. I want to know what are the advantages and disadvantages of macro in literate programming? 5 votes 2answers 2k views Is there a way to customize output of Doxygen index.html (and latex equivalent)? I am interested in writing an "introduction" on the index.html page, rather than have blank space. Is this a feature supported by the Doxygen tool, or must I put together a hack? 0 votes 1answer 200 views Literate programming: tool to extract and run a script from source in one pass? I just started reading about literate programming and noweb - and I find it quite interesting. As far as I understand it, the 'notangle' step is the one that extracts (machine) source code (file), ... 4 votes 3answers 470 views Infuriating Tab problem in Vim, in literate Haskell I am using "Bird" style literate haskell, which requires all code to be like the following: > module Main (main) where and if I have a block it should look something like this: > main = do ... 14 votes 1answer 587 views Literate Haskell: References And Indexing Does Literate Haskell support indexing function names, typeclasses and variable references? Is there a filter I can run on Literate Haskell source that will do this and give me either a nice PDF ... 14 votes 1answer 1k views Literate Programming using org-babel I am on a literate program using org-babel. My source is structured like so, -imports -utility fns -game structure - detailed explanations This is the normal structure of the code, what I would ... 11 votes 3answers 563 views What is legal Literate Haskell? Formal Syntax somewhere? Someone had a great idea of combining Literate Haskell and Markdown. Made sense to me, so I wanted to try it. But there is something Haskell doesn't like about the Markdown '#' header syntax: Hello ...
__label__pos
0.834103
Click or drag to resize TableUpdate Function X# -- todo -- Commits changes made to a buffered row, a buffered table, cursor, or cursor adapter. Namespace:  XSharp.VFP Assembly:  XSharp.VFP (in XSharp.VFP.dll) Version: 2.19 Syntax FUNCTION TableUpdate( nRows, lForce, uArea, cErrorArray ) AS LOGIC CLIPPER Request Example View Source Parameters nRows (Optional) Type: Usual Specifies which changes made to the table or cursor should be committed. Note Note X# enables Optimistic Row Buffering by default for those cursors associated with a CursorAdapter object. The table in the remarks section describes the values for nRows. lForce (Optional) Type: Usual Determines whether X# overwrites changes made to the table or cursor by another user on a network. The table in the remarks section describes the values for lForce. uArea (Optional) Type: Usual Specifies the alias of the table or cursor in which the changes are committed. If you include a table or cursor alias, you must include the lForce argument. Or Specifies the work area of the table or cursor in which the changes are committed. If you include a work area, you must include the lForce argument. cErrorArray (Optional) Type: Usual Specifies the name of an array created when nRows = 2 and changes to a record cannot be committed. The array contains a single column containing the record numbers of the records for which changes could not be committed. If you include an array name, you must include either a table or cursor alias uArea or a work area number. Note Note If an error other than a simple commit error occurs while updating records, the first element of cErrorArray will contain –1, and you can then use AError( ) to determine the why the changes could not be committed. X# passes the value of cErrorArray, when it exists, to the CursorAdapter AfterCursorUpdate event. Return Value Type: Logic Logical data type. TableUpdate( ) returns True (.T.) if changes to all records are committed. Otherwise, TableUpdate( ) returns False (.F.) indicating a failure. An ON ERROR routine isn't executed. The AError( ) function can be used to retrieve information about the cause of the failure. Note Note TableUpdate( ) always returns True (.T.) when you are updating data, using Table Buffering, and updating the table or tables in the data source from multiple clients when setting BatchUpdateCount to a value greater than 1. Therefore, avoid setting BatchUpdateCount to a value greater than 1 in these scenarios. Remarks TableUpdate( ) cannot commit changes made to a table or cursor that does not have row or table buffering enabled. If you issue TableUpdate( ) and row or table buffering is not enabled, X# generates an error message. However, TableUpdate( ) can still commit changes to a table or cursor that has validation rules. To enable or disable row and table buffering, use CursorSetProp( ). Changes are committed to the table or cursor open in the currently selected work area if TableUpdate( ) is issued without the optional uArea arguments. If table buffering is used and multiple records are updated, TableUpdate( ) moves the record pointer to the last record updated. Note Note Calling TableUpdate( ) for a local table or view that does not use key fields generates a long Where clause to find the update row. The default number of fields supported in the Where clause is 40. If you receive the error SQL: Statement too long (Error 1812), you should either use a key field for the update or increase the complexity of the Where clause with SYS(3055). If you use the SYS(3055) function, increase its value to a number that is eight times the number of fields in the table as shown in the following example: X# 1SYS(3055, 8 * MIN(40, FCOUNT( )) When performing a batched TableUpdate( ) operation, due to the way that Open Database Connectivity (ODBC) behaves, X# is unable to detect conflicts when no error is generated by the server, yet nothing is updated, for example, no row matches the Where clause. This can occur when you use WhereType set to DB_KEYANDUPDATable, DB_KEYANDMODIFIED, or DB_KEYANDTIMESTAMP, and another user has changed one of the underlying values in the Where clause such that the row is not found by the update statement. Interaction with CursorAdapter Objects The following behaviors apply when working with CursorAdapter objects: For more information about GetFldState( ), see GetFldState( ) Function. You can also modify data in the cursor. This functionality supports scenarios such as retrieving the autoincrement value from the base table and inserting it into the cursor. When this scenario occurs, the CursorAdapter object should automatically return to the record whose changes are about to be committed after the event has occurred and commit the changes. In X# 9.0, you cannot issue the TableRevert( ) Function when a TableUpdate( ) is in operation. Typically, the CursorAdapter object uses the transaction management functionality provided by the ADO or ODBC API's and X# closes transactions when the TableUpdate( ) function completes successfully. However, if you want to send transaction management commands directly to the backend, you can set the UseTransactions property of the CursorAdaptor object to False (.F.) and the CursorAdapter does not use transactions to send Insert, Update, or Delete commands. nRowsDescription 0 If row or table buffering is enabled, commit only the changes made to the current row in the cursor. (Default) When working with CursorAdapter objects, X# executes the appropriate command in the InsertCmd, UpdateCmd, or DeleteCmd property for that row only. 1 If table buffering is enabled, commit changes made to all records to the table or cursor. If row buffering is enabled, commit only changes made to the current record in the table or cursor. When working with CursorAdapter objects, X# executes the appropriate commands in the InsertCmd, UpdateCmd, and DeleteCmd properties for each affected row. 2 Commit changes made to the table or cursor in the same manner as when nRows = 1. However, an error does not occur when a change cannot be committed. X# continues to process any remaining records in the table or cursor. If cErrorArray is included, an array containing error information is created when an error occurs. For compatibility with previous X# applications, the nRows parameter also accepts False (.F.) and True (.T.) instead of 0 and 1 respectively. When specifying 0 or 1 for nRows, the record pointer remains on the record where changes could not be committed. To determine why the changes could not be committed, use the AError( ) function. When working with CursorAdapter objects and specifying 1 or 2 for nRows, all changes made to the cursor in the following CursorAdapter events must be committed during the same call to TableUpdate( ) unless an error occurs: X# passes the values of nRows to the CursorAdapter BeforeCursorUpdate event. lForceDescription False (.F.) Commits changes to the table or cursor, starting with the first record and continuing towards the end of the table or cursor. (Default) True (.T.) Overwrites any changes made to the table or cursor by another user on a network. The Where clause uses only key fields. When working with CursorAdapter objects, X# passes the value of lForce to the following CursorAdapter events: Examples X# 1Close Databases 2Create Table employee (cLastName C(10)) 3Set MultiLocks ON // Must turn on for table buffering. 4= CursorSetProp('Buffering', 5, 'employee' ) // Enable table buffering. 5Insert Into employee (cLastName) VALUES ('Smith') 6Clear 7? 'Original cLastName value: ' 8?? cLastName // Displays current cLastName value (Smith). 9Replace cLastName WITH 'Jones' 10? 'New cLastName value: ' 11?? cLastName // Displays new cLastName value (Jones). 12= TableUpdate(.T.) // Commits changes. 13? 'Updated cLastName value: ' 14?? cLastName // Displays current cLastName value (Jones). See Also
__label__pos
0.737267
Project General Profile Feature #11156 Suggestions to update the fhicl documentation Added by Rob Kutschke almost 5 years ago. Updated almost 5 years ago. Status: Accepted Priority: Low Assignee: - Category: - Target version: - Start date: 12/15/2015 Due date: % Done: 0% Estimated time: Scope: Internal Experiment: Mu2e SSI Package: Duration: Description I just read the latest fhicl document: https://cdcvs.fnal.gov/redmine/attachments/download/29136/quick_start_v3.pdf It’s really good. I do have a few comments. 1. Page 7. A common rookie mistake is misuse of member notation. Can you find a way to make two items more visible so that they are not missed by the casual reader: 1. Member notation must start from outer-most scope # The point that you make on page 11 illustrated below: foo : { t1 : 1 t2 : @local::foo.t1 // error because initial defintiion of foo is not yet complete } 2. Page 13. I believe that arbitrary horizontal white space is permitted between the #include and the filename. The statement that the only allowed format is exactly one space was true in the initial c++ binding but was subsequently relaxed. 3. Page 13. Expand on FHCIL_FILE_PATH. export FHICL_FILE_PATH=a:b #include “foo.fcl” will look for a/foo.fcl and b/foo.fcl and will accept the first match. It does NOT look for: a/*/foo.fcl or b/*/foo.fcl, where * means an arbitrarily deep path fragment. Can you also discuss when there is a prohibition on absolute paths and give a use case to motivate that restriction. 4. Page 14. What does the following do? foo : [ 0, 1, 2 ] @erase::foo[1] 5. Page 14. Provide use cases for protect_ignore and protect_error. I can describe the Mu2e use case if you wish. 6. The document would benefit from showing a “best practices” example that makes use of many of the high end features. We might be able to build an example using the toyExperiment package. Maybe this does not belong in the document but elsewhere, perhaps in the art workbook? If so this document should link to it. My own notion of best practice is to use nested definitions in order to provide single points of maintenance: when an expert tweaks the default parameter set for their module, everyone else should get that automatically withouth having to edit their own fcl files. History #1 Updated by Kyle Knoepfel almost 5 years ago Thanks, Rob, for the suggestions. Below, I include some comments/questions I got from Gianluca a while ago: I think this will be invaluable documentation. Provided that I can convince people to read it, that is. I have a few questions... 4.2) it might be worth anticipating that this simple behaviour can be influenced by some operators at 10.2. 5.2.1) I would stress that case sensitivity is still the rule for "true" and "false". 5.2.2) what is it expected to happen assigning "infinity" to types that don't support it (e.g., C++ short)? undefined? unsupported? 5.2.4) are string not separated by spaces automatically concatenated? "What "' about '" this "" perversion?" 8) can values in the prologs be modified, rather than overridden, inside and or outside the prolog? In the example: "a.b: 12" 9) is a comment allowed at the end of an #include line? I believe I had problems with it in the past... 10.1) @erase does not apply to list elements, right? "a3: @erase" 10.2.2) I expected a1 to completely disappear, and that the showed result would be generated by having "a1.b: @erase" 10.2.3) the choice of "a.b.c: 37" might be confusing, since you are trying to assign the same value as already in. But my question is: what happens with "d.b.c: 43"? does @local::, @table and friends preserve the binding operator? (I believe they do...) #2 Updated by Kyle Knoepfel almost 5 years ago • Status changed from New to Accepted Also available in: Atom PDF
__label__pos
0.781916
How Do I Add And Remove Programs From The Command Prompt? How do you get to the control panel? Open Control Panel Swipe in from the right edge of the screen, tap Search (or if you’re using a mouse, point to the upper-right corner of the screen, move the mouse pointer down, and then click Search), enter Control Panel in the search box, and then tap or click Control Panel.. How do I add a program? How to Add Programs to Windows Start-up FolderClick the Start button, click All Programs, right-click the Startup folder, and then click Open.Open the location that contains the item you want to create a shortcut to.Right-click the item, and then click Create Shortcut. … Drag the shortcut into the Startup folder. How do I run an EXE from command prompt? open a command prompt (Start -> Run -> cmd.exe), navigate to the location of your folder using the command prompt cd command, run the .exe from there – user13267 Feb 12 ’15 at 11:05.Alternatively you can create a batch file (.bat) of two lines.More items… How do I download Windows from the command prompt? Just enter the URL into the Address bar. Or from the command line, for example, C:\windows\explorer.exe http://somewhere.com/filename.ext . You get the classic File Download prompt. How do I uninstall a program using command prompt? The removal can also be triggered from the command line. Open the Command Prompt as administrator and type “msiexec /x ” followed by the name of the “. msi” file used by the program that you want to remove. You can also add other command line parameters to control the way the uninstall is done. How do I install a program from the command prompt? How To Install Program Via Command Prompt (installation logs) If your installation file has *. … When the error occurs do not close error message. Go to “C:|Users||AppData|Local|Temp” and find MSI installation file of the program. … Copy MSI installation file of program to the root directory C:More items… What is the shortcut key of control panel? Thankfully, there are three keyboard shortcuts that will grant you quick access to the Control Panel.Windows key and the X key. This opens a menu in the lower-right corner of the screen, with Control Panel listed among its options. … Windows-I. … Windows-R to open the run command window and enter Control Panel. How do I access programs and features in Windows 10? Right-click on the Start button or press the Windows key + X keyboard combination. When the WinX menu opens, select Apps and Features. This will open the Apps & Features pane in the new Settings app. Can you trust CCleaner? While CCleaner is safe and useful for removing unused, temporary, junk and privacy related files (cache and cookies) for Internet Explorer, Firefox, Thunderbird, Chrome, Opera, Microsoft Edge, I do not recommend using the built-in registry cleaner unless you have a good understanding of the registry. How do you open Add and Remove Programs from CMD? cpl is a run command shortcut to open the Add/Remove Programs or Uninstall a Program list on Microsoft Windows XP, Vista, 7, 8, and 10. To use the appwiz. cpl command on your computer, press the Windows Key ( ) + R on your keyboard at the same time. The Run Command window should come up. How do I access control panel from command prompt? Press Windows+R to open the Run dialog, enter control panel in the empty box and click OK. Way 6: Open the app by Command Prompt. Step 1: Tap the Start button to open the Start Menu, input cmd in the search box and click Command Prompt to open it. Step 2: Type control panel in the Command Prompt window and press Enter. How do I add Control Panel to my desktop? Step 1: On the desktop, open Settings panel with Windows+I hotkeys, and then select Personalization in the panel. Step 2: Click Change desktop icons in Personalization window. Step 3: When the window of Desktop Icon Settings opens, check the small box before Control Panel and tap OK. How do I get to add Remove Programs in Windows 10? How to Uninstall Programs in Windows 10Open the Start menu.Click Settings.Click System on the Settings menu.Select Apps & features from the left pane.Select an app you wish to uninstall.Click the Uninstall button that appears. If it is grayed out, this is a system app you cannot remove.Click the Uninstall pop-up button to confirm. How do I add or remove a program? Press the Windows key, type Programs and Features or Add and remove programs, then press Enter. A window similar to that shown above should appear. From the Programs and Features section of Windows, you can uninstall a program, adjust Windows features, and view installed updates. How do you manually remove programs from the Add Remove Programs list Windows 10? After running it, click on the large “Tools” tab in the left-hand navigation pane. Within the the Tools section, select “Uninstall” and then from the list of programs select the program you wish to remove the entry for. Select the “Delete” button. What is Programs in Control Panel? The Control Panel is a component of Microsoft Windows that provides the ability to view and change system settings. It consists of a set of applets that include adding or removing hardware and software, controlling user accounts, changing accessibility options, and accessing networking settings.
__label__pos
0.990202
Uploaded image for project: 'JDK' 1. JDK 2. JDK-6780496 Javaw process taking up 80-90 percent of CPU time! XMLWordPrintable Details • b72 • x86 • windows_vista Description FULL PRODUCT VERSION : java version "1.6.0_10" Java(TM) SE Runtime Environment (build 1.6.0_10-b33) Java HotSpot(TM) Client VM (build 11.0-b15, mixed mode, sharing) ADDITIONAL OS VERSION INFORMATION : Windows Vista Home Premium with SP1 EXTRA RELEVANT SYSTEM CONFIGURATION : Acer Aspire 9420 laptop, Intel(R) Core2 CPU T5500 1.67 GHz, 32 bit, 2 GB RAM A DESCRIPTION OF THE PROBLEM :   Interesting bug I found. I am using the new transparency functionality in my software (http://www.tervola.com/DonkeyTracker). The software creates multiple instances of JDialog with rounded corners. (AWTUtilities.setWindowShape and .setTransparency). When I create new JDialog instances with rounded corners and transparency but not yet show up, the javaw process cpu time shoot up over 90 percent! BUT after creating those new JDialog instance I briefly flash all those new JDialogs (setVisibility(true)) for about 500 ms and then, javaw process will not take up 80-90 percent of CPU anymore. But without that flashing it runs constantly over 90 until I setVisibility to true for all the JDialogs. After that it runs ok! The code difference is this (flashing added: for (int c = 0; c < playerKeys.length; c++) { HUDPlayer player = (HUDPlayer) playerMap.get(playerKeys[c]); player.setVisible(true); } try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (int c = 0; c < playerKeys.length; c++) { HUDPlayer player = (HUDPlayer) playerMap.get(playerKeys[c]); player.setVisible(false); } (HUDPlayer extends JDialog implements ImageObserver, ActionListener, HUDNotesListener...) STEPS TO FOLLOW TO REPRODUCE THE PROBLEM : 1. Create multiple JDialogs 2. Set component listeners for rounding up corners 3. set transparency 4. do not show them yet and see how much time those take from CPU. EXPECTED VERSUS ACTUAL BEHAVIOR : EXPECTED - java taking 80-90 CPU time. ACTUAL - java taking 80-90 CPU time. ERROR MESSAGES/STACK TRACES THAT OCCUR : No error messages. REPRODUCIBILITY : This bug can be reproduced always. ---------- BEGIN SOURCE ---------- for (int c = 0; c < playerKeys.length; c++) { HUDPlayer player = (HUDPlayer) playerMap.get(playerKeys[c]); player.setVisible(true); } try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (int c = 0; c < playerKeys.length; c++) { HUDPlayer player = (HUDPlayer) playerMap.get(playerKeys[c]); player.setVisible(false); } (HUDPlayer extends JDialog implements ImageObserver, ActionListener, HUDNotesListener...) ---------- END SOURCE ---------- CUSTOMER SUBMITTED WORKAROUND : Show new Jdialogs with rounded corners and transparency for 500 ms and java process will not take anymore all the time of CPU. Attachments Activity People anthony Anthony Petrov (Inactive) ndcosta Nelson Dcosta (Inactive) Votes: 0 Vote for this issue Watchers: 0 Start watching this issue Dates Created: Updated: Resolved: Imported: Indexed:
__label__pos
0.939203
Finding Discrete Definition Math Online Discrete Definition Math: the Ultimate Convenience! We don’t know its nature exactly, but www.paramountessays.com/ it’s a true substance, and consists of discrete particles of the fourth purchase. Mathematicians often discuss the attractiveness of a specific proof or mathematical outcome. An infinite quantity of matter does exist, it is only very difficult to explain and visualize. The final result is that lots of developers may have difficulty finding the best technique for their problem. It’s a feeling of comparing ourselves to others I haven’t been in a position to shake. The aforementioned instance of a coin tossing experiment is only one simple case. Discrete Definition Math at a Glance There’s another issue too. Now for increased understanding it’s far better to observe the way in which the code works. Though there are different kinds of generating functions, within this lesson we’ll limit ourselves to this simpler, and very practical kind. A good example of a very simple graph is shown below. At length, a great deal of information compression uses algorithms just delight in the Fast Fourier Transform. The prior sort of graph is known as an undirected graph while the latter kind of graph is known as a directed graph. Most often these http://lynda.harvard.edu/ variables indeed represent some kind of count like the number of prescriptions an individual takes daily. A comprehensive training pass over the full data set such that each and every example was seen once. There are 3 powerful change agents which will eventually facilitate and force significant changes in our math education system. The Good, the Bad and Discrete Definition Math A number of edges are a few edges that join the exact same two vertices. Otherwise, it’s called a disconnected graph. A graph with just vertices and no edges is called an edgeless graph. Therefore, the likelihood that the full set of computable functions could be put into place by any genuine brain are zero. This way you’ll simply have to manage a single operation at a moment. To begin with, someone has usually done much of the task for you. Taking extra steps is not too helpful, but here is among those examples. Even though you’ll have a 50 marks theory paper, which is very simple to prepare. Here are some examples to demonstrate how NatLaTeX works. Physics doesn’t study something which cannot possibly exist. Mathematics doesn’t have anything to do with Physics. General Relativity isn’t about warped space. Programming has given me the tools to learn to learn. Computing machines don’t have such constraints. It’s always simpler to believe that Machine Learning is not easy to learn. Collaboration, thus, is an important portion of the training course. This diagram is particularly helpful in discussions of the present K-12 mathematics curriculum. That’s the significance of a constant in Mathematics. This point is precisely the same distance from each one of the 3 sides of the triangle. There continue to be some like terms, but they’re on opposite surfaces of the equal sign. For instance, a coin toss can be a heads or tails. Grades on a test can vary from 0 to 100% with each possible percentage between. C Working in groups, students produce and explain an acceptable means of sharing mathematics. Some students don’t make these connections by themselves. The problem sets are instructive, and frequently wind up teaching new material outside class. Give each question a good effort before you begin to look at the solution manual or asking someone for support. To begin with, someone has usually done much of the task for you. New Ideas Into Discrete Definition Math Never Before Revealed Physics doesn’t study something which cannot possibly exist. Inside this chapter, we’ll cover the various aspects of Set Theory. Set theory is considered to be among the chief branches of computer science. Now let’s look at an issue that involves unit price. The market’s major function will then be to reflect true rates, in place of generating profit. The exact first region of the sum above is our routine cost function. We don’t know its nature how to write a dissertation exactly, but it’s a true substance, and consists of discrete particles of the fourth purchase. Mathematicians often discuss the attractiveness of a specific proof or mathematical outcome. Therefore, a resolution-limit seems required to steer clear of the issue with infinities in the growth of quantum gravity. Try to aid students understand how to approach challenging difficulties. Naturally, students want to be aware of the significance of basic math terms before they can discover how to apply them to math principles. Our students eagerly take part in national contests. To begin with, the program is completely free. It’s possible to find out more about recurrence formulas in an enjoyable course called discrete mathematics. You can opt to sit through the training class. Leave a Comment
__label__pos
0.87489
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. Join them; it only takes a minute: Sign up Here's how it works: 1. Anybody can ask a question 2. Anybody can answer 3. The best answers are voted up and rise to the top A lot of solutions to problems say that for a cyclic group, such as $\mathbb{Z}/\mathbb{Z}_3$, $\mathbb{Z}/\mathbb{Z}_{10}$, etc., a group homomorphism $\phi$ from $\mathbb{Z}/\mathbb{Z}_m$ to $\mathbb{Z}/\mathbb{Z}_n$ is determined by $\phi(1)$, but I never really understood why... can someone help me? Thanks so much in advance! share|cite|improve this question Because $\Bbb Z/n\Bbb Z$ is generated by $1$. Thus, $\varphi(2)=\varphi(1+1)=\varphi(1)+\varphi(1)$, and similarly for every other element of $\Bbb Z/n\Bbb Z$. share|cite|improve this answer      Thanks, this all makes sense but I guess my question is more what exactly does φ(1) determine and tell us specifically about this specific homomorphism? I am so lost =/ – arcastar Oct 11 '12 at 5:36      @arcastar: $\varphi(1)$ completely determines the homomorphism. This simply means that if you know $\varphi(1)$, then you know $\varphi(a)$ for every $a\in\Bbb Z/n\Bbb Z$; in other words, you know the whole function. That one value pins down every value, leaving no wiggle room. – Brian M. Scott Oct 11 '12 at 5:38      I just got the notification for this new post, so postponed. But thank you so much! It was really helpful! – arcastar Oct 11 '12 at 6:52 Hint: For example $$\varphi(2)=\varphi(1+1)=\varphi(1)+\varphi(1)$$ share|cite|improve this answer Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.958893
PHP base_convert函数的一个有趣现象 标签: , , , , , PHP 的 base_convert 函数能在任意进制之间转换数字,这是常识。那么请你不要实际运行,用常识判断一下,这句代码运行的结果: echo base_convert('http://demon.tw', 16, 10); 如果你的答案是 222,那么恭喜你答对了,其实上面那句代码跟这句是一样的: echo base_convert('de', 16, 10); 也就是说,base_convert 函数会忽略掉该进制以外的其他字符。下面通过 base_convert 函数的 C 源码来分析原因,base_convert 函数定义在 PHP 源码的 ext/standard/math.c 中: /* {{{ proto string base_convert(string number, int frombase, int tobase) Converts a number in a string from any base <= 36 to any base <= 36 */ PHP_FUNCTION(base_convert) { zval **number, **frombase, **tobase, temp; char *result; if (ZEND_NUM_ARGS() != 3 || zend_get_parameters_ex(3, &number, &frombase, &tobase) == FAILURE) { WRONG_PARAM_COUNT; } convert_to_string_ex(number); convert_to_long_ex(frombase); convert_to_long_ex(tobase); if (Z_LVAL_PP(frombase) < 2 || Z_LVAL_PP(frombase) > 36) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid `from base' (%ld)", Z_LVAL_PP(frombase)); RETURN_FALSE; } if (Z_LVAL_PP(tobase) < 2 || Z_LVAL_PP(tobase) > 36) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid `to base' (%ld)", Z_LVAL_PP(tobase)); RETURN_FALSE; } if(_php_math_basetozval(*number, Z_LVAL_PP(frombase), &temp) != SUCCESS) { RETURN_FALSE; } result = _php_math_zvaltobase(&temp, Z_LVAL_PP(tobase) TSRMLS_CC); RETVAL_STRING(result, 0); } 前面几行都是解析和校验参数是否正确,关键代码是 _php_math_basetozval 和 _php_math_zvaltobase 函数,_php_math_basetozval 定义如下: /* {{{ _php_math_basetozval */ /* * Convert a string representation of a base(2-36) number to a zval. */ PHPAPI int _php_math_basetozval(zval *arg, int base, zval *ret) { long num = 0; double fnum = 0; int i; int mode = 0; char c, *s; long cutoff; int cutlim; if (Z_TYPE_P(arg) != IS_STRING || base < 2 || base > 36) { return FAILURE; } s = Z_STRVAL_P(arg); cutoff = LONG_MAX / base; cutlim = LONG_MAX % base; for (i = Z_STRLEN_P(arg); i > 0; i--) { c = *s++; /* might not work for EBCDIC */ if (c >= '0' && c <= '9') c -= '0'; else if (c >= 'A' && c <= 'Z') c -= 'A' - 10; else if (c >= 'a' && c <= 'z') c -= 'a' - 10; else continue; if (c >= base) continue; switch (mode) { case 0: /* Integer */ if (num < cutoff || (num == cutoff && c <= cutlim)) { num = num * base + c; break; } else { fnum = num; mode = 1; } /* fall-through */ case 1: /* Float */ fnum = fnum * base + c; } } if (mode == 1) { ZVAL_DOUBLE(ret, fnum); } else { ZVAL_LONG(ret, num); } return SUCCESS; } /* }}} */ 代码太长看起来很烦,关键是这一段: for (i = Z_STRLEN_P(arg); i > 0; i--) { c = *s++; /* might not work for EBCDIC */ if (c >= '0' && c <= '9') c -= '0'; else if (c >= 'A' && c <= 'Z') c -= 'A' - 10; else if (c >= 'a' && c <= 'z') c -= 'a' - 10; else continue; if (c >= base) continue; 遍历字符串,碰到除了 [0-9a-zA-Z] 以外的字符只是用 continue 直接跳到下一次循环,所以其他字符并不影响进制的转换。而且当 c 大于 base 时也是直接跳到下一次循环,所以该进制以外的其他字母亦不会影响进制的转换。这是 base_convert 函数的一个 BUG 呢,还是设计者有意为之? 随机文章: 1. 用VBS枚举素数(质数) 2. 工行网银使用U盾时提示“请选择您要用的证书” 3. VbsEdit正版序列号 4. WMI入门教程:第一部分 5. VBS Scripting.Dictionary字典对象按键名Key进行冒泡排序 留下回复
__label__pos
0.99273
Question The 6th grade is trying to raise $500 for a new 3D printer. So far, they have raised $235. What percentage of the money has the 6th grade already raised? 1. The answer is 47% If you take the amount of money raised ($235) and put it over the total amount of money ($500), 235/500 will result in the decimal 0.47, and you can change that to a percentage by moving the decimal two places to the right Reply Leave a Comment
__label__pos
0.999824
Question The following table shows scores on the first quiz (maximum score 10 points) for eighth-grade students in an introductory level French course. The instructor grouped the students in the course as follows: Group 1: Never studied foreign language before but have good English skills Group 2: Never studied foreign language before and have poor English skills Group 3: Studied at least one other foreign language a. Defining notation and using results obtained with software, also shown in the table, report the five steps of the ANOVA test. b. The sample means are quite different, but the P-value is not small. Name one important reason for this. c. Was this an experimental study, or an observational study? Explain how a lurking variable could be responsible for Group 3 having a larger mean than the others. (Thus, even if the P-value were small, it is inappropriate to assume that having studied at least one foreign language causes one to perform better on this quiz.) $1.99 Sales0 Views116 Comments0 • CreatedSeptember 11, 2015 • Files Included Post your question 5000 
__label__pos
0.893476
Matemática yasminaasilva 1 *Seja R a região sombreada na figura* R é o conjunto dos pontos (x,y) do plano cartesiano,com y > 0 tais que: +0 (1) Respostas Grasielegomes Olá! Está um pouco complicado de visualizar as alternativas da questão, mas vamos lá: Primeiramente é preciso analisar dois pontos de cada uma das retas: Reta 1: Passa pelos pontos ( -2, 0 ) e ( 0, 3 ) Reta 2:  Passa pelos pontos ( 1, 0 ) e ( 0, 3 ) Agora utilizaremos a seguintes expressão, para ambas as retas: ( y - y1) / ( y2 - y1 ) = ( x - x1 ) / ( x2 - x1 ) Aplicando para a primeira reta: ( y - 0 ) / ( 3 - 0 ) = ( x + 2 ) / ( 0 + 2 )  y = ( 3/2 ) * x + 3 Para a segunda reta: ( y - 0 ) / ( 3 - 0 ) = ( x - 1 ) / ( 0 - 1 )  y = - 3x + 3 Adicionar resposta
__label__pos
0.978631
Software Macro A Software Macro is a software operator that ... References 2015 • (Wikipedia, 2015) ⇒ http://en.wikipedia.org/wiki/macro_(computer_science) Retrieved:2015-2-13. • A macro (short for "macroinstruction", from Greek 'long') in computer science is a rule or pattern that specifies how a certain input sequence (often a sequence of characters) should be mapped to a replacement output sequence (also often a sequence of characters) according to a defined procedure. The mapping process that instantiates (transforms) a macro use into a specific sequence is known as macro expansion. A facility for writing macros may be provided as part of a software application or as a part of a programming language. In the former case, macros are used to make tasks using the application less repetitive. In the latter case, they are a tool that allows a programmer to enable code reuse or even to design domain-specific languages. Macros are used to make a sequence of computing instructions available to the programmer as a single program statement, making the programming task less tedious and less error-prone. (Thus, they are called "macros" because a big block of code can be expanded from a small sequence of characters.) Macros often allow positional or keyword parameters that dictate what the conditional assembler program generates and have been used to create entire programs or program suites according to such variables as operating system, platform or other factors. The term derives from “macro instruction", and such expansions were originally used in generating assembly language code.
__label__pos
0.693994
Get the current logged in user id Introduction In order to get the Id of the current logged in user using ASP.NET Identity, we use the GetUserId method. GetUserId The GetUserId method returns the user id for the current HTTP request. string userId = User.Identity.GetUserId(); Namespace In order to use the GetUserId method, you have to include the following namespace : using Microsoft.AspNet.Identity;
__label__pos
0.572124
Answers 2016-03-17T21:55:09+05:30 Let the speed of the stream be x km/hr Therefore the speed of of boat upstream is 24-x km/hr and speed of the boat downstream is 24-x km/hr. time= distance/speed 32/(24-x)  - 32/ (24+x)  = 1 Solve this and you'll get the speed. 0 2016-03-20T23:55:11+05:30 Total Distance = 32km Speed in Still Water = 24km/hr Let the speed of stream be 'x' kmph then, Speed moving upstream = 24-x          Speed moving downstream = 24+x We know that \frac{Distance}{Speed} \frac  is time  </span>{32}{24-x} - \frac{32}{24+x} = 1 On reducing it to a quadratic equation, we get - x^{2} + 64x-576=0 On solving it by splitting the middle term method (8&72 as factors) we get, x = 8 or -72 Since, the speed cannot be negative, x = 8 Therefore, the speed of the stream is 8 km/hr 1 3 1 Sorry, there is a mistake after </span> text, its actually -> 32/(24-x) - 32/(24+x) = 1
__label__pos
0.990799
There are multiple versions of this document. Pick the options that suit you best. UI Database Web Application Development Tutorial - Part 6: Authors: Domain Layer Introduction In the previous parts, we've used the ABP infrastructure to easily build some services; • Used the CrudAppService base class instead of manually developing an application service for standard create, read, update and delete operations. • Used generic repositories to completely automate the database layer. For the "Authors" part; • We will do some of the things manually to show how you can do it in case of need. • We will implement some Domain Driven Design (DDD) best practices. The development will be done layer by layer to concentrate on an individual layer in one time. In a real project, you will develop your application feature by feature (vertical) as done in the previous parts. In this way, you will experience both approaches. The Author Entity Create an Authors folder (namespace) in the Acme.BookStore.Domain project and add an Author class inside it: using System; using JetBrains.Annotations; using Volo.Abp; using Volo.Abp.Domain.Entities.Auditing; namespace Acme.BookStore.Authors; public class Author : FullAuditedAggregateRoot<Guid> { public string Name { get; private set; } public DateTime BirthDate { get; set; } public string ShortBio { get; set; } private Author() { /* This constructor is for deserialization / ORM purpose */ } internal Author( Guid id, string name, DateTime birthDate, string? shortBio = null) : base(id) { SetName(name); BirthDate = birthDate; ShortBio = shortBio; } internal Author ChangeName(string name) { SetName(name); return this; } private void SetName(string name) { Name = Check.NotNullOrWhiteSpace( name, nameof(name), maxLength: AuthorConsts.MaxNameLength ); } } • Inherited from FullAuditedAggregateRoot<Guid> which makes the entity soft delete (that means when you delete it, it is not deleted in the database, but just marked as deleted) with all the auditing properties. • private set for the Name property restricts to set this property from out of this class. There are two ways of setting the name (in both cases, we validate the name): • In the constructor, while creating a new author. • Using the ChangeName method to update the name later. • The constructor and the ChangeName method is internal to force to use these methods only in the domain layer, using the AuthorManager that will be explained later. • Check class is an ABP utility class to help you while checking method arguments (it throws ArgumentException on an invalid case). AuthorConsts is a simple class that is located under the Authors namespace (folder) of the Acme.BookStore.Domain.Shared project: namespace Acme.BookStore.Authors; public static class AuthorConsts { public const int MaxNameLength = 64; } Created this class inside the Acme.BookStore.Domain.Shared project since we will re-use it on the Data Transfer Objects (DTOs) later. AuthorManager: The Domain Service Author constructor and ChangeName methods are internal, so they can be used only in the domain layer. Create an AuthorManager class in the Authors folder (namespace) of the Acme.BookStore.Domain project: using System; using System.Threading.Tasks; using JetBrains.Annotations; using Volo.Abp; using Volo.Abp.Domain.Services; namespace Acme.BookStore.Authors; public class AuthorManager : DomainService { private readonly IAuthorRepository _authorRepository; public AuthorManager(IAuthorRepository authorRepository) { _authorRepository = authorRepository; } public async Task<Author> CreateAsync( string name, DateTime birthDate, string? shortBio = null) { Check.NotNullOrWhiteSpace(name, nameof(name)); var existingAuthor = await _authorRepository.FindByNameAsync(name); if (existingAuthor != null) { throw new AuthorAlreadyExistsException(name); } return new Author( GuidGenerator.Create(), name, birthDate, shortBio ); } public async Task ChangeNameAsync( Author author, string newName) { Check.NotNull(author, nameof(author)); Check.NotNullOrWhiteSpace(newName, nameof(newName)); var existingAuthor = await _authorRepository.FindByNameAsync(newName); if (existingAuthor != null && existingAuthor.Id != author.Id) { throw new AuthorAlreadyExistsException(newName); } author.ChangeName(newName); } } • AuthorManager forces to create an author and change name of an author in a controlled way. The application layer (will be introduced later) will use these methods. DDD tip: Do not introduce domain service methods unless they are really needed and perform some core business rules. For this case, we needed this service to be able to force the unique name constraint. Both methods checks if there is already an author with the given name and throws a special business exception, AuthorAlreadyExistsException, defined in the Acme.BookStore.Domain project (in the Authors folder) as shown below: using Volo.Abp; namespace Acme.BookStore.Authors; public class AuthorAlreadyExistsException : BusinessException { public AuthorAlreadyExistsException(string name) : base(BookStoreDomainErrorCodes.AuthorAlreadyExists) { WithData("name", name); } } BusinessException is a special exception type. It is a good practice to throw domain related exceptions when needed. It is automatically handled by the ABP and can be easily localized. WithData(...) method is used to provide additional data to the exception object that will later be used on the localization message or for some other purpose. Open the BookStoreDomainErrorCodes in the Acme.BookStore.Domain.Shared project and change as shown below: namespace Acme.BookStore; public static class BookStoreDomainErrorCodes { public const string AuthorAlreadyExists = "BookStore:00001"; } This is a unique string represents the error code thrown by your application and can be handled by client applications. For users, you probably want to localize it. Open the Localization/BookStore/en.json inside the Acme.BookStore.Domain.Shared project and add the following entry: "BookStore:00001": "There is already an author with the same name: {name}" Whenever you throw an AuthorAlreadyExistsException, the end user will see a nice error message on the UI. IAuthorRepository AuthorManager injects the IAuthorRepository, so we need to define it. Create this new interface in the Authors folder (namespace) of the Acme.BookStore.Domain project: using System; using System.Collections.Generic; using System.Threading.Tasks; using Volo.Abp.Domain.Repositories; namespace Acme.BookStore.Authors; public interface IAuthorRepository : IRepository<Author, Guid> { Task<Author> FindByNameAsync(string name); Task<List<Author>> GetListAsync( int skipCount, int maxResultCount, string sorting, string filter = null ); } • IAuthorRepository extends the standard IRepository<Author, Guid> interface, so all the standard repository methods will also be available for the IAuthorRepository. • FindByNameAsync was used in the AuthorManager to query an author by name. • GetListAsync will be used in the application layer to get a listed, sorted and filtered list of authors to show on the UI. We will implement this repository in the next part. Both of these methods might seem unnecessary since the standard repositories already provide generic querying methods and you can easily use them instead of defining such custom methods. You're right and do it like in a real application. However, for this "learning" tutorial, it is useful to explain how to create custom repository methods when you really need it. Conclusion This part covered the domain layer of the authors functionality of the book store application. The main files created/updated in this part was highlighted in the picture below: bookstore-author-domain-layer Contributors Last updated: August 05, 2024 Edit this page on GitHub Was this page helpful? Please make a selection. To help us improve, please share your reason for the negative feedback in the field below. Please enter a note. Thank you for your valuable feedback! Please note that although we cannot respond to feedback, our team will use your comments to improve the experience. In this document Community Talks ABP Studio: The Missing Tool for .NET Developers 15 Aug, 17:00 Online Watch the Event Mastering ABP Framework Book Mastering ABP Framework This book will help you gain a complete understanding of the framework and modern web application development techniques. Learn More
__label__pos
0.966845
Explain about spiral model, Software Engineering Q. Explain about Spiral Model? The Spiral model is one of the well-liked model used for large projects. This model was projected by Boehm in 1988 and it focuses on minimizing the risk through the use of prototype. We are able to view the Spiral Model as a waterfall model with each stage preceded by Risk analysis stage. The model is separated into four quadrants each with a specific purpose as shown in the fig. Every spiral represents the progress made in the project. In the first quadrant objectives and alternative means to develop product and constraints imposed on the products are identified. The next quadrant compact with identification of risk and strategies to resolve the risks. The third bottom right quadrant goes after the waterfall model. In the bottom left quadrant customer calculates the product requirements are further refined. If at a few stage during the project risk cannot be resolved project is terminated. The model is utilized if the requirements are very complex or several new technology is being introduced by the company. Advantages: 1. The model tries to resolve every possible risk involved in the project. 2. Every phase of the model enhances the quality of the product. Disadvantages: 1. The model is suitable merely for large size projects because in some cases the cost of risk analysis may perhaps exceed the actual cost of the project. 2. Expertise in risk management along with project management is essential. 843_Explain about Spiral Model.png   Spiral Model Posted Date: 7/26/2013 3:22:18 AM | Location : United States Related Discussions:- Explain about spiral model, Assignment Help, Ask Question on Explain about spiral model, Get Answer, Expert's Help, Explain about spiral model Discussions Write discussion on Explain about spiral model Your posts are moderated Related Questions Draw E-R diagram for the following situation An account is a relationship between customer and bank. A customer has a name. A bank has a branch. A customer may have numerous ac Discuss in details the design steps in transaction mapping. Re-Check the fundamental model. Re-check and refine the DFD for the software. Determine the DFD has either Level 2 (Repeatable) Organisation satisfies all the requirements of level-1. At this stage, basic project management policies and associated procedures are established. Insti m2+m3+m5+m7+m12+m8+m9 simplify using k-map Define software reliability. What is the difference between hardware & software reliability? Ans: Software reliability is the possibility that software will provide failure-f What does it mean by business process engineering tools ? as software project manager in company specialized on offshore oil industry have been tasked to discover factors affecting mantainability of the system developed by the company.wh List the process maturity levels in SEIs CMM. Level 1: Initial - Few processes are explained and individual efforts are taken. Level 2: Repeatable - To track cost schedul Q. Compare CMM with ISO 9001 ? 1: Management responsibility: ISO 9001 needs that the quality policy be defined and documented and understood as well implemented and maintaine
__label__pos
0.965759
Главная Алгебра 7 класс А.Г.Мордкович, Л.А.Александрова, Т.Н.Мишустина, Е.Е.Тульчинская ГДЗ учебник по алгебре 7 класс А.Г.Мордкович, Л.А.Александрова, Т.Н.Мишустина, Е.Е.Тульчинская авторы: , , , . издательство: "Мнемозина" 2013 г Раздел: Номер №11.5. Является ли пара чисел (60;30) решением системы уравнений: а) { 4 x 7 y = 30 , 4 x 5 y = 90 ; б) { 3 x + 5 y = 330 , 6 x 8 y = 110 ? Решение а { 4 x 7 y = 30 4 x 5 y = 90 { 4 60 7 30 = 240 210 = 30 4 60 5 30 = 240 150 = 90 { 30 = 30 90 = 90 Ответ: является Решение б { 3 x + 5 y = 330 6 x 8 y = 110 { 3 60 + 5 30 = 180 + 150 = 330 6 x 8 y = 6 60 8 30 = 360 240 = 110 { 330 = 330 120 110 Ответ: не является
__label__pos
0.996187
Skip navigation links org.openide.loaders 7.71.1 Package org.openide.loaders Datasystems are the logical layer between a filesystem and higher-level file-oriented operations. See: Description Package org.openide.loaders Description Datasystems are the logical layer between a filesystem and higher-level file-oriented operations. The Datasystems API provides a higher-level view of files in terms of useful data - data which has specific types, actions that can be performed on these types, and relationships to other files. For example, NetBeans might find these files in a newly-opened directory: Logically, all of these files are interlinked, and it is the job of a data loader to associate them. In this case, a loader installed by the Form Editor into the system's loader pool would recognize the common basename of the files, and produce a special data object which encapsulates that there is a Java source with an accompanying form and compiled class files. This data object would then provide operations appropriate to a form on disk, and assist in creating an Explorer node subtree for it. Skip navigation links org.openide.loaders 7.71.1
__label__pos
0.58983
4 Hours To Years Answer: 4 hours is equal to 0.00045662100456621 years. Solution : To start Hours/Years conversion first need to know 1 Hours is how many Years ? 1 Hours = 0.00011415525114155 Years Then,to find how many years multiply 0.00011415525114155 with 4. 4 X 0.00011415525114155 = 0.00045662100456621 So , the answer is 0.00045662100456621 years. 4 Hours In Years Conversion Questions : Calculate 4 hours to years = 0.00045662100456621 years How many years are in 4 hours = 0.00045662100456621 years 4 hours is how many years = 0.00045662100456621 years Time Calculator Tool Time Conversions: Time Calculator | TimeCalculator.info A time calculator is a useful tool that can be utilized in various settings such as school, business life, and in real life. This tool provides an easy and quick way to calculate time differences, add or subtract time from a given date, and convert time between different units. Let's take a closer look at how a time calculator can be used in these different settings. In school, time calculators can be used to calculate the duration of an assignment or project. For example, a student may need to know how long it will take to complete a research paper that is due in three weeks. Using a time calculator, they can easily determine the number of hours they need to allocate each day to complete the project on time. Time calculators can also be used in math and science classes to calculate time-based equations or problems. In business life, time calculators can be used to manage schedules and deadlines. For example, a project manager may need to know the number of days between the start and end dates of a project to ensure that it is completed on time. They can also use a time calculator to determine the duration of specific tasks or activities within the project. Time calculators can also be useful for scheduling meetings and appointments, ensuring that everyone is on the same page with regards to the time and duration of the meeting. In real life, time calculators can be used to manage personal schedules and activities. For example, if someone wants to start a workout regimen, they can use a time calculator to determine the amount of time they need to dedicate each day to meet their fitness goals. A time calculator can also be used to calculate the duration of a road trip or vacation, helping to ensure that all necessary activities are included and accounted for in the schedule. In conclusion, time calculators are versatile tools that can be used in a variety of settings such as school, business life, and real life. They provide an easy and quick way to calculate time differences, add or subtract time from a given date, and convert time between different units. Whether you're a student, a project manager, or an individual looking to manage your personal schedule, a time calculator can help you stay on top of your tasks and activities. Time Units To Calculate : There are several time units that can be used to measure time, and here are some of the most common ones along with their meanings: 1. Second - the base unit of time in the International System of Units (SI), defined as the duration of 9,192,631,770 periods of the radiation corresponding to the transition between two hyperfine levels of the ground state of the caesium-133 atom. 2. Minute - a unit of time equal to 60 seconds. 3. Hour - a unit of time equal to 60 minutes or 3,600 seconds. 4. Day - a unit of time equal to 24 hours or the time it takes for one rotation of the Earth on its axis. 5. Week - a unit of time equal to seven days. 6. Month - a unit of time based on the lunar cycle and typically defined as either 28, 29, 30, or 31 days. 7. Year - a unit of time equal to the time it takes for the Earth to complete one revolution around the Sun, typically defined as 365 or 366 days. Time units calculation tool. About Us | Contact | Privacy Copyright 2023 - © TimeCalculator.info
__label__pos
0.992936
   802.1X | Wi-Fi Radio Types 802.1X, also known as EAPOL, for EAP over LAN, is a basic protocol supported by enterprise-grade Wi-Fi networks, as well as modern wired Ethernet switches and other network technologies. The idea behind 802.1X is to allow the user's device to connect to the network as if the RADIUS server and advanced authentication systems did not exist, but to then block the network link for the device for all other protocols except 802. IX, until authentication is complete. The network's only requirements are twofold: prevent all data traffic from or to the client except for EAPOL (using Ethernet protocol 0×888E) from passing; and taking the EAPOL frames, removing the EAP messages embedded within, and tunneling those over the RADIUS protocol to the AAA server. The job of the network, then, is rather simple. However, the sheer number of protocols can make the process seem complex. We'll go through the details slowly. The important thing to keep in mind is that 802.1X is purely a way of opening what acts like a direct link between the AAA server and the client device, to allow the user to be authenticated by whatever means the AAA server and client deem necessary. The protocols are all layered, allowing the highest-level security protocols to ride on increasingly more specific frames that each act as blank envelopes for its contents. Once the AAA server and the client have successfully authenticated, the AAA server will use its RADIUS link to inform the network that the client can pass. The network will tear down its EAPOL-only firewall, allowing generic data traffic to pass. In the same message that the AAA server tells the network to allow the client (an EAP Success), it also passes the PMK—the master key that the client also has and will be used for encryption—to the network, which can then drop into the four-way handshake to derive the PTK and start the encrypted channel. This PMK exchange goes in an encrypted portion of the EAP response from the RADIUS server, and is removed when the EAP Success is forwarded over the air. The encryption is rather simple, and is based on the shared password that the RADIUS server and controller or access point have. Along with the PMK comes a session lifetime. The RADIUS server tells the controller or access point how long the authentication, and subsequent use of the keys derived from it, is valid. Once that time expires, both the access point and the client are required to erase any knowledge of the key, and the client must reauthenticate using EAP to get a new one and continue using the network. For network administrators, it is important to keep in mind that the EAP traffic in EAPOL is not encrypted. Because the AAA server and the client have not agreed on the keys yet, all of the traffic between the client and the RADIUS server can be seen by passive observers. This necessarily limits the EAP methods—the specific types of authentication—that can be used. For example, in the early days of 802.1X, an EAP method known as EAP-MD5 was used, where the user typed a password (or the client used the user's computer account password), which was then hashed with the MD5 one-way cryptographic hash algorithm, and then sent across the network. Now, MD5 is flawed, but is still secure enough that an attacker would have a very hard time reverse-engineering the password from the hash of it. However, the attacker wouldn't need to do this, as he could just replay the same MD5 hashed version himself, as if he were the original user, and gain access to the network. For this reason, no modern wireless device supports EAP-MD5 for wireless authentication. No comments: Telecom Made Simple Related Posts with Thumbnails  
__label__pos
0.516635
Data Meeting Toolkit icon, wrench and screwdriver Data Meeting Toolkit   What is the data meeting toolkit? The Data Meeting Toolkit is a suite of tools that groups can use to guide conversation around data and support databased decisionmaking. The toolkit provides resources to support success before, during, and after data meetings, including • A description of essential data meeting roles and responsibilities, including key stakeholders • A protocol of steps before, during, and after meetings to guide selection, analysis, and decisionmaking using data • Examples of how to use the toolkit to address a range of data meeting needs • Guidelines and editable templates for planning, facilitating, and documenting data meetings • Additional resources to support data use A key part of the data analysis process involves talking about data and making meaning of data together. This toolkit helps agencies leverage data they have gathered, engage in a process of data-informed decisionmaking through guided conversation, and build capacity for the ongoing use of data for continuous improvement. Who can use the toolkit and how? Groups engaged in making decisions using data that can use the toolkit include • State and local education agencies • Advocacy groups • Internal and external program evaluators Data meeting organizers can use the toolkit’s protocol as a stand-alone resource or with other parts of the toolkit for a comprehensive approach to planning and conducting data meetings. They can use the toolkit to • Better understand and value data • Support more sophisticated data analysis • Synthesize data from multiple sources • Determine root causes of identified concerns • Prepare data presentations to meet information needs of multiple audiences • Support federal, state, and local reporting needs Toolkit Components Roles in a Data Meeting Data meetings are most effective when team members serve specific roles for planning and conducting the meeting, including a protocol lead, meeting facilitator, notetaker and timekeeper, and stakeholder participants. Individuals can play one or multiple roles, and each role has specific responsibilities. Identifying key roles, clarifying responsibilities, and strategically including stakeholders in data meetings can help maximize participation and align meeting efforts with desired outcomes. Data Meeting Protocol The protocol explains steps to follow before, during, and after a meeting. Groups can use the protocol during a single meeting or series of meetings as part of a recurring decisionmaking process. Meeting organizers and participants can use the protocol’s strategies and facilitation tips to help ensure that they pay careful attention not just to what happens during the meeting but also to intentional planning before the meeting and effective follow up after the meeting. Before the meeting, the protocol lead plans the meeting with input from other members of the meeting team. 1. Determine objective 2. Identify data 3. Identify participants and key responsibilities 4. Organize data to present 5. Prepare and distribute agenda During the meeting, a designated facilitator guides the data discussion during the meeting. 1. Do introductions and review key messages 2. Present the data  3. Discuss observations of the data  4. Discuss interpretations of the data 5. Discuss implications of the data  6. Determine next steps for the group  7. Reflect on the meeting’s effectiveness  After the meeting, the protocol lead recaps the meeting and next steps. 1. Distribute notes from protocol process 2. Confirm next steps and timeline for additional actions  Data Meeting Examples Groups use the meeting protocol to construct meaning from data for different purposes. The protocol steps are the same, but the purposes, desired outcomes, range of stakeholders, and depth of analysis they will undertake may differ. These examples represent just a few of the ways groups can use the data meeting toolkit.     Data Meeting Templates Editable templates such as customizable participant and process agendas, action plan templates, and follow-up checklists help with planning and conducting meetings.           Additional Resources to Support Data Use The Data Meeting Toolkit can support the analysis and use of data within groups for a variety of purposes. Some data meeting groups, however, may need additional support or want to investigate data use topics more deeply.  
__label__pos
0.997483
once clicked on one of the image it appears on the window with a close button.once closed any other image will appear on the screen.How to fix this? Code: <!doctype html> <html> <head> <meta charset="utf-8"> <title>Untitled Document</title> <style> *{margin:0px;padding:0px;} #slider{ width:100%; height:100px; border:1px solid black; position:absolute; top:0px; } #mainbox{ position:relative; top:100px; height:460px; width:100%; opacity: .1; border:1px solid black; background-color:blue; } #img_container{ width:600px; height:400px; position:absolute; margin-left:250px; border:1px solid black; top:100px; } #img_container img{ width:600px; height:400px; } #slider img{ height:100px; width:100px; } #close{ width:150px; height:30px; background-color:blue; margin:0 auto; position:relative; top:60px; z-index:2000; } a{ margin:0 auto; text-align:center; position:absolute; margin-top:5px; margin-left:50px; font-size:20px; text-decoration:none; } </style> </head> <body style="position:relative;"> <div id="mainbox"></div> <div id="img_container"></div> <div id="slider"></div> <script> var imag=["image1.jpg","image2.jpg","image3.jpg","image4.jpg","image5.jpg","image6.jpg","image7.jpg","image8.jpg","image9.jpg","image10.jpg"]; function loading(){ var images_slider=document.getElementById("slider"); var wdth=images_slider.offsetWidth; var no_of_img=parseInt(wdth/(100) ); var i; for(i=0;i<no_of_img;i++){ images_slider.innerHTML += '<img src="'+imag[i]+'" id="' + i + '" onclick="show(this.id);"/>';} } </script> <script>loading();</script> <script> function show(i){ var shw=document.getElementById("img_container"); shw.innerHTML= '<img src="'+imag[i]+'" /><div id="close" onclick="clse();"><a href="#">close</a></div>'; } </script> <script> function clse(){ var s=document.getElementById("img_container"); (s.style.display=="block")?[s.style.display="none"]:[s.style.display="block"]; } </script> </body> </html>
__label__pos
0.986448
Below is a short sequence describing the steps an ASA takes when authenticating VPN users. 1. First, the user initiates a connection to the ASA. 2. The ASA is configured to authenticate that user with the Microsoft Active Directory (AD)/LDAP server. 3. The ASA connects to the LDAP server with the credentials configured on the ASA (ASAusername in this case), and looks up the user provided username. The ASAusername user must have the appropriate credentials to list contents within Active Directory. 4. If the username is found, the ASA attempts to bind to the LDAP server with the credentials that the user provided at login. 5. If the second bind is successful, authentication succeeds and the the ASA processes the attributes of the user. For step two, we need to configure the username which the ASA will authenticate to the Microsoft Active Directory/LDAP server. ASA Configuration In global configuration mode: ldap attribute-map AD-VPN-GROUP map-name memberOf IETF-Radius-Class* map-value memberOf “CN=example-group-containing-the-ldap-login-dn username,OU=Security Groups, ” VPNName aaa-server example protocol ldap aaa-server example (Inside) host 172.16.0.1 ldap-base-dn dc=example,dc=com,dc=au ldap-scope subtree ldap-naming-attribute SAMAccountName  ldap-login-password *****  ldap-login-dn [email protected] ldap-attribute-map AD-VPN-GROUP *IETF-Radius-Class (Group_Policy in ASA version 8.2 and later)—Sets the group policy based on the directory department or user group (for example, Microsoft Active Directory memberOf) attribute value. The group policy attribute replaced the IETF-Radius-Class attribute with ASDM version 6.2/ASA version 8.2 or later. Finally, to apply it to the VPN: tunnel-group example tunnel-group example general-attributes authorization-server-group AD-VPN-GROUP Confirming Changes You can use ‘debug ldap 0-255′ to output the information the ASA sends/receives followed by issuing the test aaa-server command. Output from ‘debug ldap’ with everything wrok HomeASA# test aaa-server authentication example host 172.16.0.1 username ASAusername password LDAPpassword INFO: Attempting Authentication test to IP address <172.16.19.1> (timeout: 12 seconds) INFO: Authentication Successful   Lets take a more detailed look by using debug ldap 255. INFO: Attempting Authentication test to IP address <172.16.0.1> (timeout: 12 seconds) [9228] Session Start [9228] New request Session, context 0xcb3fe840, reqType = Authentication [9228] Fiber started [9228] Creating LDAP context with uri=ldap://172.16.0.1:389 [9228] Connect to LDAP server: ldap://172.16.0.1:389, status = Successful [9228] supportedLDAPVersion: value = 3 [9228] supportedLDAPVersion: value = 2 [9228] Binding as [email protected] [9228] Performing Simple authentication for [email protected] to 172.16.19.1 [9228] LDAP Search: Base DN = [dc=example,dc=com,dc=au] Filter = [SAMAccountName=exampleusername] Scope = [SUBTREE] [9228] User DN = [CN=Active Directory User Group,CN=Users,DC=example,DC=com,DC=au] [9228] Talking to Active Directory server 172.16.0.1 [9228] Reading password policy for ASAusername, dn:CN=Active Directory User Group,CN=Users,DC=example,DC=com,DC=au [9228] Read bad password count 0 [9228] Binding as ASAusername [9228] Performing Simple authentication for ASAusername to 172.16.0.1 [9228] Processing LDAP response for user ASAusername [9228] Message (exampleusername): [9228] Authentication successful for ASAusername to 172.16.0.1 [9228] Retrieved User Attributes: [9228] objectClass: value = top [9228] objectClass: value = person [9228] objectClass: value = organizationalPerson [9228] objectClass: value = user [9228] cn: value = Active Directory User Group [9228] distinguishedName: value = CN=Active Directory User Group,CN=Users,DC=example,DC=com,DC=au [9228] instanceType: value = 4 [9228] whenCreated: value = 20141023031250.0Z [9228] whenChanged: value = 20141030214258.0Z [9228] displayName: value = Active Directory User Group [9228] uSNCreated: value = 6548494 [9228] uSNChanged: value = 6621658 [9228] name: value = Active Directory User Group [9228] objectGUID: value = …..ZvK……t. [9228] userAccountControl: value = 66048 [9228] badPwdCount: value = 0 [9228] codePage: value = 0 [9228] countryCode: value = 0 [9228] badPasswordTime: value = 0 [9228] lastLogoff: value = 0 [9228] lastLogon: value = 0 [9228] pwdLastSet: value = 130591229034905000 [9228] primaryGroupID: value = 513 [9228] objectSid: value = …………”~G.A…..)_…. [9228] accountExpires: value = 9223372036854775807 [9228] logonCount: value = 0 [9228] sAMAccountName: value = ASAusername [9228] sAMAccountType: value = 805306368 [9228] userPrincipalName: value = [email protected] [9228] lockoutTime: value = 0 [9228] objectCategory: value = CN=Person,CN=Schema,CN=Configuration,DC=example,DC=com,DC=au [9228] dSCorePropagationData: value = 16010101000000.0Z [9228] lastLogonTimestamp: value = 130591789638914025 [9228] Fiber exit Tx=589 bytes Rx=2686 bytes, status=1 [9228] Session End INFO: Authentication Successful   Issues that can arise If the the ldap-login-dn did not include the base-dn FQDN, the authentication will fail and error the following: Without debug ldap 255 HomeASA(config-aaa-server-host)# test aaa-server authentication example host 172.16.0.1 username ASAusername password ****** INFO: Attempting Authentication test to IP address <172.16.0.1> (timeout: 12 seconds) ERROR: Authentication Server not responding: AAA Server has been removed The above is the most ambiguous error message known to man. This will occur if the ASAusername doesn’t have the @example.com.au on the end for our ldap-login-dn. With debug ldap 255 HomeASA(config)# test aaa-server authentication example host 172.16.0.1 username ASAusername password ****** INFO: Attempting Authentication test to IP address <172.16.0.1> (timeout: 12 seconds) [9109] Session Start [9109] New request Session, context 0xcb3fe840, reqType = Authentication [9109] Fiber started [9109] Creating LDAP context with uri=ldap://172.16.0.1:389 [9109] Connect to LDAP server: ldap://172.16.0.1:389, status = Successful [9109] supportedLDAPVersion: value = 3 [9109] supportedLDAPVersion: value = 2 [9109] LDAP server 172.16.0.1 is Active directory [9109] Binding as ASAusername [9109] Performing Simple authentication for ASAusername to 172.16.0.1 [9109] Simple authentication for ASAusername returned code (49) Invalid credentials [9109] Failed to bind as administrator returned code (-1) Can’t contact LDAP server [9109] Fiber exit Tx=176 bytes Rx=662 bytes, status=-2 [9109] Session End ERROR: Authentication Server not responding: AAA Server has been removed   Further reading: https://www.cisco.com/c/en/us/support/docs/security/asa-5500-x-series-next-generation-firewalls/98625-asa-ldap-authentication.html https://learningnetwork.cisco.com/servlet/JiveServlet/download/428502-95349/aaa_ldap.pdf About The Author Timothy Timothy started his networking career in 2014, working for one of the largest telecommunication operators in Australia. When he's not working, he's obsessing over German Shepherd Dogs. Close
__label__pos
0.862533
src/HOL/Analysis/Riemann_Mapping.thy changeset 66941 c67bb79a0ceb parent 66827 c94531b5007d child 67399 eab6ce8368fa 1.1 --- a/src/HOL/Analysis/Riemann_Mapping.thy Mon Oct 30 16:03:21 2017 +0000 1.2 +++ b/src/HOL/Analysis/Riemann_Mapping.thy Mon Oct 30 17:20:56 2017 +0000 1.3 @@ -1416,7 +1416,56 @@ 1.4 qed 1.5 1.6 1.7 -text\<open>Finally, pick out the Riemann Mapping Theorem from the earlier chain\<close> 1.8 +subsection\<open>More Borsukian results\<close> 1.9 + 1.10 +lemma Borsukian_componentwise_eq: 1.11 + fixes S :: "'a::euclidean_space set" 1.12 + assumes S: "locally connected S \<or> compact S" 1.13 + shows "Borsukian S \<longleftrightarrow> (\<forall>C \<in> components S. Borsukian C)" 1.14 +proof - 1.15 + have *: "ANR(-{0::complex})" 1.16 + by (simp add: ANR_delete open_Compl open_imp_ANR) 1.17 + show ?thesis 1.18 + using cohomotopically_trivial_on_components [OF assms *] by (auto simp: Borsukian_alt) 1.19 +qed 1.20 + 1.21 +lemma Borsukian_componentwise: 1.22 + fixes S :: "'a::euclidean_space set" 1.23 + assumes "locally connected S \<or> compact S" "\<And>C. C \<in> components S \<Longrightarrow> Borsukian C" 1.24 + shows "Borsukian S" 1.25 + by (metis Borsukian_componentwise_eq assms) 1.26 + 1.27 +lemma simply_connected_eq_Borsukian: 1.28 + fixes S :: "complex set" 1.29 + shows "open S \<Longrightarrow> (simply_connected S \<longleftrightarrow> connected S \<and> Borsukian S)" 1.30 + by (auto simp: simply_connected_eq_continuous_log Borsukian_continuous_logarithm) 1.31 + 1.32 +lemma Borsukian_eq_simply_connected: 1.33 + fixes S :: "complex set" 1.34 + shows "open S \<Longrightarrow> Borsukian S \<longleftrightarrow> (\<forall>C \<in> components S. simply_connected C)" 1.35 +apply (auto simp: Borsukian_componentwise_eq open_imp_locally_connected) 1.36 + using in_components_connected open_components simply_connected_eq_Borsukian apply blast 1.37 + using open_components simply_connected_eq_Borsukian by blast 1.38 + 1.39 +lemma Borsukian_separation_open_closed: 1.40 + fixes S :: "complex set" 1.41 + assumes S: "open S \<or> closed S" and "bounded S" 1.42 + shows "Borsukian S \<longleftrightarrow> connected(- S)" 1.43 + using S 1.44 +proof 1.45 + assume "open S" 1.46 + show ?thesis 1.47 + unfolding Borsukian_eq_simply_connected [OF \<open>open S\<close>] 1.48 + by (meson \<open>open S\<close> \<open>bounded S\<close> bounded_subset in_components_connected in_components_subset nonseparation_by_component_eq open_components simply_connected_iff_simple) 1.49 +next 1.50 + assume "closed S" 1.51 + with \<open>bounded S\<close> show ?thesis 1.52 + by (simp add: Borsukian_separation_compact compact_eq_bounded_closed) 1.53 +qed 1.54 + 1.55 + 1.56 +subsection\<open>Finally, the Riemann Mapping Theorem\<close> 1.57 + 1.58 theorem Riemann_mapping_theorem: 1.59 "open S \<and> simply_connected S \<longleftrightarrow> 1.60 S = {} \<or> S = UNIV \<or>
__label__pos
0.999168
2 $\begingroup$ The below text is from Statistical Learning Page no.225 Consider a case with $n = p$, and $\mathbf{X}$ a diagonal matrix with 1’s on the diagonal and 0’s in all off-diagonal elements. To simplify the problem further, assume also that we are performing regression without an intercept. With these assumptions, the usual least squares problem simplifies to finding $\beta_1,\ldots,\beta_p$ that minimize $$\sum_{j=1}^p(y_j−β_j)^2$$ In this case, the least squares solution is given by $$\hatβ_j = y_j$$ And in this setting, ridge regression amounts to finding $\beta_1,\ldots,\beta_p$ such that $$\sum_{j=1}^p(y_j-β_j)^2+λ \sum_{j=1}^p β_j^2$$ is minimized, and the lasso amounts to finding the coefficients such that $$\sum_{j=1}^p(y_j-β_j)^2+λ \sum_{j=1}^p |β_j|$$ Up to this it is comprehensible to me but I am not able to understand the below text. Can anyone explain how the results shown below were derived ? is minimized. One can show that in this setting, the ridge regression estimates take the form $$\hatβ^R_j = \frac{y_j}{1 + λ} $$ and the lasso estimates take the form $$\hatβ^L_j =y_j −\frac{λ}{2} \hspace{1cm} if \hspace{.3cm} y_j > \frac{λ}{2}$$ $$\hatβ^L_j =y_j +\frac{λ}{2} \hspace{1cm} if \hspace{.3cm} y_j <−λ/2$$ $$\hatβ^L_j = 0 \hspace{1cm} if \hspace{1cm} |y_j|≤\frac{λ}{2}$$ $\endgroup$ 4 $\begingroup$ For ridge regression, the problem is to minimize $$r(\underline{\beta})=\sum_{j=1}^{p}\left(y_{j}-\beta_{j}\right) ^{2}+\lambda\sum_{j=1}^{p}\beta_{j}^2=\sum_{j=1}^{p}\left[ \left( y_{j}-\beta_{j}\right) ^{2}+\lambda \beta_{j}^2\right],$$ where $\underline{\beta}=(\beta_1,\beta_2,\ldots,\beta_p)$. Now, this equation is additively separable, $$r(\underline{\beta}) =\sum_{j=1}^{p}r(\beta_{j})$$ so the derivative with respect to $\beta_j$ is $$\frac{\partial}{\partial\beta_j}r(\underline{\beta})=\frac{d}{d\beta_j}r(\beta_{j}).$$ Thus, minimizing with respect to $\underline{\beta}$ is equivalent to $p$ component-wise minimizations with respect to $\beta_{j}$ for $j=1,2,\ldots,p$. So, $$\frac{d}{d\beta_j}r(\beta_{j})=\frac{d}{d\beta_j}\left[\left(y_{j}-\beta_{j}\right) ^{2}+\lambda \beta_{j}^2\right] =\frac{d}{d\beta_j}\left[y_{j}^2-2y_j\beta_{j}+(1+\lambda)\beta_{j}^2\right]=-2y_j+2(1+\lambda)\beta_j.$$ Setting this to zero provides the minimum, $$2(1+\lambda)\hat{\beta}_j^R-2y_j=0\Leftrightarrow\hat{\beta}_j^R=\frac{y_j}{1+\lambda}.$$ Similarly, the LASSO problem minimizes the additively separable function $$l(\underline{\beta})=\sum_{j=1}^{p}\left(y_{j}-\beta_{j}\right) ^{2}+\lambda\sum_{j=1}^{p}\left\vert\beta_{j}\right\vert=\sum_{j=1}^{p}\left[ \left( y_{j}-\beta_{j}\right) ^{2}+\lambda\left\vert \beta_{j}\right\vert \right].$$ Thus, for $j=1,2,\ldots,p$, we must find the derivatives $$\frac{d}{d\beta_j}l(\beta_{j})=\frac{d}{d\beta_j}\left[\left(y_{j}-\beta_{j}\right) ^{2}+\lambda\left\vert \beta_{j}\right\vert \right]=\frac{d}{d\beta_j}\left[y_{j}^2-2y_j\beta_{j}+\beta_{j}^2+\lambda\left\vert \beta_{j}\right\vert\right].$$ Because of the $-\beta_{j}y_{j}$ term in the objective function, we choose $\beta_{j}$ to have the same sign as $y_{j}$ to preserve the formation of the problem. 1. Suppose that $y_{j}>0$, then for $j=1,2,\ldots,p$, we must minimize $$l(\beta_{j}) =y_{j}^{2}-2y_{j}\beta_{j}+\beta_{j}^{2}+\lambda\beta_{j},$$ since $\left\vert \beta_{j}\right\vert =\beta_{j}$ when $\beta_{j}\geq0$. The derivative is $$l^{\prime}(\beta_{j})=-2y_{j}+2\beta_{j}+\lambda=2\left[\beta_{j}-\left( y_{j}-\frac{\lambda}{2}\right)\right].$$ a. If $\left\vert y_{j}\right\vert \leq\frac{\lambda}{2}$ then $-\left(y_{j}-\frac{\lambda}{2}\right) >0$ so that $l^{\prime}\left( \beta_{j}\right) >0$ for all $\beta_{j}\geq0$. Thus $l(\beta_{j})$ is strictly increasing for all $\beta_{j}\geq0$ and $\hat{\beta}_{j}^{L}=0$. b. If $\left\vert y_{j}\right\vert >\frac{\lambda}{2}$ then $-\left( y_{j}-\frac{\lambda}{2}\right) \leq0$ and setting $l^{\prime}\left( \beta_{j}\right) =0$ gives the solution $$\hat{\beta}_{j}^{L}=y_{j}-\frac{\lambda}{2} \textrm{ if }y_j>\frac{\lambda}{2}.$$ 2. Similarly, for $y_{j}<0$ we must minimize $$l(\beta_{j}) =y_{j}^{2}-2y_{j}\beta_{j}+\beta_{j}^{2}-\lambda\beta_{j},$$ since $\left\vert \beta_{j}\right\vert =-\beta_{j}$ when $\beta _{j}\leq0$. The derivative is $$l^{\prime}\left( \beta_{j}\right) =-2y_{j}+2\beta_{j}-\lambda=2\left[\beta_{j}-\left( y_{j}+\frac{\lambda}{2}\right)\right].$$ a. If $\left\vert y_{j}\right\vert\leq\frac{\lambda}{2}$ then $-\left( y_{j}+\frac{\lambda}{2}\right) <0$ so that $l^{\prime}\left(\beta_{j}\right) <0$ for all $\beta_{j}\leq0$. Thus $l(\beta_{j})$ is strictly decreasing for all $\beta_{j}\leq0$ and $\hat{\beta}_{j}^{L}=0$. b. If $\left\vert y_{j}\right\vert >\frac{\lambda}{2}$ then $-\left( y_{j}+\frac{\lambda}{2}\right) \geq0$ and setting $l^{\prime}\left( \beta_{j}\right) =0$ gives the solution $$\hat{\beta}_{j}^{L}=y_{j}+\frac{\lambda}{2} \textrm{ if }y_j<-\frac{\lambda}{2}.$$ From 1a and 2a, $$\hat{\beta}_{j}^{L}=0 \textrm{ if }\left\vert y_{j}\right\vert\leq\frac{\lambda}{2}.$$ $\endgroup$ 5 • $\begingroup$ thanks a lot for taking out the time and providing the solution. I don't understand one thing i.e.∂∂βjr(β−)=ddβjr(βj).How partial derivative becomes equal to full derivative. (Is it a rule or something else) If its a rule can you provide me a source where i can learn more about this . $\endgroup$ – learner Apr 12 '16 at 7:47 • $\begingroup$ That equation follows from the one just before it. Suppose that r(β1,β2)=r(β1)+r(β2)=2β1+3β2. Then ∂/∂β1 r(β1,β2) = d/dβ1 r(β1) = 2. r(β1) is a function of β1 alone - thus the partial derivative is the full derivative. Make sense? $\endgroup$ – StatGrrl Apr 12 '16 at 8:11 • $\begingroup$ sorry i didn't get it. $\endgroup$ – learner Apr 12 '16 at 8:31 • $\begingroup$ Not sure how else I can explain.From my example above, ∂/∂β2 r(β1,β2) = ∂/∂β2 (2β1 + 3β2) = 3. d/dβ2 r(β2) = d/dβ2 (3β2) = 3. $\endgroup$ – StatGrrl Apr 12 '16 at 9:03 • $\begingroup$ See calculus.subwiki.org/wiki/Additively_separable_function $\endgroup$ – StatGrrl Apr 12 '16 at 9:07 Your Answer By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.997594
Beefy Boxes and Bandwidth Generously Provided by pair Networks The stupid question is the question not asked   PerlMonks   Re: regular expressions. help by matija (Priest) on Jun 29, 2004 at 19:26 UTC ( #370590=note: print w/ replies, xml ) Need Help?? in reply to regular expressions. help Of course it's not matching: there's an asterisk in the way. You should change it to: /^HISTOGRAM OF\s*\*\s*(\w+)$/ Comment on Re: regular expressions. help Download Code Re^2: regular expressions. help by apocalyptica (Acolyte) on Jun 29, 2004 at 19:48 UTC Hmmm... That looks like it should be correct, yes (like I said, I'm no good at regular experessions, but it looks right to me), but it's still not working. Let me just post the whole stupid program to give you an idea what I am trying to do: #!/usr/local/bin/perl $fl = '-?\d+\.\d+'; $evalme = q[ while(<>) { s/^ //; if(^HISTOGRAM OF\s*\*\s*(\w+)$/) { printf ("In loop.\n"); #just here for testing purposes +. write if $header; undef($cache); $header=$1; $varnum=$2; } if($header) { ]; eval <<EOM; $evalme (\$meanH, \$usersH) = (\$1, \$2) if /^GROUP\\s+(\\S+)\\s+( +\\S+)/; (\$mean, \$users) = (\$1, \$2) if /^MEAN\\s+(${fl})\\s+(${ +fl})/; \$levene = \$1 if /\\s+VARIABILITY\\s+${fl}\\s+(${fl})/; \$pooled = \$1 if /\\s+POOLED T\\s+${fl}\\s+(${fl})/; \$separate = \$1 if /\\s+SEPARATE T\\s+${fl}\\s+(${fl})/; \$mann = \$1 if /\\s+MANN-WHIT.\\s+${fl}\\s+(${fl})/; } } EOM write STDOUT; format STDOUT_TOP = | @|||| | @|||| | Levene-P | Pooled-P | Mann-P | Sep +arate $meanH, $usersH ----------+----------+----------+----------+----------+----------+---- +------ . format STDOUT = @<<<<<<<< | @##.#### | @##.#### | @##.#### | @##.#### | @##.#### | @## +.#### $header, $mean, $users, $levene, $pooled, $mann, $se +parate ----------+----------+----------+----------+----------+----------+---- +------ . It reads through the input file until it finds HISTOGRAM OF and then begins pulling out the data as per above. Does any of it work? Well, I don't know, I still can't get this one stupid thing to work. The (\w+)$ is killing you again. You match 'HISTOGRAM OF', whitespace, asterisk, whitespace, but the rest of your string is not all \w (word chars), and since you added the '$' to match until the end, the \w+ fails to match when it hits whitespace again. I cannot stress enough to regex learners that whitespace NEEDS to be treated like all other characters. Okay. So I could theoretically get rid of the $ so that it doesn't match until the end, then? Or what would be the best way to get around this? Thanks for your help, by the way. This is leaving me more than a bit frazzled. Log In? Username: Password: What's my password? Create A New User Node Status? node history Node Type: note [id://370590] help Chatterbox? and the web crawler heard nothing... How do I use this? | Other CB clients Other Users? Others having an uproarious good time at the Monastery: (7) As of 2015-05-25 02:19 GMT Sections? Information? Find Nodes? Leftovers? Voting Booth? In my home, the TV remote control is ... Results (478 votes), past polls
__label__pos
0.878473
Home Wisim 24 Aug 2014 桌面插件AppWidget深入理解-基于系统音乐播放器的桌面音乐插件 光有一个空壳不行,桌面插件必须要有后台的应用程序为它提供内容和服务,这样才能真正让桌面插件发挥它的优势。 1.首先来分析AppWidgetProvider中关于插件生命周期的几个方法 值得注意的是只有在onReceive(Context context, Intent intent)使用父类的onReceive方法: public void onReceive(Context context,Intent intent) { super.onReceive(context,intent); } 之后如下所述的几个方法才能被成功调用,否则无效 。 • public void onEnable(Context context):第一个插件添加到桌面时会调用此方法。 • public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds):每向桌面添加一个插件都会调用此方法。 • public void onDeleted(Context context, int[] appWidgetIds):每删除一个插件,都会调用此方法。 • public void onDisabled(Context context):最后一个插件删除之后会调用此方法。 2. 另外,从Manifest.xml文件中对于WppWidgetProvider的注册就知道它本质上是一个广播接收器: <receiver android:name="com.wxp.made.MediaProvider"> <intent-filter > <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/> <action android:name="com.android.music.playstabloganged"/> <action android:name="com.android.music.metachanged"/> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/appwidget_info"/> </receiver> 所以对于音乐插件的基本思路就有了:后台播放服务每当播放或者暂停音乐时都会发送一个广播,这个广播包含了当前音乐的所有信息:播放状态(播放or暂停),作者,歌曲名,专辑名等等。只要在AppWidgetProvider中接收这个广播就可以相应的更新桌面插件的界面。如上两个就是音乐播放器放送的广播的Action,playstabloganged表示音乐播发状态的变化,metachangde表示歌曲信息的变化。 在onReceive方法中实现接收到广播之后立即更新界面的功能: @Override public void onReceive(Context context, Intent intent) { super.onReceive(context, intent); playData=(ApplicationData)context.getApplicationContext(); if(intent.getExtras()!=null){ if (intent.getExtras().getLong("id")!=0) { bundle =intent.getExtras(); playData.setBundle(bundle); updateViews(context, bundle); } } } 代码中playData.setBundle(bundle);用于保存当前播放音乐的信息,以便用户多次添加插件时能够正确更新桌面插件。因此在更新方法中可以直接调用已经保存了的Bundle @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { playData=(ApplicationData)context.getApplicationContext(); if(playData.getBundle()!=null){ updateViews(context, playData.getBundle()); } } 3.因为只有在播放或者暂停音乐后台服务才会发送广播,所以仅靠接收广播来判断是否有音乐在播放还不能完全解决问题。比如正在播放音乐时,用户向桌面添加了第一个插件,由于此时并未触发播放/暂停事件,也就不会发送广播,所以插件并不会接收到广播而更新界面。因此需要在onEnabled方法中开启一个新的服务来调用远程服务以获取当前音乐的状态。 Intent intent=new Intent(context, EnableService.class); context.startService(intent); 在EnableService中会使用AIDL来获取后台播放服务的一些接口 关于AIDL的使用不再赘述,可参照另一篇文章:Service初探-AIDL简单实现 在ServiceConnection的onServiceConnected方法中获取到音乐信息在再封装成bundle并发送一个广播以便插件更新界面。 try { boolean mplaying = mIMediaPlaybackService.isPlaying(); Long mauid=mIMediaPlaybackService.getAudioId(); String mtrack=mIMediaPlaybackService.getTrackName(); String malbum=mIMediaPlaybackService.getAlbumName(); String martist=mIMediaPlaybackService.getArtistName(); Bundle bundle=new Bundle(); bundle.putLong("id", mauid); bundle.putBoolean("playing", mplaying); bundle.putString("track", mtrack); bundle.putString("album", malbum); bundle.putString("artist", martist); Intent intent=new Intent("com.android.music.metachanged"); intent.putExtras(bundle); sendBroadcast(intent); } catch (RemoteException e) { e.printStackTrace(); } 4.而桌面插件触发音乐播放或者暂停事件的功能则需要通过RemoteView和PendingIntent来实现,代码如下: public static final String TOGGLEPAUSE_ACTION = "com.android.music.musicservicecommand.togglepause"; ComponentName serviceName=new ComponentName("com.android.music","com.android.music.MediaPlaybackService"); Intent intent= new Intent(TOGGLEPAUSE_ACTION); intent.setComponent(serviceName); PendingIntent pendingIntent= PendingIntent.getService(context, 0 /* no requestCode */, intent, 0 /* no flag */); RemoteViews views.setOnClickPendingIntent(R.id.control_play, pendingIntent); THE END.
__label__pos
0.911255
MongoDB + Node.js: one collection per request or one static collection? MongoDB + Node.js: one collection per request or one static collection? I am using the 'mongodb' NPM module in small web server. I am using the 'mongodb' NPM module in small web server. I'm wondering whether I should always call db.collection('') on every request that hits the server, or should I rather init a (singleton) collection after I established the db connection, and use the same collection for all requests? Especially since I have the collection at hand during initialization, to set a unique index, it is pretty tempting to just keep this collection reference and re-use it in all http request handlers. Could I run into awkward concurrency issues, say, if multiple requests at nearly the same time operate on exactly the same collection instance? node-js mongodb What's new in Bootstrap 5 and when Bootstrap 5 release date? How to Build Progressive Web Apps (PWA) using Angular 9 What is new features in Javascript ES2020 ECMAScript 2020 Deno Crash Course: Explore Deno and Create a full REST API with Deno How to Build a Real-time Chat App with Deno and WebSockets Convert HTML to Markdown Online HTML entity encoder decoder Online Random Password Generator Online HTML Color Picker online | HEX Color Picker | RGB Color Picker How to Use Express.js, Node.js and MongoDB.js In this post, I will show you how to use Express.js, Node.js and MongoDB.js. We will be creating a very simple Node application, that will allow users to input data that they want to store in a MongoDB database. It will also show all items that have been entered into the database. How to Hire Node.js Developers And How Much Does It Cost? A Guide to Hire Node.js Developers who can help you create fast and efficient web applications. Also, know how much does it cost to hire Node.js Developers. Build a REST API using Node.js, Express.js, Mongoose.js and MongoDB Node.js, Express.js, Mongoose.js, and MongoDB is a great combination for building easy and fast REST API. You will see how fast that combination than other existing frameworks because of Node.js is a packaged compilation of Google’s V8 JavaScript engine and it works on non-blocking and event-driven I/O. Express.js is a Javascript web server that has a complete function of web development including REST API. Node.js, ExpressJs, MongoDB and Vue.js (MEVN Stack) Application Tutorial In this tutorial, you'll learn how to integrate Vue.js with Node.js backend (using Express framework) and MongoDB and how to build application with Node.js, ExpressJs, MongoDB and Vue.js Hands on with Node.Js Streams | Examples & Approach The practical implications of having Streams in Node.js are vast. Nodejs Streams are a great way to handle data chunks and uncomplicate development.
__label__pos
0.873455
 "Approximation Theory" related terms, short phrases and links KeyWEn.com         Approximation Theory       Article     History   Tree Map   Encyclopedia of Keywords > Related Areas > Approximation Theory   Michael Charnine Keywords and Sections LINEAR SYSTEM THEORY UNIVERSITY IMPORTANT PARTIAL DIFFERENTIAL EQUATIONS NUMERICAL APPROXIMATION BOOK SPECIAL FUNCTIONS NUMERICAL METHOD CONTEMPORARY MATHEMATICS HARMONIC ANALYSIS NUMERICAL ANALYSIS WAVELETS RESEARCH INTERESTS RELATED AREAS APPROXIMATION THEORY Review of Short Phrases and Links     This Review contains major "Approximation Theory"- related terms, short phrases and links grouped together in the form of Encyclopedia article. Definitions 1. Approximation theory is a branch of mathematics, a quantitative part of functional analysis. 2. Approximation theory is a branch of mathematics that strives to understand the fundamental limits in optimally representing different signal types. Linear System Theory 1. Many applications of approximation theory are to be found in linear system theory and model reduction. (Web site) University 1. Talbot, A., Approximation theory or a miss is better than a mile, Inaugural Lecture at University of Lancaster, 1970. (Web site) Important 1. The Chebyshev nodes are important in approximation theory because they form a particularly good set of nodes for polynomial interpolation. (Web site) Partial Differential Equations 1. The main topics include ordinary and partial differential equations, fluid flow, optimization, linear algebra, and approximation theory. (Web site) Numerical 1. A text in numerical methods should discuss the Hilbert matrix in its section on approximation theory. Approximation 1. Approximation theory also studies the size and properties of the error introduced by approximation. Book 1. As an introduction to approximation theory, this book serves quite well. (Web site) Special Functions 1. Approximation theory, asymptotics, combinatorics, integral transforms and operational calculus, orthogonal polynomials and special functions. (Web site) Numerical Method 1. A given numerical method for a problem can be recast into the framework of approximation theory. Contemporary Mathematics 1. Its increasing importance in contemporary mathematics has created an entirely new area known as Approximation Theory. (Web site) Harmonic Analysis 1. In the last chapter applications to PDE, evolution equations and approximation theory as well as the connection with harmonic analysis are described. (Web site) Numerical Analysis 1. If you teach numerical analysis or approximation theory, then this book will give you some good examples to discuss in class. (Web site) 2. Chapter 7 is important to all working in numerical analysis, wherein the author discusses approximation theory. Wavelets 1. These techniques play an important role in applications as for instance in approximation theory, quantum mechanics and in the theory of wavelets. Research Interests 1. My research interests are in information theory, signal processing, mathematical statistics, approximation theory, optimization and distributed algorithms. 2. His research interests include function related operator theory, theory of Hardy and Bergman spaces and approximation theory. 3. Research Interests: applied and numerical analysis, approximation theory, and interdisciplinary applications. Related Areas 1. The Popov Prize recognizes distinguished research accomplishments in Approximation Theory and related areas of mathematics. 2. The Journal of Approximation Theory is devoted to advances in pure and applied approximation theory and related areas. (Web site) Approximation Theory 1. The methods employ classical ideas from the theory of convex sets, probability theory, approximation theory, and the local theory of Banach spaces. (Web site) 2. Academic researchers in applied mathematics (in particular: numerical analysis, partial differential equations, approximation theory, real analysis). 3. Research Interests: approximation theory, applied harmonic analysis, image processing, and wavelets. Categories 1. Related Areas 2. Research Interests 3. Information Technology > Computer Science > Algorithms > Numerical Analysis 4. Convex Sets 5. Science > Mathematics > Mathematical Analysis > Harmonic Analysis 6. Books about "Approximation Theory" in Amazon.com Book: Keywen Category Structure   Short phrases about "Approximation Theory"   Originally created: March 20, 2008.   Links checked: March 29, 2013.   Please send us comments and questions by this Online Form   Please click on Move Up to move good phrases up. 0.0078 sec. a=1..
__label__pos
0.999773
You are previewing Professional Swift. O'Reilly logo Professional Swift Book Description Transition from Objective-C to the cleaner, more functional Swift quickly and easily Professional Swift shows you how to create Mac and iPhone applications using Apple's new programming language. This code-intensive, practical guide walks you through Swift best practices as you learn the language, build an application, and refine it using advanced concepts and techniques. Organized for easy navigation, this book can be read end-to-end for a self-paced tutorial, or used as an on-demand desk reference as unfamiliar situations arise. The first section of the book guides you through the basics of Swift programming, with clear instruction on everything from writing code to storing data, and Section II adds advanced data types, advanced debugging, extending classes, and more. You'll learn everything you need to know to make the transition from Objective-C to Swift smooth and painless, so you can begin building faster, more secure apps than ever before. • Get acquainted with the Swift language and syntax • Write, deploy, and debug Swift programs • Store data and interface with web services • Master advanced usage, and bridge Swift and Objective-C • Professional Swift is your guide to the future of OS X and iOS development. Table of Contents 1. Cover Page 2. Title Page 3. Copyright 4. Dedication 5. ABOUT THE AUTHOR 6. CREDITS 7. ACKNOWLEDGMENTS 8. CONTENTS 9. INTRODUCTION 10. PART I: Building Applications with Swift 1. Chapter 1: A Swift Primer 1. WHAT IS SWIFT? 2. WORKING WITH CONSTANTS AND VARIABLES 3. WORKING WITH OPERATORS 4. MAKING DECISIONS WITH CONTROL FLOW 5. GROUPING TYPES WITH ENUMERATIONS 6. WORKING WITH FUNCTIONS 7. SUMMARY 2. Chapter 2: Writing a Swift Program 1. SETTING UP XCODE 2. EXPERIMENTING WITH PLAYGROUNDS 3. WRITING SWIFT IN XCODE 4. DEBUGGING SWIFT APPLICATIONS 5. SUMMARY 3. Chapter 3: Classes, Structs, and Enums 1. WORKING WITH CLASSES AND STRUCTS 2. WORKING WITH PROPERTIES 3. UNDERSTANDING METHODS 4. UNDERSTANDING THE DIFFERENCE BETWEEN CLASSES AND STRUCTS 5. WORKING WITH ENUMERATIONS 6. SUMMARY 4. Chapter 4: Concurrency in Swift 1. WHAT IS CONCURRENCY? 2. CONCURRENCY IN iOS AND OS X 3. SUMMARY 5. Chapter 5: Interfacing with Web Services 1. UNDERSTANDING WEB SERVICES 2. IMPLEMENTING A WEB SERVICES CLIENT 3. SUMMARY 6. Chapter 6: Storing Data with Core Data 1. WHAT IS CORE DATA? 2. USING CORE DATA WITH SWIFT 3. SUMMARY 11. PART II: Advanced Swift Concepts 1. Chapter 7: Extending Classes 1. WORKING WITH CLASS EXTENSIONS 2. SPECIFYING BEHAVIOR WITH PROTOCOLS 3. WORKING WITH GENERICS 4. SUMMARY 2. Chapter 8: Advanced Data Types 1. WORKING WITH ENUMS AND ALGEBRAIC DATA TYPES 2. WORKING WITH OPTIONAL TYPES 3. UNDERSTANDING TYPE CASTING 4. GROUPING VALUES WITH TUPLES 5. CUSTOM OPERATORS 6. USING FUNCTIONS AND CLOSURES 7. SUMMARY 3. Chapter 9: Bridging Swift and Objective-C 1. THE SUCCESSOR TO OBJECTIVE-C 2. INTRODUCING NAMESPACES AND MODULES 3. HOW SWIFT AND OBJECTIVE-C INTERACT 4. USING C AND C++ CODE WITH SWIFT 5. SUMMARY 4. Chapter 10: Debugging Swift Applications 1. THE ART OF DEBUGGING 2. CREATING CIRCLEVIEW 3. PRINTING VALUES 4. WORKING WITH DEBUGGERS 5. EXAMINING ERRORS WITH LLDB, THE LLVM DEBUGGER 6. SUMMARY 5. Chapter 11: The Swift Runtime 1. WHAT IS A RUNTIME? 2. UNDERSTANDING THE OBJECTIVE-C RUNTIME 3. EXPLORING THE SWIFT RUNTIME 4. SUMMARY 6. APPENDIX: An Overview of C
__label__pos
1
Giải bài tập trang 61 SGK Toán 1: Số 0 trong phép trừ Lời giải bài tập trang 61 SGK Toán 1 Giải bài tập trang 61 SGK Toán 1: Số 0 trong phép trừ với lời giải đầy đủ chi tiết cho từng bài tập SGK giúp các em học sinh ôn tập, củng cố kiến thức các dạng bài tập số 0 trong phép trừ. Mời các em cùng tham khảo. Hướng dẫn giải bài Giải bài tập trang 61 SGK Toán 1: Số 0 trong phép trừ (bài 1, 2, 3 trang 61/SGK Toán 1) Bài 1: (Hướng dẫn giải bài tập số 1 SGK) Tính 1 - 0 = 1 - 1 = 5 - 1 = 2 - 0 = 2 - 2 = 5 - 2 = 3 - 0 = 3 - 3 = 5 - 3 = 4 - 0 = 4 - 4 = 5 - 4 = 5 - 0 = 5 - 5 = 5 - 5 = Hướng dẫn giải 1 - 0 = 1 1 - 1 = 0 5 - 1 = 4 2 - 0 = 2 2 - 2 = 0 5 - 2 = 3 3 - 0 = 3 3 - 3 = 0 5 - 3 = 2 4 - 0 = 4 4 - 4 = 0 5 - 4 = 1 5 - 0 = 5 5 - 5 = 0 5 - 5 = 1 Bài 2: (Hướng dẫn giải bài tập số 2 SGK) Tính 4 + 1 = 2 + 0 = 3 + 0 = 4 + 0 = 2 - 2 = 3 - 3 = 4 - 0 = 2 - 0 = 0 + 3 = Hướng dẫn giải 4 + 1 = 2 + 0 = 3 + 0 = 4 + 0 = 2 - 2 = 3 - 3 = 4 - 0 = 2 - 0 = 0 + 3 = Bài 3: (Hướng dẫn giải bài tập số 3 SGK) Giải bài tập trang 61 SGK Toán 1 Hướng dẫn giải Giải bài tập trang 61 SGK Toán 1 >> Bài tiếp theo: Giải bài tập trang 62 SGK Toán 1: Luyện tập Số 0 trong phép trừ Đánh giá bài viết 1 2.633 0 Bình luận Sắp xếp theo Giải bài tập Toán lớp 1 Xem thêm
__label__pos
0.992908
Delbridge Solutions - Unlocking the Power of MongoDB Databases Oct 24, 2023 Introduction Delbridge Solutions is a leading provider of IT services, computer repair, web design, and software development. We understand the importance of leveraging cutting-edge technologies to drive business growth and deliver exceptional results for our clients. In this article, we will explore the power of MongoDB databases and how they can revolutionize the way your business operates. What is MongoDB? MongoDB is an open-source, document-oriented database that allows businesses to store, retrieve, and analyze large volumes of data in a highly scalable and efficient manner. Unlike traditional relational databases, MongoDB offers a flexible schema design, enabling companies to adapt to evolving data requirements without sacrificing performance or stability. Why Choose MongoDB? 1. Scalability and Performance MongoDB's architecture is designed to handle massive amounts of data and high traffic loads. With its distributed nature and automatic sharding capabilities, MongoDB scales horizontally, allowing businesses to seamlessly expand their databases as their needs grow. This ensures that your applications and services perform optimally and consistently, even under heavy workloads. 2. Flexibility and Agility Traditional relational databases require a predefined schema, imposing rigid structure constraints on data. MongoDB, on the other hand, offers a dynamic schema, allowing you to store and process data of any structure or format. This flexibility enables organizations to quickly adapt to changing business requirements, making MongoDB an ideal choice for agile development practices and emerging technologies. 3. Rich Data Model MongoDB's document-oriented data model allows businesses to store complex hierarchical structures and rich data types, such as arrays and nested documents. This makes it easier to represent real-world entities and relationships, resulting in more natural and intuitive data access patterns. By leveraging the power of MongoDB's expressive query language, businesses can unlock deeper insights from their data and make data-driven decisions with ease. 4. High Availability and Fault Tolerance MongoDB ensures high availability and fault tolerance through built-in replication and automated failover mechanisms. By replicating data across multiple nodes, MongoDB maintains data redundancy, allowing for seamless recovery in case of hardware failures or network disruptions. This guarantees uninterrupted access to critical business information and minimizes the risk of data loss. Use Cases MongoDB's versatility makes it well-suited for a wide range of applications and industries. Some popular use cases include: • Content Management Systems (CMS): MongoDB's flexible schema design is perfect for managing dynamic content, facilitating smooth content updates and retrieval processes. • E-commerce Platforms: MongoDB's scalability and performance capabilities enable businesses to handle ever-growing product catalogs and supply chain data efficiently. • Internet of Things (IoT): MongoDB's ability to handle the high velocity and variety of IoT-generated data makes it a preferred choice for IoT platforms and sensor data management. • Real-Time Analytics: MongoDB's fast read and write operations allow for real-time data analysis, empowering businesses to gain valuable insights and make informed decisions on the fly. Conclusion In today's data-driven business landscape, harnessing the power of MongoDB databases is crucial for organizations aiming to stay ahead of the competition. Delbridge Solutions, with its expertise in IT services, computer repair, web design, and software development, is well-positioned to help your business unlock the full potential of MongoDB. Our skilled team of professionals can guide you through the entire process, from designing and setting up MongoDB databases to optimizing their performance and security. Contact us at Delbridge Solutions today to embark on a transformative journey with MongoDB. Silvana Kozlovic Great article! 😄 MongoDB databases definitely have the potential to take businesses to the next level. Thanks for the valuable insights! Nov 9, 2023 Keith Everett Interesting read, thanks for sharing! Nov 7, 2023
__label__pos
0.98519
// Copyright (c) 2017 Elements of Programming Interviews. All rights reserved. #include #include #include #include #include #include #include using std::cout; using std::default_random_engine; using std::endl; using std::max; using std::stack; using std::string; using std::random_device; using std::uniform_int_distribution; using std::vector; // @include int LongestValidParentheses(const string& s) { int max_length = 0, end = -1; stack left_parentheses_indices; for (int i = 0; i < s.size(); ++i) { if (s[i] == '(') { left_parentheses_indices.emplace(i); } else if (left_parentheses_indices.empty()) { end = i; } else { left_parentheses_indices.pop(); int start = left_parentheses_indices.empty() ? end : left_parentheses_indices.top(); max_length = max(max_length, i - start); } } return max_length; } // @exclude template int ParseFromSide(char paren, IterType begin, IterType end) { int max_length = 0, num_parens_so_far = 0, length = 0; for (IterType i = begin; i < end; ++i) { if (*i == paren) { ++num_parens_so_far, ++length; } else { // *i != paren if (num_parens_so_far <= 0) { num_parens_so_far = length = 0; } else { --num_parens_so_far, ++length; if (num_parens_so_far == 0) { max_length = max(max_length, length); } } } } return max_length; } int LongestValidParenthesesConstantSpace(const string& s) { return max(ParseFromSide('(', begin(s), end(s)), ParseFromSide(')', s.rbegin(), s.rend())); } void SmallTest() { assert(LongestValidParentheses(")(((())()(()(") == 6); assert(LongestValidParentheses("((())()(()(") == 6); assert(LongestValidParentheses(")(") == 0); assert(LongestValidParentheses("()") == 2); assert(LongestValidParentheses("") == 0); assert(LongestValidParentheses("()()())") == 6); assert(LongestValidParenthesesConstantSpace(")(((())()(()(") == 6); assert(LongestValidParenthesesConstantSpace("((())()(()(") == 6); assert(LongestValidParenthesesConstantSpace(")(") == 0); assert(LongestValidParenthesesConstantSpace("()") == 2); assert(LongestValidParenthesesConstantSpace("") == 0); assert(LongestValidParenthesesConstantSpace("()()())") == 6); } string RandString(int length) { default_random_engine gen((random_device())()); string result; while (length--) { uniform_int_distribution left_or_right(0, 1); result += left_or_right(gen) ? '(' : ')'; } return result; } int main(int argc, char** argv) { SmallTest(); if (argc == 2) { string s = argv[1]; cout << "s = " << s << endl; cout << LongestValidParentheses(s) << endl; } else { default_random_engine gen((random_device())()); uniform_int_distribution dis(0, 100000); for (int times = 0; times < 1000; ++times) { string s = RandString(dis(gen)); assert(LongestValidParenthesesConstantSpace(s) == LongestValidParentheses(s)); } } return 0; }
__label__pos
0.999841
Share your code. npm Orgs help your team discover, share, and reuse code. Create a free org » dj-logger 4.0.2 • Public • Published dj-logger Transactional logger. Keep it simple to write log about transactions in asynchronous application. Version npm NPM Motivation Dj-logger is a logging library for node.js (wrapping Winston library), that helps you write logs with request context. Node.js is a single threaded engine for any internal work. When it comes to external work (like accessing DB, IO, etc.) we'll most likely want to use another thread to handle other requests to our server until the external works will finish. This behavior makes it hard to write logs with fully context of the request in every step of our flow. For example, assume you want to set a Guid for a server request, and write it in every log of an asynchronous flow. You'll probably set the Guid when the flow starts, save it somewhere in your app and use it every time you write a log. That way, when your server will get its first request your logs will contain the request Guid you set, all the way of your asynchronous action. Now, assume that your server decided to handle a second request while it waiting to this action to finish. It'll set the second request Guid and override the first Guid! When the asynchronous action will finish, every time you'll want to use the request id, you'll end up using the second request id! One way to solve this problem is to give access to the request object (the one you get in your route handler), from any point of your app. Most of the time you won't want to do this, because most of your code shouldn't be aware of the request context, especially when you need this information just for logs. Dj-logger gives you a transparent way to set transactional parameters like request id and write them in any of the request log. Installation npm install dj-logger Usage There are several features you would like to be aware of: Logger Initialization var dj = require('dj-logger'); var config = require('./logger.config'); //configuration for the logger var loggerFactory = dj.LoggerFactory.init(config); var logger = loggerFactory.get('logger-name'); The LoggerFactory initialized with the loggers' configuration and can retrieve logger by its name using the get method. You must call the LoggerFactory init method once before using its get method with configurable logger name. Note: The LoggerFactory is static, so you CANNOT use its init more than a single time! The second overload of get method receives logger name (yours to choose) and a configuration for the logger. In case you've already created a logger with this name, the factory will return it (ignoring the new configuration), Otherwise it'll create a new logger and will set its settings according to the configuration object. (see Setup Logger Configuration to understand the configuration of the logger) After you have an instance of the logger, you can start writing logs! Setup Logger Configuration Dj-logger configuration is a Json object, which its keys is the different loggers' names and the value of each is the logger configuration. A logger configuration is a Json object, which its keys is the transport method name and the value is Winston's settings for this transport. The current supported transports are Winston's supported transports (which its key is the transport's name) and custom transport. You can use a custom key for a custom transport and set in its settings a 'module' which contains your transport module name. For example: {     "my-logger": {         "file": {             "formatter": "splunk",             "filename": "./log.txt",             "level": "debug",             "silent": false,             "colorize": false,             "maxsize": 100 * 1000 * 1024,             "maxFiles": 100,             "json": false,             "zippedArchive": false,             "fsoptions": {flags: "a"}         }     } } As you can see, the configuration sets a single file transport and sets its settings. The transport's settings are the same as Winston transport's settings, with one exception - the formatter option. Winston library gives you a way, through the transport's settings to set a formatter function of your own. Dj-logger comes with new approach that gives you a way to inherit from base Formatter class and override the format function. After calling super.format(log) in your format function, all the transactional parameters will be accessible through log.meta. For example, assume that I've create a new formatter module and called it MyFormatter, which contains the following code: var Formatter = require('dj-logger').Formatter;   module.exports = class MyFormatter extends Formatter {     format(log) {             super.format(log); //you MUST call base formatter before your logic!               // format the log object to your custom string and return it.           } } Now, to use this formatter, all you need to do is to declare it in your configuration: {     file: {         formatter: 'MyFormatter',         ...     } } By default, Dj-logger comes with 2 kinds of formatter - Winston default formatter (to use it you need to remove the formatter option from configuration) and Splunk formatter (easy format for Splunk engine to read, you can use it by specifying 'splunk' in the formatter option, as I've done in the first example). For more information about other configuration settings you can see Winston's documentation. Using Winston Logger Dj-logger is based on winston logging library and you can use the logger the exactly the same way you are using winston. For more information about Winston logger you can see Winston's documentation. Transactions The main use of Dj-logger is for handling transactions that involve asynchronous actions. In this section, I'll explain how simple it is to use Dj-logger to solve this problem Initialize Transactions Dj-logger uses the library Continuation-Local-Storage to handle all the context issues. It means every request should run in its own namespace. By using Dj-logger you don't need to be aware of this mechanism (if you want to know more, you can read Continuation-Local-Storage's documentation), you simply need to use the startTransaction middleware exposed by Dj-logger BEFORE your routes handlers var dj = require('dj-logger'); var config = require('./logger.config'); dj.LoggerFactory.init(config); var logger = dj.LoggerFactory.get('logger-name');   var app = express();   app.use(dj.startTransaction(logger,'YOUR-SYSYTEM-NAME','SYSTEM-COMPONENT', (req) => logger.setParam("user", req.headers.user)));   //your routes comes here! The startTransaction method sets your first transactional parameters and returns a middleware that sets any request in its own namespace. The startTransaction parameters are: the transactional logger (each transactional logger should be initiate separately), your system name, the name of the system's component (e.g. "App Server", "Users Micro-Service", etc.), a callback that receives the request object and will execute before the call to next() method (optional). After executing this middleware, your logs will contain transactionId (generated automatically, or sets by the request's 'transaction-id' header), your system name, your current system component and requestUrl. Get Transaction ID Getting the transactionId is pretty easy. All you have to do is call the getTransactionId() function of the logger in the following matter: var transactionId = logger.getTransactionId(); Set Transactional Parameters There are two ways to set transactional parameters: single parameter and many parameters at once. The Logger expose two methods: setParam and setMany to handle the above. Examples: logger.setParam('myParam', 'myValue'); The code above sets a transactional parameter called 'myParam' and sets its value to 'myValue'. This parameter will be accessible in your custom formatter and from the (already exists) splunk formatter in every log written in the current request. The Splunk formatter will write this parameter in every log in the current request context that will come after this code. Examples: logger.setManyParams({     one: 'First Value',     two: 'Second Value' }); This code will set two transactional parameters called 'one' and 'two' with the values 'First Value' and 'Second Value'. Those parameters will be accessible in your custom formatter and from the (already exists) Splunk formatter in every log written in the current request. The Splunk formatter will write those parameters in every log in the current request context that will come after this code. Measure Actions in Transaction One of the coolest features of Dj-logger is its simple logging of functions or promises measurement. Measure Functions: function f1() {     //some code... }   let x = logger.measure('myMeasure', f1, "f1 measure"); //more code... logger.logMeasurements('my message'); The code above will execute and measure the method f1. The first parameter is a name for the measurement, the second parameter is the method or promise to measure and the last parameter (optional) tells the logger to log the measurement right after f1 finished its executing with message "f1 measure". If the third parameter (which is a log message) exists, the measurements will be logged as info with this message and parameter myMeasureTime=x (x will be the number of milliseconds took to execute f1). If the third parameter is absent or set to false, all the measurements of the request will be stored until executing logMeasurements. logMeasurements will write info log with the measures results (all the measures in single log). When calling measure with function as the second parameter, measure's return value will be the input function's return value. Assume we have the following code: logger.measure('myMeasure', f1); logger.measure('myMeasure', f1); logger.measure('myMeasure', f1); logger.measure('myMeasure', f1); logger.logMeasurements('my message'); logMeasurements will print an info log with the following details: myMeasureTotalTime (the total time of all the measures called 'myMeasure' in milliseconds), myMeasureCount (the count of measures called 'myMeasure', in this example it will be 4), myMeasureAvgTime (the average time of all the measures called 'myMeasure' in milliseconds), myMeasureMin and myMeasureMax (the minimum and maximum time of all the measures called 'myMeasure' in milliseconds). Measure Promises: function f1() {     //some asyn code that return a promise }   logger.measure('myMeasure', f1, "f1 measure").then((result) => console.log(`f1 result is ${result}`)); //more code... logger.logMeasurements('my message'); This code executes the same way as function measuring, except when getting a promise as the second parameter, measure's return value is a promise containing f1 result. You can do number of promise measures with the same name, it will act the same as number of function measures with the same name. install npm i dj-logger Downloadsweekly downloads 24 version 4.0.2 license ISC homepage github.com repository Gitgithub last publish collaborators • avatar
__label__pos
0.658915
Question Repeat Exercise 2.12 if the probability assignment is changed to: An experiment consists of tossing a coin twice and observing the sequence of coin tosses. The sample space consists of four outcomes ξ1 = (H, H), ξ2 (H, T), ξ3 (T, H), and ξ4 (T, T). Suppose the coin is not evenly weighted such that we expect a heads to occur more often than tails and as a result, we assign the following probabilities to each of the four outcomes: (a) Does this probability assignment satisfy the three axioms of probability? (b) Given this probability assignment, what is ? (c) Given this probability assignment, what is ? Sales0 Views37 Comments0 • CreatedNovember 19, 2015 • Files Included Post your question 5000
__label__pos
0.999803
# -*- perl -*- # # Copyright (C) 2004-2011 Daniel P. Berrange # # This program is free software; You can redistribute it and/or modify # it under the same terms as Perl itself. Either: # # a) the GNU General Public License as published by the Free # Software Foundation; either version 2, or (at your option) any # later version, # # or # # b) the "Artistic License" # # The file "COPYING" distributed along with this file provides full # details of the terms and conditions of the two licenses. =pod =head1 NAME Net::DBus::Binding::Message::Error - a message encoding a method call error =head1 SYNOPSIS use Net::DBus::Binding::Message::Error; my $error = Net::DBus::Binding::Message::Error->new( replyto => $method_call, name => "org.example.myobject.FooException", description => "Unable to do Foo when updating bar"); $connection->send($error); =head1 DESCRIPTION This module is part of the low-level DBus binding APIs, and should not be used by application code. No guarentees are made about APIs under the C namespace being stable across releases. This module provides a convenience constructor for creating a message representing an error condition. =head1 METHODS =over 4 =cut package Net::DBus::Binding::Message::Error; use 5.006; use strict; use warnings; use Net::DBus; use base qw(Net::DBus::Binding::Message); =item my $error = Net::DBus::Binding::Message::Error->new( replyto => $method_call, name => $name, description => $description); Creates a new message, representing an error which occurred during the handling of the method call object passed in as the C parameter. The C parameter is the formal name of the error condition, while the C is a short piece of text giving more specific information on the error. =cut sub new { my $proto = shift; my $class = ref($proto) || $proto; my %params = @_; my $replyto = exists $params{replyto} ? $params{replyto} : die "replyto parameter is required"; my $msg = exists $params{message} ? $params{message} : Net::DBus::Binding::Message::Error::_create ( $replyto->{message}, ($params{name} ? $params{name} : die "name parameter is required"), ($params{description} ? $params{description} : die "description parameter is required")); my $self = $class->SUPER::new(message => $msg); bless $self, $class; return $self; } =item my $name = $error->get_error_name Returns the formal name of the error, as previously passed in via the C parameter in the constructor. =cut sub get_error_name { my $self = shift; return $self->{message}->dbus_message_get_error_name; } 1; __END__ =back =head1 AUTHOR Daniel P. Berrange. =head1 COPYRIGHT Copyright (C) 2004-2009 Daniel P. Berrange =head1 SEE ALSO L =cut
__label__pos
0.993964
cancel Showing results for  Search instead for  Did you mean:  intapiuser Community Team Member Community Team Member Description Creating a clickable link control over a filter from another widget is a very common requirement. The end user clicks on a specific record inside of a PIVOT table. Then, a separate widget is being filtered based on the user choice.  Special thanks to Elliott Herz and Artem Yevtushenko for helping creating the script. Example When the end-user clicks on "Creative Preview", the "Item Preview" widget is being filtered based on the auto_id in the Items List. 1st Click -  2nd Click - Limitations The creation of the visible link script works currently with PIVOT table only Solution Steps 1. Create 2 Widgets and a dashboard filter-  a. The controlling widget - PIVOT table b. The controlled widget - BloX (works with every type of widget) c. Dashboard filter that is based on the same field of the first column of the controlling PIVOT widget and can effect on the controlled widget. The controlling widget - PIVOT table - The first column should include a value that will be send to the dashboard filter The controlled widget - BloX - The controlled widget has to be affected by the created dashboard filter - Test its effect by changing the filter value. - Copy to notepad the widget from the URL -  The dashboard filter Set the filter type to be a "Single Select" widget: Modify the script in the edit page of the controlling PIVOT widget: Replace a. var dim = [TableName.dashboardfilterfieldname] b. var iframeWidgetId = 'controlled widget id' var dim = "[Sheet1.auto_id]"; widget.on('domready', function(se, ev) { /*** USER CONFIGURATION **/ var columnToMakeUrls = 0; // set the column to make linkable (index starts at 0) var removeLinkDecoration = false; // remove the link underline var newText='Creative Preview'; // Replace the text in the column to be specifc text, leave blank to keep the original text var iframeWidgetId = '5c8fbdaa03aff6379426e2cb'; //replace with iframewidget oid var realColumnIndex = columnToMakeUrls + 1; //nth-child function is 1 based, make it zero for consistency with pivot version var cellsSelector = 'table tbody td:nth-child(' + realColumnIndex + ')'; var cells = $(cellsSelector, element); //get all the cells of the column var pivots = $('dashboard widget.columnar'); if (cells.length > 0) { cells.each(function() { createLinkHTML($(this)); }); } else { console.log('Cells were not found'); } // create html link tag according to the cell and tag function createLinkHTML(cell) { var linkElement = $(cell); var link = linkElement.text(); var linkText = newText || link; var htmlLink = '<a id="url" href="' + link + '" target="_blank">' + linkText + '</a>'; //var htmlLink = '<t>' + newText + '</t>'; if (removeLinkDecoration) { htmlLink = $(htmlLink).css('textDecoration', 'none').prop('outerHTML'); } linkElement.html(htmlLink); linkElement.on('click', function(event) { event.preventDefault(); // Find the iframe widget var matchingWidgets = prism.$ngscope.dashboard.widgets.$$widgets.filter(function(widget) { return widget.oid == iframeWidgetId; }); // Only run if there was a match var iframeWidget = $$get(matchingWidgets, '0',null); if (iframeWidget) { iframeWidget.dashboard.filters.$$items.forEach((item) => { if(item.jaql.dim === dim) { item.jaql.filter.members[0] = $(this).attr("val"); iframeWidget.dashboard.refresh(); } }); } }); } }); After saving the script and refreshing the PIVOT table widget edit page, the link should appear: Save the widget (apply) Check the functionality in the dashboard - click on the links and the controlled widget should react accordingly. Version history Last update: ‎03-02-2023 09:07 AM Updated by: Contributors Community Toolbox Recommended quick links to assist you in optimizing your community experience: Developers Group: Product Feedback Forum: Need additional support?: Submit a Support Request The Legal Stuff Have a question about the Sisense Community? Email [email protected] Share this page:
__label__pos
0.982627
System Management Showing results for  Search instead for  Do you mean  Is there a way to rename disk device names on Alpha's running Openvms? SOLVED Go to Solution Advisor Is there a way to rename disk device names on Alpha's running Openvms? We have an Alpha running Openvms in the far east which has the following internal disk devices configured once booted. DKA0: DKC0: DKC100: and so on   I have another Alpha which is connected to an EVA 4400 which when the disks are presented it configures the disk device names as follows: DGA17: DGA18: and so on   Does anyone know if there is a way to rename or force the names of the devices so they replicate the names in the far east? IE DGA17: is renamed to DKA0:? 7 REPLIES Highlighted Respected Contributor [Founder] Re: Is there a way to rename disk device names on Alpha's running Openvms? Rather than attempting to rename the devices (which is not possible), focus on using logical names that are not tied to specific hardware.   As an example:  Define/system/exec D0 DKC0:   With the above statement executed during startup, D0 is the same as DKC0.  Using this as the starting point, you can now set up the locical name definition in the startup files for each system and refer to D0 rather than either of the actual hardware device names.  This is the beauty of OpenVMS logical names.    Going further, you can use "concealed devices" which can further hide hardware (and directories).  I'll leave that portion of the discussion for a later time.   Dan Advisor Re: Is there a way to rename disk device names on Alpha's running Openvms? Thanks for the response. We do use logical names here, but unfortunatly, they have the actual device name hard-coded into most of the command files and data files, so I was looking at an easy way to get round amending all the occurrences within these files.   If it is not possible to rename the actual devices, I will have to write something to amend the command files and go through the data files manually.   Thanks for the response.  Honored Contributor [Founder] Re: Is there a way to rename disk device names on Alpha's running Openvms? In SYLOGICALS.COM $ Define/system/exec DKA0 _$1$DGA12:   etc   or edit command files to replace the device names with logical names.   ____________________ Purely Personal Opinion Respected Contributor [Founder] Re: Is there a way to rename disk device names on Alpha's running Openvms? As Ian pointed out, using the "_" will work.  Keep in mond, that this will further complicate things in the future.  Having been through a similar exercise recently, your time is better spent removing all device specific references once and for all.  In the code I just revised, there were up to 6 logical name translations to get from initial name to final device, all because of similar "patches" as you are describing.  Spending a little time simplified all of the procedures.   Dan Advisor Re: Is there a way to rename disk device names on Alpha's running Openvms? I was going to speak to them about changing these occurrences before the refresh to meet the best practice we follow. Thanks for the advice Honored Contributor [Founder] Re: Is there a way to rename disk device names on Alpha's running Openvms? Careful...   Prior to VAX/VMS V4.0, the leading _ underscore notation on a device specification bypassed the logical name translation.    With V4.0 and later, the leading _ doesn't bypass a logical name translation.   It's translated, and if the translation fails, gets stripped off and used.  To remap the _ddcu specification to a translation, simply define the logical name with the leading _ present, and the reference will be redirected to the translation.   Occasional Contributor Re: Is there a way to rename disk device names on Alpha's running Openvms? If you have volume shadowing license you can in a sense. Because with shadowing you can have e.q.   $ mount/sys dsa1:/shadow=$3$dkc0: usr urs   on one system and on another   $ mount/sys dsa1:/shadow=$1$dga17: usr usr   This was your users and apps would see consistent DSAnnn device names whatever the actual underlying hw names.   Downside is very small added overhead on io layer and possibly hefty pricetag on license. PLus side would be ability to actually shadow disks and move onto larger disks on the fly (depending on your VMS version) as after V7.3-2 VMS supports dissimilar device shadowing etc nice feafures.   _veli
__label__pos
0.737929
backtrader源码解读 (1):读懂源码的钥匙——认识元类 backtrader是著名的基于Python语言的量化工具,它可以帮助我们实现投资策略的回测、参数优化以及可视化,甚至可以接入实盘交易。 现如今有许多backtrader的使用教程,而解读backtrader源码的文章却寥寥无几。事实上,阅读backtrader的底层代码可以让我们理解它的工作原理,从而在使用它进行量化投资时实现更个性化的配置、更高效的debug、以及在必要时提高运行性能。 作为第一步,我们需要理解元类 (metaclass)。 事实上,backtrader采用了元编程的技术,在代码中引入了大量的元类。元类的使用节省了大量重复的代码,并实现了一些相对复杂的功能,然而代价就是让代码晦涩难懂。可以说,理解元类是畅读backtrader源码的基础,也是第一个难点。 在介绍元类之前,我们简单复习有关类的知识。在包括Python的多数语言中,类 (class) 用来创建对象 (object)。在example 1中,我们定义了类Student,并且让类Student创建对象s。 请注意,为了区分单一案例中的多次打印,我们会在每次打印的内容前加上数字标签。 # example 1 class Student: pass s = Student() print('[1]', s) [1] <__main__.Student object at 0x0000020BBA1DC4F0> 这里,我们称Student为类,是因为它可以创建对象。 在Python中,万物皆对象。所以,类也是对象 那么,既然类Student本身也是对象,那么它一定也是由某个"类"所创建。不卖关子,这个"类"是type,而type是一个元类。 1. 重新认识type 我们对type比较熟悉的功能是:把某个对象作为参数传给type,返回该对象的类型,见example 2。 # example 2 a = 1 print('[1]', type(a)) b = 'apple' print('[2]', type(b)) class Student: pass s = Student() print('[3]', type(s)) [1] <class 'int'> [2] <class 'str'> [3] <class '__main__.Student'> 然而,type还有一个完全不同的功能,那就是动态创建类,具体的方式如下: type(name, bases, dct) type接受三个参数,其中, • name:字符串,类的名称; • bases:元组,其元素为类的父类; • dct:字典,键为类的属性名或方法名,值为对应的属性值或函数; 并返回一个类。事实上,在我们使用class关键字定义类的时候,背后调用的就是type。 这么说有一些空洞,我们来举一个具体的例子。 在example 3.1中,我们用常规的方法,也就是class关键字,来定义类Dog1:类Dog1继承类Animal,并拥有类变量isAnimal,初始化方法__init__,以及实例方法run。 # example 3.1 class Animal: pass class Dog1(Animal): isAnimal = True def __init__(self, name): self.name = name def run(self): print(f'Dog {self.name} is running') print('[1]', Dog1.__mro__) d1 = Dog1('Puppy') print('[2]', d1.isAnimal) d1.run() [1] (<class '__main__.Dog1'>, <class '__main__.Animal'>, <class 'object'>) [2] True Dog Puppy is running 在example 3.2中,我们用type来创建类Dog2。 请注意,我们给type传递了三个参数:第一个参数'Dog2'代表创建类的名称;第二个参数bases是元组,其元素为创建类的父类;第三个参数dct是字典,该字典的键和值对应的是创建类的变量名和值,或者方法名和函数。 我们把type的返回值赋予Dog2。可以看到,Dog2的继承关系以及可实现的功能和Dog1一致。 # example 3.2 class Animal: pass bases = (Animal, ) def __init__(self, name): self.name = name def run(self): print(f'Dog {self.name} is running') dct = {'isAnimal': True, '__init__': __init__, 'run': run} Dog2 = type('Dog2', bases, dct) print('[1]', Dog2.__mro__) d2 = Dog2('Kala') print('[2]', d2.isAnimal) d2.run() [1] (<class '__main__.Dog2'>, <class '__main__.Animal'>, <class 'object'>) [2] True Dog Kala is running 2. 什么是元类 将example 3.2中动态创建类和类创建对象的两行代码放在一起进行比较,我们可以发现“上一级”创建“下一级”的方式非常类似:type创建类就好比类创建对象。 • type创建类Dog2:type后面加括号,括号里传入参数 Dog2 = type('Dog2', bases, attrs) • 类Dog2创建对象d2:Dog2后面加括号,括号里传入参数 d2 = Dog2('Kala') 请记住,在Python中,万物皆对象。只要是对象,那么它一定是由某个类所创建。我们可以通过对象的__class__属性来查看它是由什么类所创建,见example 4.1。 # example 4.1 a = 1 print('[1]', a.__class__) b = 'apple' print('[2]', b.__class__) def func(p1, p2): return p1 + p2 print('[3]', func.__class__) class Student: pass s = Student() print('[4]', s.__class__) [1] <class 'int'> [2] <class 'str'> [3] <class 'function'> [4] <class '__main__.Student'> 我们再次重申:在Python中,万物皆对象 这里的万物,是真正字面上的everything,它不仅包括例如example 4.1中的整数a、字符串b、函数func、或者是自定义类的实例对象s,也包括类本身。也就是说,类也是对象,它也是由某个类所创建。 所谓元类,是创建类的类。 在Python中,type是内置用来创建类的元类。如果不加以声明,所有的类默认都是由type来创建。 在example 4.2中,我们可以看到,创建int类、str类、function类、Student类的类都是type。 # example 4.2 print('[1]', a.__class__.__class__) print('[2]', b.__class__.__class__) print('[3]', func.__class__.__class__) print('[4]', s.__class__.__class__) [1] <class 'type'> [2] <class 'type'> [3] <class 'type'> [4] <class 'type'> 3. 自定义元类 在了解了什么是元类以及type是默认创建类的元类之后,我们提出这样一个问题:我们能否不用type来创建类,而是自定义的元类来创建类? 答案是yes! 在Python 3中,自定义元类创建类的基本方法为: • 第一步:创建元类,一个类必须继承type才能使其成为一个元类; • 第二步:创建类,使用关键词参数metaclass指定创建它的元类。 在example 5中,我们定义了元类MyMetaClass (因为它继承了type) ,并且指定它为创建类MyClass的元类。 # example 5 class MyMetaClass(type): pass class MyClass(metaclass = MyMetaClass): pass 这里我们查看类MyClass的__class__属性,显示的是元类MyMetaClass。 # example 5 - continued print('[1]', MyClass.__class__) [1] <class '__main__.MyMetaClass'> 我们再深挖一步,如果将元类MyMetaClass视作一个对象 (请始终牢牢记住:在Python中,万物皆对象) ,创建它的类是什么?通过查看元类MyMetaClass的__class__属性,我们得到:type创建了元类MyMetaClass。 # example 5 - continued print('[1]', MyMetaClass.__class__) [1] <class 'type'> 所以说,元类也是由type所创建。从这个层面上说,元类也是类。事实上,example 5第2至3行等价于下面的语句,这么一看就比较容易理解了。 MyMetaClass = type('MyMetaClass', (type, ), {}) 4. 元类的__new__方法 在学习了如何自定义元类创建类之后,我们不禁要问:这么做的意义是什么? 事实上,使用元类最主要的目的是在元类创建类的过程中按照我们的预设自动修改类。在实际应用场景中,大量不面向用户的“脏活累活”都被放在元类中处理,从而可以最终展现给用户一个简洁且直观的界面。这在backtrader中的运用非常常见,我们在后续的讲解中就会再次提及。 具体来说,实现上述目的主要依赖元类的__new__方法,该方法负责创建类:它将创建类所需要的“原料”作为参数传入,并返回一个类。 另外,在类的创建过程中,元类的__new__方法和__init__方法会被先后调用,前者负责创建类,后者负责类的初始化。在实际使用中,大多类的初始化工作都可以放在__new__方法中进行,所以为了代码简洁往往只需要定义__new__方法。在backtrader中,元类__new__方法的使用频率要远远高于元类__init__方法。 接下来,我们通过一个例子来详细了解元类的__new__方法。在example 6中,我们定义了元类MyMetaClass,并重写了它的__new__方法。 这里需要注意两点: 1. 我们让__new__方法接受动态参数*args,即无论__new__方法接受多少个位置参数都会打包进一个元组给args,我们再通过for循环依次打印args内的元素以展示元类的__new__方法创建类所需要的“原料”; 2. __new__方法需要返回一个对象,这一步还是交给"专业人士"type来做,我们会将所需要的参数args打散传递给type.__new__。 # example 6 class MyMetaClass(type): def __new__(*args): for i, item in enumerate(args): print(f'[{i}] {item}') return type.__new__(*args) 定义好元类MyMetaClass之后,我们让该元类创建类MyClass:该类的父类是类MyBaseClass,并拥有类变量var和实例方法func。 # example 6 - continued class MyBaseClass: pass class MyClass(MyBaseClass, metaclass = MyMetaClass): var = 1 def func(self): pass [0] <class '__main__.MyMetaClass'> [1] MyClass [2] (<class '__main__.MyBaseClass'>,) [3] {'__module__': '__main__', '__qualname__': 'MyClass', 'var': 1, 'func': <function MyClass.func at 0x00000221682CC040>} 通过example 6的打印结果,我们可以知晓,类MyClass的创建过程中调用了元类MyMetaClass的__new__方法,该方法接受四个参数,分别为: 1. 元类MyMetaClass自身; 2. 创建类的名称; 3. 创建类的父类组成的元组; 4. 创建类的属性名或方法名为键,对应的属性值或函数为值所组成的字典。 由于__new__方法是静态方法,所以无论是在定义还是调用时,第一个参数永远是定义它的类本身。另外,__new__方法第二、三、四个参数就是type创建类所接受的参数。在下文中,我们让元类的__new__方法通过四个形参:meta、name、bases、dct来接受实参,这里形参的命名与backtrader中一致。 在example 6中,我们重写了元类的__new__方法,让它做了除了创建类之外的事情:打印接受的参数。事实上,元类可以做更复杂的事情,最常见的方式是在__new__方法中改变接受的参数。在example 7中,我们用元类实现了这样的功能:元类创建类的属性名和方法名,只要不是以双下划线开头,均自动转化为大写。 # example 7 class UpperMetaClass(type): def __new__(meta, name, bases, dct): print('[1]', dct) upper_dct = { k if k.startswith("__") else k.upper(): v for k, v in dct.items() } return type.__new__(meta, name, bases, upper_dct) class MyClass(metaclass = UpperMetaClass): var = 1 def func(self): pass print('[2]', MyClass.__dict__) [1] {'__module__': '__main__', '__qualname__': 'MyClass', 'var': 1, 'func': <function MyClass.func at 0x00000221683B5550>} [2] {'__module__': '__main__', 'VAR': 1, 'FUNC': <function MyClass.func at 0x00000221683B5550>, '__dict__': <attribute '__dict__' of 'MyClass' objects>, '__weakref__': <attribute '__weakref__' of 'MyClass' objects>, '__doc__': None} 具体来说,example 7中功能的实现经历了以下几个步骤: 1. 我们在类MyClass中定义了属性var和方法func,随后元类UpperMetaClass介入类MyClass的创建; 2. 这些属性名或方法名与对应的值或函数组成的键值对构成的字典传给了元类UpperMetaClass的__new__方法的形参dct; 3. 在元类UpperMetaClass的__new__方法内部,我们对字典dct进行了修改:只要dct的键不是以双下划线开头则转化为大写,并将修改后的字典赋给upper_dct; 4. 在将参数传递给type.__new__创建类时,我们将dct替换成upper_dct,随后类MyClass创建完成。 通过上面的步骤,我们可以理解元类是如何实现"黑魔法"的: 1. 介入类的创建; 2. 对类进行修改; 3. 返回修改后的类。 以上的工作机制在backtrader中运用得非常广泛。 5. 小结 元编程是backtrader的底层技术,理解元类是畅读backtrader源码的基础。本文作为backtrader源码解读系列文章的第一篇,根据元类在backtrader中的应用对重要知识点进行了介绍,这其中包括type动态创建类、自定义元类、元类常用工作机制之__new__方法等。 参考: backtrader源码解读 (1):读懂源码的钥匙——认识元类 0 0 投票数 Article Rating 订阅评论 提醒 guest 0 评论 内联反馈 查看所有评论 0 希望看到您的想法,请您发表评论x
__label__pos
0.92801
Tutoriales cargando... Tutorial 3 para SEO - Para construir tu sitio web teniendo la optimizacion en motores de busqueda o SEO en mente. 1.  Para crear contenido que sea compatible con los motores de búsqueda La mayoría del contenido que un motor de búsqueda puede ver en un sitio web es contenido escrito (al contrario de imágenes, etc.). si deseas que los motores de búsqueda gusten de tu sitio web y que te envíen visitantes, entonces debes tener una cantidad considerable de contenido escrito.  Manteniendo el enfoque del tema en las paginas   Cuando comiences a desarrollar una de las paginas de tu sitio considera el enfoque principal de la misma y revisa tu lista de palabras clave - ¿cuáles son las palabras clave que mejor describen el contenido de esta pagina?   Existen ciertas áreas de una pagina web que son importantes ya que le “avisan” al motor de búsqueda de que se trata esta pagina. Un buen plan a seguir cuando estés creando una pagina es mantener el enfoque de la misma a través de la integración de las palabras clave en áreas como: • La etiqueta del titulo • La etiqueta de descripción • La etiqueta de palabras clave • Los encabezados • El formato especial, tal como negrita o cursiva • A lo largo de todo el contenido escrito • En enlaces de texto 2. Para escribir las etiquetas de titulo, descripción y palabras clave Cada una de estas meta-etiquetas (titulo, descripción y palabras clave) puede ser agregada en tu sitio a través del menú de Pagina > Propiedades de pagina.  • El espacio designado Titulo de la ventana es en donde vas a introducir tu etiqueta de titulo. Esta etiqueta debería de incluir la palabra clave o concepto principal de tu pagina, el nombre de tu empresa o tu sitio web, y tu ubicación geográfica si consideras que esto es importante para tus visitantes. Por otro lado también es recomendable que no tenga mas de 70 caracteres en tamaño.  Este es un ejemplo básico:                                     Joyería de Oro Fino | Compañía Joyera ABC | Cuidad, Estado  • El espacio designado Descripción es en donde vas a introducir tu etiqueta de descripción. Esta etiqueta debería de incluir la palabra clave o concepto principal de tu pagina, el nombre de tu compañía, y tu ubicación geográfica si consideras que esto es importante para tus visitantes. Debe de contener no mas de 200 caracteres y tiene que atraer a los visitantes para que hagan clic. Este es un ejemplo:                                     La Compañía Joyera ABC le proporciona a los clientes de mi cuidad y los alrededores de mi estado la joyería mas fina a base de oro                                                       regular y blanco importada directamente desde Italia ¡Visítanos hoy mismo!   • El espacio designado Palabras clave es en donde vas a introducir las palabras clave principales para la pagina. No amontones palabras clave, introduce únicamente las palabras que estén relacionadas directamente con el contenido de la pagina. Este es un ejemplo:                                     Joyería fina de oro, joyería de oro, joyas de oro blanco, Compañía Joyera ABC, Ciudad, Estado   3. Para incorporar las palabras clave en el contenido  Cuando escribes el contenido de una pagina las palabras clave deben de mezclarse de forma natural – no exageres el uso de palabras clave o los motores de búsqueda van a ignorar la pagina. El contenido de internet debe de ser fácil de acceder y “ojear” para el usuario. Tu puedes generar este efecto con:  • Párrafos pequeños. • Separaciones lógicas en el contenido de las pagina con encabezados y subtítulos.   • Listas enumeradas y puntuadas.  • Texto en negrita o cursiva (esto es mas útil para el motor de búsqueda que para el lector, no exageres).  • Crear palabras clave que a su vez son enlaces.  A continuación se presenta un pequeño ejemplo utilizando el sitio web de la Compañía Joyera ABC acerca de la joyería fina de oro. Considera los lugares en donde las palabras clave “joyería fina de oro” son utilizadas.                                                                                                                                                                                       Disfruta de joyería fina de oro     Las joyas de oro nunca pasan de moda, y por buenas razones. La joyería fina de oro ha adornado los cuerpos de las personas por cientos de años, desde la realeza hasta las personas comunes y corrientes. La compra de joyería de oro puede ser una experiencia muy reconfortante ¿Estas buscando el tipo de prendas de oro que no puedes conseguir en tu localidad? En la Compañía Joyera ABC nos especializamos en el oro de clase Premium para crear las prendas que marcaran esa ocasión especial es tu vida.    Lo que debes tener en mente al momento de comprar joyería fina de oro: • El tipo de uso y desgaste que la prenda va a tener.  • La persona dueña de la prenda, prefiere el oro blanco o regular? • ¿Cuál es tu presupuesto?  Si lo deseas, puedes obtener información mas especifica acerca de la joyería fina de oro aquí en nuestro sitio web. Tenemos una fuerte pasión por el oro y la queremos compartir contigo                                                                                                                                                                                            4. Para asignar texto alternativo a las imágenes  Los motores de búsqueda no pueden “ver” gráficos ya que operan en base a texto. Sin embargo, tu puedes ayudar a que los motores de búsqueda reconozcan o “vean” tus gráficos por medio de la asignación de algo llamado un “atributo alternativo” o “texto alternativo” o “alt-text” por su definición en ingles.    Si agregaste la imagen utilizando el widget de imagen, puedes hacer lo siguiente para agregar texto alternativo: 1. Haz clic en el área del componente y luego haz clic en “Editar” que esta en la esquina superior izquierda.  2. En la ventana de dialogo que se abre, ubica el campo denominado “texto alternativo” e introduce una descripción de tu imagen.  3. Una vez que hayas terminado haz clic en “Guardar” y el texto será asignado a la imagen.  También puedes asignar texto alternativo a las imágenes que has agregado con el widget de texto, pero para esto necesitas editar el código HTML: 1. Haz clic en el área del widget de texto y luego haz clic en el botón HTML que se encuentra en el extremo derecho de la barra de herramientas del editor de texto.  2. Luego se abrirá el editor de texto con los códigos HTML de widget de texto. Ahora necesitas localizar el código de tu imagen, éste código va a comenzar con <image scr = “ 3. Edita esta porción de código para que quede parecido a  esto: <img src="filename.gif" alt="El Texto Alternativo va aquí"> 4. En la porción de texto que haz editado, reemplaza “El Texto Alternativo va aquí” con el texto alternativo que deseas asignar a tu imagen. 5. Una vez que hayas terminado haz clic en “Aceptar” y luego el texto será asignado en tu imagen.  5. Para crear enlaces de texto o “hipervínculos” que sean compatibles con los motores de búsqueda.  Los motores de búsqueda analizan los enlaces de texto de un sitio web y también verifican y toman nota del texto que esta siendo utilizado. Al convertir tus palabras clave en hipervínculos estarás aumentando aun mas la relevancia de estas palabras en tu sitio. Para convertir texto en hipervínculo en el Constructor de Sitios sigue estos pasos: 1. Haz clic en el área del componente de texto y resalta las palabras que deseas convertir en un hipervínculo.  2. Luego haz clic en el botón “Enlace” que se encuentra en la parte central de la barra de herramientas del editor de texto.  3. A continuación selecciona hacia donde o con que deseas que el texto esté vinculado. 4. Haz clic en “Aceptar” y el texto será convertido en un hipervínculo. 
__label__pos
0.797295
fibonacci series in c Today, We want to share with you fibonacci series in c.In this post we will show you What is the Fibonacci sequence? & fibonacci series program in c using recursion, hear for Fibonacci Series generates subsequent number by including two previous numbers. we will give you demo and example for implement.In this post, we will learn about GO Program To Display Fibonacci Sequence with an example. Fibonacci Series Program In C each number is the sum of the two previous numbers. The first two numbers in the Fibonacci series are 0 and 1. Fibonacci series satisfies the following conditions − Fn = Fn-1 + Fn-2 The beginning of the sequence is thus: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …….. Algorithm Algorithm of this fibonacci series is very simply − START Step 1 → Take integer variable A, B, C Step 2 → Set A = 0, B = 0 Step 3 → DISPLAY A, B Step 4 → C = A + B Step 5 → DISPLAY C Step 6 → Set A = B, B = C Step 7 → REPEAT from 4 - 6, for n times STOP Fibonacci Series up to n series Example 1: #include <stdio.h> int main() { int i, n, firstVal = 0, secondVal = 1, andThenValue; printf("Enter the number of series: "); scanf("%d", &n); printf("Fibonacci Series: "); for (i = 1; i <= n; ++i) { printf("%d, ", firstVal); andThenValue = firstVal + secondVal; firstVal = secondVal; secondVal = andThenValue; } return 0; } Output Enter the number of series: 10 Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, Fibonacci Sequence Up to a Certain Number Example 2: #include <stdio.h> int main() { int firstVal = 0, secondVal = 1, andThenValue = 0, n; printf("Enter a positive number: "); scanf("%d", &n); printf("Fibonacci Series: %d, %d, ", firstVal, secondVal); andThenValue = firstVal + secondVal; while (andThenValue <= n) { printf("%d, ", andThenValue); firstVal = secondVal; secondVal = andThenValue; andThenValue = firstVal + secondVal; } return 0; } Output Enter a positive integer: 100 Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, C Fibonacci Series Program using For Loop Example 3: #include <stdio.h> int main() { int Number, Next, i, First_Value = 0, Second_Value = 1; printf("\n Please Enter the Range Number: "); scanf("%d",&Number); for(i = 0; i <= Number; i++) { if(i <= 1) { Next = i; } else { Next = First_Value + Second_Value; First_Value = Second_Value; Second_Value = Next; } printf("%d \t", Next); } return 0; } Fibonacci series in C using Functions #include<stdio.h> void ExampleOfFiboDemo_series(int Number) ; int main() { int Number; printf("Enter the number of series\n"); scanf("%d", &Number); printf("ExampleOfFiboDemo series First %d Numbers:\n", Number); ExampleOfFiboDemo_series(Number) ; return 0; } void ExampleOfFiboDemo_series(int Number) { int i, First_Value = 0, Second_Value = 1, Next; for(i = 0; i <= Number; i++) { if(i <= 1) { Next = i; } else { Next = First_Value + Second_Value; First_Value = Second_Value; Second_Value = Next; } printf("%d\t", Next); } } Fibonacci series in C using Recursion #include<stdio.h> int ExampleOfFiboDemo_Series(int); int main() { int Number, i = 0, j; printf("\n Please Enter Number upto which you want too: "); scanf("%d", &Number); printf("Fibonacci series\n"); for ( j = 0 ; j <= Number ; j++ ) { printf("%d\t", ExampleOfFiboDemo_Series(j)); } return 0; } int ExampleOfFiboDemo_Series(int Number) { if ( Number == 0 ) return 0; else if ( Number == 1 ) return 1; else return ( ExampleOfFiboDemo_Series(Number - 1) + ExampleOfFiboDemo_Series(Number - 2) ); } I hope you get an idea about fibonacci series program in c using recursion. I would like to have feedback on my infinityknow.com blog. Your valuable feedback, question, or comments about this article are always welcome. If you enjoyed and liked this post, don’t forget to share.
__label__pos
0.996698
Solved Drawing a highlighted bitmap Posted on 2001-06-04 11 330 Views Last Modified: 2013-12-03 I want to draw a highlighted bitmap like the explorer when you select a item (with icon). Does anyone knows how can i do that? 0 Comment Question by:bugroger [X] Welcome to Experts Exchange Add your voice to the tech community where 5M+ people just like you are talking about what matters. • Help others & share knowledge • Earn cash & points • Learn & ask questions 11 Comments   LVL 9 Expert Comment by:ginsonic ID: 6154938 Can you give me more details , please? 0   LVL 14 Expert Comment by:DragonSlayer ID: 6155284 listening... 0   LVL 2 Author Comment by:bugroger ID: 6155371 more details: ex.  When you click on an exe-file in the explorer  the text changed to clHighlightText/clhighlight  and the icon from the exe-file will be displayed  darker.  How can I "convert" a normal icon/bitmap to such  a "darker" icon/bitmap? 0 Technology Partners: We Want Your Opinion! We value your feedback. Take our survey and automatically be enter to win anyone of the following: Yeti Cooler, Amazon eGift Card, and Movie eGift Card!   LVL 2 Author Comment by:bugroger ID: 6155811 I found the ImgList_DrawEx function. With this function you can draw a "selcected Bitmap". So you can write a function which convert a Bitmap to a "darker" bitmap. 0   LVL 34 Expert Comment by:Slick812 ID: 6157531 hello bugroger, here is some code that I used to TRY to simulate the Icon hilighting used in windows explorer windows. This uses a PatBlt with the dwRop set to $A000C9, which might be undocumented, it is a pixel blending dwRop operation. I never got an exact match for the windows highlighting operation, but this was close enough for me to use as a visual image highlighting method. private bmp: TBitmap; procedure TForm1.FormCreate(Sender: TObject); var i, k, Dot: Integer; begin {this creates a 8x8 bitmap for your Brush, I put it in create because I used this bmp many, many times} bmp:= TBitmap.Create;   With bmp Do   Begin   width := 8;   height:= 8;   PixelFormat := pf24Bit;   Dot := 0;   for i:= 0 to 7 do   begin     for k:= 0 to 7 do     if ((k+ Dot) mod 2) <> 0 then     canvas.Pixels[k,i] := clSilver     else     canvas.Pixels[k,i] := GetSysColor(COLOR_HIGHLIGHT)}; {if you don't need the same color highlight as windows, you can try clGray here or your own color}     Inc(Dot)   end;     End; end; procedure TForm1.Button_HiLiteClick(Sender: TObject); var FirstPic: TBitmap; begin if OpenpictureDialog1.Execute then   begin   FirstPic := TBitmap.Create;   FirstPic.LoadFromFile(OpenpictureDialog1.FileName); {if the bitmap is not 24 Bit then colors will be blocky}   FirstPic.PixelFormat := pf24bit; {set brush bitmap to the one you created}   FirstPic.Canvas.Brush.Bitmap := bmp; {you can try FirstPic.Canvas.Brush.Color := clHighlight ,  and you don't need the bmp or bitmap brush at all, but this didn't look close enough to the windows highlight for me} {this will blend the FirstPic with the bmp brush, and then it's ready to use}   PatBlt(FirstPic.Canvas.Handle, 0, 0, FirstPic.Width, FirstPic.Height, $A000C9);   Canvas.Draw(0,0,FirstPic); // use bitmap   FirstPic.Free;   end; end; procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction); begin bmp.Free; end; - - - - - - - - - - - - - - - - - - - - - - there must be an undocumented dwRop for the windows highlighting operation, but I couldn't find it. 0   LVL 34 Expert Comment by:Slick812 ID: 6158116 correction, I should have put this for k:= 0 to 7 do     if ((k+ Dot) mod 2) <> 0 then     canvas.Pixels[k,i] := $00AAAAAA     else     canvas.Pixels[k,i] := clHightLight; 0   LVL 2 Author Comment by:bugroger ID: 6158859 I have written my own function to highlight a bitmap. I have used ALPHA-BLENDING to realized that. NewRed    = Rs*Sr+Rd*Dr NewGreen  = Gs*Sg+Gd*Dg NewBlue   = Bs*Sb+Bd*Db NewFactor = As*Sa+Ad*Da   Rs=FactorSourceRed    | Sr=SourceRed     |   Rd=FactorDestRed      | Dr=DestRed   Gs=FactorSourceGreen  | Sg=SourceGreen   |   Gd=FactorDestGreen    | Dg=DestGreen         Bs=FactorSourceBlue   | Sb=SourceBlue    |   Bd=FactorDestBlue     | Db=DestBlue   As=FactorSourceFactor | Sa=SourceFactor  |   Ad=FactorDestFactor   | Da=DestFactor //Alpha 0.0 - 1.0 Procedure BlendWithColor(Src, Dest : TBitmap; BlendColor : TColor; Alpha : Real); TYPE  TRGB = record          r, g, b, PALType : Byte;         end;  TpRGB = packed record           b, g, r : Byte;          end; VAR  BlendColorChannels : TRGB;  DestRGBPixel       : ^TpRGB;  SrcRGBPixel        : ^TpRGB;  y, x               : Integer;  SourceColorFaktor  : real; Begin  //Set BitPerPixel -> 24Bit  Src.PixelFormat  := pf24Bit;  Dest.PixelFormat := pf24Bit;  Dest.Width       := Src.Width;  Dest.Height      := Src.Height;  //Get RGB-Channels from Color  BlendColorChannels := TRGB(BlendColor);  IF BlendColorChannels.PalType = 128 then   BlendColorChannels := TRGB(GetSysColor((BlendColor AND $0000FFFF)));  //Get SourceColorFaktor  SourceColorFaktor := 1.0 - Alpha;  //Get all Pixels  For y := 0 to Dest.Height -1 do  Begin   //Get Pixel   SrcRGBPixel  := Src.ScanLine[y];   DestRGBPixel := Dest.ScanLine[y];   For x := 0 to Dest.Width -1 do   Begin    DestRGBPixel.r := Round(SourceColorFaktor * SrcRGBPixel.r  + Alpha * BlendColorChannels.r);    DestRGBPixel.g := Round(SourceColorFaktor * SrcRGBPixel.g  + Alpha * BlendColorChannels.g);    DestRGBPixel.b := Round(SourceColorFaktor * SrcRGBPixel.b  + Alpha * BlendColorChannels.b);      //Set Pointer to next Pixel    Inc(DestRGBPixel);    Inc(SrcRGBPixel);   End;  End; End; 0   LVL 34 Expert Comment by:Slick812 ID: 6162005 well bugroger, I like your code and it works real good, but its not an exact match for the windows icon highlighting effect, at least not on my puters. I got very close results with the alpha set to  .61 - I added a line to help the highlighted look with dark colors For x := 0 to Dest.Width -1 do  Begin   if SrcRGBPixel.r + SrcRGBPixel.g + SrcRGBPixel.b < 64 then   begin   DestRGBPixel.r := SrcRGBPixel.r;   DestRGBPixel.g := SrcRGBPixel.g;   DestRGBPixel.b := SrcRGBPixel.b;   end else   begin   DestRGBPixel.r := Round(SourceColorFaktor * SrcRGBPixel.r  + Alpha * BlendColorChannels.r);   DestRGBPixel.g := Round(SourceColorFaktor * SrcRGBPixel.g  + Alpha * BlendColorChannels.g);   DestRGBPixel.b := Round(SourceColorFaktor * SrcRGBPixel.b  + Alpha * BlendColorChannels.b);   end;   //Set Pointer to next Pixel   Inc(DestRGBPixel);   Inc(SrcRGBPixel);  End; - - - - - - - good work 0   LVL 2 Author Comment by:bugroger ID: 6162936 Here is my new code to get an exact match for the "windows icon highlighting effect." I have used ROUND(INT(......))...  For y := 0 to Dest.Height -1 do  Begin   //Get Pixel   SrcRGBPixel  := Src.ScanLine[y];   DestRGBPixel := Dest.ScanLine[y];   For x := 0 to Dest.Width -1 do   Begin     DestRGBPixel.r := ROUND(INT(SourceColorFaktor *     SrcRGBPixel.r  + BlendingColorFaktor *        BlendColorChannels.r));     DestRGBPixel.g := ROUND(INT(SourceColorFaktor *      SrcRGBPixel.g  + BlendingColorFaktor *       BlendColorChannels.g));     DestRGBPixel.b := ROUND(INT(SourceColorFaktor * SrcRGBPixel.b  + BlendingColorFaktor * BlendColorChannels.b));    //Set Pointer to next Pixel    Inc(DestRGBPixel);    Inc(SrcRGBPixel);   End;   0   LVL 34 Accepted Solution by: Slick812 earned 100 total points ID: 6165783 this looks like a match for me  - - - - - - var Dot: Integer; Dot := 0; For x := 0 to Dest.Width -1 do  Begin   if ((x+ Dot) mod 2) = 0 then   begin   DestRGBPixel.r := Round(0.38 * SrcRGBPixel.r  + 0.4 * BlendColorChannels.r);   DestRGBPixel.g := Round(0.38 * SrcRGBPixel.g  + 0.4 * BlendColorChannels.g);   DestRGBPixel.b := Round(0.38 * SrcRGBPixel.b  + 0.4 * BlendColorChannels.b);   end else   begin   DestRGBPixel.r := Round(0.38 * SrcRGBPixel.r  + 0.62 * BlendColorChannels.r);   DestRGBPixel.g := Round(0.38 * SrcRGBPixel.g  + 0.62 * BlendColorChannels.g);   DestRGBPixel.b := Round(0.38 * SrcRGBPixel.b  + 0.62 * BlendColorChannels.b);   end;   //Set Pointer to next Pixel   Inc(DestRGBPixel);   Inc(SrcRGBPixel);  End;  Inc(Dot); End; 0   LVL 6 Expert Comment by:edey ID: 6484042 Actually, if you look very carefully at a "selected" icon you can see that it's just had a mask drawn over it like this: * * * * * * * *  * * * * * * * * * * * * * * *  * * * * * * * * * * * * * * *  * * * * * * * * * * * * * * * where the spaces are transparent & the *'s are dark blue.  You could (if you've already got the "checkerboard" mask) do this with a couple of blts: bmp.canvas.copyMode := cmMergeCopy; bmp.canvas.draw(0,0,mask_bmp); bmp.canvas.copymode := cmMergePaint; bmp.canvas.draw(0,0,mask_bmp); GL Mike 0 Featured Post On Demand Webinar: Networking for the Cloud Era Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection. Question has a verified solution. If you are experiencing a similar issue, please ask a related question Introduction The parallel port is a very commonly known port, it was widely used to connect a printer to the PC, if you look at the back of your computer, for those who don't have newer computers, there will be a port with 25 pins and a small print… Introduction I have seen many questions in this Delphi topic area where queries in threads are needed or suggested. I know bumped into a similar need. This article will address some of the concepts when dealing with a multithreaded delphi database… Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo… If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo… 695 members asked questions and received personalized solutions in the past 7 days. Join the community of 500,000 technology professionals and ask your questions. Join & Ask a Question
__label__pos
0.510265
blob: f679f8a4ac4fd4937cba54e8cab054124318b65b [file] [log] [blame] // Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/public/renderer/media_stream_utils.h" #include <memory> #include <utility> #include "base/callback.h" #include "base/guid.h" #include "base/rand_util.h" #include "base/strings/utf_string_conversions.h" #include "content/renderer/media/external_media_stream_audio_source.h" #include "content/renderer/media/media_stream_video_capturer_source.h" #include "content/renderer/media/media_stream_video_source.h" #include "content/renderer/media/media_stream_video_track.h" #include "media/base/audio_capturer_source.h" #include "media/capture/video_capturer_source.h" #include "third_party/WebKit/public/platform/WebMediaStream.h" #include "third_party/WebKit/public/platform/WebMediaStreamSource.h" #include "third_party/WebKit/public/web/WebMediaStreamRegistry.h" namespace content { bool AddVideoTrackToMediaStream( std::unique_ptr<media::VideoCapturerSource> video_source, bool is_remote, blink::WebMediaStream* web_media_stream) { DCHECK(video_source.get()); if (!web_media_stream || web_media_stream->IsNull()) { DLOG(ERROR) << "WebMediaStream is null"; return false; } blink::WebMediaStreamSource web_media_stream_source; MediaStreamVideoSource* const media_stream_source = new MediaStreamVideoCapturerSource( MediaStreamSource::SourceStoppedCallback(), std::move(video_source)); const blink::WebString track_id = blink::WebString::FromUTF8(base::GenerateGUID()); web_media_stream_source.Initialize( track_id, blink::WebMediaStreamSource::kTypeVideo, track_id, is_remote); // Takes ownership of |media_stream_source|. web_media_stream_source.SetExtraData(media_stream_source); web_media_stream->AddTrack(MediaStreamVideoTrack::CreateVideoTrack( media_stream_source, MediaStreamVideoSource::ConstraintsCallback(), true)); return true; } bool AddAudioTrackToMediaStream( scoped_refptr<media::AudioCapturerSource> audio_source, int sample_rate, media::ChannelLayout channel_layout, int frames_per_buffer, bool is_remote, blink::WebMediaStream* web_media_stream) { DCHECK(audio_source.get()); if (!web_media_stream || web_media_stream->IsNull()) { DLOG(ERROR) << "WebMediaStream is null"; return false; } const media::AudioParameters params( media::AudioParameters::AUDIO_PCM_LOW_LATENCY, channel_layout, sample_rate, sizeof(int16_t) * 8, frames_per_buffer); if (!params.IsValid()) { DLOG(ERROR) << "Invalid audio parameters."; return false; } blink::WebMediaStreamSource web_media_stream_source; const blink::WebString track_id = blink::WebString::FromUTF8(base::GenerateGUID()); web_media_stream_source.Initialize( track_id, blink::WebMediaStreamSource::kTypeAudio, track_id, is_remote); MediaStreamAudioSource* const media_stream_source = new ExternalMediaStreamAudioSource(std::move(audio_source), sample_rate, channel_layout, frames_per_buffer, is_remote); // Takes ownership of |media_stream_source|. web_media_stream_source.SetExtraData(media_stream_source); blink::WebMediaStreamTrack web_media_stream_track; web_media_stream_track.Initialize(web_media_stream_source); if (!media_stream_source->ConnectToTrack(web_media_stream_track)) return false; web_media_stream->AddTrack(web_media_stream_track); return true; } void RequestRefreshFrameFromVideoTrack( const blink::WebMediaStreamTrack& video_track) { if (video_track.IsNull()) return; MediaStreamVideoSource* const source = MediaStreamVideoSource::GetVideoSource(video_track.Source()); if (source) source->RequestRefreshFrame(); } } // namespace content
__label__pos
0.968338
Find the Derivative - d/dx 2x^2 Find the Derivative - d/dx 2x^2 Since is constant with respect to , the derivative of with respect to is . Differentiate using the Power Rule which states that is where . Multiply by . Do you need help with solving Find the Derivative - d/dx 2x^2? We can help you. You can write to our math experts in our application. The best solution for you is above on this page.
__label__pos
0.624011
New Latitude 5470 Discussion in 'Dell Latitude, Vostro, and Precision' started by jasperjones, Dec 16, 2015. 1. jasperjones jasperjones Notebook Evangelist Reputations: 293 Messages: 427 Likes Received: 4 Trophy Points: 31 So, it seems some new Latitudes can now be ordered. I'm looking at the Latitude 5470. I like that it has a quad in the standard config. It seems they ship with an M.2 SSD. It's not clear to me whether a bay for a 2.5" hard disk is also available. Does anyone know?   2. win32asmguy win32asmguy Moderator Moderator Reputations: 475 Messages: 1,877 Likes Received: 621 Trophy Points: 131 I took a look at these new models and it appears that you have a couple of different configuration options: i5 + dedicated graphics + M.2 SSD i5 / i7 + integrated graphics + 2.5" HDD / M.2 SSD I like the fact that we can get a nice beefy quad core without dedicated graphics, still supporting the edock. This should be a great Linux machine. The bigger brother of this model, the E5570, also has an optional Thunderbolt 3 port and larger battery available. Also, the FHD displays should be wide viewing angle (IPS), according to the service manual, even though the configurator does not mention it.   jasperjones likes this. 3. jasperjones jasperjones Notebook Evangelist Reputations: 293 Messages: 427 Likes Received: 4 Trophy Points: 31 ^^^ Thanks! I just talked to Dell's customer support (EMEA). In our region, they only sell the new 14" Latitude 5470 with M.2 SSDs. (There's no option for a dedicated GPU, either, which is fine by me.) The laptop has an additional slot for 2.5 inch drives with a z-heigth of 7 mm, but it's not officially supported. But, I mean, who cares? You can still just go ahead and fit a second drive aftermarket...   huntnyc likes this. 4. M0del M0del Notebook Enthusiast Reputations: 0 Messages: 37 Likes Received: 4 Trophy Points: 16 Quad-Core in a 14 inch chassis with business quality is a rare thing... Sadly no TB3 slot.   Kent T likes this. 5. jasperjones jasperjones Notebook Evangelist Reputations: 293 Messages: 427 Likes Received: 4 Trophy Points: 31 What do you need it for? It supports the e-dock. (So no reason to go for a TB-based dock.) TB devices are rare and pretty much overpriced. It's about the gazillion-th new port Apple is pushing. They will let it die in a few years just as they always do (cf. Firewire, DVI, Mini-DP etc.)   Kent T likes this. 6. gametime10 gametime10 Notebook Consultant Reputations: 2 Messages: 117 Likes Received: 16 Trophy Points: 31 What would get better graphics performance: Dual-Core Broadwell + 840M (5450) or Quad-Core Skylake + HD530 (5470)?   7. John Ratsey John Ratsey Moderately inquisitive Super Moderator Reputations: 6,839 Messages: 28,775 Likes Received: 1,706 Trophy Points: 581 You can compare the GPU performance at notebookcheck. There's not a big difference in some benchmarks but more significant in others so you have to figure out what is relevant to your possible usage. John   gametime10 likes this. 8. M0del M0del Notebook Enthusiast Reputations: 0 Messages: 37 Likes Received: 4 Trophy Points: 16 Would be a nice platform for an eGPU via TB3 - cause of the 14' and Quad-Core.   9. win32asmguy win32asmguy Moderator Moderator Reputations: 475 Messages: 1,877 Likes Received: 621 Trophy Points: 131 Yep, seems silly its missing given the XPS 13 and Alienware 13 have it.   10. jasperjones jasperjones Notebook Evangelist Reputations: 293 Messages: 427 Likes Received: 4 Trophy Points: 31 I see. I checked out eGPU a bit and am shocked how popular it is on Notebookreview. Call me old-fashioned, but if I was a gamer, I would play on a desktop for sure. Anyways, I don't fault Dell for not providing TB3 in the 5470. I doubt a significant number of their customers needs it.   Loading... Share This Page
__label__pos
0.846241
The Importance of Responsive Web Design in Enhancing User Experience Discover why responsive web design is crucial in today's digital landscape, including benefits, best practices, and how it impacts SEO. In the digital era, having a website that adjusts fluidly across various devices and screen sizes is no longer optional but a critical aspect of web design. Responsive web design ensures that a website's content and layout provide an optimal viewing experience for users, irrespective of the device they are using. This approach uses flexible grids, layouts, and CSS media queries to adapt the presentation of a website to the user's environment. With a multitude of devices in the market, from smartphones to large desktop monitors, responsive design helps in maintaining consistency in functionality and aesthetics. A laptop, tablet, and smartphone displaying a website, all seamlessly adjusting to different screen sizes The adoption of responsive web design offers significant advantages, including improved user experience and enhanced SEO performance. As web browsing behaviors shift towards mobile devices, it becomes essential for websites to be accessible and navigable on smaller screens without losing functionality. This adaptability not only helps retain visitors but also supports a website's ranking on search engines, where mobile-friendliness is a ranking factor. Moreover, with responsive design, site owners can avoid the need for a separate mobile site, streamlining content management and ensuring that all users get access to the same information. Key Takeaways • Responsive web design adapts a website's layout to the user's device for an optimized viewing experience. • This design approach enhances user satisfaction and supports SEO efforts. • A single adaptable website eliminates the need for multiple device-specific versions. Fundamentals of Responsive Web Design A laptop displaying a website on a desk, with a smartphone and tablet nearby. The website adjusts seamlessly as the devices are resized Responsive web design is an approach aiming to create websites that offer an optimal viewing experience across a wide range of devices. Below, the core concepts behind this critical aspect of modern web development are dissected to impart a better understanding of its significance. Defining Responsive Web Design Responsive Web Design (RWD) is a web development methodology that creates dynamic changes to the appearance of a website, depending on the screen size and orientation of the device being used to view it. This strategy of adapting to users' needs ensures that the website maintains functionality and aesthetic quality at all times. The Evolution of Web Design Web design has transitioned from static pages suited for desktop display to flexible layouts that adjust seamlessly across different devices, such as smartphones and tablets. This transition underscores the shift towards a mobile-first approach, where the rise in mobile traffic has necessitated designs that cater to varying screen sizes. Key Principles of Responsiveness Adaptability: The layout of a website must fluidly adapt to different screen sizes. Utilizing flexible grids and layouts, responsive websites reposition content based on device dimensions.Images: They remain within their containing elements without overflowing thanks to techniques for responsive images.Media Queries: CSS media queries form the cornerstone of RWD by allowing the page to use different CSS style rules based on device characteristics, mainly width.Performance: Sites must not only look good but also load efficiently, emphasizing the optimal usability regardless of the device. Impact and Benefits of Responsive Design A diverse array of devices displaying a website, all seamlessly adapting to different screen sizes, showcasing the impact and benefits of responsive design Responsive Web Design offers a seamless and consistent experience across different device and screen sizes. It's essential in a world where mobile browsing prevails. Enhanced User Experience A responsive website automatically adjusts its layout, images, and content to fit the device's screen size, leading to a more intuitive and satisfying user experience. This adaptability means that users are more likely to stay on the site longer, reducing bounce rates and increasing the likelihood of engagement. Improved Search Engine Rankings Websites that are responsive are more favored by search engines like Google. This is because a single responsive site reduces the chance of on-page SEO errors and is easier for search engine spiders to index and rank, potentially resulting in higher search engine rankings. Cost-Effectiveness and Efficiency Maintaining separate sites for mobile and desktop users can be resource intensive. Responsive design eliminates the need for multiple codes, ensuring that businesses save time and money on development, maintenance, and updates. It also means that any updates made to the site only need to be done once, reflecting across all devices. Other posts
__label__pos
0.73753
node package manager Share your code. npm Orgs help your team discover, share, and reuse code. Create a free org » mojito-cache mojito-cache Build Status Mojito Cache is a package of caching libraries that perform optimizations that are not natively supported by mojito and are not necessarily desirable in the mainstream mojito distribution. Mojito Cache allows the reuse of the same Action Context between mojit instances of the same type, which is appropriate in most cases. Mojito Cache is not intended as a communication facility between mojit instances, but rather as a transparent optimization mechanism for high performance applications. Usage In the application configuration file (often application.yaml) include the following properties:     "request-cache": {         "refreshAddons": ["myAddon"]     } You can specify the list of addons that need to be refreshed across mojit instances FOR THE SAME REQUEST. Caching in that context can be useful if much is shared between mojits instances on the same page. Typically 'params' and 'config' need to be refreshed for the instances to render differently.
__label__pos
0.632832
首页 > C# > C#基础语法 阅读:25,731 C# continue语句 < 上一页C# break C# goto下一页 > C# 中的 continue 语句有点像 break 语句。但它不是强制终止,continue 会跳过当前循环中的代码,强制开始下一次循环。 对于 for 循环,continue 语句会导致执行条件测试和循环增量部分。对于 while 和 do while 循环,continue 语句会导致程序控制回到条件测试上。 提示:C# continue 语句必须在循环语句中使用。 【实例】使用 for 循环输出1~10的数,但是不输出 4。 根据题目要求,在 for 循环中当值迭代到 4 时使用 continue 结束本次迭代,继续下一次迭代,代码如下。 class Program { static void Main(string[] args) { for(int i = 1; i <= 10; i++) { if (i == 4) { continue; } Console.WriteLine(i); } } } 执行上面的代码,效果如下图所示。 在循环中使用continue语句 从上面的执行效果可以看出,当 for 循环中的值迭代到 4 时 continue 语句结束了本次 迭代,继续下一次迭代,因此在输出结果中没有 4。 关注微信公众号「站长严长生」,在手机上阅读所有教程,随时随地都能学习。本公众号由C语言中文网站长运营,每日更新,坚持原创,敢说真话,凡事有态度。 魏雪原二维码 微信扫描二维码关注公众号 < 上一页C# break C# goto下一页 >
__label__pos
0.841601
GCF and LCM Calculator Logo What is the Greatest Common Factor of 52 and 59? Greatest common factor (GCF) of 52 and 59 is 1. GCF(52,59) = 1 We will now calculate the prime factors of 52 and 59, than find the greatest common factor (greatest common divisor (gcd)) of the numbers by matching the biggest common factor of 52 and 59. GCF Calculator and and How to find the GCF of 52 and 59? We will first find the prime factorization of 52 and 59. After we will calculate the factors of 52 and 59 and find the biggest common factor number . Step-1: Prime Factorization of 52 Prime factors of 52 are 2, 13. Prime factorization of 52 in exponential form is: 52 = 22 × 131 Step-2: Prime Factorization of 59 Prime factors of 59 are 59. Prime factorization of 59 in exponential form is: 59 = 591 Step-3: Factors of 52 List of positive integer factors of 52 that divides 52 without a remainder. 1, 2, 4, 13, 26 Step-4: Factors of 59 List of positive integer factors of 59 that divides 52 without a remainder. 1 Final Step: Biggest Common Factor Number We found the factors and prime factorization of 52 and 59. The biggest common factor number is the GCF number. So the greatest common factor 52 and 59 is 1. Also check out the Least Common Multiple of 52 and 59
__label__pos
0.992392
Hi, I'm a beginning C++ student and have an assignment to dynamically create an array of a struct to store students' first names, last names, and test grade scores, and then pass it via pointer to a function that will sort the grades and names in ascending order. I wrote a function that finds the lowest numeric grade score of the pointer array of struct, puts it in the first (0) index position, and then puts the numeric value that was in the first (0) index position in the index position that was formerly occupied by the newly found lowest value. Then, it starts at the next highest index position and finds the next lowest value, etc, and swaps it. The issue that I'm having is that I can get the numeric scores sorted properly and moved in the function, but I can't get the first and last names in the array to change position, except somewhat unpredictably. Sometimes, one of the names will overwrite another name and be listed twice in the final output. I have them declared as a string data type and ideally would like them to do the same thing that I have the numeric values doing, but can't seem to achieve it. I've tried using char and strcpy but that's not working, either. I'm sure there's an easier way to do what I'm doing but the assignment is worded very specifically. I'm not sure if it's a simple logic error in the nested loop or perhaps I need to use a different syntax or method to change the index positions of the strings, since I'm using pointers? Maybe a constructor for struct? This is my first post on any C++ forum, so please excuse any transgressions I may have made in code etiquette, posting, etc! I read all the faqs first and tried to follow them as much as possible, so my apologies if I shouldn't have posted the whole code- I just wanted to give a clear idea of the problem! I'd really appreciate any help... Thanks in advance! Evan /* Test Scores #2 programming challenge */ #include <iostream> #include <iomanip> #include <string> #include <cstring> using namespace std; struct TestData //create TestData structure to hold students' first name, last name, and grade score { string studentFirstName; string studentLastName; float studentGrade; }; typedef struct TestData StructDataType; //create a data type StructDataType to be able pass the entire //structure back and forth by pointers StructDataType *getScores(int ); //function prototype to dynamically create a pointer array of struct with data //type of StructDataType to be able to input mixed string/int values into the array, //then pass it back into int main by using pointers void structSort(StructDataType *, int); //function prototype to sort the pointer array of struct by integer grade score, //then pass it back by pointer into int main float findAverage(StructDataType *, int); //function prototype to find the average integer grade test score, passes again //by use of pointers to and from findAverage function void printScores(StructDataType *, int); //outputs resorted pointer array of struct int main() { int numScores; cout << "How many test scores would you like to enter? "; cin >> numScores; StructDataType *test1Scores = getScores(numScores); /*sets pointer array of data type StructDataType equal to results of calling function getScores, which dynamically creates an array and asks user to enter in required data */ structSort(test1Scores, numScores); //calls function to perform selection sort by integer test score float averageScore = findAverage(test1Scores, numScores); /*sets float integer averageScore equal to results of function call findAverage, which passes test1Scores array to function that finds average of all test scores*/ printScores(test1Scores, numScores); //function call to output resorted list to screen cout << "\nAverage test score in your array is: " << setprecision(3) << averageScore << endl << endl; cout << endl; system("pause"); return 0; } StructDataType *getScores(int numScores) { const int numChars = 20; StructDataType *test1Scores; while (numScores < 2) { cout << "Test score array can't be less than 2!\n" << "\nPlease enter a number " << "2 or greater for test score array: "; //validate entries to be greater than 1 for array size cin >> numScores; } test1Scores = new StructDataType[numScores]; for (int index = 0; index < numScores; index++) //for loop for user to enter input up to however many records are to be created { cout << "\nEnter student # " << index + 1 << " first name: "; cin >> test1Scores[index].studentFirstName; //enter first name for record in test1Scores array of struct cout << "Enter student # " << index + 1 << " last name: "; cin >> test1Scores[index].studentLastName; //enter last name for record in test1Scores array of struct cout << "Enter student # " << index + 1 << " test score: "; cin >> test1Scores[index].studentGrade; //enter grade score record in test1Scores array of struct while (test1Scores[index].studentGrade < 0 || test1Scores[index].studentGrade > 100) /*validate numeric test grade score entries to be greater than 0 and less than 101 */ { cout << "Test score value can't be less than 0 or over 100!\n" << "\nPlease enter a value " << "greater than -1 and less than 100 for test score " << index + 1 << ": "; cin >> test1Scores[index].studentGrade; } } return test1Scores; } void structSort(StructDataType *test1Scores, int numScores) /*function to perform selection sort based value of studentGrade, which is the float data variable to hold numeric test score */ { string tempFirstName, tempLastName; int startScan, minIndex; float minValue; for (startScan = 0; startScan < numScores - 1; startScan++) //nested loops to find lowest value of studentGrade { minIndex = startScan; minValue = (test1Scores + startScan)->studentGrade; for (int index = startScan + 1; index < numScores; index++) { if ((test1Scores + index)->studentGrade < minValue) { minValue = (test1Scores + index)->studentGrade; minIndex = index; } } /*this is the issue! these statements are supposed to swap the numeric value of the lowest value of studentGrade found in the pointer struct array with the first position of the array's index, and also swap the first and last names of the new lowest score with the first and last names that were in index position 0. i.e., if the lowest test grade score was at index position 4, put it at position 0 along with the first and last names that were at that position, and put the old value of position 0 at position 4, along with the first and last names that were at position 0. This is working with the numeric values perfectly but for some reason it's not working with with the string values for the students' first and last names. I tried switching to char data type within the intial struct declaration and using strcpy and passing the array by reference (see below comments) but that's not working, either! */ (test1Scores + minIndex)->studentFirstName = (test1Scores + startScan)->studentFirstName; (test1Scores + minIndex)->studentLastName = (test1Scores + startScan)->studentLastName; (test1Scores + minIndex)->studentGrade = (test1Scores + startScan)->studentGrade; (test1Scores + startScan)->studentGrade = minValue; //strcpy(&test1Scores[startScan].studentFirstName, &test1Scores[minValue].studentFirstName); //strcpy(&test1Scores[startScan].studentLastName, &test1Scores[minValue].studentLastName); } } float findAverage(StructDataType *test1Scores, int numScores) { float total = 0, average; for (int index = 0; index < numScores; index ++) { total += (test1Scores+index)->studentGrade; } average = total / numScores; return average; } void printScores(StructDataType *test1Scores, int numScores) { for (int index = 0; index < numScores; index++) { cout << "\n" << (test1Scores+index)->studentLastName << ", " << (test1Scores+index)->studentFirstName << ": " << (test1Scores+index)->studentGrade; } cout << endl; } Recommended Answers I wrote a function that finds the lowest numeric grade score of the pointer array of struct, puts it in the first (0) index position, and then puts the numeric value that was in the first (0) index position in the index position that was formerly occupied by the newly … Jump to Post All 3 Replies I wrote a function that finds the lowest numeric grade score of the pointer array of struct, puts it in the first (0) index position, and then puts the numeric value that was in the first (0) index position in the index position that was formerly occupied by the newly found lowest value. [3][2][1][0] [0][2][1][3] ... Then, it starts at the next highest index position and finds the next lowest value, etc, and swaps it. [3][2][1][0] [0][2][1][3] [0][1][2][3] So it appears to be algorithmically sound assuming you implement it properly :) The issue that I'm having is that I can get the numeric scores sorted properly and moved in the function, but I can't get the first and last names in the array to change position, except somewhat unpredictably. The best advice I have for you is to run your code under a debugger and see for yourself what is happening. If you're using Visual Studio be sure to "start debugging" and set some breakpoints to examine the contents of your variables. If you don't know what I mean I will make a youtube video of it and link you to it, but who knows when that will be. Found the fix thanks to a classmate- posting it here so maybe someone else can benefit! replace this section in my code (actual line numbers 105-110 in my original post): (test1Scores + minIndex)->studentFirstName = (test1Scores + startScan)->studentFirstName; (test1Scores + minIndex)->studentLastName = (test1Scores + startScan)->studentLastName; (test1Scores + minIndex)->studentGrade = (test1Scores + startScan)->studentGrade; (test1Scores + startScan)->studentGrade = minValue; with below single line of code: swap(test1Scores[startScan], test1Scores[minIndex]); Apparently, you can swap out one whole record array of struct using the "swap" command instead of having to do each item individually, as I was trying to do! Evan Be a part of the DaniWeb community We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.
__label__pos
0.540079
Intereting Posts Установка разрешения EFI Framebuffer при загрузке Почему “ IFS = read` используется так часто, а не `IFS =; в то время как читать..`? Предотвратите debian от испортить конфигурацию grub Установить коммерческие правила ModSecurity Могу ли я отправлять электронную почту в фоновом режиме в Mutt, но при этом уведомляются об ошибках? сохранение расширенных атрибутов cp / rsync Как я могу навсегда изменить тип шрифта консоли TTY, чтобы он сохранялся после перезагрузки? Редактирование файла eps, созданного Tecplot Отправка функциональных клавиш (F1-F12) через SSH grep не выводит до EOF, если пропущен через cat Включить встроенные прошивки в ядре двоичного кода cp не будет работать в текущем каталоге скрипта bash Как открыть все файлы, которые являются результатом команды ls? GPIO в непривилегированном контейнере LXC Отключить сенсорную панель при вводе текста, а также нажать сенсорную панель для сеанса X Настройка xinetd для OpenSuSE Мне нужно запустить пример пакета прокси для пакетов Debian / Ubuntu в окне OpenSuSE. До сих пор я конвертировал инсталляционный пакет с .deb в .rpm с помощью alien . Установка полученного .rpm дала мне approx двоичную информацию в /usr/sbin/approx . В Debian, approx начинается с использования inetd . OpenSuSE, похоже, предпочитает xinetd . Итак, в настройке xinetd YaST2 я создал новую запись, используя • имя службы: «approx» (я также попробовал «9999», так как я предполагаю, что это происходит, когда происходит сопоставление имен служб с номерами портов – это имя должно соответствовать описанию порта в / etc / services, правильно?) • Тип: stream • протокол: tcp • опция nowait • пользователя: root и • service: /usr/sbin/approx . Однако независимо от того, какой статус я назначаю для входа, конфигурация xinetd переходит к «деактивированному», как только я нажимаю «ОК», и я не могу получить никакой реакции от системы при обращении к ней на порт 9999. Итак, во-первых, правильно ли я использую конфигурацию xinetd или я понимаю что-то не так? Во-вторых, автоматическая деактивация панели конфигурации xinetd в YaST2 является ошибкой программного обеспечения или пользователя? Благодаря вкладу Нихиля я решил это. При настройке xinetd YaST использует имена сервисов, а не номера портов. К сожалению, по некоторым историческим причинам, по умолчанию используется порт 9999. Он зарегистрирован в другой службе с именем «отличная». Таким образом, решение ad-hoc состояло в том, чтобы переименовать службу порта 9999 в «приблизительный» в / etc / services и ввести новую службу в конфигурацию xinetd с именем «approx» (это, как я подозревал, сопоставлено с портом 9999 ), пользователь приблизительный и группа ок. Это файл службы, созданный YaST: $ cat /etc/xinetd.d/approx service approx { socket_type = stream protocol = tcp wait = no user = approx group = approx server = /usr/sbin/approx } Разумеется, правильным решением будет переход на сервер и все клиентские компьютеры на другой порт (тот, который еще не назначен IANA). Вы пытались указать номер порта в конфигурации? Что говорят журналы? service approx { flags = REUSE socket_type = stream protocol = tcp wait = no user = root server = /usr/sbin/approx log_on_failure += USERID disable = no port = 9999 }
__label__pos
0.77735
How to keep a copy of my email messages after downloading them via Outlook Express? Please configure your Outlook Express by following the steps below: 1. Click "Tools". 2. Click "Accounts...". 3. Choose your account. 4. Click "Properties". 5. Select "Advanced" tab. 6. Tick the "Leave a copy of messages on server" checkbox. • Email, SSL • 0 Users Found This Useful Was this answer helpful? Related Articles Why I can't send out emails using my local email client (eg: Outlook Express, Eudora etc)? First, please do the following:Click "Tools", then "Accounts..."Choose the... How do I setup my email account in Outlook Express? Please follow the steps below for configuring in Outlook...
__label__pos
1
Jump to content • Advertisement Sign in to follow this   kumpaka Quaternions This topic is 2454 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic. If you intended to correct an error in the post then please contact us. Recommended Posts Hi there, So I've been working around with quaternions, let me just see if i got this straight: v' = q . v. q^-1 Will get me a new vector with an applied rotation? To do this multiplication we turn v into a quaternion by adding scale with value 0, and from the resulting quat. we can extract the vector value to get the result. But on this new resulting quat, for us to just simply extract the values doesnt the scale of the resulting quaternion need to be 0? Or whatever the value is, we just dont mind and extract the vector values anyways? Thanks in advance. Share this post Link to post Share on other sites Advertisement While your formula is correct, you can simply compute v' = q * v * conj(q) because, for quaternions that represent rotations, |q| = 1. I am not sure what you mean by the "scale" of a quaternion. v' as a quaternion has zero real part, if that's what you mean. Proving that theorem shouldn't be too hard. So just don't worry about it and extract your vector. Share this post Link to post Share on other sites I started to prove that today on paper(yeah by scalar i meant real part, on book im reading he calls it scalar, on some toturials it's the 'w') and thats what i got, it should be zero i was just afraid i did the math wrong. The examples i try on my code dont end up getting 0 on the real part, means im doing something wrong... need to find out what and correct it, just wanted to be sure i was on the right path. Btw, you say for quaternions that represent rotations |q| = 1, i calculated it, for example with this: alpha = 90º v = (1.0,0.0,0.0) q = [cos(90/2), sin(90/2) * (v)] But it did not result in a normalized quaternion, again the math on my code must be working improperly right? Thank you. PS(before calculating the cos or sin, i convert de degree's to radians) Share this post Link to post Share on other sites Remember that v needs to have lenght 1 for that code to work. If it does, |q| = 1 is guaranteed. If you don't think this is the case, please post a complete example so we can discuss it. EDIT: Oh, sorry. You did post a complete example. Well, perhaps you can post why you think the resulting quaternion is not normalized. Share this post Link to post Share on other sites Its solved, the math i had on paper was right but not the one on code =( both problems were solved, my vector dot product and vector cross product had mistakes. Thank you. PS: If the vector i want to rotate does not have lenght 1, i need to normalize it? Rotation quaternions, if calculated by that formula are always unit quaternions? Share this post Link to post Share on other sites PS: If the vector i want to rotate does not have lenght 1, i need to normalize it? Rotation quaternions, if calculated by that formula are always unit quaternions? Yes, if the vector that indicates the axis doesn't have length 1, you need to normalize it. Once you have a vector of length 1, the length of the resulting quaternion is length(q) = length(cos(alpha/2) + sin(alpha/2)*x*i + sin(alpha/2)*y*j + sin(alpha/2)*z*k) = cos(alpha/2)^2 + sin(alpha/2)^2*(x^2+y^2+z^2) = cos(alpha/2)^2 + sin(alpha/2)^2 = 1 Share this post Link to post Share on other sites I see, that was very helpful indeed thank you. What about the vector i want to rotate? on v' = q . v . conj(q), does 'v' also need to be normalized? Because if it does, wont it alter the result intended? Very sorry if this sound like dumb questions, just started looking at quaternions a few days ago =( You're help is much appreciated. Share this post Link to post Share on other sites This is making me confused, i tought and it made sense. I was happy i got this out of the way, but now i found this here: http://content.gpwiki.org/index.php/OpenGL:Tutorials:Using_Quaternions_to_represent_rotation#Rotating_vectors They actually normalize the vector they are about to rotate: // Multiplying a quaternion q with a vector v applies the q-rotation to v Vector3 Quaternion::operator* (const Vector3 &vec) const { Vector3 vn(vec); vn.normalise(); Quaternion vecQuat, resQuat; vecQuat.x = vn.x; vecQuat.y = vn.y; vecQuat.z = vn.z; vecQuat.w = 0.0f; resQuat = vecQuat * getConjugate(); resQuat = *this * resQuat; return (Vector3(resQuat.x, resQuat.y, resQuat.z)); } Share this post Link to post Share on other sites This is making me confused, i tought and it made sense. I was happy i got this out of the way, but now i found this here: http://content.gpwik...otating_vectors That's just wrong. Ignore it. Share this post Link to post Share on other sites Sign in to follow this   • Advertisement × Important Information By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy. GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry. Sign me up!
__label__pos
0.54339