id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23535600
I would like to substitute all Identificators like "#a1_field_box" using char variable x How can I cahnge "#a1_field_box" using var x? so if parameter is b I would get "#b1_field_box", if x = 'c' I would get "#c1_field_box" and so on function ShowIfOther1() { var x = 'a'; if ( $('#con1').prop('checked') ) { $("#a1_field_box").show().fadeIn(500); $("#a1_display_as_box").fadeIn(500); $("#field-a1").fadeIn(500); $("#a2_field_box").show().fadeIn(500); $("#a2_display_as_box").fadeIn(500); $("#field-a2").fadeIn(500); $("#a3_field_box").show().fadeIn(500); $("#a3_display_as_box").fadeIn(500); $("#field-a3").fadeIn(500); $("#a4_field_box").show().fadeIn(500); $("#a4_display_as_box").fadeIn(500); $("#field-a4").fadeIn(500); $("#a5_field_box").show().fadeIn(500); $("#a5_display_as_box").fadeIn(500); $("#field-a5").fadeIn(500); } else { $("#a1_field_box").hide('slow'); $("#a1_display_as_box").hide('slow');$("#field-a1").hide('slow'); $("#a2_field_box").hide('slow'); $("#a2_display_as_box").hide('slow');$("#field-a2").hide('slow'); $("#a3_field_box").hide('slow'); $("#a3_display_as_box").hide('slow');$("#field-a3").hide('slow'); $("#a4_field_box").hide('slow'); $("#a4_display_as_box").hide('slow');$("#field-a4").hide('slow'); $("#a5_field_box").hide('slow'); $("#a5_display_as_box").hide('slow');$("#field-a5").hide('slow'); } } A: * *show() in .show().fadeIn(500) is redundant. It can be removed as fadeIn() is show() + animation. *All the selectors can be combined and used as comma-separated, on which same operation is to be done. Eg. fadeIn() and hide(). *You can concat variables using + operator Code: function ShowIfOther1(x) { if ($('#con1').prop('checked')) { $('#' + x + '1_field_box, #' + x + '1_display_as_box, #field-' + x + '1, #' + x + '2_field_box, #' + x + '2_display_as_box, #field-' + x + '2, #' + x + '3_field_box, #' + x + '3_display_as_box, #field-' + x + '3, #' + x + '4_field_box, #' + x + '4_display_as_box, #field-' + x + '4, #' + x + '5_field_box, #' + x + '5_display_as_box, #field-' + x + '5').fadeIn(500); } else { $('#' + x + '1_field_box, #' + x + '1_display_as_box, #field-' + x + '1, #' + x + '2_field_box, #' + x + '2_display_as_box, #field-' + x + '2, #' + x + '3_field_box, #' + x + '3_display_as_box, #field-' + x + '3, #' + x + '4_field_box, #' + x + '4_display_as_box, #field-' + x + '4, #' + x + '5_field_box, #' + x + '5_display_as_box, #field-' + x + '5').fadeOut(500); } } And call it like ShowIfOther1('a'); Also I would suggest to use same class names for each of those separate #id's and using jQuery parent() method you can show/hide easily with very less code.
doc_23535601
{ "_id" : ObjectId("608d5b653979af6a8555f643"), "eMail" : "ben@moskitofactory.com", ... "billing" : [ { "company" : "MoskitoFactory", "salutation" : "1", "firstname" : "Ben", "lastname" : "Water", "address_line_1" : "Black 1235", "address_line_2" : "", "address_line_3" : "", "zip" : "555", "city" : "Onecity" }, { "company" : "Witchcraft4U", "salutation" : "1", "firstname" : "Mike", "lastname" : "Phone", "address_line_1" : "Sea 4445", "address_line_2" : "", "address_line_3" : "", "zip" : "12345", "city" : "Somecity" } ] } how do I get the billing address with array index 0? I thought this way $billing = $db->buyer->findOne([ '_id' => new MongoDB\BSON\ObjectID($_SESSION['uid']) ],[ 'projection' => ['billing.0' => 1] ] ); var_dump($billing->billing); but it gives me only object(MongoDB\Model\BSONArray)#28 (1) { ["storage":"ArrayObject":private]=> array(2) { [0]=> object(MongoDB\Model\BSONDocument)#26 (1) { ["storage":"ArrayObject":private]=> array(0) { } } [1]=> object(MongoDB\Model\BSONDocument)#27 (1) { ["storage":"ArrayObject":private]=> array(0) { } } } } I don't know if the query is correct and I simply don't know how to display the result. But If I read this right it gives me two objects back instead of one (billing address No 0) A: try $slice operator to get specific element from array of object, this will return single element object in array. $billing = $db->buyer->findOne([ '_id' => new MongoDB\BSON\ObjectID($_SESSION['uid']) ],[ 'projection' => ['billing' => ['$slice' => [0,1]]] ]) Playground If you want to get object only instead of array try $arrayElemAt operator to get object from specific index, This is Starting in MongoDB 4.4, you can use aggregation operator in find / findOne method's projection, $billing = $db->buyer->findOne([ '_id' => new MongoDB\BSON\ObjectID($_SESSION['uid']) ],[ 'projection' => ['billing' => ['$arrayElemAt' => ['$billing', 0] ]] ]) Playground
doc_23535602
I'm trying to allow the community organizer to create events : * *To which users can donate funds to ; *Which users can attend . I use stripe as the payment gateway. I've setup a controller/model scaffolding for the Event model so far : class Event < ActiveRecord::Base extend FriendlyId friendly_id :title, use: :slugged belongs_to :org_user #organization_user has_one :category end Here is my organization user model : class OrgUser < ActiveRecord::Base extend FriendlyId friendly_id :username, use: :slugged has_many :posts has_many :comments has_many :events end I was told that I may need these particular patterns inside of my events and org_user models class Event < ActiveRecord::Base event has_many :attendances event has_many :users, through: :attendances end class OrgUser < ActiveRecord::Base org_user has_many :attendances org_user has_many :events, through: :attendances end class User < ActiveRecord::Base end What is your advice on creating the relationship. I also don't want to forget the User.rb which will sign the form to be a part of the event posted by the :org_user. Only the org_user will have the ability to create/post events. Normal Users will have access to the signup form to attend those events. Please, help me clear this hurdle. A: Several things : * *The way you right has many through relationship is wrong (see the doc ) *You don't model your donation relationship from users to events You could model things like this : class Event < ActiveRecord::Base has_many :attendances has_many :users, through: :attendances end class OrgUser < ActiveRecord::Base has_many :events # as coordinations end class User < ActiveRecord::Base has_many :donations has_many :attendances end class Attendance < ActiveRecord::Base belongs_to :user has_one :event end class Donation < ActiveRecord::Base belongs_to :user has_one :event end
doc_23535603
I have written code like this: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Data.Odbc; namespace ConsoleApplication1{ class Program { static void Main(string[] args) { SqlConnection con = new SqlConnection (""); con.Open(); SqlCommand cmd = new SqlCommand ("select Temprature,time,date from temprature3 ", con); SqlDataReader data = cmd.ExecuteReader(); OdbcConnection dcon = new OdbcConnection(); dcon.ConnectionString = @"Driver={Microsoft Excel Driver(*.xls)};Create_DB=C:\Documents andSettings\Administrator\Desktop\Excel\Report.xls;DBQ=C:\Documents and Settings\Administrator\Desktop\Excel\Report.xls; ReadOnly=True"; dcon.Open(); OdbcCommand dcom=new OdbcCommand ("create table Report new (Temperature double,Time datetime,Date datetime)",dcon); dcom.ExecuteNonQuery(); Console.WriteLine("table has been created"); OdbcCommand dinsert=new OdbcCommand("insert into Report values(?,?,?)",dcon); OdbcParameter Temprature=new OdbcParameter("@Temperature",OdbcType.Double); OdbcParameter Time=new OdbcParameter("@Temperature",OdbcType.DateTime); OdbcParameter Date=new OdbcParameter("@Temperature",OdbcType.DateTime); dinsert.Parameters.Add(Temprature); dinsert.Parameters.Add(Time); dinsert.Parameters.Add(Date); int count=0; while(data.Read()) { Temprature.Value=data[0]; Time.Value=data[1]; Date.Value=data[2]; dinsert.ExecuteNonQuery(); count=count+1; } Console.WriteLine("------------------------------------------------------"); Console.WriteLine(count+"Number of rows are exported to excel"); Console.WriteLine("-------------------------------------------------------"); Console.ReadLine(); } } } I'm getting error like this: ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified A: My 2 Cents on this :- Make sure the data source name was given correctly. If this is correct make sure the driver is installed correctly. Try reinstalling it. Also make sure the data source name was defined using the same Windows NT account the application is running under. If the application is running as a Windows NT service, the data source must be a system data source.
doc_23535604
I would like to know if it would be possible to have the globe object rotate around it's y-axis with minor additions to the code or whether it has to be rewritten from the ground up. var canvas = document.querySelector('canvas'); var width = canvas.offsetWidth, height = canvas.offsetHeight; var colors = [ new THREE.Color(0xac1122), new THREE.Color(0x96789f), new THREE.Color(0x535353)]; var renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true }); renderer.setPixelRatio(window.devicePixelRatio > 1 ? 2 : 1); renderer.setSize(width, height); renderer.setClearColor(0xffffff); var scene = new THREE.Scene(); var raycaster = new THREE.Raycaster(); raycaster.params.Points.threshold = 6; var camera = new THREE.PerspectiveCamera(50, width / height, 0.1, 2000); camera.position.set(0, 0, 350); var galaxy = new THREE.Group(); scene.add(galaxy); // Create dots var loader = new THREE.TextureLoader(); loader.crossOrigin = ""; var dotTexture = loader.load("img/dotTexture.png"); var dotsAmount = 3000; var dotsGeometry = new THREE.Geometry(); var positions = new Float32Array(dotsAmount * 3); var sizes = new Float32Array(dotsAmount); var colorsAttribute = new Float32Array(dotsAmount * 3); for (var i = 0; i < dotsAmount; i++) { var vector = new THREE.Vector3(); vector.color = Math.floor(Math.random() * colors.length); vector.theta = Math.random() * Math.PI * 2; vector.phi = (1 - Math.sqrt(Math.random())) * Math.PI / 2 * (Math.random() > 0.5 ? 1 : -1); vector.x = Math.cos(vector.theta) * Math.cos(vector.phi); vector.y = Math.sin(vector.phi); vector.z = Math.sin(vector.theta) * Math.cos(vector.phi); vector.multiplyScalar(120 + (Math.random() - 0.5) * 5); vector.scaleX = 5; if (Math.random() > 0.5) { moveDot(vector, i); } dotsGeometry.vertices.push(vector); vector.toArray(positions, i * 3); colors[vector.color].toArray(colorsAttribute, i*3); sizes[i] = 5; } function moveDot(vector, index) { var tempVector = vector.clone(); tempVector.multiplyScalar((Math.random() - 0.5) * 0.2 + 1); TweenMax.to(vector, Math.random() * 3 + 3, { x: tempVector.x, y: tempVector.y, z: tempVector.z, yoyo: true, repeat: -1, delay: -Math.random() * 3, ease: Power0.easeNone, onUpdate: function () { attributePositions.array[index*3] = vector.x; attributePositions.array[index*3+1] = vector.y; attributePositions.array[index*3+2] = vector.z; } }); } var bufferWrapGeom = new THREE.BufferGeometry(); var attributePositions = new THREE.BufferAttribute(positions, 3); bufferWrapGeom.addAttribute('position', attributePositions); var attributeSizes = new THREE.BufferAttribute(sizes, 1); bufferWrapGeom.addAttribute('size', attributeSizes); var attributeColors = new THREE.BufferAttribute(colorsAttribute, 3); bufferWrapGeom.addAttribute('color', attributeColors); var shaderMaterial = new THREE.ShaderMaterial({ uniforms: { texture: { value: dotTexture } }, vertexShader: document.getElementById("wrapVertexShader").textContent, fragmentShader: document.getElementById("wrapFragmentShader").textContent, transparent:true }); var wrap = new THREE.Points(bufferWrapGeom, shaderMaterial); scene.add(wrap); // Create white segments var segmentsGeom = new THREE.Geometry(); var segmentsMat = new THREE.LineBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0.3, vertexColors: THREE.VertexColors }); for (i = dotsGeometry.vertices.length - 1; i >= 0; i--) { vector = dotsGeometry.vertices[i]; for (var j = dotsGeometry.vertices.length - 1; j >= 0; j--) { if (i !== j && vector.distanceTo(dotsGeometry.vertices[j]) < 12) { segmentsGeom.vertices.push(vector); segmentsGeom.vertices.push(dotsGeometry.vertices[j]); segmentsGeom.colors.push(colors[vector.color]); segmentsGeom.colors.push(colors[vector.color]); } } } var segments = new THREE.LineSegments(segmentsGeom, segmentsMat); galaxy.add(segments); var hovered = []; var prevHovered = []; function render(a) { var i; dotsGeometry.verticesNeedUpdate = true; segmentsGeom.verticesNeedUpdate = true; raycaster.setFromCamera( mouse, camera ); var intersections = raycaster.intersectObjects([wrap]); hovered = []; if (intersections.length) { for(i = 0; i < intersections.length; i++) { var index = intersections[i].index; hovered.push(index); if (prevHovered.indexOf(index) === -1) { onDotHover(index); } } } for(i = 0; i < prevHovered.length; i++){ if(hovered.indexOf(prevHovered[i]) === -1){ mouseOut(prevHovered[i]); } } prevHovered = hovered.slice(0); attributeSizes.needsUpdate = true; attributePositions.needsUpdate = true; renderer.render(scene, camera); } function onDotHover(index) { dotsGeometry.vertices[index].tl = new TimelineMax(); dotsGeometry.vertices[index].tl.to(dotsGeometry.vertices[index], 1, { scaleX: 10, ease: Elastic.easeOut.config(2, 0.2), onUpdate: function() { attributeSizes.array[index] = dotsGeometry.vertices[index].scaleX; } }); } function mouseOut(index) { dotsGeometry.vertices[index].tl.to(dotsGeometry.vertices[index], 0.4, { scaleX: 5, ease: Power2.easeOut, onUpdate: function() { attributeSizes.array[index] = dotsGeometry.vertices[index].scaleX; } }); } function onResize() { canvas.style.width = ''; canvas.style.height = ''; width = canvas.offsetWidth; height = canvas.offsetHeight; camera.aspect = width / height; camera.updateProjectionMatrix(); renderer.setSize(width, height); } var mouse = new THREE.Vector2(-100,-100); function onMouseMove(e) { var canvasBounding = canvas.getBoundingClientRect(); mouse.x = ((e.clientX - canvasBounding.left) / width) * 2 - 1; mouse.y = -((e.clientY - canvasBounding.top) / height) * 2 + 1; } TweenMax.ticker.addEventListener("tick", render); window.addEventListener("mousemove", onMouseMove); var resizeTm; window.addEventListener("resize", function(){ resizeTm = clearTimeout(resizeTm); resizeTm = setTimeout(onResize, 200); }); Codepen here - https://codepen.io/quickwaste/pen/PaGPdw Thanks. (A stretch goal would be to have the camera move in response to mouse movement) A: Simply add galaxy.rotateY(0.005 * Math.PI); to render(), right before renderer.render(scene, camera) call, like this: // pulled from the CodePen function render(a) { // ... omitted for brevity prevHovered = hovered.slice(0); attributeSizes.needsUpdate = true; attributePositions.needsUpdate = true; galaxy.rotateY(0.005 * Math.PI); renderer.render(scene, camera); } I used a multiplier of 0.005 to give the globe a nice, lazy spin. The 'galaxy' object is a THREE.Group, a wrapper of sorts for collections of THREE.Object3D objects. The Object3D has all sorts of nifty functions to help rotate, translate, and transform 3D objects. The rotateY() will spin the model around its local y-axis.
doc_23535605
<label class="radio normalFontWeight"> <input type="radio" name="Criteria" data-ng-value="EVERYONE_REVIEWED" data-ng-model="stage.completionRule" checked="checked"> option 1 </label> <label class="radio normalFontWeight"> <input type="radio" name="Criteria" data-ng-value="HAS_MIN_REVIEWS" data-ng-model="stage.completionRule"> option 2 </label> i have tried with both checked="checked" && checked but was not successful , as on first render both of the options r unselected A: I have figured out the problem: The ng-model value needs to be initialized with corresponding input value of radio button to be checked by default i.e. in my case stage.completionRule = "EVERYONE_REVIEWED"
doc_23535606
doc_23535607
I'm making an IOCP server and I have ironed out most issues so far but one still remain and I do not know where to start looking at. When I run the client/server on my machine everything is fine and dandy. It matches the speed of the Windows SDK Sample maybe a little bit faster and definitely uses less CPU cycle. However when I run the client from a separate computer, transfer speed caps at 37 KB/s and has a roundtrip latency of 200ms (as opposed to 0). Now if I connect the client to the SDK Sample server, I don't have that problem so there is something wrong with my code. As far as I know, the sockets are initialized the exact same way with the same options. I have also ran my server in a profiler to check for bottleneck but I couldn't find any. Also, the computers I have tried it on were connected to the same gigabit switch (with gigabit adapter). I know this is kind of vague but that's because I couldn't pinpoint the problem so far and I would be eternally grateful if any of you guys could point me in the right direction. Cheers, -Roxy EDIT2: After following Mike's advise, I did some research on the code and found out that when a remote client connects to the server most of the time the code is waiting on GetQueuedCompletionStatus. This suggest that IO request are simply taking a long time to complete but I still don't understand why. This only occurs only when the client is on a remote computer. I'm thinking this has something to do with how a setup the sockets or how I'm posting the request but I don't see any difference with the sample code. Any ideas? EDIT (Added sample code): Alright, here it is! It ain't pretty though! If you have the Windows SDK installed, you can connect to it using the iocpclient sample (Program Files\Microsoft SDKs\Windows\v7.1\Samples\netds\winsock\iocp\client) and changing it's default port at line 73 to 5000. Weird things I've just noticed when trying it myself is that it seems the sample iocpclient doesn't cause the same caps at 37KB/s issue... However it looks like the sample code has a limit set to around 800KB/s. I'll post a client if that can be of any help. #pragma comment(lib, "Ws2_32.lib") #include <WinSock2.h> #include <stdio.h> unsigned int connection = 0; unsigned int upload = 0; unsigned int download = 0; #define IO_CONTEXT_COUNT 5 class NetClientHost { friend class gNetProtocolHost; public: enum Operation { kOperationUnknown, kOperationRead, kOperationWrite, }; struct ClientData { SOCKET socket; }; struct IOContext { WSAOVERLAPPED overlapped; WSABUF wsaReceiveBuf; WSABUF wsaSendBuf; char *buf; char *TESTbuf; unsigned long bytesReceived; unsigned long bytesSent; unsigned long flags; unsigned int bytesToSendTotal; unsigned int remainingBytesToSend; unsigned int chunk; Operation operation; }; NetClientHost() { memset((void *) &m_clientData, 0, sizeof(m_clientData)); } NetClientHost::IOContext *NetClientHost::AcquireContext() { while (true) { for (int i = 0; i < IO_CONTEXT_COUNT; ++i) { if (!(m_ioContexts + i)->inUse) { InterlockedIncrement(&(m_ioContexts + i)->inUse); //ResetEvent(*(m_hContextEvents + i)); if ((m_ioContexts + i)->ioContext.TESTbuf == 0) Sleep(1); return &(m_ioContexts + i)->ioContext; } } //++g_blockOnPool; //WaitForMultipleObjects(IO_CONTEXT_COUNT, m_hContextEvents, FALSE, INFINITE); } } const ClientData *NetClientHost::GetClientData() const { return &m_clientData; }; void NetClientHost::Init(unsigned int bufferSize) { _InitializeIOContexts(bufferSize ? bufferSize : 1024); } void NetClientHost::ReleaseContext(IOContext *ioContext) { int i = sizeof(_IOContextData), j = sizeof(IOContext); _IOContextData *contextData = (_IOContextData *) (((char *) ioContext) - (i - j)); InterlockedDecrement(&contextData->inUse); //SetEvent(*(m_hContextEvents + contextData->index)); } struct _IOContextData { unsigned int index; volatile long inUse; IOContext ioContext; }; ClientData m_clientData; _IOContextData *m_ioContexts; HANDLE *m_hContextEvents; void _InitializeIOContexts(unsigned int bufferSize) { m_ioContexts = new _IOContextData[IO_CONTEXT_COUNT]; m_hContextEvents = new HANDLE[IO_CONTEXT_COUNT]; memset((void *) m_ioContexts, 0, sizeof(_IOContextData) * IO_CONTEXT_COUNT); for (int i = 0; i < IO_CONTEXT_COUNT; ++i) { (m_ioContexts + i)->index = i; (m_ioContexts + i)->ioContext.buf = new char[bufferSize]; (m_ioContexts + i)->ioContext.wsaReceiveBuf.len = bufferSize; (m_ioContexts + i)->ioContext.wsaReceiveBuf.buf = (m_ioContexts + i)->ioContext.buf; (m_ioContexts + i)->ioContext.TESTbuf = new char[10000]; (m_ioContexts + i)->ioContext.wsaSendBuf.buf = (m_ioContexts + i)->ioContext.TESTbuf; *(m_hContextEvents + i) = CreateEvent(0, TRUE, FALSE, 0); } } void _SetSocket(SOCKET socket) { m_clientData.socket = socket; } }; bool WriteChunk(const NetClientHost *clientHost, NetClientHost::IOContext *ioContext) { int status; status = WSASend(clientHost->GetClientData()->socket, &ioContext->wsaSendBuf, 1, &ioContext->bytesSent, ioContext->flags, &ioContext->overlapped, 0); if (status == SOCKET_ERROR && WSAGetLastError() != WSA_IO_PENDING) { // ... return false; } return true; } bool Write(NetClientHost *clientHost, void *buffer, unsigned int size, unsigned int chunk) { //__ASSERT(m_clientHost); //__ASSERT(m_clientHost->GetClientData()->remainingBytesToSend == 0); NetClientHost::IOContext *ioContext = clientHost->AcquireContext(); if (!chunk) chunk = size; ioContext->wsaSendBuf.buf = ioContext->TESTbuf; ioContext->operation = NetClientHost::kOperationWrite; ioContext->flags = 0; ioContext->wsaSendBuf.buf = new char[size]; memcpy((void *) ioContext->wsaSendBuf.buf, buffer, chunk); ioContext->wsaSendBuf.len = chunk; ioContext->chunk = chunk; ioContext->bytesToSendTotal = size; ioContext->remainingBytesToSend = size; return WriteChunk(clientHost, ioContext); } void Read(NetClientHost *clientHost) { NetClientHost::IOContext *ioContext = clientHost->AcquireContext(); int status; memset((void *) ioContext, 0, sizeof(NetClientHost::IOContext)); ioContext->buf = new char[1024]; ioContext->wsaReceiveBuf.len = 1024; ioContext->wsaReceiveBuf.buf = ioContext->buf; ioContext->flags = 0; ioContext->operation = NetClientHost::kOperationRead; status = WSARecv(clientHost->GetClientData()->socket, &ioContext->wsaReceiveBuf, 1, &ioContext->bytesReceived, &ioContext->flags, &ioContext->overlapped, 0); int i = WSAGetLastError(); if (status == SOCKET_ERROR && WSAGetLastError() != WSA_IO_PENDING) { // ... } } bool AddSocket(HANDLE hIOCP, SOCKET socket) { ++connection; int bufSize = 0; LINGER lingerStruct; lingerStruct.l_onoff = 1; lingerStruct.l_linger = 0; setsockopt(socket, SOL_SOCKET, SO_SNDBUF, (char *) &bufSize, sizeof(int)); setsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char *) &bufSize, sizeof(int)); setsockopt(socket, SOL_SOCKET, SO_LINGER, (char *) &lingerStruct, sizeof(lingerStruct) ); NetClientHost *clientHost = new NetClientHost; clientHost->_InitializeIOContexts(1024); clientHost->Init(0); clientHost->_SetSocket(socket); // Add this socket to the IO Completion Port CreateIoCompletionPort((HANDLE) socket, hIOCP, (DWORD_PTR) clientHost, 0); Read(clientHost); return true; } int read = 0, write = 0; DWORD WINAPI WorkerThread(LPVOID param) { LPOVERLAPPED overlapped; NetClientHost *clientHost; HANDLE hIOCP = (HANDLE) param; DWORD ioSize; BOOL status; while (true) { status = GetQueuedCompletionStatus(hIOCP, &ioSize, (PULONG_PTR) &clientHost, (LPOVERLAPPED *) &overlapped, INFINITE); if (!(status || ioSize)) { --connection; //_CloseConnection(clientHost); continue; } NetClientHost::IOContext *ioContext = (NetClientHost::IOContext *) overlapped; switch (ioContext->operation) { case NetClientHost::kOperationRead: download += ioSize; Write(clientHost, ioContext->wsaReceiveBuf.buf, ioSize, 0); write++; clientHost->ReleaseContext(ioContext); break; case NetClientHost::kOperationWrite: upload += ioSize; if (ioContext->remainingBytesToSend) { ioContext->remainingBytesToSend -= ioSize; ioContext->wsaSendBuf.len = ioContext->chunk <= ioContext->remainingBytesToSend ? ioContext->chunk : ioContext->remainingBytesToSend; // equivalent to min(clientData->chunk, clientData->remainingBytesToSend); ioContext->wsaSendBuf.buf += ioContext->wsaSendBuf.len; } if (ioContext->remainingBytesToSend) { WriteChunk(clientHost, ioContext); } else { clientHost->ReleaseContext(ioContext); Read(clientHost); read++; } break; } } return 0; } DWORD WINAPI ListenThread(LPVOID param) { SOCKET sdListen = (SOCKET) param; HANDLE hIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 0); CreateThread(0, 0, WorkerThread, hIOCP, 0, 0); CreateThread(0, 0, WorkerThread, hIOCP, 0, 0); CreateThread(0, 0, WorkerThread, hIOCP, 0, 0); CreateThread(0, 0, WorkerThread, hIOCP, 0, 0); while (true) { SOCKET as = WSAAccept(sdListen, 0, 0, 0, 0); if (as != INVALID_SOCKET) AddSocket(hIOCP, as); } } int main() { SOCKET sdListen; SOCKADDR_IN si_addrlocal; int nRet; int nZero = 0; LINGER lingerStruct; WSADATA wsaData; WSAStartup(0x202, &wsaData); sdListen = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_IP, NULL, 0, WSA_FLAG_OVERLAPPED); si_addrlocal.sin_family = AF_INET; si_addrlocal.sin_port = htons(5000); si_addrlocal.sin_addr.s_addr = htonl(INADDR_ANY); nRet = bind(sdListen, (struct sockaddr *)&si_addrlocal, sizeof(si_addrlocal)); nRet = listen(sdListen, 5); nZero = 0; nRet = setsockopt(sdListen, SOL_SOCKET, SO_SNDBUF, (char *) &nZero, sizeof(nZero)); nZero = 0; nRet = setsockopt(sdListen, SOL_SOCKET, SO_RCVBUF, (char *)&nZero, sizeof(nZero)); lingerStruct.l_onoff = 1; lingerStruct.l_linger = 0; nRet = setsockopt(sdListen, SOL_SOCKET, SO_LINGER, (char *)&lingerStruct, sizeof(lingerStruct) ); CreateThread(0, 0, ListenThread, (LPVOID) sdListen, 0, 0); HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); while (true) { COORD c = {0}; SetConsoleCursorPosition(console, c); printf("Connections: %i \nUpload: %iKB/s \nDownload: %iKB/s ", connection, upload * 2 / 1024, download * 2 / 1024); upload = 0; download = 0; Sleep(500); } return 0; } A: This kind of asynchronous system should be able to run at full datalink speed. Problems I've found wrong are such as: * *timeout settings causing needless retransmissions *in the receiving process, received message A might trigger a database update, such that received message B has to wait, causing an unnecessary delay in the response to message B back to the sender, when the DB update could actually be done in idle time. There's something called wireshark that can give you some visibility into the message traffic. I used to do it the hard way, with time-stamped message logs. BTW: I would first use this method on the individual processes, to clean out any bottlenecks, before doing the asynchronous analysis. If you haven't done this, you can bet they're in there. Just any old profiler isn't reliable. There are good ones, including Zoom.
doc_23535608
So can i do that with pdb? and how? A: The answer is No. pdb has no such option to do this.('variable' called 'reference' may be better). The variable in python is different from C/C++, For example: the integer 1, in C his storage form: 0000 0000 0000 0001 However, in python, 1 is not a pure number, It's a structure. If you look at Python-2.7.13\Include\intobject.h you will see this: typedef struct { PyObject_HEAD long ob_ival; } PyIntObject; I do not think there is a need to look at the storage form of a variable in python. Sometimes we just need to know what a varible is. In this situation, you can use 'p' or 'pp'. Doc in https://docs.python.org/2/library/pdb.html. p expression Evaluate the expression in the current context and print its value. pp expression Like the p command, except the value of the expression is pretty-printed using the pprint module.
doc_23535609
Here's my code : int a = 0; while(a < 10) { a++; } if (a == 10) { NSString *q = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:@"http://localhost/myURL.txt"] encoding:NSUTF8StringEncoding error:nil]; NSURLRequest *url = [NSURLRequest requestWithURL:[NSURL URLWithString:q]]; NSURLConnection *c = [[NSURLConnection alloc] initWithRequest:url delegate:self]; } The code above should get a url from a txt file and call it, When it's called it must create a new directory but it's not. A: You have to launch the connection: NSURLConnection *c = [[NSURLConnection alloc] initWithRequest:requestURL delegate:self startImmediately:YES]; or: NSURLConnection *c = [[NSURLConnection alloc] initWithRequest:requestURL delegate:self]; Then, if you want receive the event of this object, be sure to make your close conforms to protocol NSURLConnectionDelegate, NSURLConnectionDataDelegate. So in your file header (.h): @interface YourClass <NSURLConnectionDelegate, NSURLConnectionDataDelegate> and in your file implementation (.m) for example you can write the method called when the connection finish to load: - (void)connectionDidFinishLoading:(NSURLConnection *)connection { //your code } You will see the other delegate methods in the apple documentation. If you want run this in another thread, you should run the method in the main thread and then pass a queue to the URLConnection: NSOperationQueue *networkOperationsQueue = [NSOperationQueue new]; NSURLConnection *c = [[NSURLConnection alloc] initWithRequest:requestURL delegate:self startImmediately:NO]; [c setDelegateQueue:networkOperationsQueue]; [c start]; In any case your code above is redundant: while(a < 10) { a++; } if (a == 10) If you are in a while cycle and wait the that a == 10 to go out for the while, you don't need to check if a is equal 10..because is so.
doc_23535610
<a-scene renderer ="antialias: true; colorManagement: true;` sortObjects: true; physicallyCorrectLights: true; maxCanvasWidth: 1920; maxCanvasHeight: 1920;"></a-scene> Example pseudo code of what I wish to implement: <script> var update = document.queryselector('a-scene'); if(fps < 60){ update.maxCanvasWidth = 800; update.maxCanvasHeight = 800; } </script> A: renderer is an attribute of the scene element, so you would use setAttribute. Specifically, refer to the documentation on updating multi-property component data. e.g. const scene = document.querySelector('a-scene'); scene.setAttribute('renderer', 'maxCanvasWidth', 800); A: Actually, I was able to figure it out: sceneEl = document.querySelector('a-scene'); sceneEl.maxCanvasSize = {height: , width: };
doc_23535611
/path/to/project/dist/server.js:225854 __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); else {}})(this,function(){"use strict"; function b(a,b){return"undefined"==typeof b?b={autoBom:!1}:"object"!=typeof b&&(console.warn("Depricated: Expected third argument to be a object"),b={autoBom:!b}),b.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*; .*charset\s*=\s*utf-8/i.test(a.type)?new Blob(["\uFEFF",a],{type:a.type}):a}function c(b,c,d){var e=new XMLHttpRequest;e.open("GET",b),e.responseType="blob",e.onload=function(){a(e.response,c,d)},e.onerror=function(){console.error("could not download file")},e.send()}function d(a){var b=new XMLHttpRequest; return b.open("HEAD",a,!1),b.send(),200<=b.status&&299>=b.status}function e(a){try{a.dispatchEvent(new MouseEvent("click"))}catch(c){var b=document.createEvent("MouseEvents"); b.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),a.dispatchEvent(b)}}var f="object"= ReferenceError: HTMLAnchorElement is not defined at Object.<anonymous> (/path/to/project/dist/server.js:225854:1182) I'm not sure where it is coming from, and there didn't seem to be any other questions that got to the same question. Here is the server.ts file I made: import 'zone.js/dist/zone-node'; import 'reflect-metadata'; import { renderModuleFactory } from '@angular/platform-server'; import { enableProdMode } from '@angular/core'; import * as express from 'express'; import { join } from 'path'; import { readFileSync } from 'fs'; // Faster server renders w/ Prod mode (dev mode never needed) enableProdMode(); // Express server const app = express(); const PORT = process.env.PORT || 4000; const DIST_FOLDER = join(process.cwd(), 'dist'); // Our index.html we'll use as our template const template = readFileSync(join(DIST_FOLDER, 'browser', 'index.html')).toString(); // Fix for window const domino = require('domino'); const win = domino.createWindow(template); global['window'] = win; global['document'] = win.document; global['navigator'] = win.navigator; global['CSS'] = undefined; // * NOTE :: leave this as require() since this file is built Dynamically from webpack const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/server/main'); const { provideModuleMap } = require('@nguniversal/module-map-ngfactory-loader'); app.engine('html', (_, options, callback) => { renderModuleFactory(AppServerModuleNgFactory, { // Our index.html document: template, url: options.req.url, // DI so that we can get lazy-loading to work differently (since we need it to just instantly render it) extraProviders: [ provideModuleMap(LAZY_MODULE_MAP) ] }).then(html => { callback(null, html); }); }); app.set('view engine', 'html'); app.set('views', join(DIST_FOLDER, 'browser')); // Server static files from /browser app.get('*.*', express.static(join(DIST_FOLDER, 'browser'))); // All regular routes use the Universal engine app.get('*', (req, res) => { res.render(join(DIST_FOLDER, 'browser', 'index.html'), { req }); }); // Start up the Node server app.listen(PORT, () => { console.log(`Node server listening on http://localhost:${PORT}`); }); And here is the webpack.server.config.js: const path = require('path'); const webpack = require('webpack'); module.exports = { entry: { server: './server.ts' }, mode: 'none', resolve: { extensions: ['.js', '.ts'] }, target: 'node', // this makes sure we include node_modules and other 3rd party libraries externals: [/(node_modules|main\..*\.js)/,'bufferutil', 'utf-8-validate'], output: { path: path.join(__dirname, 'dist'), filename: '[name].js' }, module: { rules: [ { test: /\.ts$/, loader: 'ts-loader' } ] }, plugins: [ // Temporary Fix for issue: https://github.com/angular/angular/issues/11580 // for "WARNING Critical dependency: the request of a dependency is an expression" new webpack.ContextReplacementPlugin( /(.+)?angular(\\|\/)core(.+)?/, path.join(__dirname, 'src'), // location of your src {} // a map of your routes ), new webpack.ContextReplacementPlugin( /(.+)?express(\\|\/)(.+)?/, path.join(__dirname, 'src'), {} ), new webpack.IgnorePlugin( /uws/ ) ] } There is no problem running normal client-side building (e.g. npm start). Any suggestions on what might be causing the issue? Any other info that would be helpful? Thanks in advance!
doc_23535612
public class Main { public static <T extends Number> void bar(Wrapper<List<T>> wrapper) { // do something } public static void foo(Wrapper<List<? extends Number>> wrapper) { // do something } public static <T extends Number> void bar2(List<T> aList) { // do something } public static void foo2(List<? extends Number> aList) { // do something } public static void main(String[] args) { List<Integer> aList = Collections.singletonList(1); foo2(aList); // compiles bar2(aList); // compiles Wrapper<List<Integer>> wrapper = new Wrapper<>(Collections.singletonList(1)); foo(wrapper); // not compiles bar(wrapper); // compiles } private static class Wrapper<T> { private final T t; public Wrapper(T t) { this.t = t; } } } So the question is why javac gives an error when I try to compile the code: Main.java:26: error: method foo in class Main cannot be applied to given types; foo(wrapper); // not compiles ^ required: Wrapper<List<? extends Number>> found: Wrapper<List<Integer>> reason: argument mismatch; Wrapper<List<Integer>> cannot be converted to Wrapper<List<? extends Number>> 1 error A: Because Java generics are not covariant. In your case Wrapper<List<Integer>> instance cannot be used as Wrapper<List<? extends Number>> parameter because List<Integer> does not extend List<? extends Number> A: Wrapper<List<Integer>> is not a subtype of Wrapper<List<? extends Number>>. Use Wrapper<? extends List<? extends Number>>. To see why you can't pass Wrapper<List<Integer>> to foo, consider the following: I've replaced Wrapper with List, but it's the same thing from a type safety point of view. List<List<? extends Number>> list = new ArrayList<>(); List<List<Integer>> intList = new ArrayList<>(); So, you can add something to list: List<Double> doubles = new ArrayList<>(Arrays.asList(0.0)); list.add(doubles); But, if you were able to write this assignment: list = intList; Then calling list.add(doubles) would mean there would then be a List<Double> in intList. This is not type safe, and thus forbidden. Ideone demo However, if list has type List<? extend List<? extends Number>>, then you can't invoke add on it, so you can't get into this situation, so that would be safe. A: Because List<Integer> is not a subclass of List<? extends Number>
doc_23535613
PK!0É(r¥[Content_Types].xml ¢( ´TÉnÂ0½Wê?D¾V‰¡‡ªªº[¤Ò0ö¬z“ÇlßI QÕB A: This looks like a perfectly valid .docx-file when viewed in a text-editor. Note that all MS-Office formats are some kind of binary format and its a non-trivial process to extract the text-contents. As for .docx: it's basically a bunch of several .xml-files that are zipped together - to see those contents just rename it to .zip, unpack it with your favorite zip-tool and view the contents - you won't be happy with that either :-(
doc_23535614
CALayer *topBorder = [CALayer layer]; topBorder.frame = CGRectMake(os, 1.0f, b.bounds.size.width - (os * 2.0f), 1.0f); topBorder.backgroundColor = [c1 CGColor]; [b.layer addSublayer:topBorder]; CALayer *bottomBorder = [CALayer layer]; bottomBorder.frame = CGRectMake(os, b.bounds.size.height, b.bounds.size.width - (os * 2.0f), 1.0f); bottomBorder.backgroundColor = [c1 CGColor]; [b.layer addSublayer:bottomBorder]; //os..offset, b..uibutton, c1..color this works fine when i call the function in viewDidAppear (but there is a delay then) but when i put it in viewdidlayoutsubviews it adds an additional line, what somehow looks like this i set it up with a leading and trailing space to its superview, what a i doing wrong here? A: The viewDidAppear is executed when you view appears on screen and every time come back from other view controller in your navigation flow. So your code add lines several times. You can review the view controller lifecycle here. If you want to remove the "delay" and executed once, write your code in the viewDidLoad. UPDATE I see two approach. Create a UIButton subclass and then: * *If you want to keep working with CALayers, you'll need to call a redraw method always your button change its size. If the change is animated will appear weird artifact. *The good one. I recommend you use the 'drawRect' to paint this lines and use the button frame to calculate line XY dynamically. If you button change its size, animated or not… no problem, Core Animation do all the job. - (void)drawRect:(CGRect)rect { // Frames CGRect frame = self.bounds; // Parameters (change these values if you want to change appearance) UIColor *lineColor = [UIColor colorWithRed: 0.5 green: 0.5 blue: 0.5 alpha: 1]; CGFloat topRatioPositionY = 0.02; CGFloat middleRatioPositionY = 0.6; CGFloat bottomRatioPositionY = 0.98; CGFloat middleRatioPositionX = 0.33333; CGFloat lineWidth = 1.0; //// Top line UIBezierPath* bezierPath = [UIBezierPath bezierPath]; [bezierPath moveToPoint: CGPointMake(CGRectGetMinX(frame), CGRectGetMinY(frame) + topRatioPositionY * CGRectGetHeight(frame))]; [bezierPath addLineToPoint: CGPointMake(CGRectGetMinX(frame) + 1.00000 * CGRectGetWidth(frame), CGRectGetMinY(frame) + topRatioPositionY * CGRectGetHeight(frame))]; [lineColor setStroke]; bezierPath.lineWidth = lineWidth; [bezierPath stroke]; // Middle line UIBezierPath* bezier2Path = [UIBezierPath bezierPath]; [bezier2Path moveToPoint: CGPointMake(CGRectGetMinX(frame), CGRectGetMinY(frame) + bottomRatioPositionY * CGRectGetHeight(frame))]; [bezier2Path addLineToPoint: CGPointMake(CGRectGetMinX(frame) + 1.00000 * CGRectGetWidth(frame), CGRectGetMinY(frame) + bottomRatioPositionY * CGRectGetHeight(frame))]; [lineColor setStroke]; bezier2Path.lineWidth = lineWidth; [bezier2Path stroke]; // Bottom Line UIBezierPath* bezier3Path = [UIBezierPath bezierPath]; [bezier3Path moveToPoint: CGPointMake(CGRectGetMinX(frame), CGRectGetMinY(frame) + middleRatioPositionY * CGRectGetHeight(frame))]; [bezier3Path addLineToPoint: CGPointMake(CGRectGetMinX(frame) + middleRatioPositionX * CGRectGetWidth(frame), CGRectGetMinY(frame) + middleRatioPositionY * CGRectGetHeight(frame))]; [lineColor setStroke]; bezier3Path.lineWidth = lineWidth; [bezier3Path stroke]; }// drawRect: I've attached this source code with lines with CALayer and with UIBezierPath solutions. Touch on buttons and see the difference when they change.
doc_23535615
All is well, I have developed quite a few portlets that I have made work around for (when I run into some issues that I could usually handle in a straight forward fashion). Overall Coldfusion 9 portlets work very well inside of Liferay. One thing I really dislike is that the URLs are so unreadable, and I was really hoping for clean urls for my application, so when a user searches, and the result comes back, I can have them click a link like http://liferaysite.com/web/viewitem/ABC123. Currently I get a raggedy URL that includes portlet status, properties, the portlet ID associated with the variable that I am passing (usually a combination of portlet id + variable) and other garbage that is un-needed. Is there any 'easy' way to get clean URLs? My issue is that I am not a JAVA person, so I am not too confidant in digging into jBoss/Liferay code to get something done. However I feel that Liferay is sufficiently 'hands-free' so that I can build my portlets and deploy them without modifying JAVA code and getting dirty. Any ideas? I am not able to find many articles on this, especially since Liferay 6 is so new, and there are so few people posting things about it. Maybe this would be some sort of URL rewriting in Jboss? Thank you, appreciate any and all suggestions :) A: The short answer is to use URL rewriting to achieve this and transform Liferay URLs to any form you want. There are 2 possibilities I see to do this: * *Put an Apache web server in front of your Liferay server and use mod_rewrite *Use the URL rewriting filter that is already included in Liferay as this mimics what mod_rewrite does without the requirement of an extra Apache server A: You might be interested in FriendlyUrlMappers. See this blog entry about the basics. Regarding the "easy" you have to judge about that yourself. The nature of portals, e.g. combining completely different and independent applications (portlets) on a single page bring with it that you loose control over URLs (by default), because the portal has to disambiguate quite a lot of stuff. In order to get back control, you need to do some work, FriendlyUrlMappers impose some work, but the result is worth it IMHO.
doc_23535616
Is there any way to manage three different installs of VS code so that each one has its own set of extensions with related tasks.
doc_23535617
https://presentation.io Hope you will understand the thing I am looking for and provide some useful suggestion to me. Thanks.
doc_23535618
It loads new html (including div tags and all) to show up on the page. I included a 'more' link to load additional data. This more link links to my javascript function. The 'more' link is located in a div, which I gave a unique id. The next time the load function is called, I use document.getElementById(the id).style.display="none"; to "remove" this div from the look of the page. I set error traps for this, the div with that id is found without problems, but javascript fails to change my style property. I tested alert(document.getElementById(the id).innerHTML); and that worked without problems - hence the title of the question. So, does anyone have any ideas/do I need to offer more information? The main problem is that it doesn't throw any errors anywhere, yet it fails to complete the task I asked... Here's a bit of code to go with it - try { var myidthing = "morelink" + ContentStart.toString(); //the id is correct var div = document.getElementById(myidthing); if (!div) { } else { div.style.display="none"; //this doesn't work, but doesn't raise an error alert(div.innerHTML); //this works without problem } } catch(theerr) { alert(theerr); } ------------------------->EDIT<------------------------- I'm incredibly sorry if I upset any people. I'm also angry at myself, for it was a stupid thing in my code. Basically, I had a variable that stored the contents of a parent div. Then I (succesfully) removed the div using the removeChild() method. Then my code pasted the contents of that vaiable (including the div I wanted gone) back into the parent div. I switched around the order and it works fine now. Again, excuse me for this. A: Throwing out a few ideas of things to look for: * *You said the div is generated by javascript. Is it possible the div you are targeting is not the one you think you are? It could be you are targeting another div, which is already hidden, or obstructed... or maybe the innerHTML you are displaying goes with a different element than the one you intend to target. Put an alert or script breakpoint in the if(!div) case, also, and see if it's going down that path. *If the above code is only a stripped-down version of your actual code, check your actual code for typos (for example: style.display = "none;";) *Using the FireBug plugin for FireFox, inspect the target element after the operation completes, and make sure that the display: none appears in the style information. If not, use FireBug's debugger to walk through your javascript, and see if you can figure out why. *Use FireBug to break on all script errors, in case there is another error causing this behavior. A: Try empty quotes instead of 'none' and see if that works?: document.getElementById('element_id').style.display=""; Failing that, don't change the style, just add a class which hides the element.
doc_23535619
Everything goes fine if I simply create a date field in the group and summarize it by distinctcount - I get the correct number of course completions by completion date. (I have a resource to independently verify this.) However, I also need to create a formula that will, eventually, calculate the average number of course sessions conducted per year. With that in mind, I have tried to create a formula and insert it into the group, but every time I do this I get a completely incorrect number - it's a count of every single completion date, regardless of if it's distinct or not or even if it's in the single organization. I've tried the following as a forumla: Distinctcount({*data source*.*completion date field*}) and whileprintingrecords; Distinctcount({*data source*.*completion date field*}) and numbervar sessions; whileprintingrecords; sessions:=distinctcount({*data source*.*completion date field*}) None of these work - they give the grand total of course completions. I also tried whilereadingrecords, but it errors out on me and says "This function cannot be used because it must be evaluated later." Can anyone help me out here?
doc_23535620
For OIDC, Salesforce appears to require the UserInfo endpoint which B2C doesn't implement. I would like to try and use SAML for federation, where B2C is the IdP and Salesforce is the Service Provider. SAML is achievable through custom policies. Has anyone succeeded at SAML 2.0 federation between B2C (as the IdP) and Salesforce? If so, could you share your key learnings, such as a redacted SAML.xml policy & B2C App manifest file. Great appreciate the help.
doc_23535621
public class CategoryMap : ClassMap<CategoryPartRecord> { public CategoryMap() { Table("Ceck_CategoryPartRecord"); Id(x => x.Id).GeneratedBy.Native(); Map(x => x.Name); //Relationships- // Recursive: // [Category]---<[Category] References(x => x.ParentCategory) HasMany(x => x.Categories) .Inverse() .Cascade.All(); } } I have tried two approaches: using (var transactionB = session.BeginTransaction()) { CategoryPartRecord Cat1 = new CategoryPartRecord() { Name = "Exterior" }; CategoryPartRecord Cat2 = new CategoryPartRecord() { Name = "Interior" }; CategoryPartRecord Cat3 = new CategoryPartRecord() { Name = "Garden" }; CategoryPartRecord Cat4 = new CategoryPartRecord() { Name = "Paint" }; Cat1.Categories.Add(Cat4); session.Save(Cat1); session.Save(Cat2); session.Save(Cat3); transactionB.Commit(); } . using (var transactionBB = session.BeginTransaction()) { var Cat = session.Load<CategoryPartRecord>(1); //Contains "Exterior" CategoryPartRecord Cat2 = new CategoryPartRecord() { Name = "Paint" }; Cat.Categories.Add(Cat2); session.Save(Cat); transactionBB.Commit(); } Both add the new record containing "Paint", but dont link the relationship correctly, as "CategoryPartRecord_id" is always NULL -- Am I missing something really obvious because neither work? A: Hmm, hazarding a guess - inversion on a recursion would be more than interesting, so to eliminate any funny behaviour, change your mapping to this and let me know how you get on? References(x => x.ParentCategory).Cascade.SaveUpdate(); HasMany(x => x.Categories) .Cascade.SaveUpdate();
doc_23535622
checkIfEmptyDb = async => { var ref = firebase.database().ref("dynamicDb"); ref.once("value").then(snapshot => { const a = snapshot.exists(); console.log(a); // false return a; }); }; getRandomWordFromDb = async () => { let moreWords = await this.checkIfEmptyDb(); console.log("moreWords", moreWords); //UNDEFINED My solution so far is to set the state of the react app in the checkIfEmptyDbfunction, which then can be called in getRandomWordFromDb.. Thanks in advance! A: You need to return the value of the promise: checkIfEmptyDb = async => { var ref = firebase.database().ref("dynamicDb"); return ref.once("value").then(snapshot => { const a = snapshot.exists(); console.log(a); // false return a; }); };
doc_23535623
A: import re def beforePeriod(s): m = re.match('(.*)\..*',s) if m: return m.groups()[0] or def beforePeriod(s): return s[s:s.index('.')] or def beforePeriod(s): return s.split('.')[0] A: If you look through the docs.python.org section 5.6.1. String Methods you will see a str.find() function: str.find(sub[, start[, end]]) Return the lowest index in the string where substring sub is found ... The find() method should be used only if you need to know the position of sub. find() can be used as shown in the following example, which is snipped from an ipython interpreter transcript. In [2]: def defbeforePeriod(s): ...: return s[:s.find('.')] ...: In [3]: defbeforePeriod('abc2.3ty') Out[3]: 'abc2' In [4]: defbeforePeriod('abc2.3ty.zeta') Out[4]: 'abc2' A: If you are trying to manipulate filenames, have a look at os.path, in particular os.path.splitext().
doc_23535624
plot_ly(x = ~SWITCHING_SUMS_NET()$week, y = ~SWITCHING_SUMS_NET()$V1, name = 'Affordability', type = 'scatter', mode = 'lines+markers', text=~SWITCHING_SUMS_NET()$V1, textposition="top center") %>% add_trace(y = ~SWITCHING_SUMS_NET()$V2, name = 'Experience Change', mode = 'lines+markers', text=~SWITCHING_SUMS_NET()$V2) %>% add_trace(y = ~SWITCHING_SUMS_NET()$V3, name = 'Unavailability', mode = 'lines+markers', text=~SWITCHING_SUMS_NET()$V3) %>% add_trace(y = ~SWITCHING_SUMS_NET()$V4, name = 'Attracted buy another brand', mode = 'lines+markers', text=~SWITCHING_SUMS_NET()$V4) %>% layout(xaxis = list(title = ''), yaxis = list (title = 'Count',showticklabels = T), legend = list(orientation = 'h', xanchor = "center",x = 0.5,y= -0.3)) Output image: A: Whenever you have to do multiple add_trace (or other plotly functions) in plotly or geoms in ggplot, investigate possibility of reshaping your dataframe from wide to long. This way you can create a grouping column and do only one add_trace (here is an example for ggplot2: Making multi-line plots in R using ggplot2). Moreover, it is preferred to read in your data using the reactive function into a variable within shiny (i.e. plot_data <- SWITCHING_SUMS_NET()) outside of your plotting function. This way you can later apply filters, reshaping or other necessary functions on your data and with minimal edits your plot will be produced again. Also, your input data stays the same. Considering hints above, this is the best way to approach this problem. Here, I have two traces, one for text and the other for markers and lines (within plot_ly function itself). The other approach would be using annotation which I don't see as efficient. Read more here: https://plotly.com/r/text-and-annotations/ ## packages library(shiny) library(plotly) library(dplyr) library(tidyr) ## reading reactive to a variable plot_data <- SWITCHING_SUMS_NET() plot_data %>% ## rename variables to the names to be used in the plot rename_at(c("V1", "V2", "V3", "V4"), list(~c("Affordability", "Experience Change", "Unavailability", "Attracted buy another brand"))) %>% ## reshape data from wide to long pivot_longer(-week) %>% ## plot the rehsaped data ## add a trace for liens and markers with legend plot_ly(x = ~week, y = ~value, color = ~name, type = 'scatter', mode = 'lines+markers', showlegend = T) %>% ## add a trace for text without legend ## insert `color = I("Black")` to have texts in one for all add_text(text=~value, textposition="top center", showlegend = F) %>% ## set the layout layout(xaxis = list(title = ''), yaxis = list (title = 'Count', showticklabels = T), legend = list(orientation = 'h', xanchor = "center", x = 0.5, y = -0.3)) Example: I also added an illustration using iris dataset since you haven't shared your data. library(dplyr) library(tidyr) library(plotly) iris %>% filter(Species == "setosa") %>% slice(1:10) %>% arrange(Sepal.Length) %>% pivot_longer(-c(Species, Sepal.Length)) %>% plot_ly(x=~Sepal.Length, y=~value, color = ~name, type = 'scatter', mode = 'lines+markers', showlegend = T) %>% add_text(text=~value, textposition="top center", showlegend = F) %>% layout(xaxis = list(title = ''), yaxis = list (title = 'Count', showticklabels = T), legend = list(orientation = 'h', xanchor = "center", x = 0.5, y = -0.3))
doc_23535625
How do you create a pre-populated database? (what kind of file format should it be) If there are two factors can be changed, how do I get the result of a combination of these factors from the database using SQL. Will the database be wiped if the user clears app data from the Settings menu on an Android device? Grateful for any help. thanks A: Prepopulate SQLite DataBase in PhoneGap Application 1) You can create a basic database for app with the help of tools like SQLite Manager or if you already have a database in your app you can directly get the database files. 2) Then you need to install Cordova/PhoneGap SQLitePlugin by CLI . (Cordova/PhoneGap SQLitePlugin) cordova plugin add https://github.com/brodysoft/Cordova-SQLitePlugin 3) Addd following script file in your html. <script src="plugins/com.brodysoft.sqlitePlugin/www/SQLitePlugin.js"></script> 4) If you are working for emulator then copy your databas using command prompt, I have added myDB.sqlite in asset folder then run . adb push myDB.sqlite /data/data/com.my_app.my_app/databases/myDB.sqlite 5) For device, just put them in to bundle of app that is assets folder in case of Android . you need myDB.sqlite and file__0/0000000000000001.sqlite files. 6) Now you have to copy the files at the native location of application at the time of first boot of application, and make sure that the files should copy before your very first SQLite query. To copy these files you can use the following code snippet based on your environment. JAVA (Android). More... public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.init(); try { String pName = this.getClass().getPackage().getName(); this.copy("myDB.sqlite", "/data/data/" + pName + "/databases/"); this.copy("0000000000000001.sqlite", "/data/data/" + pName + "/app_database/file__0/"); } catch (IOException e) { e.printStackTrace(); } super.loadUrl(Config.getStartUrl()); } void copy(String file, String folder) throws IOException { File CheckDirectory; CheckDirectory = new File(folder); if (!CheckDirectory.exists()) { CheckDirectory.mkdir(); } InputStream in = getApplicationContext().getAssets().open(file); OutputStream out = new FileOutputStream(folder + file); // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in .close(); out.close(); } 7) Then add snippet in your js file. $(document).ready(function(e){ document.addEventListener("deviceready", dbConnection, false); }) function dbConnection(){ db = window.sqlitePlugin.openDatabase("myDB.sqlite", "1.0", "DB", 2000000); db.transaction(function(tx) { tx.executeSql("SELECT * from table", [], function(tx, res) { for(var i=0; i<res.rows.length; i++){ ; console.log("RESULT:" + res.rows.item(i)['field_name']); } }); }); } More Detail...
doc_23535626
def CreateAnimation(p,q): animation = widgets.HTML(''' <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.2.0/p5.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.2.0/addons/p5.sound.min.js"></script> <script> new p5(); let numBalls = 40; let spring = 0.1; let gravity = 0.0001; let friction = -0.9; let balls = []; let paletteList = p; let phrase = q; function setup() { createCanvas(600, 500); for (let i = 0; i < numBalls; i++) { balls[i] = new Ball( random(width), random(height), random(30, 110), i, balls, color(random(paletteList)) ); } noStroke(); fill(255, 204); } function draw() { let x = map(mouseX, 0, width, 0, 255, true) background(x); balls.forEach(ball => { ball.collide(); ball.move(); ball.display(); }); push(); fill(map(mouseX, 0, width, 255, 0, true)); textSize(40); text(phrase, (width/2 - width/2.5),(height/2 - height/4.5), height, width); pop(); } class Ball { constructor(xin, yin, din, idin, oin, hexin) { this.x = xin; this.y = yin; this.vx = 0; this.vy = 0; this.diameter = din; this.id = idin; this.others = oin; this.hex= hexin; } collide() { for (let i = this.id + 1; i < numBalls; i++) { let dx = this.others[i].x - this.x; let dy = this.others[i].y - this.y; let distance = sqrt(dx * dx + dy * dy); let minDist = this.others[i].diameter / 2 + this.diameter / 2; if (distance < minDist) { //console.log("2"); let angle = atan2(dy, dx); let targetX = this.x + cos(angle) * minDist; let targetY = this.y + sin(angle) * minDist; let ax = (targetX - this.others[i].x) * spring; let ay = (targetY - this.others[i].y) * spring; this.vx -= ax; this.vy -= ay; this.others[i].vx += ax; this.others[i].vy += ay; } } } move() { this.vy += gravity; this.x += this.vx; this.y += this.vy; if (this.x + this.diameter / 2 > width) { this.x = width - this.diameter / 2; this.vx *= friction; } else if (this.x - this.diameter / 2 < 0) { this.x = this.diameter / 2; this.vx *= friction; } if (this.y + this.diameter / 2 > height) { this.y = height - this.diameter / 2; this.vy *= friction; } else if (this.y - this.diameter / 2 < 0) { this.y = this.diameter / 2; this.vy *= friction; } } display() { fill(this.hex); ellipse(this.x, this.y, this.diameter, this.diameter); } } </script> ''') return animation #Then call it with something like this: a=CreateAnimation(['#381A38','#DD9B80','#E6937A','#B18079','#8B636C'],'It is a good day to have a good day')
doc_23535627
First thing I did was querying some information on my system with clInfo. Output was as expected, especially the device OpenCL C Version: Platform Name: AMD Accelerated Parallel Processing Number of devices: 2 Device Type: CL_DEVICE_TYPE_GPU Vendor ID: 1002h Board name: AMD Radeon R7 200 Series Platform ID: 00007FFE91EF0188 Name: Bonaire Vendor: Advanced Micro Devices, Inc. Device OpenCL C version: OpenCL C 2.0 Driver version: 2348.4 Profile: FULL_PROFILE Version: OpenCL 2.0 AMD-APP (2348.4) Next thing was playing around with some of the samples from AMD APP SDK. Quickly I noticed, an OpenCL 2.0 didn't execute properly. I stepped through the code and noticed a function, which is gathering device information with clGetDeviceInfo. At this point, the reported device OpenCL C version (see screenshot 1) differs from what I got from clInfo, and therefore, the samples, which requires OpenCL 2.0 don't execute. What did I do wrong? clGetDeviceInfo A: Switching from target platform Win32 to x64 strangely resolved the problem for me. clGetDeviceInfo reports now OpenCL 2.0 capabilities for my GPU.
doc_23535628
i have tried to modify catalog\controller\common\footer.php $data['text_information'] = $this->language->get('text_information'); $data['text_service'] = $this->language->get('text_service'); $data['text_extra'] = $this->language->get('text_extra'); $data['text_contact'] = $this->language->get('text_contact'); $data['text_return'] = $this->language->get('text_return'); $data['text_sitemap'] = $this->language->get('text_sitemap'); $data['text_manufacturer'] = $this->language->get('text_manufacturer'); $data['text_voucher'] = $this->language->get('text_voucher'); $data['text_affiliate'] = $this->language->get('text_affiliate'); $data['text_special'] = $this->language->get('text_special'); $data['text_facebook'] = $this->language->get('text_facebook); $data['text_account'] = $this->language->get('text_account'); $data['text_order'] = $this->language->get('text_order'); $data['text_wishlist'] = $this->language->get('text_wishlist'); $data['text_newsletter'] = $this->language->get('text_newsletter'); $this->load->model('catalog/information'); $data['informations'] = array(); foreach ($this->model_catalog_information->getInformations() as $result) { if ($result['bottom']) { $data['informations'][] = array( 'title' => $result['title'], 'href' => $this->url->link('information/information', 'information_id=' . $result['information_id']) ); } } $data['contact'] = $this->url->link('information/contact'); $data['return'] = $this->url->link('account/return/add', '', 'SSL'); $data['sitemap'] = $this->url->link('information/sitemap'); $data['manufacturer'] = $this->url->link('product/manufacturer'); $data['voucher'] = $this->url->link('account/voucher', '', 'SSL'); $data['affiliate'] = $this->url->link('affiliate/account', '', 'SSL'); $data['special'] = $this->url->link('product/special'); $data['facebook'] = $this->url->link('Here i think the link to my facebook page'); $data['account'] = $this->url->link('account/account', '', 'SSL'); $data['order'] = $this->url->link('account/order', '', 'SSL'); $data['wishlist'] = $this->url->link('account/wishlist', '', 'SSL'); $data['newsletter'] = $this->url->link('account/newsletter', '', 'SSL'); $data['powered'] = sprintf($this->language->get('text_powered'), $this->config->get('config_name'), date('Y', time())); and i've tried to modify : catalog\view\theme\default\template\common\footer.tpl <div class="col-sm-3"> <h5><?php echo $text_extra; ?></h5> <ul class="list-unstyled"> <li><a href="<?php echo $manufacturer; ?>"><?php echo $text_manufacturer; ?></a></li> <li><a href="<?php echo $voucher; ?>"><?php echo $text_voucher; ?></a></li> <li><a href="<?php echo $affiliate; ?>"><?php echo $text_affiliate; ?></a></li> <li><a href="<?php echo $special; ?>"><?php echo $text_special; ?></a></li> <li><a href="<?php echo $facebook; ?>"><?php echo $text_facebook; ?></a></li> </ul> </div> and catalog\language\english\common\footer.php $_['text_facebook'] = 'facebook'; I'm sure that I'm wrong :p What's the problem ? Thanks
doc_23535629
Here is the code: http://jsfiddle.net/czNn2/9/ 'graph-data-array2.json' contains: [{ name: 'Asia', data: [502, 635, 809, 947, 1402, 3634, 5268] }, { name: 'Africa', data: [106, 107, 111, 133, 221, 767, 1766] }, { name: 'Europe', data: [163, 203, 276, 408, 547, 729, 628] }, { name: 'America', data: [18, 31, 54, 156, 339, 818, 1201] }, { name: 'Oceania', data: [2, 2, 2, 6, 13, 30, 46] }] When I run this on my site there are no errors on the console and the area where the graph should be is blank. I am following the advice from the 2nd answer to this prior question: Creating 100% stacked area graph for a website I also tried a json file formated as: [ ["Price", "Us", "You"], [0,0.5,0.5], [1,0.5,0.5], [2,0.5,0.5] ] But it did not work either. In this case I get an error in the console "Uncaught Highcharts error #13" A: Just to make sure (since I didn't see it in your code), add your chart to your <div id="container-chart" />. You can do this via adding a property to the chart options: chart: { renderTo: container-chart, height: 400 }, SOURCE: http://api.highcharts.com/highcharts#chart.renderTo OR use jQuery: $('#container').highcharts({ EDIT: Turns out you can't use a hypen in the id of the div you're rendering to. Your json seems fine. Here is an updated working fiddle: http://jsfiddle.net/czNn2/5 A: The problem is with cross domain problem, because you try to load json with other domain. Solution can be usuing JSONP.
doc_23535630
HTML (There are many of this div item): <div class="item"> <a href="#"> <div class="item-flip"> <div class="item-inner"> <img src="#"> </div> <div class="item-details"> <div class="item-details-inner"> <div class="down-details"> <div class="rating" data-content="9.5"> <i class="icon icon-star"></i>9.5 </div> <span class="year">2011</span> <span>Go</span> </div> </div> </div> </div> </a> </div> Javascript Mousetrap.bind("right", function() { if($('.item-flip selected').length){ var current = $('.item-flip selected'); $('.selected').removeClass('selected'); var el = current.next(); el.addClass('selected'); } else{ $('.item-flip').first().addClass('selected') } }); A: I tried how to figure out a solution, in the following my snippet the code. The points of interest are: * *To select an element with two classes you need to change from $('.item-flip selected') to $('.item-flip.selected') *To get next element you need to find the clossest div father and then search for the item-flip div. So from var el = current.next(); you need to change to: var el = current.closest('.item').next().find('.item-flip'); $(function () { Mousetrap.bind("right", function(e) { if($('.item-flip.selected').length){ var current = $('.item-flip.selected'); $('.selected').removeClass('selected'); var el = current.closest('.item').next().find('.item-flip'); el.addClass('selected'); } else{ $('.item-flip').first().addClass('selected') } }); }); .selected { background-color: red; } <script src="https://code.jquery.com/jquery-1.12.1.min.js"></script> <script src="https://rawgit.com/ccampbell/mousetrap/master/mousetrap.js"></script> <div class="item"> <a href="#"> <div class="item-flip"> <div class="item-inner"> <img src="#"> </div> <div class="item-details"> <div class="item-details-inner"> <div class="down-details"> <div class="rating" data-content="9.5"> <i class="icon icon-star"></i>9.5 </div> <span class="year">2011</span> <span>Go</span> </div> </div> </div> </div> </a> </div> <div class="item"> <a href="#"> <div class="item-flip"> <div class="item-inner"> <img src="#"> </div> <div class="item-details"> <div class="item-details-inner"> <div class="down-details"> <div class="rating" data-content="9.5"> <i class="icon icon-star"></i>9.5 </div> <span class="year">2011</span> <span>Go</span> </div> </div> </div> </div> </a> </div> <div class="item"> <a href="#"> <div class="item-flip"> <div class="item-inner"> <img src="#"> </div> <div class="item-details"> <div class="item-details-inner"> <div class="down-details"> <div class="rating" data-content="9.5"> <i class="icon icon-star"></i>9.5 </div> <span class="year">2011</span> <span>Go</span> </div> </div> </div> </div> </a> </div>
doc_23535631
defined('BASEPATH') OR exit('No direct script access allowed'); class Login extends CI_Controller { // Load model public function __construct() { parent::__construct(); $this->load->model('user_model'); } // Halaman login public function index() { // Validasi $valid = $this->form_validation; $valid->set_rules('username','Username','required', array( 'required' => 'Username harus diisi')); $valid->set_rules('password','Password','required|min_length[6]', array( 'required' => 'Password harus diisi', 'min_length' => 'Password minimal 6 karakter')); if($valid->run()=== FALSE) { // End validasi $data = array( 'title' => 'Login Administrator'); $this->load->view('admin/login_view', $data, FALSE); // Check username dan password compare dengan databas }else{ $i = $this->input; $username = $i->post('username'); $password = $i->post('password'); // Check di database $check_login = $this->user_model->login($username, $password); // Kalau ada record, maka create session dan redirect ke halaman dasbor if(count($check_login) == 1) { $this->session->set_userdata('username', $username); $this->session->set_userdata('akses_level', $check_login->akses_level); $this->session->set_userdata('id_user', $check_login->id_user); $this->session->set_userdata('nama', $check_login->nama); redirect(base_url('admin/dasbor'),'refresh'); }else{ // Kalau username password tidak cocok, error $this->session->set_flashdata('sukses', 'Username atau password tidak cocok'); redirect(base_url('login'),'refresh'); } } //End checking } // Logout public function logout() { $this->session->unset_userdata('username'); $this->session->unset_userdata('akses_level'); $this->session->unset_userdata('id_user'); $this->session->unset_userdata('nama'); // $this->session->set_flashdata('sukses', 'Anda berhasil logout'); redirect(base_url('login'),'refresh'); } } /* End of file Login.php */ /* Location: ./application/controllers/Login.php */ A: you can use phpmailer libaray to send verfication link to using smtp mail like(gmail and localhost mail) and you can also create template for email with html
doc_23535632
<plugin> <groupId>org.openapitools</groupId> <artifactId>openapi-generator-maven-plugin</artifactId> <version>5.4.0</version> </plugin> And <plugin> <groupId>io.swagger.codegen.v3</groupId> <artifactId>swagger-codegen-maven-plugin</artifactId> <version>3.0.34</version> </plugin> And none work. I can't find a way (nor a working sample) to do that (generate model files with lombok support). The webflux is irrelevant to the model, but I mentioned cause both are requirements, and I can't find a sample with both (nor just spring-boot with lombok annotation generation). Thanks. A: I found a way: <plugins> <plugin> <groupId>org.openapitools</groupId> <artifactId>openapi-generator-maven-plugin</artifactId> <version>5.4.0</version> <executions> <execution> <goals> <goal>generate</goal> </goals> <configuration> <apiPackage>${api.package.to.generate}</apiPackage> <modelPackage>${model.package.to.generate}modelPackage> <inputSpec>${project.basedir}/src/main/resources/api/openapi.yaml</inputSpec> <library>spring-boot</library> <generatorName>spring</generatorName> <generateSupportingFiles>false</generateSupportingFiles> <generateApis>true</generateApis> <generateApiTests>true</generateApiTests> <generateModelTests>false</generateModelTests> <generateModels>true</generateModels> <generateModelDocumentation>false</generateModelDocumentation> <generateApiDocumentation>false</generateApiDocumentation> <additionalProperties> <skipDefaultInterface>true</skipDefaultInterface> <useLombok>true</useLombok> </additionalProperties> <configOptions> <library>spring-boot</library> <dateLibrary>java8</dateLibrary> <interfaceOnly>true</interfaceOnly> <skipDefaultInterface>true</skipDefaultInterface> <reactive>true</reactive> <additionalModelTypeAnnotations> @lombok.NoArgsConstructor;@lombok.AllArgsConstructor;@lombok.Builder </additionalModelTypeAnnotations> <openApiNullable>false</openApiNullable> </configOptions> </configuration> </execution> </executions> <dependencies> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.24</version> </dependency> </dependencies> </plugin> This configuration works for me and the only problem left now is how to get rid of the ResponseEntity in the response: Mono<ResponseEntity<GraphBrowseNodeWithRelationships>> But this one will be asked in another question. Cheers.
doc_23535633
instance = fn.apply(instance, arguments) || instance; How does this really work? And why does the following code line not work? instance = fn.apply(instance, arguments); A longer example: var createFoo = function() { var foo = {}, fn = function() { var i = 0; this.increment = function() { i++; }; this.get = function() { return i; }; }; foo = fn.apply(foo, arguments) || foo; return foo; }, foo = createFoo(); test('foo test', function () { foo.increment(); equal(foo.get(), 1, 'pass'); }); var createBar = function() { var bar = {}, fn = function() { var i = 0; this.increment = function() { i++; }; this.get = function() { return i; }; }; bar = fn.apply(bar, arguments); return bar; }, bar = createBar(); test('bar tests', function () { bar.increment(); /* undefined */ }); http://jsfiddle.net/RMh78/59/ A: What's going here has to do with how objects are passed as references and what values functions return. In your code block, you have: var createFoo = function() { var foo = {}, fn = function() { var i = 0; this.increment = function() { i++; }; this.get = function() { return i; }; }; foo = fn.apply(foo, arguments) || foo; return foo; }, foo = createFoo(); Let's break down the foo = fn.apply(foo, arguments) || foo; line. foo was declared and initialized as an empty object ({}). It was then set as the this context in the foo function (that's what .apply does). The arguments would pass any args (none) sent to createFoo to fn. So, so when fn.apply is ran, the foo objects has increment and get properties applied to it. fn doesn't have a return statement, so it returns undefined. So, now we have foo = undefined || foo;, and we have foo updated with some properties. This sets foo to itself, then the next line returns it. In the second (bar) block: var createBar = function() { var bar = {}, fn = function() { var i = 0; this.increment = function() { i++; }; this.get = function() { return i; }; }; bar = fn.apply(bar, arguments); return bar; }, bar = createBar(); You don't have || bar after fn.apply(bar, arguments). So, what happens is that fn runs, it returns undefined, bar's set to that then bar (undefined) is returned. A: So how does the following code work, and does it have any disadvantages compared to the first createFoo function? var createFoo2 = function() { var foo = {}, fn = function() { var i = 0; this.increment = function() { i++; }; this.get = function() { return i; }; }; fn.apply(foo, arguments); return foo; }, foo2 = createFoo2();
doc_23535634
var test = ["a","a","e","r","t","e","t"]; var track = ["_","_","_","_","_","_","_",]; function check(letter) { this.letter = letter; var n = []; for(var x=0;x<test.length;x++){ if(text[x] !== letter) { continue; } else { n.push(x); } } for(var c=0;c<n.length;c++) { track[n[c]] = letter; } } check("t"); console.log(test.join(" ")+"\n"+track.join(" ")); A: Did you look at errors when running this code? you have a syntax error on line where you check the letter in the first loop, should be test instead of text if(test[x] !== letter) {
doc_23535635
A: You have to add intent-filter like below in your activity in AndroidManifest.xml <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:host="www" android:scheme="https" /> </intent-filter> </activity> A: Well, another answer here may help when the app is installed, but won't help you when it is not installed. You may need to follow a different approach. The solution you need is called deferred deep linking. Use Branch.io for this. You can use Android Google Play referrer But I feel that's unreliable. As I've tried both of these methods, I prefer using Branch.io At first, setting up Branch.io SDK feels tedious and complicated, but it definitely serves the purpose. To get started you can follow this blog. This is a little old, but if you compare it with the latest Branch.io dashboard I'm sure it will help. Moreover, if you still feel stuck at any point comment down here, I'll be happy to help as I've invested more time myself implementing deferred deep linking.
doc_23535636
is there any way i can get comprehensive error messages to be able to figure out what went wrong or which file to look at? A: You have several possibilities how to debug: * *you can add your custom logs *check output logs *or catch 404 errors globally: // The route will be evaluated if the page won't exist ROUTE('#404', function() { var self = this; // Here you can found info about the URL console.log(404, self.url); self.status = 404; self.plain('404: Page not found'); });
doc_23535637
Error 1 error C2664: 'std::vector<_Ty>::push_back' : cannot convert parameter 1 from 'std::vector<_Ty>' to 'const std::vector<_Ty> &' c:\Users\Josh\Documents\Visual Studio 2008\Projects\Vectorizer Project\Vectorizer Project\Vectorizer Project.cpp 324 Why isn't it letting me push this? It's saying it wants a contant but I never specified that.... Thanks the struct: struct SHAPECONTOUR{ std::vector<USERFPOINT> UserPoints; std::vector<std::vector<GLdouble>> DrawingPoints; }; std::vector<std::vector<GLdouble>> shape_verts; SHAPECONTOUR c; c.DrawingPoints.push_back(shape_verts); A: Edit: After new additions, the problem is not const - the problem is that you're trying to push the wrong type. std::vector<std::vector<GLdouble> > v; v.push_back(std::vector<GLdouble>()); // works; pushing contained type v.push_back(std::vector<std::vector<GLdouble> >()); // <-- error: trying to push type of container. Think about if you just had a vector of doubles; you push_back a double into the vector, you don't push_back another vector. A: This has nothing to do with const. Your types are wrong. DrawingPoints is a std::vector<std::vector<GLdouble>> which means that it contains items of type std::vector<GLdouble>. You're trying to push_back(shape_verts) which is of type std::vector<std::vector<GLdouble>>. I think what you want is just to make shape_verts a std::vector<GLdouble>.
doc_23535638
String post(String...url) throws IOException { FormEncodingBuilder form = new FormEncodingBuilder(); RequestBody formBody =form.build(); Request request = new Request.Builder() .header("Cookie", x) .url(url[0]) .post(formBody) .build(); Response response = client.newCall(request).execute(); return response.body().string(); } A: Time server and server time are different things and you probably want to know how to get server time. First of all, you need a server that somehow provides time, so possible solutions are to find a webserver or create your own. Use its url to connect to it. The server can offer time in its response in different ways: - as a header which has "Date" name - as a body which you have to know how to parse.
doc_23535639
As part of our build pipeline I need to run what our dev team calls "unit tests." These unit tests are run via an ant target. Before running that ant target we must spin up, configure and partially populate (the ant target does some of the population) several containers including: * *application server *ldap instance *postgres instance It looks as if each task only supports a single container. Is there a straightforward way to get all of these running together? Ideally I could create a task that would allow me to specify a pod template with the commands running in one of the containers of that pod. I realize that I could hack this together by using the openshift client or kubernetes actions but I was hoping for something a bit more elegant. I feel like using either of those tasks would require that I build out status awareness, error checking, retry logic, etc that is likely already part of the pipeline logic and then parse the output of the ant run to determine if all of the tests were successful. This is my first foray into tekton so accepted patterns or idioms would be greatly appreciated. For greater context I see these tasks making up my pipeline: * *clone git repo *build application into intermediate image *launch pod with all necessary containers *wait for all containers to become "ready" *execute ant target to run unit tests *if all tests pass build runtime image *copy artifacts from runtime image to external storage (for deployment outside of openshift) Thank you for your time A: Have a look at sidecars. The database must be up and running for the tests to execute, so start the database in a sidecar. The steps in the task will be started as soon as all sidecars are running.
doc_23535640
@model MVC.Models.Parameters @{ ViewBag.Title = "BigCalc"; } <h2>Welcome to BigCalc!</h2> @using (Html.BeginForm("Index", "Calculator", FormMethod.Post)) { <form class="form-horizontal"> <div class="form-group"> @Html.LabelFor(model => model.number1, new { @class = "control-label col-sm-2" }) <div class="col-xs-10"> @Html.TextBoxFor(model => model.number1, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.number1) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.number2, new { @class = "control-label col-sm-2" }) <div class="col-xs-10"> @Html.TextBoxFor(model => model.number2, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.number2) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.result, new { @class = "control-label col-sm-2" }) <div class="col-xs-10"> @Html.DisplayFor(model => model.result, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.result) </div> </div> <div class="form-group"> <div class="col-xs-offset-2 col-xs-10"> <button type="submit" class="btn btn-primary">Get sum</button> </div> </div> </form> } I want to add some more space between textboxes. I know for <br\> but that isnt a fancy way. Maybe to put style=margin:bottom or something like that. Or to create a hidden div between them? Thank you in advance. A: Please take a look at this solution Here. <div class="clearfix"></div>
doc_23535641
I have one component for the table header and another for the table body. I am calling a function on the table header component to filter the data that is in the table body component. The user input is being stored in the Table Header Component and onSearch calls the onFilter to work. Now that my data is in another component how do I call it so that it gets filtered and re-rendered and what is the best way to do this? A: The way to handle this type of cross-component communication in React is through state management. And one of the simplest ways to do this is by lifting state to a parent component. The parent component holds the state, and shares it with it's children as necessary. When the state changes, the component is re-rendered, and the new state is passed to the child components, who then re-render as well. A simple example of a parent component could look like this. function ParentComponent(){ [records, setRecords] = useState(profiles); const filterRecords = (filterString) => { const filtered = _.filter(records, r => r.name.indexOf(filterString) >= 0); setRecords(filtered); //This will trigger a re-render } return ( <table> <TableHeader onFilter={filterRecords} /> <TableBody records={records} /> </table> ); } The TableHeader might look vaguely like this: function TableHeader({onFilter}){ return ( <thead> <tr> <td> <button onClick={() => onFilter("billy")}>Filter Me</button> </td> </tr> </thead> ); } And the TableBody components might look vaguely like this: function TableBody({records}){ return ( <tbody> {_.map(records, record => <tr><td>{record.name}</td></tr>)} </tbody> ); } With this structure (if I got all the pseudo-code dots connected), clicking the filter me button in the header will tell the parent component to filter the records, and update it's state, which will trigger a re-render, causing the body to update as well.
doc_23535642
A: Gradle and Maven are build automation tools not development environments, you'd still use an IDE (like eclipse or IntelliJIdea) to develop the app and the IDE would use the build automation tools for the build process. Your question should be why use a build automation tool to build the app instead of just using the IDE. The answer is that a build automation tool has many advantages over the simple javac build: * *It can interact with source control. *It can run unit tests. *It can do automatic deployments for continuous integration. and more. If you are a single programmer developing a small standalone android app then you may not get many benefits from using a build automation tool, but will probably need to do some tasks manually. Build automation tools are indispensable in larger projects where many developers may be contributing to the code, or when the app is part of a larger system and it is necessary to ensure everything integrates.
doc_23535643
Antibody Time Repeats Customer_Col1A2 0 1 0.657532 2 0.639933 3 0.975302 5 1 0.628196 2 0.663301 3 0.921025 10 1 0.665601 2 0.785324 3 0.697913 My question is, what is the best way to calculate the average and (sample) standard error of the mean for this data (grouped by time point? So the answer for the 0 time point would be (0.657532+0.639933+0.975302)/3=0.757589 for the average and 0.188750216 for the SD. The output would look something like this: Antibody Time Average sample SD Customer_Col1A2 0 0.757589 0.188750216 5 .... .... 10 .... .... Thanks in advance A: You can group by the level of multi-index by specifying the level parameter, and calculate the average and SD using DataFrame.mean() and DataFrame.std() methods correspondingly: df1.groupby(level=[0,1]).agg({'avg': 'mean', 'sd': 'std'})
doc_23535644
I created a new module with name user_extra. Which create necessery table when Installing the module. But I also need to insert some database field in 'users_field_data' table ('user_extra_id' and 'user_office') In baseFieldDefinitions I wrote all necessery database table fields for user_extra table. public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { // Standard field, used as a unique if primary index. $fields['id'] = BaseFieldDefinition::create('integer') ->setLabel(t('Unit ID')) ->setDescription(t('The unit ID.')) ->setReadOnly(TRUE) ->setSetting('unsigned', TRUE); $fields['uuid'] = BaseFieldDefinition::create('uuid') ->setLabel(t('UUID')) ->setDescription(t('The unit UUID.')) ->setReadOnly(TRUE); . . . $fields['user_info'] = BaseFieldDefinition::create('string') ->setLabel(t('User Info')) ->setDescription(t("The User Info")) ->setSetting('max_length', 255) ->setDisplayOptions('form', array( 'type' => 'string_textfield', 'weight' => 10, )) ->setDisplayConfigurable('form', TRUE); return $fields; } When I install the module it inserts all values that I define in baseFieldDefinitions. But I also need to create 'user_extra_id' and 'user_office' in 'users_field_data' table with setDisplayOptions and setDisplayConfigurable options. This is the commenting that I made in entity file /** * @ContentEntityType( * id = "user_extra", * label = @Translation("user extra"), * handlers = { * "storage" = "Drupal\user_extra\UserextraStorage", * "storage_schema" = "Drupal\user_extra\UserextraStorageSchema", * "access" = "Drupal\user_extra\UserextraAccessControlHandler", * "list_builder" = "Drupal\user_extra\UserextraListBuilder", * "view_builder" = "Drupal\user_extra\UserextraViewBuilder", * "views_data" = "Drupal\user_extra\UserextraViewsData", * "form" = { * "default" = "Drupal\user_extra\Form\UserextraForm", * "add" = "Drupal\user_extra\Form\UserextraAddForm", * "edit" = "Drupal\user_extra\Form\UserextraEditForm", * "delete" = "Drupal\user_extra\Form\UserextraDeleteForm", * } * }, * admin_permission = "administer user_extra", * base_table = "user_extra", * entity_keys = { * "id" = "id", * "label" = "name", * "uuid" = "uuid", * }, * links = { * "canonical" = "/admin/user_extra/{user_extra}", * "add-form" = "/admin/user_extra/add", * "delete-form" = "/admin/user_extra/{user_extra}/delete", * "overview-form" = "/admin/user_extra/${user_extra}/overview", * "edit-form" = "/admin/user_extra/{user_extra}", * "collection" = "/admin/user_extra", * "children" = "/admin/user_extra/{user_extra}/children", * }, * ) */
doc_23535645
I will show you my database creating statements, as well as my java models and my view, and i really hope you can help me further to finally make this work. I tried all the annotations that are available (like @JoinColumn etc.) but not one combination of annotations worked. Maybe one of the mistakes is the fact, that I'm creating the foreign-key-column inside the many-table on my own??? I don't know... This is the final state from 15 minutes ago, I have not enough energy to try another one without some advice of you experts. (just some basic info: every "specific exam" belongs to exactly one "general exam". I'd like to have it unidirectional, which means, I do not need to store anything about the relation in the general exam, but only in the specific exam.) DATABASE CREATION: # --- !Ups # TABLES - general: create table generalExam ( id integer not null AUTO_INCREMENT, name varchar(45) not null, is_deleted boolean not null default false, constraint pk_generalexam primary key (id) ) ; create table specificExam ( id integer not null AUTO_INCREMENT, generalExam_id integer not null, // THIS IS THE FOREIGN KEY COLUMN!!!! name varchar(45) not null, constraint pk_specificexam primary key (id) ) ; JAVA MODELS: package models; import com.avaje.ebean.Page; import play.data.validation.Constraints; import play.db.ebean.Model; import javax.persistence.*; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * Created by ben on 08.08.2015. */ @Entity @Table(name = "generalExam") public class GeneralExam extends Model { @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long id; @Constraints.Required public String name; @OneToMany(mappedBy = "generalExam") public List<SpecificExam> specificExam; } ... and ... package models; import com.avaje.ebean.Page; import play.data.validation.Constraints; import play.db.ebean.Model; import javax.persistence.*; /** * Created by ben on 08.08.2015. */ @Entity @Table(name = "specificExam") public class SpecificExam extends Model { /* --- VARIABLES ---*/ @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long id; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "generalExam") public GeneralExam generalExam; @Constraints.Required public String name; } And finally THE VIEW: @(specificExamForm: Form[SpecificExam]) @import helper._ @implicitFieldConstructor = @{ FieldConstructor(twitterBootstrapInput.render) } @main { <h1>Add a specific exam</h1> @form(routes.Exams.saveSpecificExam()) { <fieldset> @select( specificExamForm("generalExam.id"), options(GeneralExam.options), '_label -> "General Exam", '_default -> "-- Choose a general exam --", '_help -> "(every specific exam belongs to a general exam)", '_showConstraints -> false ) @inputText(specificExamForm("name"), '_label -> "Specific Exam Name", '_help -> "") </fieldset> <div class="actions"> <input type="submit" value="Add this specific exam" class="btn primary"> or <a href="@routes.Exams.listExams("specific")" class="btn">Cancel</a> </div> } } Just a little more information at the end: As already mentioned, i've been trying many various combinations and some of the error messages i was getting were: [PersistenceException: ERROR executing DML bindLog[] error[Column 'name' "cannot be null"]] and [PersistenceException: ERROR executing DML bindLog[] error[Column 'ID' specified twice]] I just wanna say a BIG THANKS in advance, every help is very welcome, I couldn't get this running for over a week now -.-
doc_23535646
I've an iOS app; a tabbed RSS reader, each tab has a different navigation view of various RSS feeds. All is well, until you select the row to view the feed, when nothing happens. Code I'm using is: - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { if (_webViewController == nil) { self.webViewController = [[[WebViewController alloc] initWithNibName:@"WebViewController" bundle:[NSBundle mainBundle]] autorelease]; } RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row]; _webViewController.entry = entry; [self.navigationController pushViewController:_webViewController animated:YES]; } Where RSSEntry is a class which just sets the variables for the RSS feed. I've set up a WebViewController.xib, m and h to hold the view. When you select the row, nothing happens. Any ideas gratefully accepted. thanks Rob A: _webViewController has likely been released when you go to use it, because you've allocated it within the if block. At the end of that block, it is autoreleased. Remove the autorelease clause in your alloc statement for WebViewController, and add [webViewController release] after your call to pushViewController. A: Does self.navigationController evaluate to non-nil? In some cases the property navigationController may not point to your enclosing UINavigationController. I've seen this with special view controller hierarchies...
doc_23535647
http://events.discoverportland.net/ The menu should load to a blue square just to the right of the discover portland logo. There are serveral nested ul's in the menu, the problem i'm having is getting them to load to the side of the menus above them As it load now, you can't get to the teritairy links unless you move VERY fast. Is there any way to get the uls to load inline as i'm hovering over them, or is there a better solution? this my nav html: <nav> <a href="#" id="menu-icon"></a> <div class="clearfix hd8 suckerfish" > <ul id="md"> <li><a href="http://www.discoverportland.net/index.php">Home2</a></li> <li><a href="http://www.discoverportland.net/index.php/neighborhoods">Neighborhoods</a> <ul> <li><a href="http://www.discoverportland.net/index.php/neighborhoods/northwest">Northwest</a> <ul> <li><a href="http://www.discoverportland.net/index.php/neighborhoods/northwest/pearl-district">Pearl District</a></li> <li><a href="http://www.discoverportland.net/index.php/neighborhoods/northwest/oldtown-chinatown">Oldtown-Chinatown </a></li> <li><a href="http://www.discoverportland.net/index.php/neighborhoods/northwest/nob-hill">Nob Hill</a></li> </ul> </li> <li><a href="http://www.discoverportland.net/index.php/neighborhoods/southwest">Southwest</a> <ul> <li><a href="http://www.discoverportland.net/index.php/neighborhoods/southwest/west-end">West End</a></li> <li><a href="http://www.discoverportland.net/index.php/neighborhoods/southwest/riverplace-south-waterfront">Riverplace-South Waterfront</a></li> <li><a href="http://www.discoverportland.net/index.php/neighborhoods/southwest/downtown">Downtown</a></li> </ul> </li> <li><a href="http://www.discoverportland.net/index.php/neighborhoods/southeast">Southeast</a> <ul> <li><a href="http://www.discoverportland.net/index.php/neighborhoods/southeast/sellwood-westmoreland">Sellwood-Westmoreland</a></li> <li><a href="http://www.discoverportland.net/index.php/neighborhoods/southeast/hawthorne">Hawthorne</a></li> <li><a href="http://www.discoverportland.net/index.php/neighborhoods/southeast/clinton-division">Clinton-Division</a></li> </ul> </li> <li><a href="http://www.discoverportland.net/index.php/neighborhoods/northeast">Northeast</a> <ul> <li><a href="http://www.discoverportland.net/index.php/neighborhoods/northeast/alberta">Alberta</a></li> <li><a href="http://www.discoverportland.net/index.php/neighborhoods/northeast/lloyd-district">Lloyd District</a></li> <li><a href="http://www.discoverportland.net/index.php/neighborhoods/northeast/hollywood">Hollywood District</a></li> </ul> </li> <li><a href="http://www.discoverportland.net/index.php/neighborhoods/north">North</a> <ul> <li><a href="http://www.discoverportland.net/index.php/neighborhoods/north/mississippi">Mississippi</a></li> <li><a href="http://www.discoverportland.net/index.php/neighborhoods/north/williams">Williams</a></li> <li><a href="http://www.discoverportland.net/index.php/neighborhoods/north/st-johns-university-of-portland">St. Johns</a></li> </ul> </li> </ul> </li> <li><a href="http://www.discoverportland.net/index.php/itineraries">Itineraries</a></li> <li><a href="http://www.discoverportland.net/index.php/day-trips">Day Trips</a></li> <li><a href="http://www.discoverportland.net/index.php/food-and-drink">Food+Drink</a> <ul> <li><a href="http://www.discoverportland.net/index.php/food-and-drink/dining-picks">Dining Picks</a></li> <li><a href="http://www.discoverportland.net/index.php/food-and-drink/food-cart-fare">Food Cart Fare </a></li> <li><a href="http://www.discoverportland.net/index.php/food-and-drink/beer-wine-spirits">Beer, Wine &amp; Spirits</a></li> <li><a href="http://www.discoverportland.net/index.php/food-and-drink/cafe-culture">Café Culture</a></li> </ul> </li> <li><a href="http://www.discoverportland.net/index.php/to-do">To Do</a> <ul> <li><a href="http://www.discoverportland.net/index.php/to-do/shopping">Shopping</a></li> <li><a href="http://www.discoverportland.net/index.php/to-do/recreation">Recreation</a></li> <li><a href="http://www.discoverportland.net/index.php/to-do/culture">Culture</a> <ul> <li><a href="http://www.discoverportland.net/index.php/to-do/culture/moset-02-galleries">Galleries</a></li> </ul> </li> <li><a href="http://www.discoverportland.net/index.php/to-do/family">Family</a></li> </ul> </li> <li><a href="http://events.discoverportland.net">Events</a></li> </ul> </nav> this is the css i'm using: nav ul ul li a::before { content: "\f0da"; font-family: FontAwesome; margin-right: 8px; } nav { text-transform:uppercase; font-family: Oswald,Arial,Helvetica,sans-serif !important; font-size: 14px; font-weight: 100 !important; letter-spacing: 1px!important; } nav ul ul { display: none; } nav ul li:hover > ul { display: block; } nav ul { background: #FF0066; padding: 2px 0 0 64px; border-radius: 0px; list-style: none; position: relative; display: inline-table; } nav ul:after { content: ""; clear: both; display: block; } nav ul li { float: left; } nav ul li:hover { background: #FF0066; } nav ul li:hover a { color: #fff; } nav ul li a { display: block; padding: 15px 20px; color: #fff; text-decoration: none; } nav ul ul { background: #FF0066; border-radius: 0px; padding: 0; position: absolute; top: 100%; } nav ul ul li { float: none; position: relative; } nav ul ul li a { padding: 15px 25px; color: #fff; font-family: 'Fira Sans', sans-serif;Important; font-size: 12px; } nav ul ul li a:hover { background: #AD0548; } nav ul ul ul { position: absolute; left: 100%; top:0; } nav ul ul ul li { width: 275px !important; } @media (max-width: 767px) { #logo a { background: rgba(0, 0, 0, 0) url("http://discoverportland.net/templates/urbanlife/images/logos/DP_HeadingLogo2.png") no-repeat scroll 0 0 / 100% auto; height: 60px; margin: 0 !important; width: 60px !important; } #menu-icon { display:inline-block; } nav ul, nav:active ul { display: none; position: absolute; right: 20px; top: 60px; width: 50%; border-radius: 4px 0 4px 4px; } nav li { text-align: center; width: 100%; padding: 10px 0; margin: 0; } nav:hover #md { display: inline-block; } }
doc_23535648
My GET (all) /POST methods seem to be fine, and my PUT method seems to be fine, but my GET (single object) method, which looks just like the PUT one, throws the above error: Supplied parameters do not match any signature of call target. This throws an error during compilation: getCourse (course: Course): Observable<Course> { let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); let courseUrl = this.BaseUrl + '/' + course.id; return this.http.get(courseUrl, { course }, options) .map(this.extractData) .catch(this.handleError); } This works: put(course: Course): Observable<Course> { let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); let courseUrl = this.BaseUrl + '/' + course.id; return this.http.put(courseUrl, { course }, options) .map(this.extractData) .catch(this.handleError); } Thoughts? What am I doing wrong? A: get doesn't support a body parameter return this.http.get(courseUrl, { course }, options) should be return this.http.get(courseUrl, options) https://angular.io/docs/ts/latest/api/http/index/Http-class.html#!#get-anchor get(url: string, options?: RequestOptionsArgs) : Observable https://angular.io/docs/ts/latest/api/http/index/Http-class.html#!#put-anchor put(url: string, body: any, options?: RequestOptionsArgs) : Observable
doc_23535649
[HttpGet] [RoutePrefix("api/products/{productId}")] public HttpResponseMessage Products(int productId,TypeEnum ptype=TypeEnum.Clothes) { if(!Enum.IsDefined(typeOf(TypeEnum),ptype)) //throw bad request exception else //continue processing } Myenum is declared as public TypeEnum { Clothes, Toys, Electronics } Currently if,some garbage value is passed it is getting converted into default value. What I want to do is if i call the controller as api/products/1 then the ptype should be assigned default value i.e clothes. If I call the controller as api/products/1?pType=somegarbagevalue then the controller should throw bad request exception. How can I achieve this? A: You have to do with string and use TryParse() to convert string to Enum value. public HttpResponseMessage Products(int productId,string ptype="Clothes") { TypeEnum category = TypeEnum.Clothes; if(!Enum.TryParse(ptype, true, out category)) //throw bad request exception if you want. but it is fine to pass-through as default Cloathes value. else //continue processing } It may look naive but the benefit of this approach is to allow ptype parameter to whatever string and to perform process without exception when ptype fails to bind the value. A: Defining all your enum parameters as strings and then parsing them everywhere means you have to do this on every single action and you will need to come up with a consistent approach such that all parsing errors conform. This is a parameter binding issue and should not be dealt with in the controller layer, it should be taken care of in the pipeline. One way to do this is to create a custom filter and add it to your config. public class ModelStateValidationAttribute : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { if (!actionContext.ModelState.IsValid) { actionContext.Response = <your standardised error response> } } } And in your global.asax.cs ... GlobalConfiguration.Configure(WebApiConfig.Register); ... public class WebApiConfig { public static void Register(HttpConfiguration config) { ... config.Filters.Add(new ModelStateValidationAttribute()); ... } } If you're having trouble with the model state, it's type is a ModelStateDictionary and you simply iterate over it and then it's Errors property contains all the model binding issues. e.g. modelState = actionContext.ModelState; modelState.ForEach(x => { var state = x.Value; if (state.Errors.Any()) { foreach (var error in state.Errors) { <work your magic> } } }); A: This type of validation should be handled in pipeline not in controller. public abstract class ETagMatchAttribute : ParameterBindingAttribute { private ETagMatch _match; public ETagMatchAttribute(ETagMatch match) { _match = match; } public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter) { if (parameter.ParameterType == typeof(ETag)) { return new ETagParameterBinding(parameter, _match); } return parameter.BindAsError("Wrong parameter type"); } } something like this. refer to MSDN link for detailed explanation
doc_23535650
I use the following variant : const hasMetadata = <T extends object>(obj: T): obj is T & {metadata: unknown} => ( Object.hasOwn(obj, 'metadata') ) However I end up needing several such typeguards : I have a file with 20 or so. I am starting to consider simple code generation. Before that, I wanted to make sure that a generic property check type guard is not possible in typescript. It would look like that const hasProp = <T extends object>(obj: T, key: string): obj is T & {[key]: unknown} => ( Object.hasOwn(obj, key) ) This code fails to typecheck with the following error A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type Does someone knows of a way to achieve such a generic typeguard ? A: Just type your key with string ! const hasProp = <T extends object>(obj: T, key: string): obj is T & {[key: string]: unknown} => ( Object.hasOwn(obj, key) )
doc_23535651
I want to insert 50 column values, each column i want to check whethere the value is 0 or not. If the value is 0 then it should be null Query insert into table1 values (Case when column1 = '0' then null else column1 end, ..... Case when column50 = '0' then null else column50 end) The above query is working, but query length is too long because i am using the above query of 50 column's there is any alternative option is there for check the column value is 0 or not. like this if(column1, 0) then null Need Query Help A: Try using NULLIF: insert into table1 values (NULLIF(column1, '0'), ..... NULLIF(column50, '0'))
doc_23535652
so far this is my code: .TopNav { width: 1119px; height: 50px; background: #FAF7FC; position: relative; } #name { position: relative; text-align: center; font-size: 30px; } .arrowR .arrowL { position: relative; display: block; width: 20px; height: 20px; transition: 0.5s; box-shadow: -2px 2px 0 rgba(18, 0, 94, 0.5); cursor: pointer; } .arrowL { transform: rotate(45deg); } .arrowR { transform: rotate(225deg); } .arrowL:hover .arrowR:hover { box-shadow: -2px 2px 0 rgba(18, 0, 94, 1); } <body> <div class="TopNav col-sm-12 col-sm-12"> <div class="content"> <p id="name"> This Week </p> </div> <div class="arrowR"></div> <div class="arrowL"></div> </div> </body> This only shows the rectangle (the main bar) and the title, but does not display the arrows. what is the problem, and how can I put the arrows on each side of the bar? A: You made small mistake. You forget to add comma between two classes. And some other issue. I try to fix that. Please check below code snippet. .TopNav { width: 1119px; height: 50px; background: #FAF7FC; position: relative; } #name { position: relative; text-align: center; font-size: 30px; } .arrowR, .arrowL { position: absolute; top: 50%; left: 15px; margin-top: -10px; display: block; width: 20px; height: 20px; transition: 0.5s; box-shadow: -2px 2px 0 rgba(18, 0, 94, 0.5); cursor: pointer; } .arrowL { transform: rotate(45deg); } .arrowR { left: auto; right: 15px; transform: rotate(225deg); } .arrowL:hover, .arrowR:hover { box-shadow: -2px 2px 0 rgba(18, 0, 94, 1); } <div class="TopNav col-sm-12 col-sm-12"> <div class="content"> <p id="name"> This Week </p> </div> <div class="arrowR"></div> <div class="arrowL"></div> </div>
doc_23535653
When I set the value in class1 the value is 1, but the value in class3 is 0. class test { public void main() { Class2 cl = new Class2; thread th = new thread(new threadstart(a.start)); th.start() cl.test=1; } } class Class2 { private int test; public int test { get { return test;} set {test = value;} } public void start() { Class3 cls = new Class3(); thread th = new thread(new threadstart(cls.begin)); th.start(); } } class Class3 { public void begin() { Class2 cl = new Class2(); MessageBox.show(cl.test.tostring()); } } A: You've got two separate instances of Class2. The instance created in Class3 has no idea what the values are in the instance you created in Class1. If you know you only want a single instance of the test property to deal with, you could make it static: public static int Test { get; set; } And then reference it using: Class2.Test = 1; As an aside, I'm not sure how this compiles since you've got a public property named "test" to access the private "test" variable in Class2. Typically, people name the private variable something like _test (depends on your personal preference), or just omit the private variable altogether like I did above if your property is doing nothing other than accessing the private variable. A: I would use the built in .NET libraries for managing threads. Task Parallelism Follow some of the tutorials here. These objects make it much easier to deal with threads and wait for results. They even have thread-safe object available for you. Thread-Safe Equivalants: Array,List => ConcurrencyBag<T> Dictionary<K, T> => ConcurrentDictionary<K, T>
doc_23535654
They then navigate to the detail page for a G Suite Marketplace App (https://chrome.google.com/webstore/detail/[ID]), and it appears that whichever G Suite instance for which the user auth'd into the admin console first is defaulted as the domain for which the viewed G Suite Marketplace App will be installed. Screenshot: Defaulted account Attempting to use the supplied account picker to switch to the non-defaulted account redirects the user to the associated (non-defaulted) admin console. Based on these observed behaviors, there does not appear to be a viable route to drive a user in the given state to install a particular G Suite Marketplace App for the non-defaulted domain. Is this accurate? A: One workaround is to use this link: https://accounts.google.com/Logout?continue=https%3A%2F%2Faccounts.google.com%2FAccountChooser%3Fcontinue= This link will sign out of all current accounts (will not remove them from the 'cached account list'), then it will redirect to the Account Chooser, and finally redirect to your MarketPlace app (notice the last redirect where you have to replace the stub).
doc_23535655
<html lang="en"> <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7 /css/bootstrap.min.css" rel="stylesheet"/> <div id="order-details-booking"> <blockquote>Self-order Menu</blockquote> <div class="form-holder col-xs-14"> <div class="input-field col s4"> <input type="text" id="item-" placeholder="Item Code"/> </div> <div class="input-field col s2"> <input type="text" id="item-code" placeholder="Qty" /> </div> <div class="input-field col s5"> <input type="text" id="item-code" placeholder="Remarks" /> </div> <div class="col s1"> <i class="material-icons remove">- remove</i> </div> </div> <div class="form-holder-append"></div> <div class="row"> <div class="col-xs-4"> <i class="material-icons add">+ add</i> </div></div> </div> <div id="order-details-booking2"> <blockquote>Self-order Menu</blockquote> <div class="form-holder col-xs-1"> <div class="input-field col s4"> <input type="text" id="item-" placeholder="Item Code"/> </div> <div class="input-field col s2"> <input type="text" id="item-code" placeholder="Qty" /> </div> <div class="input-field col s5"> <input type="text" id="item-code" placeholder="Remarks" /> </div> <div class="col s1"> <i class="material-icons remove">- remove</i> </div> </div> <div class="form-holder-append"></div> <div class="row"> <div class="col-xs-4"> <i class="material-icons add">+ add</i> </div></div> </div> </html> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7 /js/bootstrap.min.js"></script> <script> var id_count = 1; $('.add').on('click', function() { var source = $('.form-holder:first'), clone = source.clone(); clone.find(':input').attr('id', function(i, val) { return val + id_count; }); clone.appendTo('.form-holder-append'); id_count++; }); //button for add second holder var id_count2 = 1; $('.add').on('click', function() { var source = $('.form-holder:first'), clone = source.clone(); clone.find(':input').attr('id', function(i, val) { return val + id_count2;`enter code here` }); clone.appendTo('.form1-holder-append'); id_count++; }); // Removing Form Field $('body').on('click', '.remove', function() { var closest = $(this).closest('.form-holder').remove(); }); </script>*** webpage contain 2 form holder, when ever i click add button the action should be performed to each holder separately, but now the if we press add button, the it add form to both form holder.I shared the code in above, I hope I may get help as soon as possible, Thank for help.. ********It looks like your post is mostly code; please add some more details. A: if you only have two formholders you can solve this by useing unique classes. var id_count = 1; $('.add1').on('click', function() { var source = $('.form-holder1:first'), clone = source.clone(); clone.find(':input').attr('id', function(i, val) { return val + id_count; }); clone.appendTo('.form-holder-append1'); id_count++; }); //button for add second holder var id_count2 = 1; $('.add2').on('click', function() { var source = $('.form-holder2:first'), clone = source.clone(); clone.find(':input').attr('id', function(i, val) { return val + id_count2;`enter code here` }); clone.appendTo('.form-holder-append2'); id_count++; }); // Removing Form Field $('body').on('click', '.remove', function() { var closest = $(this).closest('.form-holder').remove(); }); if you have a dynamic amount of formholders you should use a each() function and count the formholders and each element inside with eq(). This results in only one function for all formholders, independently how many.
doc_23535656
I’m trying to create a installation setup for my VB.net application. I need to insert a custom action while setup is running. So I add a Checkbox Dialog box to my setup. And I add a dll to the setup installation to capture Before Install and After Install events. Those are works fine. But I cannot access my check box value in those events. If u guys can give me a hint to continue my work really appreciates. Following is the Before Install event I have created. I have set some messages to verify my event works correctly. While I run the setup those messages are prompt properly. Private Sub Installer_BeforeInstall(ByVal sender As Object, _ ByVal e As System.Configuration.Install.InstallEventArgs) Handles MyBase.BeforeInstall Dim koFaxPath As String = Nothing MsgBox("Installer_BeforeInstall: Starts1") Dim contextParameters As StringDictionary Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder Dim actionDataName As String = String.Empty Dim arrayActionData() As String contextParameters = Me.Context.Parameters For Each actionDataName In Me.Context.Parameters.Keys arrayActionData = Me.Context.Parameters(actionDataName).ToString.Split("-") MsgBox(actionDataName.ToString) MsgBox(arrayActionData(0).ToString) MsgBox(Me.Context.Parameters.Item(actionDataName.ToString)) Next Try Catch ex As Exception 'needs to impliment End Try MsgBox("Installer_BeforeInstall: Ends") End Sub Thanks in advance. A: I have found the answer for that. It may useful for u as well. Once you have add your dll to the setup project, Go to dll properties. There is a property called CustomActionData. Fill it as follows /CheckBoxSequenceGenerator="[CheckBoxName]" Now you can access this in following code Context.Parameters("CheckBoxSequenceGenerator") A: Please make sure that your check-box property are not assigned to coding.
doc_23535657
The theme is being applied on some forms but on others the controls aren't working properly. They are overlapping on top of each other. To apply the theme I am using the following code try { String lookandfeel="com.jtattoo.plaf.smart.SmartLookAndFeel"; UIManager.setLookAndFeel(lookandfeel); } catch(Exception ex) { ex.printStackTrace(); } A: * *works as I expecting *L&F must be * *initialized before GUI creations *for changes on runtime, applied to all Top-Level Containers by calling SwingUtilities.updateComponentTreeUI(Component c), where simpler will be Component c == local variable for Top-Level Container, otherwise you have to iterating and to apply this look to each of JComponents separatelly, to all in the current components tree import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.Icon; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JTextPane; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.BevelBorder; public class MenuExample extends JPanel { private static final long serialVersionUID = 1L; private Icon errorIcon = UIManager.getIcon("OptionPane.errorIcon"); private Icon infoIcon = UIManager.getIcon("OptionPane.informationIcon"); private Icon warnIcon = UIManager.getIcon("OptionPane.warningIcon"); private Icon questIcon = UIManager.getIcon("OptionPane.questionIcon"); private JTextPane pane; private JMenuBar menuBar; public MenuExample() { menuBar = new JMenuBar(); JMenu formatMenu = new JMenu("Justify"); formatMenu.setMnemonic('J'); MenuAction leftJustifyAction = new MenuAction("Left", errorIcon); MenuAction rightJustifyAction = new MenuAction("Right", infoIcon); MenuAction centerJustifyAction = new MenuAction("Center", warnIcon); MenuAction fullJustifyAction = new MenuAction("Full", questIcon); JMenuItem item; item = formatMenu.add(leftJustifyAction); item.setMnemonic('L'); item = formatMenu.add(rightJustifyAction); item.setMnemonic('R'); item = formatMenu.add(centerJustifyAction); item.setMnemonic('C'); item = formatMenu.add(fullJustifyAction); item.setMnemonic('F'); menuBar.add(formatMenu); menuBar.setBorder(new BevelBorder(BevelBorder.RAISED)); pane = new JTextPane(); pane.setPreferredSize(new Dimension(250, 250)); pane.setBorder(new BevelBorder(BevelBorder.LOWERED)); JFrame frame = new JFrame("Menu Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setJMenuBar(menuBar); frame.add(pane, BorderLayout.CENTER); frame.pack(); frame.setLocation(150, 150); frame.setVisible(true); } class MenuAction extends AbstractAction { public MenuAction(String text, Icon icon) { super(text, icon); } @Override public void actionPerformed(ActionEvent e) { try { pane.getStyledDocument().insertString(0, "Action [" + e.getActionCommand() + "] performed!\n", null); } catch (Exception ex) { ex.printStackTrace(); } } } public static void main(String s[]) { try { UIManager.setLookAndFeel("com.jtattoo.plaf.smart.SmartLookAndFeel"); } catch (Exception ex) { ex.printStackTrace(); } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { MenuExample example = new MenuExample(); } }); } }
doc_23535658
This code takes my grid data and exports it to excel deleting all the gridlines i tried to google couldnt find a breaktrough can someone help me with this protected void btn_export_Click(object sender, EventArgs e) { Response.Buffer = true; Response.ClearContent(); Response.ClearHeaders(); Response.Charset = ""; string FileName = "Dashboard_FOR_PM" + DateTime.Now + ".xls"; StringWriter strwritter = new StringWriter(); HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName); grv_dashboard.GridLines = GridLines.Both; grv_dashboard.HeaderStyle.Font.Bold = true; grv_dashboard.RenderControl(htmltextwrtter); Response.Write(strwritter.ToString()); using (StringWriter sw = new StringWriter()) { using (HtmlTextWriter htw = new HtmlTextWriter(sw)) { Table table = new Table(); table.BorderStyle = BorderStyle.Solid; table.BorderWidth=new Unit(1); table.BorderColor = System.Drawing.Color.Black; table.GridLines = GridLines.Both; } } strwritter.Write(@"<html xmlns:x=""urn:schemas-microsoft-com:office:excel"">"); strwritter.Write(@"<head> <xml> <x:ExcelWorkbook> <x:ExcelWorksheets> <x:ExcelWorksheet> <x:WorksheetOptions> <x:Panes></x:Panes> <x:Print><x:Gridlines /></x:Print> </x:WorksheetOptions> </x:ExcelWorksheet> </x:ExcelWorksheets> </x:ExcelWorkbook> </xml> </head>"); Response.End(); } A: have a look at below function that I wrote before,please ask if something is unclear,hope it helps public void ToExcel(DataTable dt, string reportName) { if (dt.Rows.Count > 0) { string filename = string.Format("{0}.xls", reportName); System.IO.StringWriter sw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw); HtmlForm hf = new HtmlForm(); DataGrid dg = new DataGrid(); dg.DataSource = dt; dg.HeaderStyle.BackColor = Color.Tomato;//change to your own colors dg.HeaderStyle.ForeColor = Color.White;//change to your own colors dg.BackColor = Color.LightGoldenrodYellow;//change to your own colors dg.AlternatingItemStyle.BackColor = Color.PaleGoldenrod;//change to your own colors dg.Font.Name = "Tahoma"; dg.Font.Size = 10; dg.GridLines = GridLines.Both; dg.BorderColor = System.Drawing.Color.Black; dg.BorderStyle = BorderStyle.Solid; dg.BorderWidth = new Unit(1); dg.DataBind(); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename); HttpContext.Current.Response.Charset = ""; EnableViewState = false; Controls.Add(hf); hf.Controls.Add(dg); hf.RenderControl(htw); HttpContext.Current.Response.Write(sw.ToString()); HttpContext.Current.Response.End(); } }
doc_23535659
What am I doing wrong? <div class="body" data-spy="scroll" data-target=".navbar-fixed-top"> <section id="red" class="bc1"> </section> <section id="blue" class="bc2"> </section> <section id="green" class="bc3"> </section> <section id="blue" class="bc4"> </section> </div> <script> var $pages = $('section'), tot = $pages.length, c = 0, pagePos = 0, down = 0, listen = true; $('.body').on('DOMMouseScroll mousewheel', function(e) { e.preventDefault(); if (!listen) return; listen = false; down = e.originalEvent.detail > 0 || e.originalEvent.wheelDelta < 0; c = Math.min(Math.max(0, down ? ++c : --c), tot - 1); pagePos = $pages.eq(c).offset().top; $(this).stop().animate({ scrollTop : pagePos }, 850, function() { listen = true; }); }); </script> A: The problem is that offset measures the distance of the element from the top of the body. But once you have scrolled the offset is different since the elements have moved closer/further from the last scroll. So in order to account for this you need to add the scrollTop() of the .body element. Updated code var $pages = $('section'), tot = $pages.length, c = 0, pagePos = 0, down = 0, listen = true, body = $('.body'); body.on('DOMMouseScroll mousewheel', function(e) { e.preventDefault(); if (!listen) return; listen = false; down = e.originalEvent.detail > 0 || e.originalEvent.wheelDelta < 0; c = Math.min(Math.max(0, down ? ++c : --c), tot - 1); pagePos = $pages.eq(c).offset().top + body.scrollTop(); $(this).stop().animate({ scrollTop: pagePos }, 850, function() { listen = true; }); }); html, body { margin: 0; padding: 0; width: 100%; height: 100%; } .bc1, .bc2, .bc3, .bc4 { height: 100vh; } #red { background: red; } #blue { background: blue; } #green { background: green; } .body { height: 100vh; overflow: hidden; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="body" data-spy="scroll" data-target=".navbar-fixed-top"> <section id="red" class="bc1"></section> <section id="blue" class="bc2"></section> <section id="green" class="bc3"></section> <section id="blue" class="bc4"></section> </div>
doc_23535660
* *Make a new split. *Launch a terminal program. *Wait for the program to stop and close the split. *Read the output produced in the second step into the original buffer. This seems like a very common work flow, but I'm having trouble getting it to work. The problem is in steps 3 and 4. As a test I defined: function MyExitFunction(a,b,c) close read blah endfunction Then did: :new | call termopen('fzf>blah',{on_exit:MyExitFunction} which does start the terminal and close the split after the program is done. The read command, however, seems to do nothing. Perhaps it reads the input into a wrong split? What should I do to get the actual program output into my current buffer? Note, fzf is not the actual program I'm running, but it works a bit like it. A: If you have a command that cleanly outputs to stdout, then you simply need :read !<command>. If you want interactivity, i.e. reading from stdin first, then you should probably run it inside a terminal with :vs | te and then yank the output over. Vim doesn't have a clean and easy way to interop with interactive scripts, so this is probably as good as it's gonna get.
doc_23535661
A: The default is release but you can change this in the scheme editor A: Watch your scheme details to see which configuration is used for the Archive stage (as I assume you're making the Ad-Hoc build from the archived product). In the menu bar, navigate to Product > Scheme > Edit Scheme… and switch to the one you're currently building if needed.
doc_23535662
2,4,8,10 satisfies the requirement while the following set 2,4,5,7 does not since the interval between 4 and 5 is less than 2. Is there any way to achieve this? Thanks! A: N = 10; % number of integers required delta = 2; % minimum difference required a = randperm(100); idx = 1; b = a(idx); while(length(b) < N && idx < length(a)) idx = idx+1; c = abs(b - a(idx)); if any(c < delta) continue; end b = [b; a(idx)]; end b
doc_23535663
layer { name: "pool2" type: "Pooling" bottom: "conv5" top: "pool2" pooling_param { pool: MAX kernel_w: 2 kernel_h: 1 stride_w: 2 stride_h: 1 pad_h: 0 pad_w: 0 } } The blob shape before is 1x64x1x30, and after is 1x64x1x15. Shouldn't it be 1x64x1x14? From caffe doc: w_o = (w_i + 2*pad_w - kernel_w)/stride_w = (30 - 2)/2 = 14. It makes sense since the pool would be: [0,1] [2,3] [4,5] ... [28,29] which are 14 elements. A: In general, the max pooling layer accepts an input volume of size W1 x H1 x D1 and requires two hyperparameters -- the stride (S) and kernel size (K). It produces an output volume of size W2 x H2 x D2 where we have W2 = (W1 - K)/S + 1, H2 = (H1 - K)/S + 1, and D2 = D1. Simple computation yields that a kernel size of 2 and stride of 2 halve the input, verifying caffe's network output shape.
doc_23535664
A: If you wont change anything in storyboard and set design according to that then the design will look exactly same in iPhone 5 / 5s sized (4 inch) as storyboard. EDIT : May be this is what you want to set.
doc_23535665
#Gzip # compress the files AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/x-javascript # removes some bugs BrowserMatch ^Mozilla/4 gzip-only-text/html BrowserMatch ^Mozilla/4\.0[678] no-gzip BrowserMatch \bMSIE !no-gzip !gzip-only-text/html Header append Vary User-Agent #End Gzip But when using yslow I get following: Compressing http://s7.addthis.com/js/250/addthis_widget.js could save 64.9KiB (64% reduction). Compressing http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js could save 50.3KiB (65% reduction). Compressing http://storyfollower.com/jquery.js could save 50.3KiB (65% reduction). Compressing http://storyfollower.com/js/jquery-1.4.min.js could save 45.0KiB (66% reduction). Compressing http://s7.addthis.com/static/r07/widget76.css could save 29.4KiB (78% reduction). Compressing http://storyfollower.com/js/jquery.fancybox-1.2.6.js could save 12.6KiB (73% reduction). Compressing http://storyfollower.com/js/jquery.autocomplete.min.js could save 9.2KiB (66% reduction). Compressing http://storyfollower.com/js/facebox.js could save 6.3KiB (69% reduction). Compressing http://www.statcounter.com/counter/counter.js could save 5.9KiB (66% reduction). Compressing http://storyfollower.com/jquery.freeow.js could save 3.9KiB (71% reduction). Compressing http://storyfollower.com/js/basic.js could save 3.8KiB (75% reduction). Compressing http://storyfollower.com/css/jquery.fancybox-1.2.6.css could save 3.5KiB (78% reduction). Compressing http://storyfollower.com/style/freeow/freeow.css could save 3.2KiB (72% reduction). Compressing http://storyfollower.com/js/liteaccordion.jquery.js could save 3.1KiB (64% reduction). Compressing http://www.youtube.com/embed/u7pTrqFU5MY?hd=1 could save 2.9KiB (62% reduction). Compressing http://storyfollower.com/css/mobile.css could save 2.9KiB (70% reduction). Compressing http://storyfollower.com/css/styles.css could save 2.8KiB (71% reduction). Compressing http://storyfollower.com/css/liteaccordion.css could save 2.4KiB (69% reduction). Compressing http://storyfollower.com/css/common.css could save 1.8KiB (64% reduction). Compressing http://storyfollower.com/js/jquery.elastic.js could save 973B (57% reduction). Compressing http://storyfollower.com/css/facebox.css could save 900B (65% reduction). Compressing http://storyfollower.com/css/jquery.autocomplete.css could save 359B (45% reduction). Compress all content is enabled in Cpanel! Also this is a dedicated Server! Thanks A: Give it some time... clearing browser cache yslow checkes the cached files
doc_23535666
* I'm bad with CSS, and I'm trying to get the ui-icon on the same line as the text in a LI. <ul> <li class="ui-state-default"> <span>Hello</span> <span class="ui-icon ui-icon-close"></span> </li> </ul> Normally text doesn't do that within a li, so I think it's something with the ui-icon css, but I couldn't find what was causing it. A: Further to my question comment above, I've found this in my jQuery-ui CSS, assuming that's what you're using: /* states and images */ .ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; } Changing (or overriding) the display: block using display: inline-block should allow the icon to appear on the same line
doc_23535667
What I want to do is to call a method when clicking a dropdown item. My previous code using vue-bootstrap is like this. <! -- This part is inside for loop --> <b-dropdown variant="transparent"> <b-dropdown-item @click="aMethod(index, 'Hello')">A</b-dropdown-item> <b-dropdown-item @click="aMethod(index, 'Bye')">B</b-dropdown-item> </b-dropdown> And now I want to do this using vuetify but how can I call method? <v-overflow-btn label="A" :items="aList" /> ... aList: [{text: 'A'},{text: 'B'}] I want to pass the index as a parameter to the method. Also how can I make the default label the same looking as the items like dropdown in bootstrap does? A: You can add a @change event on you button: <v-overflow-btn label="A" :items="aList" @change="aMethod(arg1, arg2, etc...)" />
doc_23535668
//LOAD XML FILE <?php $xml = simplexml_load_file($cat.".xml"); $users = new SimpleXMLElement($xml->asXML()); $count = count($users); $ids = $xml->xpath("//content/id"); // select all ids $cur_id = max(array_map("intval", $ids)) + 1; // change objects to `int`, get `max()`, + 1 $query = $users->addChild("content"); $query->addChild("id",$cur_id); $query->addChild("title",$title); $query->addChild("code",$code); $query->addChild("postedby",$adminName); $query->addChild("image",$lesimg); $query->addChild("video",$lesvid); $query->addChild("live",$lestry); $users->asXML($cat.".xml"); $xml = simplexml_load_file($cat.".xml"); $dom = new DOMDocument('1.0'); $dom->preserveWhiteSpace = false; $dom->formatOutput = true; $dom->loadXML($xml->asXML()); $dom->save($cat.".xml"); header ("location: home.php"); ?> myxml.xml structure <?xml version="1.0" encoding="UTF-8"?> <root> <content> <id>3</id> <title></title> <code></code> <postedby></postedby> <image></image> </video></video> <live></live> </content> </root> when adding tag with attribite like <iframe width="560" height="315" src="https://www.youtube.com/embed/5DpGuk_fWGQ?list=PL8XXvQHPisgC7VEA0tSgzXK3uL4bfWaF-" frameborder="0" allowfullscreen></iframe> the output in xml is <live> <iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/5DpGuk_fWGQ?list=PL8XXvQHPisgC7VEA0tSgzXK3uL4bfWaF-\" frameborder=\"0\" allowfullscreen></iframe> </live> the problem is tag with attribute having =\"\" NOTE: using freehosting site accord this problem. NOTE: using localhost it works properly without =\"\" what do u guy think cause this problem? A: This might be a result of the option magic_quotes_gpc. It might be turned on in your freehosting site and turned off in your localhost. Use get_magic_quotes_gpc() to see whether the option is turned on. If it is, you can use stripslashes() to filter your data from escaped characters ( such as \")
doc_23535669
<script type="text/javascript"> window.onload = function () { var mapOptions = { center: new google.maps.LatLng(12.9715987, 77.59456269999998),//FROM address Latitude , Longitude value zoom: 14, mapTypeId: google.maps.MapTypeId.ROADMAP }; var infoWindow = new google.maps.InfoWindow(); var latlngbounds = new google.maps.LatLngBounds(); var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions); google.maps.event.addListener(map, 'click', function (e) { alert("Latitude: " + e.latLng.lat() + "\r\nLongitude: " + e.latLng.lng());// i got TO address Latitude , Longitude value }); } </script> <div id="dvMap" style="width: 300px; height: 300px"> A: Hi This one will Helpfull for you , Small Example of Direction Service, i'm using the center point of FROM address , and TO address where ever you clicking it will takes the TO address . the map draw the driving root . <!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <title>Google Maps JavaScript API v3 Example: Directions Travel Modes</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script> <input type="text" id="from_Latlng" value="12.9301397, 77.58773180000003" /> <input type="text" id="to_Latlng" value="" /> <script> $(function(){ initialize(); }); var directionDisplay; var directionsService = new google.maps.DirectionsService(); var map; function initialize() { var From = new google.maps.LatLng(12.9301397, 77.58773180000003); var to_latLng=$("#to_Latlng").val(); if(to_latLng!='') { var to_LatLngSplit=to_latLng.split(","); var to_lat=to_LatLngSplit[0]; var to_lng=to_LatLngSplit[1]; var to = new google.maps.LatLng(to_lat,to_lng); } else { var to = new google.maps.LatLng(12.9997841, 77.68394269999999); } directionsDisplay = new google.maps.DirectionsRenderer(); var mapOptions = { zoom: 14, mapTypeId: google.maps.MapTypeId.ROADMAP, center: From } map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions); // If there are any parameters at eh end of the URL, they will be in location.search var lat,lng,zoom,type; //looking something like "?marker=3" directionsDisplay.setMap(map); calcRoute(From,to); google.maps.event.addListener(map, 'click', function (e) { //alert("Latitude: " + e.latLng.lat() + "\r\nLongitude: " + e.latLng.lng());// i got TO address Latitude , Longitude value $('#to_Latlng').val(e.latLng.lat()+","+e.latLng.lng()); initialize(); }); } function calcRoute(From,to) { var selectedMode = "DRIVING"; var request = { origin: From, destination: to, travelMode: google.maps.TravelMode[selectedMode] }; directionsService.route(request, function(response, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(response); } else { alert("Directions Request Failed, "+status); } }); } </script> </head> <body onload="initialize()"> <div> <b>Mode of Travel: </b> </div> <div id="map_canvas" style="height: 450px;"></div> </body> </html> Demo
doc_23535670
{ "json.transactionDetails":{ "transactionDate":1266518024, "transactionType":"bought", "userDescription":"reimbursement", "transactionDescription":"Bought 10 AAPL @200", "quantity":10, "amount":"2010.00", "price":"200.00", "commission":"10.00", } } Then a PHP file getting the JSON: $t_detail = file_get_contents("details.json"); $transaction_detail = json_decode($t_detail); $tr_detail = $transaction_detail->json.transactionDetails; //this is my issue $transaction_type = $tr_detail->transactionType; $user_description = $tr_detail->userDescription; How do I parse the "json.transactionDetails"? The period is causing my script to fail. If I remove the "json." from both scripts everything works fine. Is there a way to skip over the first object in the tree or what? I can't change the way the JSON is outputted because it's coming from and external API. A: try to $transaction_detail = json_decode($t_detail,true); $tr_detail = $transaction_detail['json.transactionDetails']; When you make 2 nd parameter of json_decode to true , it will parse the json as an array so you can simply get the values using array['key'] syntax or you can $transaction_detail = json_decode($t_detail); $tr_detail = $transaction_detail->{"json.transactionDetails"};
doc_23535671
HTML <p ng-bind-html="whatIsay" addHello></p> AngularJS app.controller('MainCtrl', function($scope, $sce) { $scope.whatIsay = $sce.trustAsHtml('<span>I say </span>') }) app.directive('addHello', function() { return { link: function(scope, element) { element.append(angular.element('<span>hello!</span>')) } } }) The end result should be <p><span>I say</span> <span>hello!</span></p> Basically, I want ng-bind-html to do its work, then I want my directive addHello to run after it. A: If you don't want to use the $timeout hack, you can do away with ng-bind-html and add a parameter to your directive, like so: <body ng-controller="MainCtrl"> <p add-hello="whatIsay"></p> </body> And here's the directive code: app.directive('addHello', function() { return { scope: { trustedHtml: "=addHello", }, link: function(scope, element) { element.append("<p>hello</p>" + scope.trustedHtml.toString() + "<p>goodbye</p>"); } }; }); And here's the plunker. A: Not pretty, but if you do a $timeout call in the directive's linking function you'll get the desired effect. see the plunkr here link: function(scope, element) { $timeout(function () { element.append(angular.element('<span>hello!</span>')) }, 0); } I don't think priority work's here, because the element hasn't been updated yet? Maybe someone knows better.
doc_23535672
My DIV formatting was fine until I tried to embed the YouTube video. Why is my YouTube video stuck directly beneath the header? Also, the DIV/Table on the right side of the page is also out of whack. It just want the YT video on the left and the table on the right, and I want them to line up horizontally. Thanks for any assistance. Click to view the Webpage, with obvious errors. CODE: HTML- <!DOCTYPE> <html> <head> <link rel="stylesheet" type="text/css" href="FamilyBookMain.css"> </head> <title>FamilyBook.com</title> <body> <div id="top"> </div> <div class="video-container"> <iframe width="560" height="315" src="//www.youtube.com/embed/MQgdE1_lHnA?rel=0" allowfullscreen></iframe> <div class="famtree"> <img src="images/fambooktree.png" width="705" height="221"/> </div> </div> <div id="body"> <table style="border-collapse:collapse;"> <thead> <h1>Your Ancestors Are Dead.</h1> <h1>But Here, They're Still Alive.</h1> <br> </thead> <tbody> <tr> <td style="padding:10px"> <p class="table"><br>Welcome to the world's <strong>largest</strong> online resource for social media profiles and data from the twenty-first century. FamilyBook.com is home to billions of profiles from MySpace, FaceBook, Twitter, Instagram, and more. <br> <br> We are the <strong>leading provider of social media data</strong> from the early 2000s, including searchable image tags, status updates, relationship histories, friendships and family networks. Our mission is to link people to the personal histories of their ancestors- one social media profile at a time.</p></td> </tr> <tr><td style="padding:10px"> <p class="table"> Imagine the stories that you'll uncover as you explore your loved one's Facebook timeline and likes, private messages and chat logs, Twitter conversations, and Instagram uploads. The <strong>secrets</strong> that you uncover may even surprise you.<br> <br> Simply start with a name and <strong>we'll do the rest. </strong> Discover your ancestor's past. Learn where you came from. <br> </p></td> </tr> </tbody> <thead> <tr> <th class="head" colspan="2"> <strong>Our services are coming soon!</strong><br><br> </tr> </thead> </table> </div> <div class="footer"> <p id="footer"><img src="http://img.photobucket.com/albums/v483/CrazyInsaneJess/familybook.png" width="139" height="25"/> <br>Jessica E. Tompkins 2014 | <a href="http://en.gravatar.com/jesstompkins"> About</a> </p> </div> </body> </html> CSS- @charset "UTF-8"; /* CSS Document */ body { background-color:#EEEEEE; position: fixed; } #top { width: 100%; height: 60px; background- image:url('http://img.photobucket.com/albums/v483/CrazyInsaneJess/familybook.png'); background-color:#FFF; background-repeat:no-repeat; background-position:60px bottom; border-bottom-width:thin; border-bottom-color: #333; border-bottom-style:solid; position: fixed; top: 0px; } #body { width: 550px; height: 400px; background-color: #99aabb; text-align: right; margin: 10px; position: relative; left: 650px; bottom: 215px; } h1 { color: #333; font-family: Arial, Verdana, sans-serif; text-align: center; margin: 0px; top: 10px; position: relative; } .video { position: relative; left:170px; top: 170px; } ul.crap { color: #333; font-family: Georgia, "Times New Roman", Times, serif; font-size:12px; } #video { color: #99aacc; font-family: Arial, Verdana, sans-serif; text-align: center; height: 200; width: 450; margin: 350px 0px 0px; position: absolute; } .table { font-family:Arial, Helvetica, sans-serif; text-align:left; font-size:14px; color: white; } .head { color: #333; font-family: Verdana, Geneva, sans-serif; font-size:16px; padding: 15px; font-weight:100; } .footer{ width: 100%; height: 60px; background-color: #99aacc; border:1px solid #333; position:fixed; bottom:0px; } #footer{ font-family:Arial, Helvetica, sans-serif; font-size:9px; padding:5px; color: white; text-align:center; } a { text-decoration:none; } A: First of all, welcome to StackOverflow. I only spent about a minute looking over and editing your code, but I think I get the gist of what you want to do. Please see the code below: Change your #body element to match the code below: (I positioned the div absolutely.) #body { width: 550px; height: 400px; background-color: #99aabb; text-align: right; margin: 10px; position: absolute; left: 650px; top:65px } Paste this into your CSS: .video-container{ width:auto; height:auto; margin-top:75px; } Now, let me just say that your HTML kind of messy and could be streamlined quite a bit. As @Havard Brynjulfsen pointed out, there are a few IDs and classes that remain unused. In any case, the code above, should yield the desired results, but what you are trying to do could be accomplished much more elegantly if you are willing to change up your HTML structure. Also, there are some bugs in your HTML. I would highly suggest validating your code with the official W3C validator. There are too many issues for me to list here without going off-topic, but here are the biggies: * *Your doctype declaration is incorrect, it should be <!DOCTYPE html>. *Your <title> should be in the <head> of your document.
doc_23535673
Here is a piece of code. seconds += 1 let (h,m,s) = secondsToHoursMinutesSeconds(seconds: Int(seconds)) let secondsQuantity = HKQuantity(unit: HKUnit.second(), doubleValue: Double(s)) let minutesQuantity = HKQuantity(unit: HKUnit.minute(), doubleValue: Double(m)) let hoursQuantity = HKQuantity(unit: HKUnit.hour(), doubleValue: Double(h)) displayTimeLabel.text = ""+hoursQuantity.description+" "+minutesQuantity.description+" "+secondsQuantity.description let distanceQuantity = HKQuantity(unit: HKUnit.meter(), doubleValue: distance) milesLbl.text = "" + distanceQuantity.description paceLbl.text = ""+String((instantPace*3.6*10).rounded()/10)+" km/h"//"Pace: "+String((distance/seconds*3.6*10).rounded()/10)+" km/h" let kg = 75 caloriesLbl.text = ??? A: Here is the sample code I have converted from a java example It follows the principles laid by Compendium of Physical Activities. Most of the excercise applications use these algorithms for calculating matabolic activities. typedef NS_ENUM(NSUInteger, Gender){ Male, Felmale }; /** * Calculated the energy expenditure for an activity. Adapted from the following website https://sites.google.com/site/compendiumofphysicalactivities/corrected-mets * * @param height The height in metres. * @param age The date of birth. * @param weight The weight of the user. * @param gender The gender of the user. * @param durationInSeconds The duration of the activity in seconds. * @param stepsTaken The steps taken. * @param strideLengthInMetres The stride length of the user * @return The number of calories burnt (kCal) */ - (float)calculateEnergyExpenditureWith:(float) height DOB:(NSDate*) dateOfBirth Weight:(float) weight Gender:(int)gender DurationInSecs:(int) durationInSeconds StepsTaken:(int) stepsTaken StrideLengthInMeters:(float)strideLengthInMetres { float ageCalculated = [self getAgeFromDateOfBirth:dateOfBirth]; float harrisBenedictRmR = [self convertKilocaloriesToMlKmin:[self harrisBenedictRmrWithGender:gender WeigthKg:weight Age:ageCalculated HeightCm:[self convertMetresToCentimetre:height] ] WeigthInKg:weight]; float kmTravelled = [self calculateDistanceTravelledInKM:stepsTaken EntityStrideLength:strideLengthInMetres]; float hours = durationInSeconds/(3600.0); float speedInMph = (kmTravelled/1000.0) / hours; float metValue = [self getMetForActivity:speedInMph]; float constant = 3.5f; float correctedMets = metValue * (constant / harrisBenedictRmR); return correctedMets * hours * weight; } /** * Gets a users age from a date. Only takes into account years. * * @param age The date of birth. * @return The age in years. */ - (float) getAgeFromDateOfBirth:(NSDate*) dateOfBirth { NSCalendar *calendar = [NSCalendar currentCalendar]; unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay; NSDateComponents *dateComponentsNow = [calendar components:unitFlags fromDate:[NSDate date]]; NSDateComponents *dateComponentsBirth = [calendar components:unitFlags fromDate:dateOfBirth]; if (([dateComponentsNow month] < [dateComponentsBirth month]) || (([dateComponentsNow month] == [dateComponentsBirth month]) && ([dateComponentsNow day] < [dateComponentsBirth day]))) { return [dateComponentsNow year] - [dateComponentsBirth year] - 1; } else { return [dateComponentsNow year] - [dateComponentsBirth year]; } } - (float) convertKilocaloriesToMlKmin:(float)kilocalories WeigthInKg:(float)weightKgs { float kcalMin = kilocalories / 1440.0; kcalMin /= 5; return ((kcalMin / (weightKgs)) * 1000.0); } -(float)convertMetresToCentimetre:(float) metres{ return metres * 100; } - (float) calculateDistanceTravelledInKM:(int)stepsTaken EntityStrideLength:(float) entityStrideLength { return (((float) stepsTaken * entityStrideLength) / 1000); } /** * Gets the MET value for an activity. Based on https://sites.google.com/site/compendiumofphysicalactivities/Activity-Categories/walking . * * @param speedInMph The speed in miles per hour * @return The met value. */ - (float) getMetForActivity:(float) speedInMph { if (speedInMph < 2.0) { return 2.0f; } else if (speedInMph == 2.0f) { return 2.8f; } else if (speedInMph > 2.0f && speedInMph <= 2.7f) { return 3.0f; } else if (speedInMph > 2.8f && speedInMph <= 3.3f) { return 3.5f; } else if (speedInMph > 3.4f && speedInMph <= 3.5f) { return 4.3f; } else if (speedInMph > 3.5f && speedInMph <= 4.0f) { return 5.0f; } else if (speedInMph > 4.0f && speedInMph <= 4.5f) { return 7.0f; } else if (speedInMph > 4.5f && speedInMph <= 5.0f) { return 8.3f; } else if (speedInMph > 5.0f) { return 9.8f; } return 0; } /** * Calculates the Harris Benedict RMR value for an entity. Based on above calculation for Com * * @param gender Users gender. * @param weightKg Weight in Kg. * @param age Age in years. * @param heightCm Height in CM. * @return Harris benedictRMR value. */ - (float) harrisBenedictRmrWithGender:(Gender) gender WeigthKg:(float) weightKg Age:(float) age HeightCm:(float)heightCm { if (gender == Felmale) { return 655.0955f + (1.8496f * heightCm) + (9.5634f * weightKg) - (4.6756f * age); } else { return 66.4730f + (5.0033f * heightCm) + (13.7516f * weightKg) - (6.7550f * age); } } A: Swift5 Version typealias AppHealthKitValueCompletion = ((Double?, Error?)->Void) func loadCalory(since start: Date = Date().startOfDay, to end: Date = Date(), completion: @escaping AppHealthKitValueCompletion) { guard let type = HKQuantityType.quantityType(forIdentifier: .activeEnergyBurned) else { return } let predicate = HKQuery.predicateForSamples(withStart: start, end: end, options: .strictStartDate) let query = HKStatisticsQuery(quantityType: type, quantitySamplePredicate: predicate, options: .cumulativeSum) { (_, result, error) in var resultCount = 0.0 guard let result = result else { completion(nil, error) return } if let quantity = result.sumQuantity() { resultCount = quantity.doubleValue(for: HKUnit.kilocalorie()) } DispatchQueue.main.async { completion(resultCount, nil) } } healthStore.execute(query) }
doc_23535674
The content of the files looks like this: rs3094315 1 742429 AA rs12562034 1 758311 GG rs3934834 1 995669 CC There are tabs between each field. There's about 500,000 lines in each file. In order to compare them easily, I wanted to keep only the data points that both the files contained, and discard any data points unique to either of them. To do this, I have created a list of all the DNA positions that are unique and now I am trying to search through each line of the original datafile and print all lines NOT containing these unique DNA positions to a new file. Everything in my code has worked up until I try to search through the genome file using regex to print all non-unique DNA positions. I can get the script to print all items in the LaurelSNP_left list inside the for loop, but when I try to use re.match for each item, I get this error message: Traceback (most recent call last): File "/Users/laurelhochstetler/scripts/identify_SNPs.py", line 57, in <module> if re.match(item,"(.*)", Line): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 137, in match return _compile(pattern, flags).match(string) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 242, in _compile p = sre_compile.compile(pattern, flags) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_compile.py", line 500, in compile p = sre_parse.parse(p, flags) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_parse.py", line 673, in parse p = _parse_sub(source, pattern, 0) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_parse.py", line 308, in _parse_sub itemsappend(_parse(source, state)) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/sre_parse.py", line 401, in _parse if state.flags & SRE_FLAG_VERBOSE: TypeError: unsupported operand type(s) for &: 'str' and 'int' My question is two-fold: * *How can I use my list in an regex expression? *Is there a better way to accomplish what I am trying to do here? Here's my code: #!/usr/bin/env python import re #this imports regular expression module import collections MomGenome=open('/Users/laurelhochstetler/Documents/genetics fun/genome_Mary_Maloney_Full_20110514145353.txt', 'r') LaurelGenome=open('/Users/laurelhochstetler/Documents/genetics fun/genome_Laurel_Hochstetler_Full_20100411230740.txt', 'r') LineNumber = 0 momSNP = [] LaurelSNP = [] f = open("mom_edit.txt","w") for Line in MomGenome: if LineNumber > 0: Line=Line.strip('\n') ElementList=Line.split('\t') momSNP.append(ElementList[0]) LineNumber = LineNumber + 1 MomGenome.close() for Line in LaurelGenome: if LineNumber > 0: Line=Line.strip('\n') ElementList=Line.split('\t') LaurelSNP.append(ElementList[0]) LineNumber = LineNumber + 1 momSNP_multiset = collections.Counter(momSNP) LaurelSNP_multiset = collections.Counter(LaurelSNP) overlap = list((momSNP_multiset and LaurelSNP_multiset).elements()) momSNP_left = list((momSNP_multiset - LaurelSNP_multiset).elements()) LaurelSNP_left = list((LaurelSNP_multiset - momSNP_multiset).elements()) LaurelGenome=open('/Users/laurelhochstetler/Documents/genetics fun/genome_Laurel_Hochstetler_Full_20100411230740.txt', 'r') i = 0 for Line in LaurelGenome: for item in LaurelSNP_left: if i < 1961: if re.match(item, Line): pass else: print Line i = i + 1 LineNumber = LineNumber + 1 A: Short answer: I don't think you need regexp for what you're trying to do. Long answer: Let's analyse your code. At the beginning there's: LineNumber = 0 MomGenome = open('20110514145353.txt', 'r') for Line in MomGenome: if LineNumber > 0: Line = Line.strip('\n') ElementList = Line.split('\t') momSNP.append(ElementList[0]) LineNumber = LineNumber + 1 MomGenome.close() That it could be improved with the with statement, and I guess your line counting is only there to skip some kind of header, I'll use next() for that: with open('20110514145353.txt') as mom_genome: next(mom_genome) # skipping the first line for line in mom_genome: elements = line.strip().split('\t') mom_SNP.append(elements[0]) If you noticed I also tried to avoid using CamelCase names for variables, this way you'll be following some style guides. I also changed .strip('\n') to .strip() check the official str.strip() to see if that still does what you want. The above can be done on your other file too. After you read the files there's this line: overlap = list((momSNP_multiset and LaurelSNP_multiset).elements()) Are you sure this does what you want? Shouldn't that and be an &, like: overlap = list((momSNP_multiset & LaurelSNP_multiset).elements()) Let's look at this example: >>> from collections import Counter >>> a = Counter(a=4, b=2, c=0, d=-2) >>> b = Counter(a=2, b=0, c=0) >>> a Counter({'a': 4, 'b': 2, 'c': 0, 'd': -2}) >>> b Counter({'a': 2, 'c': 0, 'b': 0}) >>> a and b # This will return b Counter({'a': 2, 'c': 0, 'b': 0}) >>> c & d # this will return the common elements Counter({'a': 2}) a and b it will return b since bool(a) is evaulated to True, take a look at the official doc. After that it comes the match, this is really not clear. You do: LaurelGenome = open('20100411230740.txt', 'r') i = 0 for Line in LaurelGenome: for item in LaurelSNP_left: if i < 1961: if re.match(item, Line): pass else: print Line i = i + 1 LineNumber = LineNumber + 1 So as I was saying at the beginning I think you don't need regexp at all. And I think you're trying to do something like: with open('20100411230740.txt') as laural_genome: for line in laureal_genome: i = 0 for item in laurelSNP_left: if i > 1960: break if line.strip().split('\t')[0] == item: print line i += 1 I've guessed a lot during this answer, so feel free to give more information and tell me where I guessed wrong :) A: The third argument of re.match is for options (see the manual). You're calling it with something bogus (the line number) A: Am I missing something critical about the problem? I feel this solution is alarmingly less involving than the existing ones. For two different genome files, I have: with file('zzz.txt') as f1: first = frozenset([i.strip() for i in f1 if i.strip()]) with file('yyy.txt') as f2: common = [i.strip().split('\t') for i in f2 if i.strip() in first] genomes = {} for i in common: genomes[i[0]] = i[1:] This should print out all duplicates (entries that are common to both files) while requiring no more space than the size of the first read file. Thus, you can speed it up by checking which is a smaller file (perhaps by filesize) beforehand to minimize the memory impact. Regex does not seem to be necessary here--and if not this solution, frozensets have intersection as well, if you prefer not using list comprehensions. EDIT: Updated to have each iteration in a Python dict. A: You want to print every line from file 2 whose ID does not occur in file 1. Make a set of the IDs in file 1, and use them as you loop through file 2: momSNP = set() for line in MomGenome: snp, rest = line.split(None, 1) # Split into two pieces only momSNP.add(snp) for line in MyGenome: snp, rest = line.split(None, 1) if snp in momSNP: print line This only needs to store the 500k SNPs, so it shouldn't be too much of a problem memory-wise.
doc_23535675
public void modifyExam(String [] names) { String name; Scanner scanner = new Scanner(System.in); System.out.println("Please enter the name of the student whose grade you would like to modify: "); name = scanner.nextLine(); boolean nameMatch = true; for (int i=0; i<names.length; i++) { // .... } A: You should use .equals() to compare strings in Java. Example: public void modifyExam(String [] names) { String name; Scanner scanner = new Scanner(System.in); System.out.println("Please enter the name of the student whose grade you would like to modify: "); name = scanner.nextLine(); boolean nameMatch = false; for (int i=0; i<names.length; i++) { if( names[i].equals(name) ) { // do your logic here ... } } } A: I would recommend that you store your students in a Map with the name as the key. Then you wouldn't have to iterate (assuming your names are unique). Map<String, Student> students = new HashMap<String, Student>(); Student s = new Student("Joe Smoe"); students.put(s.getName(), s); Then you can lookup the student to update like this: Student studentToUpdate = students.get(name); if (studentToUpdate != null) { // logic here... } Note Returns null if this map contains no mapping for the key. So you would want to add a null check before using the return value of the get call and deal with it accordingly. A: Equalities. if(name.equals(name[i])) System.out.println("match at " i); A: boolean nameMatch = false; for (int i=0; i<names.length; i++) { if(names[i].equals(name)) { namesMatch = true; break; } } The break means you don't carry on searching the array as a match has been found. A: I would break this function into two functions. One called findName() or even more generic findString() and the other called modifyExam. Let findString() return an index, use the index in modify exam. Here is what findString() should do int findString(String [] names, String name) { for ( int i = 0; i < names.length; i++ ) { if names[i].equals(name) return // either a boolean or an index or something. } return -1 // or null } You could also use binary search if the search array is large and already sorted. Using binarySearch() the findString method will be something like :- int findString(String[] names, String name, int startIndex, int stopIndex) { if ( startIndex > stopIndex) return; int mid = (stopIndex - startIndex)/2 if ( name < names[mid] ) return findString(names, name, startIndex, mid-1); else if ( names[mid].equals(name) ) return mid; else return findString(names, name, mid+1, stopIndex); }
doc_23535676
I try to install laravel 8.0 on my local server PHP 8.0,Composer 2.6, but give this error pls help me Message Show [InvalidArgumentException] Could not find package laravel/laravel with version 8.0 in a version installable using your PHP version, PHP extens ions and Composer version. A: Use --ignore-platform-reqs when you are installing a lower version of laravel. full code: composer create-project laravel/laravel:^8.0 example --ignore-platform-reqs then change the php version on your composer.json from 7.3 to 8.0 Hope this solve your installation problem. Another fix would be to install the last specific version of laravel 8: composer create-project laravel/laravel:8.6.11 example-boilerplate --prefer-dist
doc_23535677
when they are received in the app we use the notification builder to show the message: NotificationChannel mChannel = new NotificationChannel( "com.....app.notification", "...", android.app.NotificationManager.IMPORTANCE_HIGH); mChannel.setShowBadge(true); mNotificationManager.createNotificationChannel(mChannel); mBuilder = new NotificationCompat.Builder(context, mChannel.getId()); mBuilder.setWhen(System.currentTimeMillis()) .setContentTitle(fromHtml(title)) .setTicker(fromHtml(title)) .setContentIntent(contentIntent) .setAutoCancel(true) .setPriority(Notification.PRIORITY_MAX); ... mNotificationManager.notify(appName, notId, mBuilder.build()); all works well, except that on some devices, the push are delivered, only when the user unlocks the screen. i know that there are several android settings that might allow this or not. but they are too complex and no user could possibly find all of them. so my question is: is there a way to programaticaly make sure that the push are always shown?
doc_23535678
Until yesterday, I was having similar success. However, today i recieved a Jira item with a bug to be fixed. As is usual and recommended, I click the Jira item's link to create a branch and then browse to the branch on bitbucket to check it out or clone it. However, today, I created the branch in Jira and browsed to the branch in bitbucket to check it out (cloning and checkout seem to both put a local copy of the development branch in a local folder for me, maybe one is checked out and the other checks itself out the first time I make a change). But, today, although a branch is created by Jira, and i can find an active link in Jira that will browse me to the branch in Jira, I cannot locate that branch in the bitbucket list of branches no matter which of all the available methods for finding a branch I try. And, whether I clone the branch or check it out, sourcetree downloads, not the branch I want (a copy of development with the new branch name to match the task name in Jira) but rather a copy of the bare repository that is the root of the GIT project in bitbucket. I have tried this repeatedly today in every way I am able. But I am unable to view the new branch in the BitBucket list of branches, and I can only download the bare repository, not the copy of the most recent development branch. What is going on, or what could have happened? A: As it turns out, Jira is somehow selecting to create the new branch in a different repository from the one I expected. That is why I could not find it in the normal repository. It is also why when trying to clone or checkout the branch I'm getting the bare repository. This has apparently happened before, about twenty times. There are about twenty branches created in this other repository. All of these have no changes. That is, they were created under the same error conditions I encountered. Perhaps no one is aware of where the missing branches are being created. In any case, this is no longer a question, it has become a mystery. So, before the monitor, dings my chips, I'm buggin' out! Actually, there is one more thing: it's not a mystery. What the problem is, is this: I was not remembering to select the repository in the dropdown in the bitbucket create a branch dialog. Well ok then!
doc_23535679
the error shown is: Traceback (most recent call last): File "C:\Users\AdvaitSNambiar\Desktop\Myfolder\SUTT task\Final\task1test-2-final.py", line 63, in <module> ws['D' + str(i) ].value = ws['D' + str(i)].value + '+ EEE' TypeError: unsupported operand type(s) for +: 'NoneType' and 'str' if (h2 == 'A3'): ws['D' + str(i) ].value = ws['D' + str(i)].value + '+ EEE' this was the concatenation I tried to perform my code is given below import openpyxl from openpyxl import load_workbook wb = load_workbook('names.xlsx') ws = wb.active i = 0 while(i<24): i = 2 while(i<24): idnum = ws['A' + str(i)] idnum1 = idnum.value idnum2 = idnum1[4:8] if (idnum2 == 'AAPS'): ws['D' + str(i)] = 'ECE' if (idnum2 == 'ABPS'): ws['D' + str(i) ] = 'Manu' if (idnum2 == 'A1PS'): ws['D' + str(i)] = 'chemical' if (idnum2 == 'A2PS'): ws['D' + str(i) ] = 'civil' if (idnum2 == 'A3PS'): ws['D' + str(i) ] = 'EEE' if (idnum2 == 'A4PS'): ws['D' + str(i)] = 'Mech' if (idnum2 == 'A5PS'): ws['D' + str(i) ] = 'pharma' if (idnum2 == 'A7PS'): ws['D' + str(i) ] = 'CSE' if (idnum2 == 'A8PS'): ws['D' + str(i) ] = 'ENI' if (idnum2 == 'B1PS'): ws['D' + str(i) ] = 'MSc Bio' if (idnum2 == 'B2PS'): ws['D' + str(i) ] = 'MSc Chem' if (idnum2 == 'B3PS'): ws['D' + str(i) ] = 'MSc Eco' if (idnum2 == 'B4PS'): ws['D' + str(i) ] = 'MSc Math' if (idnum2 == 'B5PS'): ws['D' + str(i) ] = 'MSc Physics' if (idnum2[-2:] != 'PS'): h1=idnum2[0:3] h2=idnum2[-2:] if (h1 == 'B1'): ws['D' + str(i) ].value = 'MSc Bio' if (h1 == 'B2'): ws['D' + str(i) ].value = 'MSc Chem' if (h1 == 'B3'): ws['D' + str(i) ].value = 'MSc Eco' if (h1 == 'B4'): ws['D' + str(i) ].value = 'MSc Math' if (h1 == 'B5'): ws['D' + str(i) ].value = 'MSc Physics' if (h2 == 'AA'): ws['D' + str(i)].value = ws['D' + str(i)].value + '+ ECE' if (h2 == 'AB'): ws['D' + str(i) ].value = ws['D' + str(i)].value + '+ Manu' if (h2 == 'A1'): ws['D' + str(i)].value = ws['D' + str(i)].value + '+ chemical' if (h2 == 'A2'): ws['D' + str(i) ].value = ws['D' + str(i)].value + '+ civil' if (h2 == 'A3'): ws['D' + str(i) ].value = ws['D' + str(i)].value + '+ EEE' if (h2 == 'A4'): ws['D' + str(i)].value = ws['D' + str(i)].value + '+ Mech' if (h2 == 'A7'): ws['D' + str(i) ].value = ws['D' + str(i)].value + '+ CSE' if (h2 == 'A8'): ws['D' + str(i) ].value = ws['D' + str(i)].value + '+ ENI' i=i+1 j = 2 while(j<24): idnum3 = ws['A' + str(j)] idnum4 = idnum3.value idnum5 = idnum4[8:12] ws['E' + str(j)] = 'f2022' +idnum4+ '@pilani.bits-pilani.ac.in' j=j+1 wb.save('names.xlsx') import pandas as pd df1 = pd.read_excel('names.xlsx') print(df1) excel_data = pd.read_excel('names.xlsx',sheet_name='Sheet1') json_str = excel_data.to_json(orient='records') print('Excel Sheet to JSON:\n', json_str)
doc_23535680
viewer.fitToView([dbId]); let color = new THREE.Vector4(0, 0, 0.5, 0.5); window.viewer.setThemingColor(item.link,color) I can clear the theming colors with clearThemingColors() call. But for now, I use the home icon at the top to return to the home position. Is there a way to do this programmatically. A: viewer.utilities.goHome(); Ref: https://forge.autodesk.com/en/docs/viewer/v2/reference/javascript/viewingutilities/#gohome
doc_23535681
A: Solrj is bundled with Solr, so if you download the Solr Source package you will find the Solrj source code included in it. https://archive.apache.org/dist/lucene/solr/3.2.0/apache-solr-3.2.0-src.tgz It's located in the directory solr/src/sorlj A: If you mean the latest stable release than it is exactly like @Daniel said. If you want the latest source files you can find the in the Subversion repository of Apache. They latest source (not a stable release) can be viewed here here or checked out from here You can check the stability of this code by looking at the hudson build server and seeing the health of the latest build. Back when I was trying to do better sharding support for Solr I worked a lot with the nightly builds (if you need regular bug fixes). You can get the nightly build from the links I added below it will be in the form of a jar and can be used the same way you use the stable release, but again be advised you need to look at the build health to see that it is worth the risk. * *Nightly builds for Solr3.3 - jar, status *Nightly builds for Solr4 - jar, status Also if you really need to be on top of what's going on in the code but don't want a completely unstable release, you can wait for a release candidate and download it. If you want to know when release candidates are available the best way is to subscribe to the "lucene-dev" mailing list and look for voting on a release candidate. example Tell me if you need more information
doc_23535682
A couple code snippets included here... This is from the Draggable Dialog: function PaperComponent(props) { return ( <Draggable cancel="input"> <Paper {...props} /> </Draggable> ); } const GenericDialog = props => { return ( <Dialog disableBackdropClick disableEscapeKeyDown disableRestoreFocus fullWidth={true} maxWidth={props.maxWidth} open={props.open} onClose={props.onClose} PaperComponent={PaperComponent} > <DialogTitle>{props.dialogTitle}</DialogTitle> {props.children} <DialogActions> <Button onClick={props.onSubmit} color="primary"> Submit </Button> <Button onClick={props.onClose} color="secondary" autoFocus> Cancel </Button> </DialogActions> )} </Dialog> This is how the text field that I am unable to click/type into is defined: <TextField style={{ margin: 0, width: '350px' }} label="Task Description" helperText="(1024 character maximum)" inputProps={{ maxLength: 1024 }} multiline rows="4" onChange={this.handleChange('taskDescription')} value={this.state.task.taskDescription} variant="outlined" /> A: My confusion was that I thought the TextField was an input. But with the multiline prop, it is instead a textarea. To resolve the problem, I changed the Draggable cancel prop to: cancel="input, textarea" A: <TextField style={{ margin: 0, width: '350px' }} label="Task Description" helperText="(1024 character maximum)" inputProps={{ maxLength: 1024 }} multiline rows="4" autoFocus={true} onChange={this.handleChange('taskDescription')} value={this.state.task.taskDescription} variant="outlined"/>
doc_23535683
These are the validation codes for the edittext EditText txtDislikes = (EditText) findViewById(R.id.txtDislikes); txtDislikes.setHint("e.g. Skating, Photography separate by comma"); txtDislikes.setFilters(new InputFilter[] { new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { if(source.equals("")) { return source; } if(source.toString().matches("[a-z A-Z -]+")) { return source; } return ""; } } }); I've tried to type in like source.setError("ONLY LETTERS ARE ALLOWED"); in if(source.equals("")) { return source; } else { source.setError("ONLY LETTERS ARE ALLOWED"); } if(source.toString().matches("[a-z A-Z -]+")) { return source; } else { source.setError("ONLY LETTERS ARE ALLOWED"); } return ""; But I've got error says "The method setError(String) is undefined for the type CharSequence". Not sure what that means. Plus, I couldn't find any good examples for this. Any help or examples provided will be greatly appreciated. Thanks! A: There is no setError() method for type CharSequence. Refer to TextView.setError(), you should setError() on your txtDislikes instead of source.
doc_23535684
Given the following: var s = "abc1!?d$"; alert(s.replace(/\W+/, " ")); I am alerted: abc d$ Why is it not stripping out the last dollar? A: Because there's an intervening word character. Try this: alert(s.replace(/\W+/g, ' ')); Without the "g" suffix on the regex, it only makes one substitution. That handles the "!?" in the middle, but that "d" ends the sequence. A: Because you're not using the (g)lobal flag on your matcher, so it's only matching the first consecutive sequence of non-word characters. The following should give the result you expect: var s = "abc1!?d$"; alert(s.replace(/\W+/g, " "));
doc_23535685
SELECT * FROM [Asset] WHERE Id=@AssetId AND CustomerId=(SELECT CustomerId FROM [User] WHERE UserId=@UserId); This is great, but with many entries in the Asset and User tables, this query could take up a ton of time. This is bad since every request made to my API that needs the Asset data should be doing this check. I could set up an index, and in fact UserId is a Secondary Key in User because it's a unique identifier from the auth provider, but I'm not sure if I should add an index for CustomerId in Asset. The Asset table should grow relatively slowly compared to some other tables (have a messaging record table for auditing purposes), but I'm not sure if that's the right answer, or if there's some simpler answer that's more optimized. Or is this kind of query so fast at scale that I have nothing to worry about? A: For your particular case, it looks like the perfect context to build a junction table between the User table and the Asset table. Both field together will become the primary key. Individually, AssetId and UserId will be foreign keys. Let's say the junction table is called AssetUser. Foreign keys : CONSTRAINT [FK_AssetUser_User] FOREIGN KEY ([UserId]) REFERENCES [User]([UserId]) CONSTRAINT [FK_AssetUser_Asset] FOREIGN KEY ([AssetId]) REFERENCES [Asset]([AssetId]) Primary key : CONSTRAINT [PK_AssetUser] PRIMARY KEY([AssetId], [UserId])); You shouldn't worry about scale too much unless you are going to have ALOT of data and/or the performance is critical in your application. If so, you have the option to use hadoop or to migrate to a NoSQL database.
doc_23535686
I have a storedproc that returns a list of departments create procedure [dbo].[getDepartments] as begin select distinct department from ViewEmpInfo end department is a custom field Name(varchar(100)), not my doing, I just inherited from the previous developer. On my repository @Query(value = "EXEC [getDepartments]", nativeQuery = true) List<String> getDepartments(); Calling it on my code: List<String> genderStatsHeader = departmentRepository.getDepartments(); which results to an error: org.springframework.orm.jpa.JpaSystemException: No Dialect mapping for JDBC type: -9 I also tried replacing the return from List<String> to List<Object> but the same error occurs. Any help would be appreciated. A: Found an answer on the previous similar issues, I Casted the department with to varchar, it doesn't work with nvarchar. I do hope it will help those who stumbles with this issue.
doc_23535687
Action : "android.intent.action.VIEW" URI : "google.navigation:q=48.605086,2.367014/48.607231,2.356997" Component Name of the navigation app : For example Google Maps "com.google.android.apps.maps/com.google.android.maps.MapsActivity" For example: Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri); mapIntent.setPackage("com.google.android.apps.maps"); startActivity(mapIntent); from : https://developers.google.com/maps/documentation/urls/android-intents * *I want to trigger navigation with multiple way points, Is it possible on TomTom Go Mobile, Google Maps, Waze, Here WeGo and Sygic via Intent ? *Can I trigger navigation on the application above and start driving automatically? Without user interaction ? I tried to trigger the above intent via ADB and do some tweaking by adding "," , ";", "and". Nothing worked. A: In order to open the navigation mode in the HERE WeGo app you can use the following function private fun navigateToDestination(destination: GeoCoordinate) { try { val intent = Intent().apply { action = "com.here.maps.DIRECTIONS" addCategory(Intent.CATEGORY_DEFAULT) data = Uri.parse("here.directions://v1.0/mylocation/${destination.latitude},${destination.longitude}") } intent.resolveActivity(packageManager)?.let { startActivity(intent) } } catch (t: Throwable) { Timber.e(t) } } Sygic: private fun navigateToDestination(destination: GeoCoordinate) { try { val intent = Intent(Intent.ACTION_VIEW, Uri.parse("com.sygic.aura://coordinate|${destination.longitude}|${destination.latitude}|drive")) intent.resolveActivity(packageManager)?.let { startActivity(intent) } } catch (t: Throwable) { Timber.e(t) } } Waze: private fun navigateToDestination(destination: GeoCoordinate) { try { val intent = Intent(Intent.ACTION_VIEW, Uri.parse("waze://?ll=${destination.latitude}, ${destination.longitude}&navigate=yes")) intent.resolveActivity(packageManager)?.let { startActivity(intent) } } catch (t: Throwable) { Timber.e(t) } } You can also resolve the installed apps that can be used for navigation and let the user decide which one s/he wants to use: private fun navigateToDestination(destination: GeoCoordinate) { try { val intent = Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:q=${destination.latitude}, ${destination.longitude}")) val resolvedPackages = packageManager.queryIntentActivities(intent, PackageManager.MATCH_ALL) if (resolvedPackages.isNotEmpty()) { val packageNames = resolvedPackages.map { it.activityInfo.packageName } val targetIntents = packageNames.map { packageManager.getLaunchIntentForPackage(it) } val intentChooser = Intent.createChooser(Intent(), "Choose a navigation app") intentChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetIntents.toTypedArray()) startActivity(intentChooser) } } catch (t: Throwable) { Timber.e(t) } }
doc_23535688
<?php set_time_limit(0); ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); $rss_url = 'https://grabo.bg/rss/exportxml/stolicabg/?affid=50781'; $xml = simplexml_load_file($rss_url); foreach($xml->deal as $item){ $title = htmlspecialchars($item->title, ENT_XML1 | ENT_QUOTES, 'UTF-8'); //$websiteUrl = $item->WEB; $offerUrl = $item->url; $description = htmlspecialchars($item->description, ENT_XML1 | ENT_QUOTES, 'UTF-8'); $offerTerms = htmlspecialchars($item->terms, ENT_XML1 | ENT_QUOTES, 'UTF-8'); $originalPrice = $item->price_regular; $finalPrice = $item->price; $offerDiscount = $item->price_discount; //$offerSales = $item->SALES; $offerEnds = $item->expire; $lat_coordinates = $item->addresses->address->lat; $lng_coordinates = $item->addresses->address->lng; $adress = $item->addresses->address->addr; $hood = $item->addresses->address->section; $company = $item->company; //$category = utf8_encode($item->categories->category); $category = htmlspecialchars($item->categories->category, ENT_XML1 | ENT_QUOTES, 'UTF-8'); $img = $item->image; mysqli_query($link, " INSERT INTO `offers` (offerName, offerImgUrl, offerUrl, OfferDetails, offerTerms, offerRegularPrice, offerDiscount, offerFinalPrice, offerCategory, offerExpires, offerCompany, offerCity, offerNeighbourhood) VALUES ('$title', '$img', '$offerUrl', '".$description."', '".$offerTerms."', '$originalPrice', '$offerDiscount', '$finalPrice', '$category', '$offerEnds', '$company', '$adress', '$hood')") or die(mysqli_error($link)); } ?> As you can see I tried to set the UTF8 encoding with htmlspecial chars, I tried with iconv function, also with 'set names utf8' with mysqli_query, but inserted data is still unreadable.. Of course my db charset is utf8_general_ci. Thats the inserted data in the db:
doc_23535689
$mysqliStmt->execute(); It does NOT update or insert into a table. It just delivers stmt results. There are no errors, warnings, or anything else. (See below) The Insert query I use: INSERT INTO testdatabase.`test` (`test1`, `test2`) VALUES(?, ?) The Update query: UPDATE testdatabase.`test` SET `test1` = ? WHERE `id` = ? LIMIT 1 Resultinformation (update): 'fieldCount' => 0, 'affectedRows' => 1, 'numRows' => 0, 'paramCount' => 2, 'insertId' => 0, 'sqlstate' => '00000', 'threadId' => 5291, 'errno' => 0, 'error' => '', 'warningCount' => 0, 'warnings' => false 'connectErrno' => 0, 'connectError' => NULL, 'hostInfo' => 'Localhost via UNIX socket', 'protocolVersion' => 10, 'serverInfo' => '5.1.49-3', 'serverVersion' => 50149, 'clientInfo' => '5.0.27', 'clientVersion' => 50027, 'info' => 'Rows matched: 1 Changed: 1 Warnings: 0' The code: $stmt = self::$_connection->prepare($query); //binds params -> like/with $stmt::bind_param() but more generic $this->_bindParameters($stmt) $stmt->execute(); Now the update/insert data should be stored into database or I'm wrong? If I use phpMyAdmin or MySQL console to verify the results of the queries, the database table was neither updated nor was the new data inserted.
doc_23535690
https://www.telerik.com/forums/how-ti-bind-dictionary-to-radproperty-grid but it is show count and capacity. If I change PropertySetMode property on RadPropertyGrid still no luck. Can anyone help me solve this issue ? I have to use only MVVM pattern.
doc_23535691
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using MySql.Data.MySqlClient; namespace DataBaseModule.General { public class ManagedDataReader : IDisposable { private bool _disposed = false; private MySqlCommand _command; private MySqlDataReader _dataReader; // The class constructor. public ManagedDataReader(string StrSQL) : this(new MySqlCommand(StrSQL)) { } public ManagedDataReader(MySqlCommand SQL_Cmd) { try { _command = SQL_Cmd; _command.Connection = new MySqlConnection(DbAccessProvider._connectionString); DbAccessProvider.SqlCommandsPerformed++; _command.Connection.Open(); _dataReader = _command.ExecuteReader(); } catch (Exception ex) { DataBaseModule.Log.CommonLogger.Log_Database_Error(new Exception("Sql command Was: " + _command.CommandText, ex)); throw ex; } } public int VisibleFieldCount() { return _dataReader.VisibleFieldCount; } public bool Read() { return _dataReader.Read(); } public object this[int i] { get { if (_dataReader[i].Equals(DBNull.Value)) { return null; } else { return _dataReader[i]; } } } public object this[string FieldName] { get { if (_dataReader[FieldName].Equals(DBNull.Value)) { return null; } else { return _dataReader[FieldName]; } } } // Implement IDisposable. // Do not make this method virtual. // A derived class should not be able to override this method. public void Dispose() { Dispose(true); // This object will be cleaned up by the Dispose method. // Therefore, you should call GC.SupressFinalize to // take this object off the finalization queue // and prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } // Dispose(bool disposing) executes in two distinct scenarios. // If disposing equals true, the method has been called directly // or indirectly by a user's code. Managed and unmanaged resources // can be disposed. // If disposing equals false, the method has been called by the // runtime from inside the finalizer and you should not reference // other objects. Only unmanaged resources can be disposed. protected void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!this._disposed) { // If disposing equals true, dispose all managed // and unmanaged resources. if (disposing) { if (_dataReader != null) { _dataReader.Close(); } if (_command != null) { if (_command.Connection != null) { _command.Connection.Dispose(); _command.Connection = null; //Free the reference. } _command.Dispose(); } } // Call the appropriate methods to clean up // unmanaged resources here. // If disposing is false, // only the following code is executed. // Note disposing has been done. _disposed = true; } } // This finalizer will run only if the Dispose method // does not get called. // It gives your base class the opportunity to finalize. // Do not provide finalize methods in types derived from this class. ~ManagedDataReader() { // Do not re-create Dispose clean-up code here. // Calling Dispose(false) is optimal in terms of // readability and maintainability. Dispose(false); } } } My problem is that for some reason, sometimes i got exception when calling Read(): the exception is that my _dataReader member is null. That's weird, because i have try-catch block on its initialization, and no exception is caught (i use my loging mechanism to check this). This behavior is rare, but occures aprox. once a week (i'm running milions of queries per day) Thanks a lot to anyone who tries to solve this mistery!! A: I came up with the same problem. And it turned out that ExecuteReader () can actually return null in some cases. I looked up the code of the connector and this is what I found: catch (MySqlException ex) { ... // if we caught an exception because of a cancel, then just return null if (ex.IsQueryAborted) return null; Digging a little deeper turns out IsQueryAborted is true when the server returns MySqlErrorCode.QueryInterrupted or MySqlErrorCode.FileSortAborted. And so far it turns out that this is some server problem as at least in my case the problem is not consistent and looks like a multi-threading issue in the server code. A: I reviewed the code and I find the only way to get with NULL reader is to have an exception in the initialization code. As SqlDataReader.ExecuteReader is return an object in all cases and can't return null. Tatiana Racheva had confirmed that by reflection SqlDataReader class in this answer. The second scenario to have NULL reader is if you are trying to use the reader after your ManagedDataReader object is disposed by the garbage collector.
doc_23535692
struct Position { public int X { get; private set; } public int Y { get; private set; } // etc } I would like to add a method that allows me to create a modified copy of the struct with arbitrarily changed properties. For example, it would be convenient to use this: var position = new Position(5, 7); var newPos = position.With(X: position.X + 1); Is this idiom hacky? Are there better ways to support this? public Position With(int? X = null, int? Y = null) { return new Position(X ?? this.X, Y ?? this.Y); } Edit: in case it was unclear, the struct is immutable, I simply want to create a new value with some values modified. Incidentally, this is very similar to Haskell's syntactic sugar for records, where one would write newPos = oldPos { x = x oldPos + 1 }. This is just a bit experimental as to whether such an idiom is helpful in C#. A: Personally, I consider the idiom of a plain-old-data-struct to be vastly underrated. Mutable structs which encapsulate state in anything other than public fields are problematic, but sometimes it's useful to bind together a fixed collection of variables stuck together with duct tape so they can be passed around as a unit. A plain-old-data-struct is a perfect fit for that usage; it behaves like a fixed collection of variables stuck together with duct tape, since that's what it is. One can with some work come up with an immutable class which requires slow and hard-to-read code to do anything with, or with some more work come up with something that's still slow but not quite so unaesthetic; one can also code structures in such fashion as to mimic such classes. In many cases, however, the only effect of going through all that effort is that one's code will be slower and less clear than it would have been if one had simply used a PODS. The key thing that needs to be understood is that a PODS like struct PersonInfo { public string Name, SSN; public Date Birthdate; } does not represent a person. It represents a space that can hold two strings and a date. If one says var fredSmithInfo = myDatabase.GetPersonInfo("Fred Smith");, then FredSmithInfo.BirthDate doesn't represent Fred Smith's birthdate; it represents a variable of type Date which is initially loaded with the value returned by a call to GetPersonInfo--but like any other variable of type Date, could be changed to hold any other date. A: That's about as neat a way as you're going to get. Doesn't seem particularly hacky to me. Although in cases where you're just doing position.X + 1 it'd be neater to have something that was like: var position = new Position(5,7); var newPos = position.Add(new Position(1,0)); Which would give you a modified X value but not a modified Y value. A: One could consider this approach as a variant of the prototype pattern where the focus is on having a template struct rather than avoiding the cost of new instances. Whether the design is good or bad depends on your context. If you can make the message behind the syntax clear (I think the name With you're using is a bit unspecific; maybe something like CreateVariant or CreateMutant would make the intention clearer), I would consider it an appropriate approach. A: I'm adding an expression based form as well. Do note the horrendous boxing/unboxing which needs to be done due to the fact that it is a struct. But as one can see the format is quite nice: var p2 = p.With(t => t.X, 4); var p3 = p.With(t => t.Y, 7).With(t => t.X, 5); // Yeah, replace all the values :) And the method is really applicable to all kinds of types. public void Test() { var p = new Position(8, 3); var p2 = p.With(t => t.X, 4); var p3 = p.With(t => t.Y, 7).With(t => t.X, 5); Console.WriteLine(p); Console.WriteLine(p2); Console.WriteLine(p3); } public struct Position { public Position(int X, int Y) { this._X = X; this._Y = Y; } private int _X; private int _Y; public int X { get { return _X; } private set { _X = value; } } public int Y { get { return _Y; } private set { _Y = value; } } public Position With<T, P>(Expression<Func<Position, P>> propertyExpression, T value) { // Copy this var copy = (Position)this.MemberwiseClone(); // Get the expression, might be both MemberExpression and UnaryExpression var memExpr = propertyExpression.Body as MemberExpression ?? ((UnaryExpression)propertyExpression.Body).Operand as MemberExpression; if (memExpr == null) throw new Exception("Empty expression!"); // Get the propertyinfo, we need this one to set the value var propInfo = memExpr.Member as PropertyInfo; if (propInfo == null) throw new Exception("Not a valid expression!"); // Set the value via boxing and unboxing (mutable structs are evil :) ) object copyObj = copy; propInfo.SetValue(copyObj, value); // Since struct are passed by value we must box it copy = (Position)copyObj; // Return the copy return copy; } public override string ToString() { return string.Format("X:{0,4} Y:{1,4}", this.X, this.Y); } }
doc_23535693
But when i use any android device Chrome browser, the printing is either keep on stuck, or the results were printed as below. Can anyone help on this. A: We can only guess there. But I'd say bytes sent by your web bluetooth app varies enough so that the device understands it differently. Can you try sending less bytes at once and see how it reacts? Can you share your source code as well? You may want to look into your android device logs as well. See full instructions at https://www.chromium.org/developers/how-tos/file-web-bluetooth-bugs#:~:text=following%20these%C2%A0instructions.-,Android,-ADB%20logs adb logcat -v time | grep -E " |[Bb]luetooth|cr.Bluetooth|BtGatt|BluetoothGatt|bt_btif_config"
doc_23535694
<div> text1 <a>link_1</a> <a>link_2</a> text2 <a>link_3</a> text3 </div> I want to get all the nodes between text1 and text2. The problem is there is no p or span tag. There are only plain text with content is text1 and text2. How could I do this with XPATH? Thank you! A: How about this way : /div/* [ preceding-sibling::text()[normalize-space(.) = 'text1'] and following-sibling::text()[normalize-space(.) = 'text2'] ]
doc_23535695
In terminal "ll" works but from php system("ll") outputs sh: ll: command not found How do I exit "sh" and execute my terminal commands? P.S.: May be I missunderstood the basic linux components shell and bash. In this case, please correct me/the post A: The PHP docs aren't clear about this, but presumably PHP's system is a reflection of Standard C's system(3), which hands the argument command to the command interpreter sh(1). If you want to avoid the shell, you'll need to use another feature of PHP besides system (like explicit fork/exec). That's context, but it won't help you solve your problem. In your case it seems you just want the aliases in an rcfile. Scripts invoked by system calls aren't going to read your rcfile unless you take extraordinary steps to make that happen, and even if you do, it's going to be non-obvious to the maintenance programmer. I'd strongly advise you to put the alias in the script or command argument itself, or simply call the command explicitly (ls -al). You can also manually source the rcfile from your script, or call system(csh -i 'yourcommands') to force csh to be invoked as an interactive shell (which should cause your rcfile to be read). I think this is a bad idea because it is effectively forcing the shell to behave inconsistently with its environment, but I'm including it here for completeness. Most of the above I got from a quick read through the Startup and shutdown section of the csh manual on my Mac (Mavericks). There are other potential solutions there that I haven't laid out, as well.
doc_23535696
Docker Version: 1.0.0 Docker host: ubuntu 14.04 Here is the Dockerfile FROM ubuntu:latest ENV HOME /home/larry RUN useradd larry && echo 'larry:docker' | chpasswd RUN echo "larry ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers # arrange ssh key ADD larry.id_rsa $HOME/.ssh/id_rsa RUN \ chmod 700 $HOME/.ssh &&\ chmod 600 $HOME/.ssh/id_rsa RUN chown -R larry:larry $HOME After I build the image and run into container and su to user larry, I got $ id uid=1000(larry) gid=1000(larry) groups=1000(larry) $ ls -al total 12 drwxr-xr-x 5 larry larry 4096 Jun 21 01:29 . drwxr-xr-x 5 root root 4096 Jun 21 01:29 .. drwx------ 2 larry larry 4096 Jun 21 01:29 .ssh $ cd .ssh -su: cd: .ssh: Permission denied Maybe I missed some basic concept in docker ? Just wired from normal unix user point of view. I put this in github as well https://github.com/dotcloud/docker/issues/1295#issuecomment-46700769 A: You just met bug #6047 which basically says they are issues with chown when run after chmod. The following Dockerfile will work: FROM ubuntu:latest ENV HOME /home/larry RUN useradd larry && echo 'larry:docker' | chpasswd RUN echo "larry ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers # arrange ssh key ADD larry.id_rsa $HOME/.ssh/id_rsa RUN chown -R larry:larry $HOME RUN \ chmod 700 $HOME/.ssh &&\ chmod 600 $HOME/.ssh/id_rsa
doc_23535697
I am using MS SQL Server 2005, and the stored procedure is used as a query in SAP BI. I have this part: SET @cmd ='Update PriceList 5' SET @sql ='UPDATE a SET a.price= round( (b.price*0.9),0), a.currency=b.currency FROM ['+@trgDB+'].[dbo].[ITM1] a ' SET @sql =@sql+' INNER JOIN ['+@trgDB+'].[dbo].[ITM1] b ON ( a.ItemCode=b.itemcode AND b.PriceList=1) ' SET @sql =@sql+' WHERE a.PriceList=5 ' IF @filter IS NOT NULL BEGIN SET @sql =@sql+' AND a.[ItemCode] LIKE '+char(39)+@filter+'%'+char(39)+' ' SET @cmd = @cmd+' ('+@filter+'%'+') ' END This will update the price on every item acording to filter. I need to leave some items unchanged, so how can I add NOT LIKE 'VSK%' AND NOT LIKE 'VFH%' to the code above? It doesn't matter if the flter is left out, but then I need every price to be updated except NOT LIKE 'VSK%' AND NOT LIKE 'VFH%' . table http://qupload.com/images/clipbosjs.jpg
doc_23535698
But this is part of the code which is causing so much of delay in my project and want to optimize this. i want to know which code part is faulty and how could this be replaced. i guess,few can say that use of this function is heavy compared and other ligher method are available to do this work please help, thanks in advance for i in range(len(lists)): save=database_index[lists[i]] #print save #if save[1]!='text0194'and save[1]!='text0526': using_data[save[0]]=save p=os.path.join("c:/begpython/wavnk/",str(str(str(save[1]).replace('phone','text'))+'.pm')) x1=open(p , 'r') x2=open(p ,'r') for i in range(6): x1.readline() x2.readline() gen = (float(line.partition(' ')[0]) for line in x1) r= min(enumerate(gen), key=lambda x: abs(x[1] - float(save[4]))) #print r[0] a1=linecache.getline(str(str(p).replace('.pm','.mcep')), (r[0]+1)) #print a1 p1=str(str(a1).rstrip('\n')).split(' ') #print p1 join_cost_index_end[save[0]]=p1 #print join_cost_index_end gen = (float(line.partition(' ')[0]) for line in x2) r= min(enumerate(gen), key=lambda x: abs(x[1] - float(save[3]))) #print r[0] a2=linecache.getline(str(str(p).replace('.pm','.mcep')), (r[0]+1)) #print a2 p2=str(str(a2).rstrip('\n')).split(' ') #print p2 join_cost_index_strt[save[0]]=p2 #print join_cost_index_strt j=j+1 #print j #print join_cost_index_end #print join_cost_index_strt enter code here here my database_index has about 2,50,000 entries` A: def get_list(file, cmp, fout): ind, _ = min(enumerate(file), key=lambda x: abs(x[1] - cmp)) return fout[ind].rstrip('\n').split(' ') root = r'c:\begpython\wavnk' header = 6 for lst in lists: save = database_index[lst] index, base, _, abs2, abs1, *_ = save using_data[index] = save base = os.path.join(root, base.replace('phone', 'text')) fin, fout = base + '.pm', base + '.mcep' file = open(fin) fout = open(fout).readlines() [next(file) for _ in range(header)] file = [float(line.partition(' ')[0]) for line in file] join_cost_index_end[index] = get_list(file, float(abs1), fout) join_cost_index_strt[index] = get_list(file, float(abs2), fout) Don't: * *convert string to string multiple times, it'll remain a string *convert value within loop when it could be done outside the loop *use single-letter for meaning variables *iterate over sequences with range(len(sequence)) *copy-paste bits of code: use functions *use any code without reading docs first *rely on SO for psychic debugging. A: x1=open(p , 'r') x2=open(p ,'r') Why open the same file twice? Are you expecting it to change?
doc_23535699
"SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '* FROM auction WHERE etime < ?' at line 1 " My understanding of this is usually I have spelt something wrong where it says the error is occurring. However, in the following script, there is no "* FROM auction WHERE etime < ?" on line 1 of my page. Further it occurs only 3 times in the page - at line 19, 26 and 288. I've checked all these locations for a syntax blunder around it and it looks proper. So I have no idea why this is being thrown, I want it to go away. The page is rather large, bear with me: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <?php session_start(); $url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; $_SESSION['lasturl'] = $url; include("connect.php"); $pdo = connect(); $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); try{ $old = time() - (60*24*60*60); $stmt15 = $pdo->prepare("DELETE * FROM auction WHERE etime < :time"); $stmt15->bindParam(":time", $old, PDO::PARAM_INT); $stmt15->execute(); $time = time(); $stmt8 = $pdo->prepare("SELECT * FROM auction WHERE etime < :time AND closed < 1"); $stmt8->bindParam(":time", $time, PDO::PARAM_INT); $stmt8->execute(); while($row = $stmt8->fetch(PDO::FETCH_ASSOC)){ $id = $row['ID']; $holder = $row['holder']; $owner = $row['owner']; $stmt5 = $pdo->prepare("UPDATE auction SET closed = 50 WHERE ID = :id"); $stmt5->bindParam(":id", $id, PDO::PARAM_INT); $stmt5->execute(); $stmt3 = $pdo->prepare("SELECT * FROM user WHERE username = :holder"); $stmt3->bindParam(":holder", $holder, PDO::PARAM_STR); $stmt3->execute(); $row2 = $stmt3->fetch(PDO::FETCH_ASSOC); $fbtokenh = $row2['fbtoken']; $fbtokenh++; $stmt4 = $pdo->prepare("UPDATE user WHERE username = :holder SET fbtoken = :fbtoken"); $stmt4->bindParam(":holder", $holder, PDO::PARMA_STR); $stmt4->bindParam(":fbtoken", $fbtokenh, PDO::PARAM_INT); $stmt4->execute(); $stmt6 = $pdo->prepare("SELECT * FROM user WHERE username = :owner"); $stmt6->bindParam(":owner", $owner, PDO::PARAM_STR); $stmt6->execute(); $row3 = $stmt6->fetch(PDO::FETCH_ASSOC); $fbtokeno = $row2['fbtoken']; $fbtokeno++; $stmt7 = $pdo->prepare("UPDATE user WHERE username = :owner SET fbtoken = :fbtoken"); $stmt7->bindParam(":owner", $owner, PDO::PARAM_STR); $stmt7->bindParam(":fbtoken", $fbtokeno, PDO::PARAM_INT); $stmt7->execute(); } }catch(PDOException $e){ echo $e->getMessage(); } if(isset($_GET['searchbox'])){ $search = $_GET['searchbox']; } ?> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Trade diving equipment online at DiveBay</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="js/jquery.countdown.css" /> <script type="text/javascript" src="js/jquery.countdown.js"></script> <script src="js/menuscript.js" language="javascript" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="css/menustyle.css" media="screen, print" /> <link rel="stylesheet" type="text/css" href="css/searching.css" /> </head> <body> <center> <div id="wrapper"> <div id="header"> <div id="hbackground"> <img src="db3.jpg" alt="hbackground" width="100%" height="100%" style="z-index:1;" /> <div id="htitle"> <span id="banner">DIVEBAY.COM</span> <span id="byline">SEARCHING FOR STUFF ONLINE</span> <table border="0" cellpadding="0" cellspacing="0" style="float:right; background-color:transparent;"> <tr> <td> <a href="search.php" onmouseover="setOverImg('1','');" onmouseout="setOutImg('1','');" target=""><img src="buttons/button1up.png" border="0" id="button1" vspace="1" hspace="1"></a><br> <a href="sellanitem.php" onmouseover="setOverImg('2','');" onmouseout="setOutImg('2','');" target=""><img src="buttons/button2up.png" border="0" id="button2" vspace="1" hspace="1"></a><br> <a href="forum.php" onmouseover="setOverImg('3','');" onmouseout="setOutImg('3','');" target=""><img src="buttons/button3up.png" border="0" id="button3" vspace="1" hspace="1"></a><br> <a href="myaccount.php" onmouseover="setOverImg('4','');" onmouseout="setOutImg('4','');" target=""><img src="buttons/button4up.png" border="0" id="button4" vspace="1" hspace="1"></a><br> <a href="support.php" onmouseover="setOverImg('5','');" onmouseout="setOutImg('5','');" target=""><img src="buttons/button5up.png" border="0" id="button5" vspace="1" hspace="1"></a><br> <?php if(isset($_SESSION['loggedin'])){ ?> <a href="logout.php" onmouseover="setOverImg('7','');" onmouseout="setOutImg('7','');" target=""><img src="buttons/button7up.png" border="0" id="button7" vspace="1" hspace="1"></a><br> <?php }else{ ?> <a href="login_to_divebay.php" onmouseover="setOverImg('6','');" onmouseout="setOutImg('6','');" target=""><img src="buttons/button6up.png" border="0" id="button6" vspace="1" hspace="1"></a><br> <?php } ?> </td> </tr> </table> </div> </div> </div> <div id="searchandlog"> <div id="search"> <form id="searchdivebay" action="search.php" method="get"> <div id="searchboxholder"><input type="text" name="searchbox" id="searchbox" /></div> <div id="searchbuttonholder"><input type="submit" name="searchbutton" id="searchbutton" value="Search DiveBay"/></div> <input type="hidden" id="submit" name="submit" value="1"/> </form> </div> <div id="login"> <?php if(isset($_SESSION['loggedin'])){ echo '<span class="price1">Logged in as:</span>&nbsp;<span class="sessionset">'.$_SESSION['username'].'</span>'; } else{ echo '<ul class="signreg"> <li><i>Existing user?</i><a href="login_to_divebay.php">SIGN IN</a></li> <li><i>or, new?</i><a href="createacct.php">REGISTER</a></li> </ul>'; } ?> </div> </div> <?php if(isset($_POST['searchbox'])){ if($search == ""){ ?> <p style="color:black; font-size:18pt; font-family: Impact; "> You didn"t search for anything!</p> <?php }else{ try{ $time = time(); $stmt12 = $pdo->prepare('SELECT * FROM auction WHERE name LIKE :name'); $stmt12->bindParam(':name', '%'. trim($search) .'%',PDO::PARAM_STR); $stmt12->execute(); $numrows = 0; ?> <div id="searchresults"><span style="font-style:italic; font-size: 14pt; font-family:Impact;">Search results for: </span>&nbsp<span id="searchword"><?php echo $search; ?></span></div> <div id="content"> <table id="displaying" class="displayer"> <?php while($row = $stmt12->fetch(PDO::FETCH_ASSOC)){ $numrows++; $ID = $row['ID']; $img = $row['img']; $desc = $row['description']; $name = $row['name']; $owner = $row['owner']; $cprice = $row['sprice']; $iprice = $row['iprice']; $incprice = $row['incprice']; $etime = $row['etime']; $nextBid = $cprice + $incprice; $stmt21 = $pdo->prepare("SELECT * FROM user WHERE username = :username"); $stmt21->bindParam(":username", $owner,PDO::PARAM_STR); $stmt21->execute(); $thisuser = $stmt21->fetch(PDO::FETCH_ASSOC); $location = $thisuser['location']; echo' <tr class="resultindex"> <td class="imgCol"><a href="displayAuct.php?id='.$ID.'"><img src="'.$img.'" alt="'.$name.'" /></a></td> <td class="infoCol"> <div class="nameDiv"> <a class="nameLink" href="displayAuct.php?id='.$ID.'">'.$name.'</a><br/> </div> <div class="descDiv"> <span class="priceLabel2">'.$desc.'</span> </div> <div class="userdiv"> <span class="fromuser">Location: </span><br/> <span class="location">'.$location.'</span> </div> </td> <td style="width:1px; background-color:#330066;" ></td> <td class="priceCol"> <div class="currentp"><span class="priceLabel">Current Bid: </span><br/><span class="price1">$'.$cprice.'</span></div> <div class="instantp"><span class="priceLabel2">Instant Sale: </span><br/><span class="price2">$'.$iprice.'</span></div> <div style="height:5px;"></div> <div class="incp"><span class="priceLabel2">Next Bid:</span><br/><span class="price2">$'.$nextBid.'</span></div> </td> <td style="width:1px; background-color:#330066;"></td> <td class="timerCol"> <div id="timeRow"> <span class="timeleft">Time Left: </span> </div> <div id="countdownRow"></div> <script type=text/javascript> var timestamp = '. $etime * 1000 .'; var endTime = new Date(); endTime.setTime(timestamp); $("#countdownRow").countdown({until: endTime}); </script> </td> </tr> '; } if($numrows == 0){ ?> <tr> <td colspan="6"><span class="price1">Sorry your search returned no results</span></td> </tr> <?php } else{ ?> <tr> <td colspan="6"><span class="price1">Displaying <?php echo $numrows; ?> results</span></td> </tr> <?php $pdo = null; } }catch(PDOException $e){ echo $e->getMessage(); } } ?> </table> </div> <?php }else{ ?> <div id="searchresults"><span style="font-style:italic; font-size: 14pt; font-family:Impact;">Hurry, these auctions dont have long left!:</span></div> <div id="content"> <table id="displaying" class="displayer"> <?php try{ $time = time(); $in15 = time() + 900; $stmt55 = $pdo->prepare('SELECT * FROM auction WHERE etime < :etime AND etime > :time ORDER BY etime'); $stmt55->bindParam(':etime', $in15, PDO::PARAM_INT); $stmt55->bindParam(':time', $time, PDO::PARAM_INT); $stmt55->execute(); while($row = $stmt55->fetch(PDO::FETCH_ASSOC)){ $ID = $row['ID']; $img = $row['img']; $desc = $row['description']; $name = $row['name']; $owner = $row['owner']; $cprice = $row['sprice']; $iprice = $row['iprice']; $incprice = $row['incprice']; $etime = $row['etime']; $nextBid = $cprice + $incprice; $stmt23 = $pdo->prepare("SELECT * FROM user WHERE username = :username"); $stmt23->bindParam(":username", $owner,PDO::PARAM_STR); $stmt23->execute(); $thisuser = $stmt23->fetch(PDO::FETCH_ASSOC); $location = $thisuser['location']; echo' <tr class="resultindex"> <td class="imgCol"><a href="displayAuct.php?id='.$ID.'"><img src="'.$img.'" alt="'.$name.'" /></a></td> <td class="infoCol"> <div class="nameDiv"> <a class="nameLink" href="displayAuct.php?id='.$ID.'">'.$name.'</a><br/> </div> <div class="descDiv"> <span class="priceLabel2">'.$desc.'</span> </div> <div class="userdiv"> <span class="fromuser">Location: </span><br/> <span class="location">'.$location.'</span> </div> </td> <td style="width:1px; background-color:#330066;" ></td> <td class="priceCol"> <div class="currentp"><span class="priceLabel">Current Bid: </span><br/><span class="price1">$'.$cprice.'</span></div> <div class="instantp"><span class="priceLabel2">Instant Sale: </span><br/><span class="price2">$'.$iprice.'</span></div> <div style="height:5px;"></div> <div class="incp"><span class="priceLabel2">Next Bid:</span><br/><span class="price2">$'.$nextBid.'</span></div> </td> <td style="width:1px; background-color:#330066;"></td> <td class="timerCol"> <div id="timeRow"> <span class="timeleft">Time Left: </span> </div> <div id="countdownRow"></div> <script type=text/javascript> var timestamp = '. $etime * 1000 .'; var endTime = new Date(); endTime.setTime(timestamp); $("#countdownRow").countdown({until: endTime}); </script> </td> </tr> '; } $pdo = null; }catch(PDOException $e){ echo $e->getMessage(); } } ?> </table> </div> <div id="sitemap"> </div> </div> </center> </body> </html> A: Your SQL is slightly off, you have an extra * in your DELETE. It would make no sense to give a column list, since DELETE always deletes a whole row; DELETE * FROM auction WHERE etime < :time should be DELETE FROM auction WHERE etime < :time A: I'm being thrown an error You are not. In fact, you are being thrown a way more informative error message, including the exact spot where the error occurred. But for some reason you are using the code that strips all the useful info down, throwing naked error message at you. can't find source If you get rid of these try and catch operators, you will make yourself quite informed of the exact query where error occurred.