text
stringlengths
64
81.1k
meta
dict
Q: Do I have to do anything special if I want to connect to a chip with SWD and SWDIO and nRESET are on the same pin? I want to wire a MDBT40-256RV3 to a SWD programmer and on the programmer nRESET and SWDIO are on separate pins but on this chip they share the same pin, so how should I wire that? A: Just wire SWD and SWDIO, leave nReset open. This chip (NRF51xxxx) simply has no dedicated reset pin to connect to.
{ "pile_set_name": "StackExchange" }
Q: Is there a way/workaround to have the slot principle in hyperHTML without using Shadow DOM? I like the simplicity of hyperHtml and lit-html that use 'Tagged Template Literals' to only update the 'variable parts' of the template. Simple javascript and no need for virtual DOM code and the recommended immutable state. I would like to try using custom elements with hyperHtml as simple as possible with support of the <slot/> principle in the templates, but without Shadow DOM. If I understand it right, slots are only possible with Shadow DOM? Is there a way or workaround to have the <slot/> principle in hyperHTML without using Shadow DOM? <my-popup> <h1>Title</h1> <my-button>Close<my-button> </my-popup> Although there are benefits, some reasons I prefer not to use Shadow DOM: I want to see if I can convert my existing SPA: all required CSS styling lives now in SASS files and is compiled to 1 CSS file. Using global CSS inside Shadow DOM components is not easily possible and I prefer not to unravel the SASS (now) Shadow DOM has some performance cost I don't want the large Shadow DOM polyfill to have slots (webcomponents-lite.js: 84KB - unminified) A: Let me start describing what are slots and what problem these solve. Just Parked Data Having slots in your layout is the HTML attempt to let you park some data within the layout, and address it later on through JavaScript. You don't even need Shadow DOM to use slots, you just need a template with named slots that will put values in place. <user-data> <img src="..." slot="avatar"> <span slot="nick-name">...</span> <span slot="full-name">...</span> </user-data> Can you spot the difference between that component and the following JavaScript ? const userData = { avatar: '...', nickName: '...', fullName: '...' }; In other words, with a function like the following one we can already convert slots into useful data addressed by properties. function slotsAsData(parent) { const data = {}; parent.querySelectorAll('[slot]').forEach(el => { // convert 'nick-name' into 'nickName' for easy JS access // set the *DOM node* as data property value data[el.getAttribute('slot').replace( /-(\w)/g, ($0, $1) => $1.toUpperCase()) ] = el; // <- this is a DOM node, not a string ;-) }); return data; } Slots as hyperHTML interpolations Now that we have a way to address slots, all we need is a way to place these inside our layout. Theoretically, we don't need Custom Elements to make it possible. document.querySelectorAll('user-data').forEach(el => { // retrieve slots as data const data = slotsAsData(el); // place data within a more complex template hyperHTML.bind(el)` <div class="user"> <div class="avatar"> ${data.avatar} </div> ${data.nickName} ${data.fullName} </div>`; }); However, if we'd like to use Shadow DOM to keep styles and node safe from undesired page / 3rd parts pollution, we can do it as shown in this Code Pen example based on Custom Elements. As you can see, the only needed API is the attachShadow one and there is a super lightweight polyfill for just that that weights 1.6K min-zipped. Last, but not least, you could use slots inside hyperHTML template literals and let the browser do the transformation, but that would need heavier polyfills and I would not recommend it in production, specially when there are better and lighter alternatives as shown in here. I hope this answer helped you.
{ "pile_set_name": "StackExchange" }
Q: getting response on console without response on agent.add() I'm trying to send email to someone. I print the success message in the console and my code work well and send the email successfully, but when I print it in the agent as a message it show not available before the response. Here is my code: function sendEmail(agent){ //get email and name and message and subject console.log("Email befor getting: " +fetchedEmail); getEmail(agent.parameters.name).then(function(){ console.log("the email is fetched: "+fetchedEmail); const nodemailer = require('nodemailer'); const transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: '*********@gmail.com', pass: '*******************' } }); var mailOptions = { from: '*******@gmail.com', to: fetchedEmail, //receiver email subject: agent.parameters.subject, text: agent.parameters.message }; return createMessage(mailOptions,transporter).then(()=>{ console.log("email sent successfully");//this message printed on console agent.add(`email sent successfully`);// this not printed in agent }).catch(()=>{ agent.add(`fail`); }); }); }// end of send email function createMessage(mailOptions,transporter){ return new Promise((resolve,reject)=>{ // i promise to send email transporter.sendMail(mailOptions, function (error, info) { if (error) { console.log("there is error"); reject(error); } else { console.log("success");// printed on console resolve('Email sent: ' + info.response); } }); }); }//end of create message //--- A: The issue is that you are doing asynchronous functions (your calls to getEmail() and createMessage()) using Promises, but you aren't returning a Promise from sendEmail() itself. The Dialogflow library requires that, if you're doing async functions, you return a Promise so the Intent Handler dispatcher knows that you are doing async functions. In your case, the easiest way to do this is to just return the Promise from the getEmail().then() chain. So changing the line like this should work: return getEmail(agent.parameters.name).then(function(){
{ "pile_set_name": "StackExchange" }
Q: NSOpenPanel reopening after selection Some users are reporting that they cannot select files in my sandboxed app because when they select and item it reopens. Nowhere in my code am I reopening the panel so I'm a bit confused as to why this would be happening. One of my users said that the following message was logged in console a number of times: "Keychain sandbox consume extension error: s=-1 p= cannot allocate memory" I've asked them to run first aid on their keychain, and repair their disk permissions but that hasn't helped. Does anyone have any ideas what could be causing this? Thank you! Here is the code that triggers the NSOpenPanel: - (IBAction)selectHomeDirectory:(id)sender { NSOpenPanel *openPanel = [NSOpenPanel openPanel]; [openPanel setTitle:@"Select your home folder"]; [openPanel setMessage:@"Select your home folder..."]; [openPanel setPrompt:@"Choose"]; [openPanel setCanCreateDirectories:NO]; [openPanel setCanChooseFiles:NO]; [openPanel setCanChooseDirectories:YES]; [openPanel setExtensionHidden:YES]; [openPanel setAllowedFileTypes:nil]; [openPanel setAllowsMultipleSelection:NO]; [openPanel setDelegate:self]; [openPanel setDirectoryURL:[NSURL fileURLWithPath:@"/Users/"]]; [openPanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result) { if(result != NSOKButton || !openPanel.URL){ return; } /* Saves the scoped URL, and then triggers a view change */ }]; } A: This turned out to be a Mavericks issue that was fixed in the later seeds.
{ "pile_set_name": "StackExchange" }
Q: About lambda syntax I was examining JDK 8 APIs and inside Function interface I noticed identity function static <T> Function<T, T> identity() { return t -> t; } This resolves to method: R apply(T t); declared in the same Function interface. Question is why t -> t part works. If we expand this expression in terms of familiar Anonymous Inner Class new Function<String, String>() { @Override String apply(String t) { t; // Oops, compilation error } } Is t -> t kind of shortcut of t -> { return t; }? A: Question is why t -> t part works. Because a lambda expression can return the value it takes as parameter. The return is implied in the right part from the target type of the lambda expression. The expression is essentially same as: t -> { return t; } That means that t -> t would fail for a functional interface with method that has void return type, as in below case: Consumer<String> consumer = t -> t; The target type of lambda there is Consumer<T>, which has the method - void accept(T t) in it. Since the method has void return type, the above assignment fails. You can go through State of the Lambda for more insight.
{ "pile_set_name": "StackExchange" }
Q: Can I add a music library to the Xcode iOS Simulator? I'm trying to create a music player for iPhone and iPad. I get it working perfectly on my iPhone and iPad because those actually have a music library. However I want to use fastlane and some other tools with tests so I need to be able to see/add a music library to my simulator as well. I've navigated to my emulator folder. /Users/maikohermans/Library/Developer/CoreSimulator/Devices/8A14CCDB../Data However I have no clue where to look and if I even should look here to add the music. I hope someone can help me out here on how to do this. I've searched this but it seems like nobody asked this question for quite some time. So that means either everyone has given up on it or it is possible and I just can't seem to figure out how to do this. A: Although the regular believe is that this can't be done I figured out how to do it thanks to the link @BaSha mentioned. I wrote a little How To on it so everyone who faces the same problem or thinks it isn't possible will be able to get it working. To give the gist of it you will need a few things. A iOS device that actually has music on it iFunBox or something similar The id of the simulator you want to use To get the id of the device you want to test on you can run xcrun simctl list This will give you a list of all the available simulators, pick the one you want to use and copy the id, you will need this. Now navigate to the directory of the simulator you just chose. [yourHD] -> Users -> [yourusername] -> Library -> Developer -> CoreSimulator -> Devices -> [the ID you obtained in the previous step] -> data -> Media -> Itunes_Control -> Itunes Now you have to open iFunBox (connect your phone with music library to your pc). In iFunBox, select Raw File System. In this you will find a directory called Itunes_Connect from that directory you need to copy some files and directories to the simulator directory you opened before. namely: Music iTunes/Artwork iTunes/MediaLibrary.sqlitedb iTunes/MediaLibrary.sqlitedb-shm iTunes/MediaLibrary.sqlitedb-wal If you ever bought music you should also grab the following directory Raw File System/Purchases
{ "pile_set_name": "StackExchange" }
Q: Laravel полиморфные отношения Непростая задача, которую я не могу решить. Никак не пойму, как устроено все это. Есть 3 таблицы: Users, Filials, Specs Юзеры, филиалы и специальности. Каждый юзер закреплен за филиалом, и у каждого юзера есть специальность. Таблица Users `id` `name` - имена юзеров `filial_id` `spec_id` Из этого выходит, что я могу в конкретном филиале выбрать всех юзеров. В конкретной профессии всех юзеров . И также наоборот. Но у всех профессий (таблица Specs) есть уровень доступа. Таблица Specs `id` `name` - название профессии `lvl` - уровень доступа профессии Так вот у меня идет цикл перечисления всех филиалов: выводится имя филиала и юзеры с уровнем 2. Сейчас в моделе Filials я просто обращаюсь ко всем юзерам public function users() { return $this->hasMany('App\User'); } Но мне нужны только уровня специальности 2. Назначать каждому юзеру свой уровень не годится, должен именно быть у профессии уровень. Как решить мне данную проблему без цикла в цикле? Я читал, что полиморфно как-то можно, но как я не пойму. A: Во-первых, модели рекомендовано именовать в единственном числе: Filial, User, Spec. Далее, в модели User надо сделать следующее: public function spec() { return $this->belongsTo(Spec::class); } В модели Filial: public function users() { return $this->hasMany(User::class)->whereHas('spec', function($q){ // Указываем с каким уровнем доступа выбирать $q->where('lvl', 2); }); } UPD. Ссылки на соглашение об именовании: официальная документация, гитхаб
{ "pile_set_name": "StackExchange" }
Q: JPG image size reduced on imsave I am building up a library called hips where one module is involved with fetching tile images and storing them on disk. The problem here is that I fetch a tile from a remote URL and save it using scipy.misc.imsave function in a temporary directory. The saved file size is 41.0 kB, however, if I save the file manually from the remote URL, its size is 119.7 kB. I have copied the failed test case below: def test_fetch_read_write_jpg(self, tmpdir): meta = HipsTileMeta( ... ) url = 'http://alasky.unistra.fr/2MASS/H/Norder6/Dir30000/Npix30889.jpg' tile = HipsTile.fetch(meta, url) filename = str(tmpdir / 'Npix30889.jpg') tile.write(filename) tile2 = HipsTile.read(meta, filename=filename) print(tile.data.shape) print(tile2.data.shape) assert tile == tile2 Here is the failed assertion: ----------------------------------Captured stdout call-------------------------------------- (512, 512, 3) (512, 512, 3) False The code involved with tile storing is shown below: from scipy.misc import imsave def write(self, filename: str = None) -> None: path = Path(filename) if filename else self.meta.full_path imsave(str(path), self.data) I also tried saving the file using PIL.Image library, using this code: from PIL import Image image = Image.fromarray(self.data) image.save(str(path)) But, it produces the same results. I tried printing out the tile data at index [0][0] which came to be [10, 10, 10] for both cases. Also, I displayed the image using matplotlib, and the results were identical. But, I can't figure out the reason for the reduction in size / quality. A: JPEG is a lossy format. If you write an image to a JPEG file and then read it back, you won't, in general, get back the same data. For lossless image storage, you could use PNG.
{ "pile_set_name": "StackExchange" }
Q: Saving related records without saving the referenced record first I'm not sure how to explain this so I am going to try do it as clearly as I can. We have a case logging web app. When one adds a case ticket, one can add contacts and attachments to that ticket. I am trying to find a way for the visitor to fill in the case ticket information, add n contacts and then n attacheents before having to push save. The attachments and contacts are linked to the ticket table and so will need to know the tickets Id in order to insert the correct reference Id. What are the different solutions that can be implemented? A: One option is to introduce linking tables; so instead of: contact ticket ------- ------ PK id PK id <---------------------- FK ticketid you could have: ticket ticket_contact ------ -------------- contact PK id <----- FK ticketid ------- FK contactid ---> PK id Now you can save contact records before ticket (or ticket first) - and just add in the linking records when you have both. This also allows you to re-use contact in scenarios unrelated to ticket. Another (simpler) option is just to make the FK nullable... that might be OK I guess.
{ "pile_set_name": "StackExchange" }
Q: Multiplatform GLSL shader validator? Im working on a multiplatform (Pc,Mac,Linux) game that uses shaders quite extensively. Since we do not have any funding, it is pretty hard to test our game on all possible hardware configurations. While our engine seems to run fine on different platforms, its usually the slight differences in GLSL compiling that gives us headaches. We have things set up such that we can test the shaders on Ati/Nvidia cards, but since the new Macbooks have Intel graphics, I'm really looking for a tool that can simply validate my GLSL shaders for different hardware without the need of yet another system. Does anyone know such a tool? A: Khronos provides a reference GLSL compiler. It is capable of validating GLSL up to version 3.50 (full support) and up to 4.50 (partial support). It also handles ESSL (OpenGL ES's GLSL). The tool verifies that the shader conforms to the GLSL specification. This does not necessarily guarantee that it works with all drivers but it does guarantee that the shader will work with any compliant driver. This is a much stricter guarantee than merely checking the shader against a specific driver. The tool does not validate that the results of the GLSL are what you expect. In particular, there are perfectly valid GLSL sequences that have weakly specified behavior. That can result in a perfectly valid shader having quite different output on different fully-conforming implementations. A buggy driver may reject or miscompile compliant GLSL. There's no proof against that but - thankfully - it's increasingly rare as Khronos' conformance test suite has become more complete. The standalone Khronos reference GLSL compiler is easy enough to integrate into a build system to validate stand-alone GLSL files. More intricate systems that load GLSL out of specialized container format or stitch GLSL together from other sources can use the library interface to validate things. A: The GLSL specification defines how the language works. If you write a shader that conforms to that specification, and it does not work on a particular OpenGL implementation, then that OpenGL implementation has a bug in it. Which means that you are effectively asking for a tool that can reproduce the bugs in Apple's Intel drivers. That is pretty much impossible. To do that, someone would have to have a list of every bug for every driver revision in Apple's Intel graphics drivers. Even if someone tried to get a list of those bugs and wrote a parser that reproduced them, that wouldn't guarantee you anything, since there could always be new bugs introduced. Or the "validator" could have implemented those bugs incorrectly. The best you can hope for would be a shader validator that could tell if your GLSL shader conformed to the specification. But that's about it.
{ "pile_set_name": "StackExchange" }
Q: Why non surjective polynomial map between $A^n$ and $A^m$ demand image closed algebraic set? Let $f_i\in C[x_1,\dots, x_n]$ with $i\leq m$. Suppose $f_i$ are algebraically independent functions. Consider the map $\phi:A^n\to A^m$ by $\phi(x_1,\dots, x_n)=(f_i(x_1,\dots, x_n))_i$. Suppose $\phi$ is non surjection. Then $Im(\phi)$ is closed algebraic subset of $A^n$. $\textbf{Q:}$ Why is $Im(\phi)$ a closed subset if $\phi$ is not surjection? I could imagine $A^2\to A^2$ by $(x,y)\to (x,xy)$. Clearly $x,xy$ are algebraically independent. Furhtermore, the map is not surjection as part of $x=0$ axis is missing. It is worse that the image is not closed algebraic set. Have I misunderstood the statement? Context: The book tries to explain $f_i$ algebraic independence/essential parameters is equivalent to surjectivity of the map $\phi$ above. Ref. Beltrametti M.C., et al. - Lectures on curves, surfaces and projective varieties Sec 3.2 of Chpt 3, Pg 62 A: This is just an error in the text. You are correct that the image of $\varphi$ need not be closed. The result being proved (that $\varphi$ is surjective iff the $f_i$ are algebraically independent) is simply wrong, as your example also shows. The correct statement is that $\varphi$ is dominant (has dense image) iff the $f_i$ are algebraically independent.
{ "pile_set_name": "StackExchange" }
Q: Django how to update object with multiple fields which is already saved in Database I'm trying to create a logic in Django which checks if User had already provided certain information. If not then it creates new object and save in the databse. And information was already there then it updates the same object with the new information. I'm making some mistake because it is able to create a new object but not updating it. try: # Check if user already have data available data_created_or_not = UserUsageInfo.objects.get(user_id=request.user.id).data_available_or_not except Exception: # If not available than, make it false data_created_or_not = False if not data_created_or_not: # If its False then create new object UserUsageInfo.objects.create(user=request.user, space_used=used_space, space_allocated=allocated_space, folders_list=folders, files_list=files, files_hash_list=files_hash, data_available_or_not=True ) else: # If already there then update it UserUsageInfo.objects.update(user=request.user, space_used=used_space, space_allocated=allocated_space, folders_list=folders, files_list=files, files_hash_list=files_hash, data_available_or_not=True ) A: You can use QuerySet.update_or_create for this: UserUsageInfo.objects.update_or_create(user_id=request.user.id, data_available_or_not=True, defaults={ 'user': request.user, 'space_used': used_space, 'space_allocated': allocated_space, 'folders_list': folders, 'files_list': files, 'files_hash_list': files_hash, }) So here we use user_id=request.user.id as filter as well as data_available_or_not=True. In case that exists, we update with defaults, otherwise we create a new object with user_id=request.user.id, data_available_or_not=True, and all the defaults. Given the database engine you use supports this operation, this can result in a single query. If not, Django can emulate it (of course then it will cost multiple queries).
{ "pile_set_name": "StackExchange" }
Q: New iPad camera button I am trying to draw a button in my iOS app which would look exactly like a button in camera App of the new iPad (like on this image) Since I don't have the new iPad, I can't check it by my own. But what I want to know is, how does this button look like if the background is dark, and if it is some complicated image behind, not just smooth blurred single color as on their screenshot. If somebody has the screenshots of camera app when background is not so ideal, I would appreciate if you share them. Or maybe somebody has values of colors, gradients, sizes, which are used in this button, then it would also be great to see. Thank you. A: It's a semi-transparent image. Here's two quick grabs. Noisy background: Black background: These images were takes from a third generation iPad running iOS 5.1 (9B176)
{ "pile_set_name": "StackExchange" }
Q: How to display formatted output with Write-Host I'm little confused about how PowerShell handles the format of the objects when they displayed with Write-Host vs. Write-Output vs. directly calling the object. I need to use Write-Host, because Write-Output breaks my code when I call it in functions. But when I used Write-Host, displayed data is not what I expected. I wanted to see my object like in when I directly called it (Write-Host is also the same). PS> $files = GetChildItem C:\ PS> $files # Or Write-Output $files PS> Write-Host $files PS> Write-Host $files |Format-Table PS> $files | Format-Table | Write-Host A: Out-String will convert the table format to a string. As pointed out by Nick Daniels $files | Format-Table | Out-String|% {Write-Host $_}
{ "pile_set_name": "StackExchange" }
Q: Recursively count the number of bits required to represent a number Hallo :) i wanna count the Binary numbers, with this Method private static int helper ( int c,int zaehler){ if (c>>1 == 1){ return zaehler + 2; }else{ return helper(c>>1,zaehler++); } A: So you want to recursively count the number of bits required to represent a number (i.e. log2)? class Foo { private static int helper (int c, int zaehler){ if (c == 0) { // Base case, c = 0 so no more bits to count return zaehler; } else { // c >>> 1 is the number without the LSB (assuming Java) return helper(c >>> 1, zaehler + 1); } } public static void main(String[] args) { System.out.println(helper(Integer.parseInt(args[0]), 1)); } } Here are examples showing that it works: $ java Foo 5 # 5 = 101 3 $ java Foo 15 # 15 = 1111 4 $ java Foo 16 # 16 = 10000 5
{ "pile_set_name": "StackExchange" }
Q: What level of compliance do I need as a software vendor? I am having a bit a difficult time trying to assess to what level my business needs to be PCI compliant. My business is developing eCommerce websites that are hosted by the client. The websites have an iFrame on the checkout which links to the payment gateway application that takes and processes the payment information. This payment gateway application is also developed by my business and handed over to the client who is hosting it on a PCI compliant server that my business does not have access to. As my business is only providing software development services I was always under the impression that we don't need to be PCI compliant. However, my clients believe that I am falling under SAQ D. I went through SAQ D but as my business is not in charge of hosting any of the applications I am struggling to fill in the questionnaire. Does my business require PCI compliance? And if yes, what is the correct questionnaire? Any help is appreciated! A: Edit: This actually is unlikely to be correct. See dave_thompson_085's answer about the PA-DSS instead. Original answer: Unfortunately, you do need to be PCI compliant, as a SAQ-D Service Provider. Here is a link to the official PCI Quick Reference guide. Some quotes: The standards apply to all entities that store, process or transmit cardholder data – with requirements for software developers and manufacturers of applications and devices used in those transactions. [page 6] The PA-DSS is for software vendors and others who develop payment applications that store, process or transmit cardholder data and/or sensitive authentication data as part of authorization or settlement, when these applications are sold, distributed or licensed to third parties. Most card brands encourage merchants to use payment applications that are tested and approved by the PCI SSC. [page 7] Think of it this way: If your network gets compromised, no one gets cardholder data. But a vulnerability could be inserted into your application without you being aware, which would then be distributed to all your clients. (This is known as a supply chain attack.) This page even explicitly calls it out: However, not all organizations recognize their role as a service provider, and this lack of awareness puts their business—and their customers’ businesses—at risk. The last part of the service provider definition (“also includes companies that provide services that control or could impact the security of cardholder data”) is what often causes confusion. If a company offers, for example, a managed network firewall, and their customer uses that firewall to protect their point of sale systems and back office computer that make up their card data environment, then they absolutely can impact the security of card data. Examples of service providers that often don’t know they are service providers include hosting, billing account management, back office services and co-location providers, just to name a few. I haven't had to fill out a SAQ-D SP myself, but I believe you should be able to mark large swaths of it N/A (with supporting explanation in appendix C). For example: The questions specific to application development and secure coding (Requirements 6.3 and 6.5) only need to be answered if your organization develops its own custom applications. You would need to fill out these sections, since you're developing software. The questions for Requirements 9.1.1 and 9.3 only need to be answered for facilities with “sensitive areas” as defined here: “Sensitive areas” refers to any data center, server room or any area that houses systems that store, process, or transmit cardholder data. You could N/A this section, since you aren't touching the data yourself. As always, I am not a QSA. You should probably consult with one to confirm/help define what you need to assess, rather than relying on one random person on the internet. This should get you started, though. A: As Bobson quoted but apparently didn't read, with emphasis added: The PA-DSS is for software vendors and others who develop payment applications that store, process or transmit cardholder data and/or sensitive authentication data as part of authorization or settlement, when these applications are sold, distributed or licensed to third parties. Most card brands encourage merchants to use payment applications that are tested and approved by the PCI SSC PA-DSS is the Payment Application Data Security Standard, an entirely separate document available on the PCISSC website -- click on the Filter box and select PA-DSS. (In the old Web1.0 days I could give a hyperlink but the brave new world requires manual interaction for everything even for the tiny fraction of websites not 'monetizing' their users.) Nearly all the substantive requirements in PA-DSS are based on requirements in the normal DSS, the one applicable to merchants and service providers (and now issuers) who actually process cardholder data and transactions, but many are adjusted to reflect the software development process. For example, where DSS requires a merchant/etc to configure access privileges for different users based on business need, such as viewing unmasked PAN, PA-DSS requires the application vendor to support such privileges and provide guidance on how the merchant can assign them after installing the software. Where DSS requires the merchant/SP to monitor logs and respond to problems, PA-DSS requires the application provide suitable logs to be monitored. And so on. The requirements about actually operating the network (including quarterly external scans) and physical environment don't apply at all. The only substantive requirement unique to PA-DSS is that you must write and provide an Implementation Guide and some related documentation that the merchant/etc, or a reseller/integrator if applicable (sounds like not in your case), can use in ensuring and documenting their system using your software as a whole satisfies DSS. The bad news is there is no self-assessment track for PA-DSS application vendors; you must have an audit by a QSA specifically for PA-DSS called a PA-QSA or Payment Application Assessor -- note this is a separate item under the 'Assessors & Solutions' tab which leads to this list. A possible alternative is that if you are contracted sufficiently under the direction of the merchant(s), they could treat you as effectively in-house, i.e. part of their own development team(s), developing 'solely' for them. But in that case they must be able to produce on demand all your design documents, coding standards, logs showing code changes were reviewed by a second person, training qualifications and possibly background investigations of all staff, etc. This will be very intrusive. For more on the relationship between DSS and PA-DSS, see page 9 of DSS, particularly the last paragraph, emphasis added: PCI DSS may apply to payment application vendors if the vendor stores, processes, or transmits cardholder data, or has access to their customers’ cardholder data (for example, in the role of a service provider).
{ "pile_set_name": "StackExchange" }
Q: WebHook implementation example? Reviewer's Note The title is exactly as it is supposed to be, even if the accepted answer suggests WebSockets. We are building an application where customer will send data to our application. Our application have different events, like validating the data, saving it to data base and etc. I want to notify the client about the status of their data, like the data is validated, data is saved in SQL, etc. Our backend service will be in C#. I am new to this WebHook concept and have never implemented this before. I am looking for code examples for both sending and receiving side of WebHooks. I would really appreciate any help. A: I think you are looking for WebSockets, and to 'push' notification to the client, the proven and most popular .NET solution is SignalR, last time I checked :) There are alternatives too, GitHub search: websockets c# Most WebSocket libs will fallback to legacy ways, like polling, when WebSockets are not supported.
{ "pile_set_name": "StackExchange" }
Q: I need to write a big-endian single-precision floating point number to file in C# I have a file format I'm trying to write to using C#. The format encodes integer-based RGB color values as a floating point. It also stores the values as big-endian. I found an example of what I'm trying to do, written in php, here: http://www.colourlovers.com/ase.phps I can convert the endian-ness easily. I know this code is very verbose, but I'm just using it to watch the bits swap during troubleshooting. private uint SwapEndian(uint host) { uint ReturnValue; uint FirstHalf; uint LastHalf; FirstHalf = (host & 0xFFFF0000); FirstHalf = (FirstHalf >> 16); LastHalf = (host & 0x0000FFFF); LastHalf = (LastHalf << 16); ReturnValue = (FirstHalf | LastHalf); return ReturnValue; } C# won't let me perform bit-shifts on floats. Converting to an int or uint to call my SwapEndian method above loses the encoding information the file format requires. So, how would you take a floating point number and change its endian-ness without losing the exponent data? A: You could just use: var bytes = BitConverter.GetBytes(floatVal); And reverse the array (assuming the CPU is little-endian, which you an check), or simply just access the array in the order you need. There is also a way to do this with unsafe code, treating the float* as a byte* so you can get the bytes in the order you want.
{ "pile_set_name": "StackExchange" }
Q: The [legal-concepts] tag is already the pile of random stuff on the floor We have a legal-concepts tag. I honestly don't know what its intended purpose is meant to be because it has no tag wiki or excerpt. Worst of all, there's really no clear pattern between any of the questions that currently have the tag. It seems to be used for questions which are about the law, but that's the entire site so... what is the point of the tag? Can we come up with some better, more specific tags for the questions using it? Many of them were probably added because the asker simply didn't know what tags to put on the question, or how to properly name the tag they were envisioning in their mind. So the question just ended up with a vague free-for-all tag. If this tag does have some purpose which I'm not seeing, perhaps it could be renamed to be more specific about what types of questions it's targeting? Also, a tag wiki and excerpt would be extremely useful. A: I'm removing legal-concepts from questions Where they don't already have other tags, or those other tags are inadequate, I'm re-tagging with something a little different. As nomen agentis has pointed out, a fair few of these are definitions questions. I'm tagging these as such. There's a possible use case for them when comparing two legal concepts, maybe. Please, please comment or ping me in chat if you disagree. I have now left the below comment on all of the affected posts - apologies for the post bumping. Tags on question edited as per meta post If you have been affected and would like to make a case for the legal-concepts tag staying on your question, then please, do so here! Like the rest of you, the moderation team is still finding its feet. However, this particular tag has already been the subject of discussion and it's generally agreed that it didn't really help sort or categorise the questions, with the caveat re: definitions above.
{ "pile_set_name": "StackExchange" }
Q: Jquery plugin horizontal slider I am in search of Jquery horizontal slider. Which i ed as a time line. The slider should be able to read each and every unit for example slider should read from 0-60 mins. Please help me A: How about the jquery UI Slider? http://jqueryui.com/demos/slider/#default
{ "pile_set_name": "StackExchange" }
Q: Letter or icon for app icon Do you guys think a letter (like Vine, tumblr, Facebook, Vimeo) is a better representation of a brand/app than an icon (like SnapChat, Evernote, Twitter, Dropbox)? A: I think depends on strength of a brand. Icons - images are much more recognizable for eye because they are complex. But thats just visuality. I don't think just letters are good representation a especially if its a small brand. There is only finite number of letters and their shapes. But for big brands i think it works because... well they are everywhere so you have no problem to remember and recognise them. The simplicity makes them more grand somehow. Also note, the brands that use just letters almost aways connect strong color with very specific typeface (Klavika that Facebook uses for example). I don't think its so simple though. Branding can be pretty complicated. Btw there is great free resource (course) on branding from Wolff Olins - Secred Power of Brands
{ "pile_set_name": "StackExchange" }
Q: jquery array how to get a key that has an empty value i have an array with some keys and values pair. i'm checking if there is a key that has empty value and if so I would like to know how to get this key : $(form).on('submit',function() { var arr = {}; var elemRequired = $(this).find('input:not(input[type=button], input[type=submit], input[type=reset]),textarea,select,checkbox').filter(':visible'); $('.error').empty(); elemRequired.each(function(i, el) { arr[el.id] = el.value; }); $.each(arr, function(id, val) { if (val == ""){ /*here i want to get the id that has the empty value*/ id.addClass('invalid'); }else{ } }); return false; }); i know ther might be other way to do this but i want to know if there's a way to do it like that thanks for the help A: Put this $('#'+id).addClass('invalid'); instead of this id.addClass('invalid');
{ "pile_set_name": "StackExchange" }
Q: run method after the other method is finished delayed job rails 3 I am using delayed_job gem for run methods with delay. I want run first a method and when this first method is finished run the second method. 1º method Order.delay(queue: "Job", priority: 1, run_at: job.minutes_to_in_progress_overtime.minute.from_now).inprogress_overtime(job) 2º Method Order.delay(queue: "Job", priority: 1, run_at: job.minutes_to_cancel_due_to_overtime.minute.from_now).canceled_overtime(job) Here go my class Order: class Order def self.inprogress_overtime(job) #actions goes here end def self.canceled_overtime(job) #actions goes here end end How can can I do it? Thank you ver much! A: based on what you are asking, I think it is as simple as this? # enqueue the inprogress_overtime Order.delay(queue: "Job", priority: 1, run_at: job.minutes_to_in_progress_overtime.minute.from_now).inprogress_overtime(job) class Order def self.inprogress_overtime(job) # actions goes here # now enqueue the canceled_overtime Order.delay(queue: "Job", priority: 1, run_at: job.minutes_to_cancel_due_to_overtime.minute.from_now).canceled_overtime(job) end def self.canceled_overtime(job) # actions goes here end end NOTE: delaying from inprogress_overtime might not be needed, since you are already running in the background job at that point?
{ "pile_set_name": "StackExchange" }
Q: Why did my highlights turn pink/purple in Xubuntu 14.10? Around the time of the start to testing of the second beta for Xubuntu 14.10, my highlights turned pink system-wide. What gives? A: As confirmed in remarks by Xubuntu Project Leader Simon Steinbeiß in Launchpad Bug 1373280, the changes can be adjusted through the use of the gtk-theme-config utility included in Xubuntu. This was confirmed as not a bug but a deliberate design decision. A deliberate design decision was made to emphasize the "unicorn" aspect to the 14.10 release by updating the default theme in various ways such as making the pink highlight occur even for those upgrading from 14.04 as well as for those making new installations. In the drafted release notes for Xubuntu 14.10 Beta 2, the release team stated: To celebrate the 14.10 codename "Utopic Unicorn" and to demonstrate the easy customisability of Xubuntu, highlight colors have been turned pink for this release. You can easily revert this change by using the theme configuration application (gtk-theme-config) under the Settings Manager; simply turn Custom Highlight Colors "Off" and click "Apply". Of course, if you wish, you can change the highlight color to something you like better than the default blue!
{ "pile_set_name": "StackExchange" }
Q: Selecting one option out of many - Objective c Hi I am looking for a component wherein an option can be selected out of many options given. The component allows the user to select only one option, the moment any option is selected the previously selected one gets unselected. When I look in the xcode I couldn't find any component similar to it. I have attached the image of the component here which am looking for. Can anyone point me to this component (refer image attached) in xcode. A: This is a grouped UITableView. You need to implement the logic to maintain the selection yourself in the table view delegate.
{ "pile_set_name": "StackExchange" }
Q: Passing ObservableList from one class to another Hi there I am trying to pass an ObservableList from one class to another but seem to be getting an error java.lang.NullPointerException java.lang.NullPointerException at animal_sanctuary.maintenanceController.populateBreedTable(maintenanceController.java:99) at animal_sanctuary.maintenanceController.initialize(maintenanceController.java:44) at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548) at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441) at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409) at animal_sanctuary.Controller.loadScreen(Controller.java:133) at animal_sanctuary.Main.start(Main.java:33) at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$163(LauncherImpl.java:863) at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$176(PlatformImpl.java:326) at com.sun.javafx.application.PlatformImpl.lambda$null$174(PlatformImpl.java:295) at java.security.AccessController.doPrivileged(Native Method) at com.sun.javafx.application.PlatformImpl.lambda$runLater$175(PlatformImpl.java:294) at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95) at com.sun.glass.ui.win.WinApplication._runLoop(Native Method) at com.sun.glass.ui.win.WinApplication.lambda$null$149(WinApplication.java:191) at java.lang.Thread.run(Thread.java:745) Can you tell me what i am doing wrong its is driving me crazy . Here is my Code Class 1 //=================================================== // ***** GET INFO FROM DB ***** //=================================================== public ObservableList<Breed> getBreed(){ Statement stmt = null; ArrayList<Breed> bre = new ArrayList<Breed>(); try { stmt = conn.createStatement(); ResultSet rs; rs = stmt.executeQuery("SELECT * FROM breeds;"); while(rs.next()){ String s = rs.getString("breed"); System.out.println(s); Breed b = new Breed(s); bre.add(b); } } catch (SQLException e) { e.printStackTrace(); } ObservableList<Breed> myObservableList = FXCollections.observableArrayList(bre);; return myObservableList; } Class 2 public void populateBreedTable(){ ObservableList<Breed> b = myController.getBreed(); //breedCol.setCellValueFactory(new PropertyValueFactory<>("breed")); //itemTable.setItems(); } Thanks you for your time :) **UPDATE public class maintenanceController implements Initializable, ControlledScreen { Controller myController; Connection conn; @FXML RadioButton rbType ,rbBreed, rbLocation; @FXML TextField addItemTb; @FXML TableView<Breed> itemTable; @FXML TableColumn<Breed, String > breedCol; @FXML TableView<Type> itemTable1; @FXML TableColumn<Type, String > TypeCol; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO try { conn = myController.getConnection(); populateBreedTable(); } catch (Exception e) { e.printStackTrace(); } } public void setScreenParent(Controller screenParent) { myController = screenParent; } @FXML private void goToMainScreen(ActionEvent event) { myController.setScreen(Main.mainScreen1ID); } ** public boolean setScreen(final String name) { if (screens.get(name) != null) { //screen loaded final DoubleProperty opacity = opacityProperty(); if (!getChildren().isEmpty()) { //if there is more than one screen Timeline fade = new Timeline( new KeyFrame(Duration.ZERO, new KeyValue(opacity, 1.0)), new KeyFrame(new Duration(1000), new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent t) { getChildren().remove(0); //remove the displayed screen getChildren().add(0, screens.get(name)); //add the screen Timeline fadeIn = new Timeline( new KeyFrame(Duration.ZERO, new KeyValue(opacity, 0.0)), new KeyFrame(new Duration(800), new KeyValue(opacity, 1.0))); fadeIn.play(); } }, new KeyValue(opacity, 0.0))); fade.play(); } else { setOpacity(0.0); getChildren().add(screens.get(name)); //no one else been displayed, then just show Timeline fadeIn = new Timeline( new KeyFrame(Duration.ZERO, new KeyValue(opacity, 0.0)), new KeyFrame(new Duration(2500), new KeyValue(opacity, 1.0))); fadeIn.play(); } return true; } else { System.out.println("screen hasn't been loaded!!! \n"); return false; } } A: The problem arises from the order in which the methods are executed. initialize() is called by the FXMLLoader as part of the process of loading the fxml file. Since your initialize() method invokes populateBreedTable(), the populateBreedTable() method is invoked before the call to FXMLLoader.load() completes. The myController variable is only initialized by a call to setScreenParent() which almost certainly happens after you call load() on the FXMLLoader (typically you call load and then get a reference to the controller the loader created). Thus populateBreedTable() is called before myController is initialized, and is null. You can move the call to populateBreedTable() to setScreenParent() and it should work.
{ "pile_set_name": "StackExchange" }
Q: how to make the category of chain complexes into an $\infty$-category I'd like to have some simple examples of quasi-categories to understand better some concepts and one of the most basic (for me) should be the category of chain complexes. Has anyone ever written down (more or less explicitly) what the simplicial set corresponding to the quasi-category associated with the category of (say unbounded) chain complexes on an abelian category looks like? I am not looking for an enhancement of the derived category or anything like this, I'm thinking of the much simpler infinity category where higher morphisms correspond to homotopies between complexes. My understanding is that the derived category should then be constructed as a localization of this $\infty$-category. I am guessing my problem lies with the coherent nerve for simplicial categories. A: As everybody's said, there's an obvious thing to do. As Yosemite Sam cites, it's done in Section 13 of the ArXiv version of DAG I -- you think of chain complexes as enriched over simplicial sets via Dold-Kan, and then apply the nerve construction. But there's an explicit thing you can do for any dg category, and I find it useful because it's given in terms of formulas. Moreover there's an obvious (if tedious) way to generalize this formula for any $A_\infty$-category so it's a cool thing to know. It's in the latest (February 2012) version of Higher Algebra. Since chain complexes obviously form a dg-category, this explicit method might be what you're looking for in case you want to produce some simplices in your quasi-category. Specifically, Construction 1.3.1.6 tells you how to get a quasi-category from any dg category. Then Construction 1.3.13 and Remark 1.3.1.12 should convince you that it's equivalent to the "Dold-Kan + Simplicial nerve" construction cited by everybody else. (Lurie summarizes this equivalence in Proposition 1.3.1.17.) I would write out the formulas here but I don't want to re-TeX the long discussions. So here's at least a link to the latest Higher Algebra. A: For any simplicial model category $C$, let $C^0$ denote the fullsubcategory on its fibrtant and cofibrant objects. It may be considered as a simplicial category via its simplicial-enrichment. Via the corner axioms for this enrichment, it follows that the Hom-complexes of $C^0$ are Kan complexes, so that $C^0$ is a fibrant simplicial category in the Bergner model structure on simplicial categories. Then apply the homotopy coherent nerve to $C^0$ as you suggest. Since it is the right-Quillen pair of the Quillen equivalence between the Bergner model structure on simplicial categories and the Joyal model structure on simplicial sets, the result, $N_{hc}\left(C^0\right)$ will be a fibrant simplicial set in the Joyal structure, i.e. a quasi-category. A: [ Edit: Section 13 of DAG I had everything I was looking for http://arxiv.org/pdf/math/0608228v5.pdf ] I think I now partially understand why I'm confused (I'd like to thank David's answer for providing a more high-brow perspective, I'm sure it will be useful to me as soon as I try and understand stable/derived categories) The $\infty$-category one should obtain has for vertices complexes $A,B, \ldots$, the 1-simplices are given by chain maps $A \to B$, the 2-simplices are given by maps $A \to B \to C, A \to C$ (not necessarily commuting) together with a homotopy, the 3-simplices are given by maps $A \to B \to C \to D, A \to C, B \to D, A \to D$ together with a homotopies and homotopies among homotopies and so on (perhaps I got something wrong but you get the idea). I'm pretty sure this is the coherent nerve construction for simplicial categories but I need to understand it better first. This should give the right thing, an $\infty$-enhancement of the category of complexes such that $\pi_0$ of it is the homotopy category of complexes (so no resolutions and no model categories were harmed in the process). If someone corrects and/or has a better way of writing this please do so!
{ "pile_set_name": "StackExchange" }
Q: Why does a curling rock curl? In the game of curling, players "curl" a granite "rock" (of precise size and roughly a flattened cylinder) down a "sheet" of ice towards a target; the "rock" will curve in its path in the direction of the motion of the leading edge. The question here is, what is the mechanism for the curling of the rock? Standard frictional physics indicates that angular velocity should not have any effect on translational vector; while moving, the bottom surface of the rock is subject to kinetic friction. Due to frictional deceleration, the leading edge of the rock exerts (slightly) more force on the ice than the trailing edge; this would seem to indicate that the rock would curve in the opposite direction from what it does. Intuition would indicate that the reason for the curling motion would be due to kinetic friction being modified by velocity; that is, along the "left" side of the rock (assuming a rock moving away from the observer) for a rock rotating counterclockwise, the velocity along the ground is slower than for the "right" side; if kinetic friction is decreased as velocity increases, this would be a good explanation for the motion. However, everything I've seen seems to indicate that the coefficient of kinetic friction is constant; is this correct? If so, what is the reason for the (well-observed) phenomenon? A: The coefficient of friction for a curling stone is not constant - motion on ice is different from motion on an unchanging solid surface, thanks to melting, which in turn is proportional to most of the factors that affect friction (e.g. contact area, velocity). So, exactly as you suspect, friction decreases as velocity increases. Because of the changing CofF, the stone curls more strongly at the end of its trajectory (as it gets slower) than at the beginning. Additionally, as Mark C says, the team can affect the trajectory after delivery by sweeping - the entire purpose of the sweepers is to melt or at least smooth the ice ahead of the stone (or not, as required), which tends to straighten and lengthen the trajectory by reducing the effect of friction on the leading edge of the stone.
{ "pile_set_name": "StackExchange" }
Q: How to fix list.index(min(list)) when min(list) is in scientific notation Pretty self explanatory, my list has a smallest value of 3.4972054734350166e-06. I want to find where in the list this is using list.index(min(list)) but it gives an error of: KeyError Traceback (most recent call last) <ipython-input-75-218f090090e9> in <module>() 15 print(sum(list) / len(list)) 16 print("The highest r2 value is:",max(list),"from ",country_data[list.index(max(list))].name[0]) ---> 17 print(country_data[list.index(min(list))].name[0]) 1 frames /usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py in get_value(self, series, key) 4373 try: 4374 return self._engine.get_value(s, k, -> 4375 tz=getattr(series.dtype, 'tz', None)) 4376 except KeyError as e1: 4377 if len(self) > 0 and (self.holds_integer() or self.is_boolean()): pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value() pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value() pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item() KeyError: 0 The code works with index(max(list)). A: Try this way list_name.index(min(list_name)) ;)
{ "pile_set_name": "StackExchange" }
Q: [hyperledger-fabric]: Channel and Consortium changes If consortium X1 has organization R1 and R2 and I have created a channel C1 using this consortium. In the future, if I include R3 in X1 will R3 be a part of channel C1? If yes, then will it be able to see the previous transactions? A: When a peer joins a channel, it reads all of the blocks in the ledger sequentially, starting with the genesis block of the channel and continuing through the transaction blocks and any subsequent configuration blocks. CLI command where peer joining the channel: peer0.org1.example.com peer channel join -b mychannel.block If you notice my genesis block is provided at the time of peer joining the channel. Reference: https://buildmedia.readthedocs.org/media/pdf/hyperledger-fabric/latest/hyperledger-fabric.pdf
{ "pile_set_name": "StackExchange" }
Q: Is an operator A still a contraction if $\rho(A^2x,A^2y) < \rho(x,y)?$ I am trying to prove (or disprove) that if A maps a compact metric set $(x, \rho)$ into itself and has $\rho(A^2x,A^2y) < \rho(x,y)$ then $A$ has a fixed point. My gut says that this is true and I think that it should follow directly from the Banach contraction principle, but I am struggling to show that $\rho(A^2x,A^2y) < \rho(x,y)$ implies $\rho(Ax,Ay) < \rho(x,y)$, which is a necessary condition to use the theorem. It's very possible that the answer is there is no fixed point. I'm honestly not sure A: Here's a more general statement: if $A^n$ is a contraction of a complete metric space $X$, then $A$ has a fixed point. Proof: Let $x_0$ be the unique fixed point of $A^n$. Set $x_1 = Ax_0$. Then $A^nx_1 = A^n(Ax_0) = A(A^n x_0) = Ax_0 = x_1$; since fixed points are unique we're done. Compactness is unnecessary, all we need is a space in which Banach fixed point theorem applies.
{ "pile_set_name": "StackExchange" }
Q: Scroll to div from li I have a symfony view which looks like this {% for menu in menus %} <li>{{menu.name}}</li> I want to be able to go on a specific div when I click to the li element. Here is the full simplified page: {% for menu in menus %} <li>{{menu.name}}</li> {% endfor %} <p id="generalAnchor">Some text</p> //And here i include some view depending on the li element clicked. But in fact, when depending on the imported view size, the page is not really pretty. So I want to scroll directly to the generalAnchor element. I know I can do this with a and href but here I need to work with the li and I don't know what method I can use. A: you can use jquery to scroll to the div. $("li").click(function() { $('html, body').animate({ scrollTop: $("#generalAnchor").offset().top }, 2000); });
{ "pile_set_name": "StackExchange" }
Q: Catch "IndexOutOfBoundsException" in Swift 2 I got this code in my Playground: func throwsError() throws{ var x = [1,2] print(x[3]) } func start(){ do{ try throwsError() } catch let unknown{ "unknown: \(unknown)" } } start() So obviously the'throwsError function throws an error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION Is there a way to catch this? I read online to write a subscript for the Array class that always checks for range but the issue is bigger: Am I not capable to just catch anything? A: In Swift, you can't catch anything. You can only catch errors thrown with the throw statement in other Swift code or errors, of type NSError set by called Objective C code. The default array subscript raises an exception, but does not throw a Swift error, so you cannot use try/catch with it. See also this article by Erica Sadun.
{ "pile_set_name": "StackExchange" }
Q: is there any way to search for training metadata in Bixby Studio? I can find all the places where the value string searchtheme occurs in my trainings by doing this: grep -ir "searchtheme" * t-1.training.bxb: utterance ("[g:GetContent] Show me more on the theme of (paintings)[v:SearchTheme].") t-4.training.bxb: utterance ("[g:GetContent] Tell me about (when)[v:SearchTheme] Stonehenge was built.") t-a.training.bxb: utterance ("[g:GetContent] Show me more on the theme of (music)[v:SearchTheme].") t-d.training.bxb: utterance ("[g:GetContent] Show me the (video introduction)[v:SearchTheme].") t-h.training.bxb: utterance ("[g:GetContent] Tell me more about (literature)[v:SearchTheme].") t-o.training.bxb: utterance ("[g:GetContent] Show me the (video introduction)[v:SearchTheme].") t-p.training.bxb: utterance ("[g:GetContent] Tell me about (tourism)[v:SearchTheme].") t-v.training.bxb: utterance ("[g:GetContent] Show me the (video introduction)[v:SearchTheme].") but I don't see a way to do that in Bixby Studio itself. Am I missing something? A: Yes, Bixby allows you to search the metadata using their Aligned NL syntax More information about searching your NL training
{ "pile_set_name": "StackExchange" }
Q: C#: Convert T to T[] I would like to convert T to T[] if it is an array. static T GenericFunction<T>(T t) { if (t == null) return default(T); if (t.GetType().IsArray) { //if object is an array it should be handled //by an array method return (T) GenericArrayFunction((T[])t); } ... } static T[] GenericArrayFunction<T>(T[] t) { if (t == null) return default(T); for (int i = 0 ; i < t.Length ; i++) { //for each element in array carry //out Generic Function if (t[i].GetType().IsArray()) { newList[i] = GenericArrayFunction((T[])t[i]); } else { newList[i] = GenericFunction(t[i]); } } ... } Error If I try (T[])t Cannot convert type 'T' to 'T[]' Error If I just try to pass t The type arguments for method 'GenericArrayFunction(T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. A: Judging from your particular example, could you not define two methods and let the compiler choose the correct one when an array is passed in? using System; class Program { static T GenericFunction<T>(T t) { Console.WriteLine("GenericFunction<T>(T)"); return default(T); } static T[] GenericFunction<T>(T[] t) { // Call the non-array function for(int i = 0; i < t.Length; ++i) t[i] = GenericFunction(t[i]); Console.WriteLine("GenericFunction<T>(T[])"); return new T[4]; } static void Main() { int[] arr = {1,2,3}; int i = 42; GenericFunction(i); // Calls non-array version GenericFunction(arr); // Calls array version } } A: Just because T is an array type doesn't mean that it's also an array of T. In fact, the only way that could happen would be for T to be something like object, Array or one of the interfaces implemented by arrays. What are you really trying to do? I suspect you want to find out the element type of the array, and then call GenericArrayFunction with the appropriate T - but that won't be the same T, and you'll need to call it with reflection, which will be somewhat painful. (Not too bad, but unpleasant.) I suspect you don't fully understand C#/.NET generics - please give us more context about the bigger picture so we can help you better. EDIT: The reflection approach would be something like this: private static readonly ArrayMethod = typeof(NameOfContainingType) .GetMethod("GenericArrayFunction", BindingFlags.Static | BindingFlags.NonPublic); ... static T GenericFunction<T>(T t) { if (t == null) return default(T); if (t is Array) { Type elementType = t.GetType().GetElementType(); MethodInfo method = ArrayMethod.MakeGenericMethod(new[] elementType); return (T) method.Invoke(null, new object[] { t }); } ... } Note that this will still fail for rectangular arrays, which get even harder to cope with.
{ "pile_set_name": "StackExchange" }
Q: Pass optional object without copying it I encountered the following situation while refactoring old code: // pointers to const are discouraged in our code base void Do(Foo* exists, Foo* maybe_null) { // does not change *exists or *maybe_null } int main() { // ... Do(&foos[i], test_both ? &bars[i] : nullptr); // ... HighOrderFunction(foos, bars, &Do); // ... } So, Do is called with two Foo objects of which one definitely exists while the second might not, depending on some outside test. Issues I have with this current code that I am trying to solve: The first parameter will never be null so its pointer properties are never used. I generally dislike the use of null as an empty value. So far I came up with three possible solutions, none of which I am completely satisfied with: Do(const Foo&, Foo*): The second argument has the same issue as before and now the call syntax is not uniform anymore (foos[i] and &bars[i]), which might confuse readers. Do(const Foo&, const optional<Foo>&): The second Foo object has to be copied to construct the optional. Do(const Foo&, optional<const Foo&>): Does not actually work since optional of a reference type is disallowed. Do(const Foo&) and Do(const Foo&, const Foo&) overload : Causes problems when I need to pass Do as a function pointer So, are there any better/cleaner solutions I could use in this situation? (I am using C++11 with some std additions like optional) A: Make Do a functor, not just a function. struct Do { void operator()(const Foo &must_be_provided); void operator()(const Foo &must_be_provided, const Foo &maybe_unneeded); }; and then, after implementing the two forms of Do::operator(), void some_function(Do f) { // assume access to foos and bars here if (test_both) // assume determined at run time f(foos[i]); else f(foos[i], bars[i]); } Note that a functor can be passed by value, by reference, or its address can be passed in a pointer (although the syntax for calling the functions changes a little).
{ "pile_set_name": "StackExchange" }
Q: Why can I have an indoor pizza/wood oven, but not a BBQ or smoker? (or can I...?) I know people have indoor wood-fired pizza ovens. I also know that in general people cannot have barbecues or smokers indoors, presumably because of the potential for leakage of dangerous or deadly gasses. I am confused because both of these methods involve burning wood indoors, but only the pizza oven is considered appropriate or safe. My guess at this time is that pizza ovens have sufficient ventilation to let out bad gasses and such, while barbecues and smokers traditionally do not have good ventilation. Why can I have an indoor pizza/wood oven, but not a BBQ or smoker? Would having a valve that partly closes the ventilation of a pizza oven "turn" the pizza oven into a smoker? And if so, would this also be considered dangerous? I want to make it clear that I don’t plan on poisoning my family and won’t be building something unless if is deemed safe by professionals. A: Why pizza/wood ovens, but not BBQ/smoker? Fire is not fundamentally a problem indoors; there are certainly safe ways to do it, like fireplaces. The things that make fire dangerous are lack of containment and lack of ventilation coupled with significant size. If it's at all uncontained, it's a fire hazard, and if there's not enough ventilation then you can get a smoke-filled home, carbon monoxide poisoning, and all manner of unpleasant/deadly things. Wood-fired pizza ovens are much more like fireplaces than anything else. The fire is well-contained. They have chimneys, so that all of the byproducts of the fire are safely sent outside, and new fresh air is pulled in. Standard barbecues/grills/smokers usually fail on the ventilation aspect. They don't have a way to attach a chimney so that you can reliably send all the nasty stuff outside. They may also be insufficiently well-contained. For example, a lot of charcoal grills make it relatively easy to throw sparks outside the grill, which is pretty bad indoors. Indoor smokers do exist, though. Generally they're either large, with serious ventilation, or they're small stovetop things that just burn a tiny amount of wood chips in a tiny volume, so it's safe without ventilation but not exactly comparable to a full smoker. The reason the big ones need serious ventilation is that you're deliberately holding smoke (and associated gases) inside, and you can't let that slowly build up in your home. On top of that, it's at a much lower temperature, probably 225-250F compared to a wood-fired oven at probably 600-900F, so a chimney won't even be as effective because you don't have as strong convection from all that hot air trying to rise. Can I just seal off an oven and turn it into a smoker? No. If you don't send the smoke out through the ventilation system, it'll be going into your home. (You might have experienced this yourself, if you've ever started a fire in a fireplace and accidentally left the flue closed. It can fill the room with smoke impressively quickly.) I know you said partially close, but if the oven hasn't been designed for it, you're just asking for trouble. You don't really have a good way to make sure that smoke (and probably carbon monoxide) is held within the oven enough to make it a good smoker, but is not pushed out into your home. This is fire/home safety. You really don't want to be asking for trouble here, and depending on where you live, it may well be illegal. So it's really unlikely that you can even make this conversion, and if you're doing it yourself you can't trust it anyway, and the absolute best case is that you manage to somehow build yourself an indoor smoker and you've probably had to make compromises that make it not work as well as a pizza oven. So you might as well just buy an indoor smoker. (But you still might not be as happy with it as with a regular outdoor smoker - see dlb's answer.) A: Please, Please, Please do not try to do indoor smoking without equipment made for it. It is Dangerous! DANGEROUS Devices that use open flame inside your house take advantage of a chimney to let the smoke out. Pizza ovens are just funky shaped fireplaces. In a fireplace, the hot fire causes the smoke and nasty gasses to rise up the chimney, drawing in fresh air from the front. This creates a one way flow. It is similar for just about any combustion driven heat device. Block that flow out of the chimney, and the smoke and Carbon Monoxide stay around. Since they are heavier than air, they will settle at the lowest point as they mix with cooler air and cool down. Smoking meats requires lower heat than is normally found in a fireplace. A lot lower. At this point the smoke is not going to rise as readily or quickly. Here is where you face a second problem: A column of cool air blocking your chimney. If this happens, NONE of the nasty stuff escapes and your house fills with particulates and CO and CO2. THIS CAN KILL YOU! I love smoked meats too, but I would not put yourself or loved ones at risk for it. It may be inconvenient to use an outdoor smoker, but its a lot more convenient than suffocating on Carbon Monoxide. Please don't attempt to smoke meats indoors unless you have a specifically designed indoor use smoker that has stuff to help clear the nasty stuff out and not kill you. Now for BBQ: There are ways to do BBQ indoors. so long as you are not trying to trap combustion by products, and follow safety rules, you can do some pretty tasty stuff. I use an induction cooktop and a cast iron grill to sear the meat and get the lovely hash marks, then finish it off in the oven broiler. That's just me though. There are gas ranges with grills, there are oven BBQ recipes and techniques. You can spend hours on allrecipes looking at different techniques for this meat or that. That said, ALL of them need adequate kitchen ventilation. Not as much as my prior apocalyptic ramblings, but you do need to ventilate the kitchen. TL:DR Smoke meats outside and stay safe!...oh, and enjoy A: Opinion, but there are multiple indoor options, like stove top and oven smokers, gas and electric grills with stove top ventilation systems such as those by Jenn-Air and other makers. These are not really that uncommon. They do however come with drawbacks such as better ventilation requirements and many are relatively expensive. They are limited use items that are space eaters, you give up space for something which often is not actually used enough to justify. I owned one, and the result was I had a stove-top the size of an 8 burner stove, with a very loud exhaust which was always oily, and could only use either the burners or the grill, not both at the same time due to power draw and the grill top always seemed to cause burns. I an not sure why it was easier for people to understand not to touch burners, but they could not understand the grill might also be hot, but that was the case. When you add in the mess, for most people, the outdoor option is simply cheaper and more convenient.
{ "pile_set_name": "StackExchange" }
Q: Make all input fields on the same line Im trying to use css to make all the fields for my form display on one line. It's part of the header nav on my page so it is important that it shows on one line instead of multiple lines. Here's my header code at the moment. <div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <a class="btn btn-navbar" data-target=".nav-collapse" data-toggle="collapse"> <span class="i-bar"></span> <span class="i-bar"></span> <span class="i-bar"></span> </a> <a class="brand" href="/">Bandini</a> <div class="container nav-collapse"> <ul class="nav"> <li><%= link_to "Clients", "/clients" %></li> <li><%= link_to "Jobs", "/jobs" %></li> </ul> <ul class="user_nav"> <%= render :partial => "sessions/manager" %> </ul> </div><!--/.nav-collapse --> </div> </div> </div> The <%= render :partial => "sessions/manager" %> part points to a partial which displayes another partial depending on the users login state. If they are logged out, then it displays the login form and if they are logged in then it shows th currrent users email adress and a signout link. Here's my login form. <%= simple_form_for("user", :url => user_session_path, :html => {:id => "sign_in", :class => 'form-inline' }, :remote => true, :format => :json) do |f| %> <%= f.input :email, :placeholder => 'Email' %> <%= f.input :password, :placeholder => 'Password' %> <%= f.submit 'Login' %> <%= link_to "Forgot your password?", new_password_path('user') %> <% end %> The form utilizes ajax and the simple_form gem for all the markup. Ive tried playing around in Googles element tools and adding display: inline; to all of my input fields but no such luck. Can anyone assist or point me in the right direction? Edit: HTML generated.. <ul class="user_nav"> <form accept-charset="UTF-8" action="/users/sign_in" class="simple_form form-inline" data-remote="true" id="sign_in" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;" /><input name="authenticity_token" type="hidden" value="fN0oKIlpnhS0WLZpKQafln+182IT1ONVuDP0eRtT8fg=" /></div> <div class="control-group email required"><label class="email required control-label" for="user_email"><abbr title="required">*</abbr> Email</label><div class="controls"><input class="string email required" id="user_email" name="user[email]" placeholder="Email" size="50" type="email" /></div></div> <div class="control-group password required"><label class="password required control-label" for="user_password"><abbr title="required">*</abbr> Password</label><div class="controls"><input class="password required" id="user_password" name="user[password]" placeholder="Password" size="50" type="password" /></div></div> <input name="commit" type="submit" value="Login" /> <a href="/users/password/new">Forgot your password?</a> </form> </ul> A: The reason display: inline; on your inputs is not working is because simple_form by default wraps a div tag around every input. There are two ways to fix this problem: Create a custom wrapper for simple_form https://github.com/plataformatec/simple_form#the-wrappers-api Set both your inputs and the surrounding div to be inline-block: .user_nav div, .user_nav input, .user_nav input[type="submit"] { display: inline-block; } While the .user_nav input css style theoretically should not be necessary, it helps to specify it just in case there is some other CSS rule somewhere setting inputs to block. If you're sure that inputs are behaving normally, then you should be able to remove the second part of the CSS definition above. A: By what documentation says http://twitter.github.com/bootstrap/components.html#navbar Just add navbar-form class to your form and pull-left or pull-right Also you should place it inside a li tag since you are placing it inside a ul
{ "pile_set_name": "StackExchange" }
Q: How can I know the args passed to flask_script's Manager I have a flask application, in one of its script commands I want to know what's the args passed to the Manager (not the command itself), how can I do that? $ cat manage.py #!/usr/bin/env python from flask import Flask from flask_script import Manager app = Flask(__name__) manager = Manager(app) manager.add_option("-d", "--debug", dest="debug", action="store_true") @manager.option('-n', '--name', dest='name', default='joe') def hello(name): # how can I know whether "-d|--debug" is passed in command line print("hello", name) if __name__ == "__main__": manager.run() If I run: $ python manage.py --debug hello I want to detect whether '--debug' is passed via command line args within the func of hello. I can't just change manager.add_option("-d", "--debug", dest="debug", action="store_true") to the decorator verion of: @manager.option('-d', '--debug', action='store_true', dest='debug') @manager.option('-n', '--name', dest='name', default='joe') def hello(name, debug=False): because '-d|--debug' is shared by many commands. A: Global options are passed not to command, but to app-creating function. See add-option docs. For this to work, the manager must be initialized with a factory function rather than a Flask instance. Otherwise any options you set will be ignored. So you need to do something like app = Flask(__name__) def init_manager(debug): app.debug = debug return app manager = Manager(init_manager) And then access app.debug
{ "pile_set_name": "StackExchange" }
Q: Using for loop to loop through object and throws error after reaching it's data's length I have a json object which I am using a for loop to loop through and when the loop reaches the data's length, I get an error Uncaught TypeError: Cannot read property 'RoomName' of undefined It looks like it wants to keep on looping and not finding anything. Why is it doing that? shouldn't it have broke out of the for loop once it reached the data's length of 4? $(document).ready(function () { var data2 = [ { "RoomID": 1, "RoomName": "Room 1", "Areas": [{ "id": 1, "AreaName": "Area 1" }, { "id": 10, "AreaName": "Area 10" }] }, { "RoomID": 2, "RoomName": "Room 2", "Areas": [{ "id": 2, "AreaName": "Area 2" }, { "id": 20, "AreaName": "Area 20" }] }, { "RoomID": 3, "RoomName": "Room 3", "Areas": [{ "id": 3, "AreaName": "Area 3" }, { "id": 30, "AreaName": "Area 30" }, { "id": 35, "AreaName": "Area 35" }] }, { "RoomID": 4, "RoomName": "Room 4", "Areas": [{ "id": 4, "AreaName": "Area 4" }, { "id": 40, "AreaName": "Area 40" }] } ]; // Data2 console.log("data2's length is: " + data2.length); for (i = 0; i <= data2.length; i++) { console.log(data2[i].RoomName); if (data2[i].Areas.length > 0) { for (j = 0; j < data2[i].Areas.length; j++) { console.log(" - " + data2[i].Areas[j].AreaName); } } } }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> A: The problem is in the "=" in this line for (i = 0; i <= data2.length; i++) { If you change it to for (i = 0; i < data2.length; i++) { it should be fine. This occurs because the array is zero indexed and so the length of the array is 1 more than the index of the iteration.
{ "pile_set_name": "StackExchange" }
Q: About the slope of a parametric curve at a point. (James Stewart Calculus 8th Edition.) I am reading "Calculus 8th Edition" by James Stewart. Suppose $f$ and $g$ are differentiable functions and we want to find the tangent line at a point on the parametric curve $x=f(t),y=g(t)$, where $y$ is also a differentiable function of $x$. Then the Chain Rule gives $$\frac{dy}{dt} = \frac{dy}{dx} \cdot \frac{dx}{dt}$$ If $\frac{dx}{dt} \neq 0$, we can solve for $\frac{dy}{dx}$: $$\frac{dy}{dx}=\frac{\frac{dy}{dt}}{\frac{dx}{dt}}$$ What is the differentiable function $y$ of $x$? We name the function $\phi$. Consider $x = t^2$ and $y = t^3-3t$. If $x_0 = 0$, then $x_0 = t^2$ has a unique solution $t_0 = 0$. And $y_0 = t_0^3 - 3t_0 = 0$. So, $\phi(0) = 0$. If $x_0 \in (0, +\infty)$, then, $x_0 = t^2$ has two solutions $t_0 = \pm\sqrt{x_0}$. And $y_0 = t_0^3 - 3t_0 = \pm{x_0^{\frac{3}{2}} \mp 3 x_0^{\frac{1}{2}}}$. Is $\phi(x_0) = {x_0^{\frac{3}{2}} - 3 x_0^{\frac{1}{2}}}$? Is $\phi(x_0) = -{x_0^{\frac{3}{2}} + 3 x_0^{\frac{1}{2}}}$? Can $\phi(x)$ be a differentiable function if we choose the values of $\phi$ appropriately? A: If you draw a curve from left to right (so that it passes the vertical line test) in the $xy$-plane, then you have defined a function. The curve of your parametric equations doesn't satisfy the vertical line test if you let $t$ range over all the real numbers, but if you restrict $t$ in various ways, you can define a function. In particular, if you insist that $t>0$ the graph of $\phi$ is the graph of a function. This choice forces $t=\sqrt{x}$. You can also choose $t<0$, which gives a different $\phi.$ This is an interesting curve because at the point where $t=\sqrt{3}$, there are two different tangent lines.
{ "pile_set_name": "StackExchange" }
Q: python cpu usage 98% with apscheduler from apscheduler.scheduler import Scheduler def req(): print 'some thing like hello world or foo' if __name__ == '__main__': scheduler = Scheduler() scheduler.add_date_job(req, datetime(2014, 1, 6, 21, 40, 00)) scheduler.start() while True: pass i try above code run it in python2.7 and cpu usage going up to 98% it is normal?! or something wrong with apscheduler package, can improve it with more cores? please let me know about cpu usage in python thanks Core of system 1 A: while True: pass That is going to use up your CPU. I understand that you run it to check whether the event will fire? Then you may want to utilize sleep inside of your loop to lower the times code is executed, for example. from apscheduler.scheduler import Scheduler import time def req(): print 'some thing like hello world or foo' if __name__ == '__main__': scheduler = Scheduler() scheduler.add_date_job(req, datetime(2014, 1, 6, 21, 40, 00)) scheduler.start() while True: time.sleep(1) pass
{ "pile_set_name": "StackExchange" }
Q: In Access, how can I compare a truncated division with the real division on linked table in SQL server My Access 2010 database has a linked table (on a SQL Server 2012 backend), containing fields ID, Qty, PackSize. My query is meant to select records where Qty is not a multiple of the packsize. Normally I achieve this with a where clause like so: "Where Qty/Packsize <> Fix(Qty/Packsize), but although this works on local tables or linked tables that live in other Access databases, on linked tables which live in SQL server, it returns no results. If I split up the query into two parts, one with no where clause, creating a new table with ColA: Qty/Packsize, ColB: Fix(Qty/PackSize), and then select where ColA <> ColB, it works fine. Since I don't really care what the values are, just to know whether they're different, I also tried Int() instead of Fix. Even weirder, "Where Cdbl(Qty/Packsize) = int(Qty/Packsize)" returns all the records, despite showing me that Cdbl(Qty/Packsize) is for example 425.5 and int(Qty/Packsize) is 425. Any idea what's going on or how I can achieve this another way? It needs to be in a single step though, as it's really the basis for a record selection in VBA. Why would it not work over a SQL linked table? I've tried in separate databases as well and using a different SQL table, in case it was merely a glitch. Many thanks in advance. (Also the title of this question is awful. Edits gratefully received.) A: It could be a floating point issue, so try with integers only: Where Qty <> Fix(Qty/Packsize) * Packsize By the way, Fix and Int behave the same for positive values.
{ "pile_set_name": "StackExchange" }
Q: All 3 digit numbers are written into one long number $N=100101102...999$. Find $N \pmod {210}$. I have no idea how to solve this, but I feel that $210=2\times3\times5\times7$ has something to do with the problem. A: Let's solve it explicitly based on JMoravitz's suggestion. For clarity, let's write out the number with spacing between 3 digits: $$ N = 100 101 102 103 ... 998 999. $$ We claim the following: $$ \begin{align} N &\equiv 1 \pmod 2, \quad (1) \\ N &\equiv 0 \pmod 3, \quad (2) \\ N &\equiv 4 \pmod 5, \quad (3) \\ N &\equiv 2 \pmod 7. \quad (4) \\ \end{align} $$ Once $(1)$ through $(4)$ are verified, it is straightforward to see that $N \equiv 9 \pmod 210$ where $210 = 2\cdot3 \cdot5\cdot7.$ Proof: Note that $(1)$ and $(3)$ are obvious. Prove (4) using the divisibility rule for 7 stated in the reference above: "Form the alternating sum of blocks of three from right to left" Based on this rule: $$\begin{align} N &\equiv 999 - 998 + 997 - 996 + ... + 101 - 100, \pmod 7 \\ &\equiv 1 + 1 + ... + 1, \pmod 7 \\ &\equiv 450 = 7 \cdot 64 + 2, \pmod 7\\ &\equiv 2 \pmod 7 \end{align} $$ Prove (3) using the divisibility rule for 3 stated in the reference above: "Subtract the quantity of the digits 2, 5, and 8 in the number from the quantity of the digits 1, 4, and 7 in the number. The result must be divisible by 3" To count the digits correctly, we can rely on the pseudo code below to generate (print) the number N: for (i = 1; i < 10; i++) { for (j = 0; j < 10; j++) { for (k = 0; k < 10; k++) { print one three-digit block: i, j, k } } } Thus, There are 100 blocks having the same 'i' digit occur in the leftmost digit of the block: 10 'j' values times 10 'k' values. The total counts are 300 blocks with 'i' in the {1,4,7} group and 300 with 'i' in {2, 5, 8}. Similarly, there are 100 blocks having the same 'j' digit occur in the middle digit of the block: 10 'i' values times 10 'k' values. The total counts are 300 in the {1,4,7} group and 300 in {2, 5, 8}. There are 100 blocks having the same 'k' digit occur in the rightmost digit of the block: 10 'i' values times 10 'j' values. The total counts are 300 in the {1,4,7} group and 300 in {2, 5, 8}. Thus, the total counts are 900 in the {1,4,7} group and 900 in {2, 5, 8}, which means: $$ N \equiv 0 \pmod 3$$
{ "pile_set_name": "StackExchange" }
Q: AWK fails numeric comparison when field is text AWK seems to fail a numeric comparison when the field is text. % cat tt 1 2 3 a 100 c x y z % awk '{if($2>10){print}}' tt a 100 c x y z Expecting to see only 'a 100 c'. What's the trick ? A: https://www.gnu.org/software/gawk/manual/html_node/Comparison-Operators.html "Comparison expressions have the value one if true and zero if false. When comparing operands of mixed types, numeric operands are converted to strings using the value of CONVFMT (see section Conversion of Strings and Numbers)." Force a numeric comparison: % awk '{if($2+0>10){print}}' tt a 100 c https://www.gnu.org/software/gawk/manual/html_node/Strings-And-Numbers.html#Strings-And-Numbers
{ "pile_set_name": "StackExchange" }
Q: Every Presheaf Is Colimit of Representables I am working on the proof that each presheaf $F\in \mathbf{Set}^{\mathcal C^{op}}$ is the colimit of $\mathbf{y}\circ \pi\colon \int_{\mathcal{C}}F\to \mathbf{Set}^{\mathcal C^{op}}$ where $\int_{\mathcal{C}}F$ is the category of elements of $F$, $\pi\colon (x,C)\mapsto C$ is the natural projection and $\mathbf{y}$ is the Yoneda embedding. In the course of the proof, I showed there was an embedding of $\int_{\mathcal C}F$ into the slice category $\mathbf{Set}^{\mathcal C^{op}}/F$ to obtain a cocone with vertex $F$. Then using the Yoneda lemma, for any other cocone $(p_x\colon \mathbf{y}C\to P)_{(x,C)}$ under $\mathbf{y}\circ \pi$, I constructed the natural transformation $\alpha$ componentwise, using the Yoneda lemma. However, I cannot for the life of me see where I needed the arrows of $\int_{\mathcal{C}}F$ in the proof. I see how the cocone is compatible with the arrows, but can't see how they are not extraneous to the proof. So my question boils down to: Can someone provide a counterexample of a presheaf $F$ that is not a colimit of the functor $\mathbf{y}\circ\pi$ where the domain is the discretization of the category of elements of $F$, i.e., forgetting the nontrivial arrows? A: There is a conceptual proof which goes along these lines: The Yoneda Lemma entails that for any presheaf $F\colon \mathcal C^\text{op}\to \bf Set$, there is a canonical isomorphism $F\cong \int^X\hom(-,X)\times FX$ (see here); You can interpret the former result as "any presheaf is canonically a weighted colimit"; $\bf Set$-weighted colimits correspond to colimits over the category of elements of the weight: $$ \text{lim}^{W} F\cong \text{lim}_{(c,x)\in \text{el}(W)}(F \pi) $$ The proof goes by nonsense (allow me to be sloppy but evocative, it's up to you to fill the details): $$ \begin{align*} \int^{c\in \bf C}Fc\times {Wc} &\cong {\rm coeq}\Big(\coprod_{c\to c'}Fc'\times {Wc} \rightrightarrows \coprod_{c\in \bf C}Fc\times {Wc}\Big)\\ &\cong {\rm coeq}\Big( \coprod_{c\to c'}\coprod_{x\in Wc}Fc'\rightrightarrows \coprod_{c\in\bf C}\coprod_{x\in Wc} Fc \Big)\\ &\cong {\rm coeq}\Big( \coprod_{c\to c'\in \text{el}(W)} Fc'\rightrightarrows \coprod_{(c,x)\in \text{el}(W)} Fc \Big)\\ &\cong \varinjlim_{(c,x)\in\text{el}(W)}(F\circ\pi) \end{align*} $$ Points 1+3 reads now as $F\cong \text{lim}^F\textbf{y}$, so by point 3 you get the result.
{ "pile_set_name": "StackExchange" }
Q: How to improve VATS weapon accuracy What are the different options to improve weapon accuracy. And is it in all the cases capped at 95%? A: Your VATS accuracy with ranged weapons depends on: Your character's Perception stat (which means it is improved indirectly by anything which raises Perception) Weapon accuracy stat Weapon range stat (higher means less accuracy loss at larger distances) Any equipment which explicitly gives a bonus to VATS accuracy. You can sometimes find such items as random drops from rare enemies with a ★ behind their name. Any perks which give you an explicit bonus to VATS accuracy in certain situations: Awareness 2 (5% accuracy) Sniper 3 (25% accuracy for headshots with a non-automatic scoped rifle) Penetrator 2 (no accuracy penalty for cover) Concentrated Fire 1-3 (+10%/+15%/+20% accuracy for repeated shots) Attack Dog 1 (accuracy bonus while your dog is holding the enemy) Killshot (20% accuracy bonus for headshots) - this is a bonus perk obtained by maxing the relationship score with the companion character MacCready. The 95% cap is a lie. Even though the UI never shows more than 95% accuracy, you can gain enough VATS accuracy that you never miss a shot.
{ "pile_set_name": "StackExchange" }
Q: Is there a function like String#scan, but returning array of MatchDatas? I need a function to return all matches of a regexp in a string and positions at which the matches are found (I want to highlight matches in the string). There is String#match that returns MatchData, but only for the first match. Is there a better way to do this than something like matches = [] begin match = str.match(regexp) break unless match matches << match str = str[match.end(0)..-1] retry end A: If you just need to iterate over the MatchData objects you can use Regexp.last_match in the scan-block, like: string.scan(regex) do match_data = Regexp.last_match do_something_with(match_data) end If you really need an array, you can use: require 'enumerator' # Only needed for ruby 1.8.6 string.enum_for(:scan, regex).map { Regexp.last_match }
{ "pile_set_name": "StackExchange" }
Q: Do i really need to include table names or AS in JOINS if columns are different? I noticed te other day I can joins in mysql just as easily by doing, SELECT peeps, persons, friends FROM tablea JOIN tableb USING (id) WHERE id = ? In stead of using, SELECT a.peeps, a.persons, b.friends FROM tablea a JOIN tableb b USING (id) WHERE id = ? It only works if there is no matching column names, why should I do the second rather than the first? A: Query 1 will work (as long as there are no ambiguous column names). Query 2 will be clearer be more maintainable (think of someone who doesn't know the database schema by heart) survive the addition of an ambiguous column name to one of the tables So, don't be lazy because of that pitiful few saved keystrokes.
{ "pile_set_name": "StackExchange" }
Q: Plot latitude and longitude lines I am having problems finding how to draw a longitude line like the one show in the figure. I do not want to have a complicate drawing just similar to the one in the picture. I have found some order entries about this issue but are related with more complicated views of a 3d sphere. The problem is hoot draw an arc that passes by the two poles. Thank you. A: Yes, one can draw such things without caring about whether or nor some element is hidden. Personally like those things produced by these macros, these tricks and many other posts here much better. (If are saying that these should be parts of some packages by now, I would immediately agree, though.) UPDATE: Hide the hidden part of the longitude arc. \documentclass[tikz,border=3.14mm]{standalone} \usepackage{tikz-3dplot} \begin{document} \tdplotsetmaincoords{105}{0} \begin{tikzpicture}[tdplot_main_coords,font=\sffamily,line join=bevel] \pgfmathsetmacro{\R}{3} % radius \draw[thick,gray,dashed] (0,0,-\R-1) -- (0,0,\R+1); \begin{scope} \clip plot[variable=\x,domain=0:180] ({\R*cos(\x)},{\R*sin(\x)},0) -- plot[variable=\x,domain=180:0,tdplot_screen_coords] ({\R*cos(\x)},{-\R*sin(\x)}); \shade[ball color=gray,opacity=0.2] [tdplot_screen_coords] (0,0) circle (\R); \end{scope} \draw[tdplot_screen_coords] (0,0) circle (\R); % equator \draw[fill=gray,opacity=0.15] plot[variable=\x,domain=0:360,smooth] ({\R*cos(\x)},{\R*sin(\x)},0); % upper latitude circle \pgfmathsetmacro{\Lat}{48} \draw[fill=gray,opacity=0.15] plot[variable=\x,domain=0:360,smooth] ({\R*cos(\x)*sin(\Lat)},{\R*sin(\x)*sin(\Lat)},{\R*cos(\Lat)}); % longitude halfcircle with extensions \pgfmathsetmacro{\Lon}{50} \pgfmathsetmacro{\thetacrit}{atan(cos(\tdplotmaintheta)/(sin(\tdplotmaintheta)*sin(\Lon)))} \draw[thick,gray] (0,0,-\R-1) -- (0,0,-\R) plot[variable=\x,domain={180+\thetacrit}:0,smooth] ({\R*cos(\Lon)*sin(\x)},{\R*sin(\Lon)*sin(\x)},{\R*cos(\x)}) -- (0,0,\R+1) node[black,above left] {axis of rotation}; \draw[thick] ({\R*cos(\Lon)*sin(90)},{\R*sin(\Lon)*sin(90)},{\R*cos(90)}) -- (0,0,0) -- ({\R*cos(\Lon)*sin(\Lat)},{\R*sin(\Lon)*sin(\Lat)},{\R*cos(\Lat)}) coordinate (L); \draw[thick,gray] plot[variable=\x,domain=90:\Lat,smooth] ({0.7*\R*cos(\Lon)*sin(\x)},{0.7*\R*sin(\Lon)*sin(\x)},{0.7*\R*cos(\x)}); \node [tdplot_screen_coords] at (1,0.4) {$\lambda$}; \draw[orange,tdplot_screen_coords] (L) to[out=0,in=180] ++ (2,1) node[right]{$\lambda=$latitude}; \draw[fill=blue] (L) circle (2pt); \path (0,0,\R) coordinate (N) (0,0,-\R) coordinate (S) (-\R,0,0) coordinate (W) ({\R*cos(\Lon)*sin(135)},{\R*sin(\Lon)*sin(135)},{\R*cos(135)}) coordinate (M); \draw[-latex,very thick,gray] plot[variable=\x,domain=150:30,smooth] ({cos(\x)*sin(\Lat)},{sin(\x)*sin(\Lat)},{\R+0.5}); \draw ([xshift=-2mm]W) -- ++ (-1,0) node[left]{equator} (N) to[out=180,in=0] ++ (-2,0.2cm) node[left]{north pole} (S) to[out=180,in=0] ++ (-2,-0.2cm) node[left]{south pole}; \draw[orange,tdplot_screen_coords] (M) -- ++ (0.2,-1) node[below]{meridian}; \end{tikzpicture} \end{document}
{ "pile_set_name": "StackExchange" }
Q: Android AndEngine problem with touch events I'm learning andEngine and trying to make a simple game based on some examples. My problem is that the game stops in some random moments and I can only use back button ;/ I used logcat and found problem, here's log: /release-keys' I/DEBUG ( 2656): pid: 4918, tid: 4926 >>> com.homework.mygame <<< I/DEBUG ( 2656): signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 3f8191d 4 I/DEBUG ( 2656): r0 00000000 r1 00000000 r2 3f800000 r3 000191d4 I/DEBUG ( 2656): r4 00140a30 r5 00149978 r6 449d9b18 r7 44dbe008 I/DEBUG ( 2656): r8 449d9b6c r9 43707d58 10 43707d40 fp 449d9ed8 I/DEBUG ( 2656): ip 00000000 sp 449d9b00 lr 8062eeb8 pc 806189b8 cpsr 600 00010 I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 3 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 3 item not yet recycled. Allocated 1 more . I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 4 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 4 item not yet recycled. Allocated 1 more . I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 5 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 5 item not yet recycled. Allocated 1 more . I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 6 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 6 item not yet recycled. Allocated 1 more . I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 7 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 7 item not yet recycled. Allocated 1 more . I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 8 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 8 item not yet recycled. Allocated 1 more . I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 9 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 9 item not yet recycled. Allocated 1 more . D/dalvikvm( 929): Cronos GC_EXTERNAL_ALLOC freed 166K, 55% free 2686K/5895K, ex ternal 905K/987K, paused 268ms I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 10 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 10 item not yet recycled. Allocated 1 mor e. I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 11 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 11 item not yet recycled. Allocated 1 mor e. I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 12 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 12 item not yet recycled. Allocated 1 mor e. I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 13 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 13 item not yet recycled. Allocated 1 mor e. I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 14 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 14 item not yet recycled. Allocated 1 mor e. I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 15 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 15 item not yet recycled. Allocated 1 mor e. I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 16 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 16 item not yet recycled. Allocated 1 mor e. I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 17 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 17 item not yet recycled. Allocated 1 mor e. I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 18 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 18 item not yet recycled. Allocated 1 mor e. I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 19 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 19 item not yet recycled. Allocated 1 mor e. I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 20 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 20 item not yet recycled. Allocated 1 mor e. I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 21 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 21 item not yet recycled. Allocated 1 mor e. I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 22 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 22 item not yet recycled. Allocated 1 mor e. I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 23 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 23 item not yet recycled. Allocated 1 mor e. I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 24 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 24 item not yet recycled. Allocated 1 mor e. I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 25 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 25 item not yet recycled. Allocated 1 mor e. I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 26 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 26 item not yet recycled. Allocated 1 mor e. I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 27 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 27 item not yet recycled. Allocated 1 mor e. D/dalvikvm( 929): Cronos GC_EXTERNAL_ALLOC freed 10K, 55% free 2686K/5895K, ext ernal 905K/927K, paused 294ms D/dalvikvm( 929): Cronos GC_EXTERNAL_ALLOC freed 5K, 55% free 2686K/5895K, exte rnal 920K/1016K, paused 135ms I/DEBUG ( 2656): 00 pc 000189b8 /data/data/com.homework.mygame/lib /libandenginephysicsbox2dextension.so (_ZN6b2Body13CreateFixtureEPK12b2FixtureDe f) I/DEBUG ( 2656): #01 pc 0000bfbc /data/data/com.homework.mygame/lib /libandenginephysicsbox2dextension.so (Java_com_badlogic_gdx_physics_box2d_Body_ jniCreateFixture__JJFFFZSSS) I/DEBUG ( 2656): #02 pc 00011d74 /system/lib/libdvm.so I/DEBUG ( 2656): I/DEBUG ( 2656): code around pc: I/DEBUG ( 2656): 80618998 eb00595d e3500000 0a000001 e1a00004 I/DEBUG ( 2656): 806189a8 ebfffd9f e594205c e3a03a19 e2833f75 I/DEBUG ( 2656): 806189b8 e7921003 e1a00005 e3811001 e7821003 I/DEBUG ( 2656): 806189c8 e8bd81f0 e594105c e1a00005 e284200c I/DEBUG ( 2656): 806189d8 e2811a19 e2811f76 eb0003ae eaffffe2 I/DEBUG ( 2656): I/DEBUG ( 2656): code around lr: I/DEBUG ( 2656): 8062ee98 e51d0004 e12fff1e e1a0c000 e1a00001 I/DEBUG ( 2656): 8062eea8 e1a0100c eaffffff e92d400f ebffffe1 I/DEBUG ( 2656): 8062eeb8 e3500000 43700000 e8bd800f e52de008 I/DEBUG ( 2656): 8062eec8 ebfffff8 03a00001 13a00000 e49df008 I/DEBUG ( 2656): 8062eed8 e52de008 ebfffff3 33a00001 23a00000 I/DEBUG ( 2656): I/DEBUG ( 2656): stack: I/DEBUG ( 2656): 449d9ac0 43707d58 I/DEBUG ( 2656): 449d9ac4 43707d40 I/DEBUG ( 2656): 449d9ac8 449d9ed8 I/DEBUG ( 2656): 449d9acc 80617174 /data/data/com.homework.mygame/lib/li bandenginephysicsbox2dextension.so I/DEBUG ( 2656): 449d9ad0 00149978 I/DEBUG ( 2656): 449d9ad4 449d9b18 I/DEBUG ( 2656): 449d9ad8 0000ffff I/DEBUG ( 2656): 449d9adc 44dbe008 I/DEBUG ( 2656): 449d9ae0 00000001 I/DEBUG ( 2656): 449d9ae4 00000000 I/DEBUG ( 2656): 449d9ae8 00000000 I/DEBUG ( 2656): 449d9aec 421cf249 I/DEBUG ( 2656): 449d9af0 bf800001 I/DEBUG ( 2656): 449d9af4 8062ef1c /data/data/com.homework.mygame/lib/li bandenginephysicsbox2dextension.so I/DEBUG ( 2656): 449d9af8 df002777 I/DEBUG ( 2656): 449d9afc e3a070ad I/DEBUG ( 2656): 00 449d9b00 ffffffff I/DEBUG ( 2656): 449d9b04 00000000 I/DEBUG ( 2656): 449d9b08 80632718 I/DEBUG ( 2656): 449d9b0c 43707d84 I/DEBUG ( 2656): 449d9b10 449d9b6c I/DEBUG ( 2656): 449d9b14 8060bfc0 /data/data/com.homework.mygame/lib/li bandenginephysicsbox2dextension.so I/DEBUG ( 2656): #01 449d9b18 80632718 I/DEBUG ( 2656): 449d9b1c 0016a928 I/DEBUG ( 2656): 449d9b20 00000000 I/DEBUG ( 2656): 449d9b24 00000000 I/DEBUG ( 2656): 449d9b28 00000000 I/DEBUG ( 2656): 449d9b2c 00000000 I/DEBUG ( 2656): 449d9b30 00017b00 I/DEBUG ( 2656): 449d9b34 0000ffff I/DEBUG ( 2656): 449d9b38 449d9b90 I/DEBUG ( 2656): 449d9b3c 00000003 I/DEBUG ( 2656): 449d9b40 44843052 I/DEBUG ( 2656): 449d9b44 aca11d78 /system/lib/libdvm.so I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 28 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 28 item not yet recycled. Allocated 1 mor e. I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 29 item not yet recycled. Allocated 1 more. D/dalvikvm( 602): Cronos GC_EXTERNAL_ALLOC freed 257K, 40% free 6266K/10311K, e xternal 1546K/1581K, paused 445ms I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 29 item not yet recycled. Allocated 1 mor e. I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 30 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 30 item not yet recycled. Allocated 1 mor e. I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 31 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 31 item not yet recycled. Allocated 1 mor e. I/AndEngine( 4918): org.anddev.andengine.input.touch.TouchEvent$TouchEventPool was exhausted, with 32 item not yet recycled. Allocated 1 more. I/AndEngine( 4918): org.anddev.andengine.util.pool.PoolUpdateHandler$1 was exhausted, with 32 item not yet recycled. Allocated 1 mor e. D/dalvikvm( 929): Cronos GC_EXTERNAL_ALLOC freed 11K, 55% free 2685K/5895K, ext ernal 726K/889K, paused 139ms D/dalvikvm( 929): Cronos GC_EXTERNAL_ALLOC freed 10K, 55% free 2686K/5895K, ext ernal 667K/749K, paused 140ms D/dalvikvm( 929): Cronos GC_EXTERNAL_ALLOC freed 5K, 55% free 2685K/5895K, exte rnal 920K/1016K, paused 138ms D/dalvikvm( 602): Cronos GC_EXTERNAL_ALLOC freed 32K, 40% free 6246K/10311K, ex ternal 1403K/1470K, paused 343ms I/BootReceiver( 602): Copying /data/tombstones/tombstone_02 to DropBox (SYSTEM_ TOMBSTONE) E/InputDispatcher( 602): channel '408f3600 com.homework.mygame/com.homework.myg ame.com.homework.mygame (server)' ~ Consumer closed input channel or an error oc curred. events=0x8 E/InputDispatcher( 602): channel '408f3600 com.homework.mygame/com.homework.myg ame.com.homework.mygame (server)' ~ Channel is unrecoverably broken and will be disposed! D/Zygote ( 565): Process 4918 terminated by signal (11) D/dalvikvm( 602): Cronos GC_FOR_MALLOC freed 123K, 39% free 6384K/10311K, exter nal 958K/1470K, paused 141ms I/dalvikvm-heap( 602): Grow heap (frag case) to 9.928MB for 161568-byte allocat ion D/dalvikvm( 602): Cronos GC_FOR_MALLOC freed 3K, 38% free 6538K/10503K, externa l 958K/1470K, paused 147ms I/WindowManager( 602): WIN DEATH: Window{408f3600 com.homework.mygame/com.homew ork.mygame.com.homework.mygame paused=false} D/dalvikvm( 602): Cronos GC_FOR_MALLOC freed 2K, 38% free 6537K/10503K, externa l 847K/1359K, paused 143ms I/dalvikvm-heap( 602): Grow heap (frag case) to 9.891MB for 80792-byte allocati on D/dalvikvm( 602): Cronos GC_FOR_MALLOC freed <1K, 38% free 6615K/10631K, extern al 847K/1359K, paused 144ms D/dalvikvm( 602): Cronos GC_FOR_MALLOC freed 217K, 40% free 6398K/10631K, exter nal 847K/1359K, paused 142ms I/WindowManager( 602): WIN DEATH: Window{4090fff8 SurfaceView paused=false} D/gralloc ( 602): freeing GPU buffer at 0 D/gralloc ( 602): freeing GPU buffer at 307200 I/ActivityManager( 602): Process com.homework.mygame (pid 4918) has died. W/InputManagerService( 602): Got RemoteException sending setActive(false) notif ication to pid 4918 uid 10088 D/dalvikvm( 929): Cronos GC_EXPLICIT freed 9K, 55% free 2683K/5895K, external 4 89K/889K, paused 68ms V/com.mobilityflow.animatedweather.services.UpdateService$ServiceThread( 929): Timed alarm onReceive() started at time: 2011-05-13 17:07:25.491 W/System.err( 929): java.net.UnknownHostException: www.yr.no W/System.err( 929): at java.net.InetAddress.lookupHostByName(InetAddress.jav a:506) W/System.err( 929): at java.net.InetAddress.getAllByNameImpl(InetAddress.jav a:294) W/System.err( 929): at java.net.InetAddress.getAllByName(InetAddress.java:25 6) W/System.err( 929): at org.apache.http.impl.conn.DefaultClientConnectionOper ator.openConnection(DefaultClientConnectionOperator.java:136) W/System.err( 929): at org.apache.http.impl.conn.AbstractPoolEntry.open(Abst ractPoolEntry.java:164) W/System.err( 929): at org.apache.http.impl.conn.AbstractPooledConnAdapter.o pen(AbstractPooledConnAdapter.java:119) W/System.err( 929): at org.apache.http.impl.client.DefaultRequestDirector.ex ecute(DefaultRequestDirector.java:348) W/System.err( 929): at org.apache.http.impl.client.AbstractHttpClient.execut e(AbstractHttpClient.java:555) W/System.err( 929): at org.apache.http.impl.client.AbstractHttpClient.execut e(AbstractHttpClient.java:487) W/System.err( 929): at org.apache.http.impl.client.AbstractHttpClient.execut e(AbstractHttpClient.java:465) W/System.err( 929): at com.mobilityflow.animatedweather.weather_providers.Yr Provider.loadWeatherWeek(YrProvider.java:440) W/System.err( 929): at com.mobilityflow.animatedweather.weather_providers.Yr Provider.providerLoadWeather(YrProvider.java:135) W/System.err( 929): at com.mobilityflow.animatedweather.weather_providers.We atherProvider.loadWeatherData(WeatherProvider.java:125) W/System.err( 929): at com.mobilityflow.animatedweather.WebProvider$ThreadWe atherLoad.run(WebProvider.java:256) So I guess it's because on onAreaTouched function. I use it to control a player, there are 2 arrows and we can touch them to move player from left to right. Am I doing it correctly or should I do it in another way ? Here's my code: mRArrow = new Sprite(125, CAMERA_HEIGHT - 55, mRArrowTextureRegion) { @Override protected void onManagedUpdate(float pSecondsElapsed) { super.onManagedUpdate(pSecondsElapsed); } @Override public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) { Body playerBody = mPhysicsWorld.getPhysicsConnectorManager() .findBodyByShape(mPlayer); playerBody.setTransform(new Vector2((playerBody.getPosition().x + 0.15f) ,playerBody.getPosition().y), 0); return true; } }; mLArrow = new Sprite(15, CAMERA_HEIGHT - 55, mLArrowTextureRegion) { @Override protected void onManagedUpdate(float pSecondsElapsed) { super.onManagedUpdate(pSecondsElapsed); } @Override public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) { Body playerBody = mPhysicsWorld.getPhysicsConnectorManager() .findBodyByShape(mPlayer); playerBody.setTransform(new Vector2((playerBody.getPosition().x - 0.15f) ,playerBody.getPosition().y), 0); return true; } }; Thanks in advance Greg A: Do not touch a Physics-"Body" inside of a TouchEvent. UI-Thread and UpdateThread hate working at the same time!
{ "pile_set_name": "StackExchange" }
Q: change the privileges of opening a file when it has already jumped to a remote host using tramp Good afternoon. To visit the local sudo privilege file, I use the tramp command: Ctr+f //sudo::/путьКфайлу Is it possible to open a remote file with sudo privileges if emacs already uses tramp, and the invitation to enter visiting the file looks like: Ctr+f /ssh:remoteHost:/home/uzvr It seems to me there should be a team to change the privileges of opening files when emacs is already working with deleted files. Thanks. Thank you, Michael Albinus, you get a new jump, and you can’t use the fact that you already reached the host. I use an ssh certificate to access the host (it is written in the configuration file, thank you again for this personally), a third-party application forms the command (in this case, my command looks like this: /usr/local/bin/emacs -eval ' (progn (require (quote tramp-sh)) (let ((args (assoc (quote tramp-login-args) (assoc "ssh" tramp-methods)))) (setcar (cdr args) (append (quote (("-F" "/home/alamd/ПакетыДоступа/al_kuhnia/config"))) (cadr args)))))' \ "/ssh:remoteHost: ~" Next, emacs opens the user folder. It turns out then how can I transfer the configuration file for ssh again to tramp A: Use Tramp's multi-hop: C-x C-f /ssh:remoteHost|sudo:remotehost:/home/uzvr The Tramp manual gives you more detail. This will only work if you immediately attach my ssh configuration file for the trump, but I would like not to edit all files from root.only such a solution comes to mind M-: (progn (require (quote tramp-sh)) (let ((args (assoc (quote tramp-login-args) (assoc "ssh" tramp-methods)))) (setcar (cdr args) (append (quote (("-F" "/home/alamd/ПакетыДоступа/al_kuhnia/config"))) (cadr args)))) (find-file "/ssh:remoteHost|sudo:remotehost:/etc/ssh/sshd_config"))
{ "pile_set_name": "StackExchange" }
Q: How to prove ownership of a website? We all know how banks identify themselves to users. No, not through TLS certificates. The users pay no attention to those. No, I'm talking about branding-- all those fancy logos and stock photos that give you the impression it's your actual banking site. The trouble is that anyone can copy those images for themselves and make a convincing fake of a bank's site, and trick users into entering their banking password, even though the site they're on is the wrong domain. This is why phishing works. So since users don't check the domain name or TLS certificate chain, how else can we prove, before they enter their password, that they're on a site they should trust? (e.g., showing an image the user could recognize, but a third party would have trouble forging, like a reverse captcha) (P.S. The obvious alternative solution is not to require a password at all, like in Google Authentication, but I'm retrofitting a set of websites and I'm looking for alternatives.) A: Security measures strengthen in inverse proportion to convenience... so I probably wouldn't do this... and I don't know a single site that does this... but... you did ask. How about a workflow like this: User accesses web site and enters user name Site looks up user's phone number and sends one time code or a random word as SMS. Site displays one time code and instructs user to verify it against the code/word sent to the phone Phishers won't know the user's phone number. They could in theory trigger the one time code (via MITM) but the attacker would not know the code. So if a user sees a code on the page and on the phone, (s)he knows that the site is good.
{ "pile_set_name": "StackExchange" }
Q: Saving Image to core Data I am a newbie related to core data. Could any one help me to provide proper steps/ tutorial showing how to save images to core data and its retrival too.I am able to store string data already, but my app crashes when trying to save image. For saving: DataEvent *event = (DataEvent *)[NSEntityDescription insertNewObjectForEntityForName:@"DataEvent" inManagedObjectContext:managedObjectContext]; NSURL *url2 = [NSURL URLWithString:@"xxxxxxxxxxxxxxx SOME URL xxxxxxxxxxxx"]; NSData *data = [[NSData alloc] initWithContentsOfURL:url2]; imageSave=[[UIImage alloc]initWithData:data]; NSData * imageData = UIImageJPEGRepresentation(imageSave, 100.0); [event setValue:self.imageSave forKey:@"pictureData"]; For retrival: DataEvent *event = (DataEvent *)[eventsArray objectAtIndex:indexPath.row]; UIImage *image = [UIImage imageWithData:[event valueForKey:@"pictureData"]]; UIImageView *imageViewMainBackGround = [[UIImageView alloc] CGRect rect3=CGRectMake(0,2,100.0,100.0); imageViewMainBackGround.frame = rect3; [cell.contentView addSubview:imageViewMainBackGround]; [imageViewMainBackGround release]; A: To save: NSData *imageData = UIImagePNGRepresentation(myUIImage); [newManagedObject setValue:imageData forKey:@"imageKey"]; And To Retrive Image: NSManagedObject *selectedObject = [[self fetchedResultsController] objectAtIndexPath:indexPath]; UIImage *image = [UIImage imageWithData:[selectedObject valueForKey:@"imageKey"]]; [[newCustomer yourImageView] setImage:image]; changed format
{ "pile_set_name": "StackExchange" }
Q: I want to make an array like ["test": [[0.1,0.2], [0.3,0.4]]] in Swift I want to make an array like ["test": [[0.1,0.2], [0.3,0.4]]] in Swift. I have tried the following code but it doesn't work. var testArray = [String: [[Float]]]() testArray["test"] = [] testArray["test"]!.append([0.1]) testArray["test"]!.append([0.2]) testArray["test"]!.append([0.3]) testArray["test"]!.append([0.4]) print(testArray) I didn't want to be like this, but the output was: ["test": [[0.1], [0.2], [0.3], [0.4]]] How can I get the output I want? A: var testArray = [String: [[Float]]]() testArray["test"] = [] testArray["test"]!.append([0.1, 0.2]) testArray["test"]!.append([0.3,0.4]) print(testArray)
{ "pile_set_name": "StackExchange" }
Q: What will be the cron expression for scheduling a job in every 5 minutes? I am working on a scheduler class. I want to schedule my job after every 5 minutes. But i am not getting the correct CRON expression for that. Can anyone please guide me on this. Also let me know how to for a CRON Expression? A: As Doug says, this is not apparently possible in Salesforce Cron trigger. You may want to consider a 'self re-scheduling' job, e.g. global class SelfSchedule implements schedulable { global void execute( SchedulableContext SC ) { // do whatever it is you want to do here SelfSchedule.start(); // abort me and start again System.abortJob( SC.getTriggerId() ); } public static void start() { // start keepalive again in 5 mins Datetime sysTime = System.now().addSeconds( 300 ); String chronExpression = '' + sysTime.second() + ' ' + sysTime.minute() + ' ' + sysTime.hour() + ' ' + sysTime.day() + ' ' + sysTime.month() + ' ? ' + sysTime.year(); System.schedule( 'SelfSchedule ' + sysTime, chronExpression, new SelfSchedule() ); } } You may also want to consider the solution I outlined here. Note the issues pointed out in the OP though, every 5 minutes might on occasions be problematic.
{ "pile_set_name": "StackExchange" }
Q: Backbone.js removing the model I have been trying for hours now, without luck. If you could see on the image, I have mildly complex model. Image is taken from Chrome in debug. I need to delete a model from collection, also I need to be able to change the URL where the backbone will shoot its ajax for delete. So in essence, this is my model structure: attributes: favorites { bookmarkedArticles: [{id: 123123},{id: ...}], bookedmarkedSearches: [{}], dispatchesMailds: [] } How can I delete model in bookmarkedArticles with id of 123123? I have tried this: var model = new metaModel( { favourites: { bookmarkedArticles: { id: "123123" } } } ); model.destroy(); also this aamodel.headerData.collection.remove(model); No success at all. A: The information provided is not giving a lot of details, but I will try to answer considering two scenarios: Option A: You are trying to delete a model in the collection that has bookmarkedArticle.id="123123". if that is the case and considering the bookmarkedArticles it is just an Array of objects, I would suggest to filter the Collection using the underscore method filter and then delete the models returned by the filter. var id = 123123; var modelsToDelete = aamodel.headerData.collection.filter(function(model){ // find in the bookmarked articles return _.find(model.get('bookmarkedArticles'), function(ba){ return (ba.id === id); }); }); _.each(modelsToDelete, function(model){ model.destroy(); }); Option 2: If you want to remove the bookmarked article '123123' associated to your main model using just the 'destroy' method, firstable you have to convert 'bookmarkedArticles' to a Backbone.Collection as it is just an Array of Objects, there are some utilities for Backbone that allows you to do this easily: https://github.com/blittle/backbone-nested-models But by default this is not possible, then, If you want to remove the 'bookmarkedArticle' you can create the Backbone.Model and then use the method destroy. Example: var BookmarkedArticle = Backbone.Model.extend({ url: function(){ return '/bookmarkArticle/' + this.id; } }); new BookmarkedArticle({"id": "123123","master": "5",...}).destroy(); Hope this information is useful and provide some guidance to solve your problem.
{ "pile_set_name": "StackExchange" }
Q: Why the search query always use ID? I'm trying to use ->find() I want to do query lie this Where IdBiodata = '$IdBiodata' Then I try this way : Route::get('biodata/{IdBiodata}', function ($IdBiodata) { $databiodata = DB::table('Biodata')->find($IdBiodata); if(count($databiodata)) { return view('biodata/vew',compact('databiodata')); }else{ echo "Data not Found"; } }); when I run it . I face this SQLSTATE[42S22]: [Microsoft][SQL Server Native Client 10.0][SQL Server]Invalid column name 'id'. (SQL: select top 1 * from [Biodata] where [id] = 1) how can i fix it ? thanks in advance My Table structure CREATE TABLE [dbo].[Biodata]( [IdBiodata] [int] IDENTITY(1,1) NOT NULL, [Nama] [varchar](max) NULL, [Umur] [int] NULL, CONSTRAINT [PK_Biodata] PRIMARY KEY CLUSTERED ( [IdBiodata] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] A: your search query written using query builder not using Eloquent ORM.find() function Retrieving A Record By Primary Key and Primary Key always take column name as id untill and unless you can not defined externally. So $databiodata = DB::table('Biodata')->find($IdBiodata); when you write this it's assume Primary key as id. in Eloquent ORM you can change Primary Key class Biodata extends Eloquent { protected $primaryKey = 'IdBiodata'; } Now, you can write Biodata::find($IdBiodata); if you don't wan to use Eloquent ORM so simply use other function rather than find() use where() $databiodata = DB::table('Biodata')->where('IdBiodata',$IdBiodata)->get(); SO now Replace Your Code using below code From this $databiodata = DB::table('Biodata')->find($IdBiodata); To $databiodata = DB::table('Biodata')->where('IdBiodata',$IdBiodata)->get();
{ "pile_set_name": "StackExchange" }
Q: What does offset mean in Bootstrap? What does the 'offset' parameter do in Bootsrap? For example, what is the difference between col-sm-offset-2 and col-sm-2? A: See the comment. Basically it pushes the cols to the right. So in your example, col-sm-offset-2would push the element 2 columns to the right in 'md' view. So your element kinda starts at col-3. col-sm-2 on the other hand just tells the element how wide it is. If you combine these 2 statements, you get an element that is pushed in 2 cols and is 2 cols wide.
{ "pile_set_name": "StackExchange" }
Q: Flutter - How to load JSON into futurebuilder I'm trying to create what should be a very simple flutter app that will load all data from a POST with parameters and create a scrolling list with the details. currently I'm not getting any errors, however the loading circle just spins for ever even though the JSON has been successfully returned, any help or ideas would be greatly appreciated. Here's what I have so far: import 'dart:async'; import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; Future<List<Post>> fetchPosts(http.Client client) async { var url = "contacts.json"; var client = new http.Client(); var request = new http.Request('POST', Uri.parse(url)); var body = {'type': 'getContacts'}; request.bodyFields = body; var data = http.post(url, body: {"type": "getContacts"}) .then((response) { print(response.body); return compute(parsePosts, response.body); }); } // A function that will convert a response body into a List<Photo> List<Post> parsePosts(String responseBody) { final parsed = json.decode(responseBody).cast<Map<String, dynamic>>(); return parsed.map<Post>((json) => Post.fromJson(json)).toList(); } class Post { final String First; final String Last; final String Email; final String Phone; final String Photo; final String Full; Post({this.Full, this.First, this.Last, this.Photo, this.Email, this.Phone}); factory Post.fromJson(Map<String, dynamic> json) { return new Post( Full: json['Full'] as String, First: json['First'] as String, Last: json['Last'] as String, Photo: json['Photo'] as String, Email: json['Email'] as String, Phone: json['Phone'] as String, ); } } void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final appTitle = 'CONTACTS'; return MaterialApp( title: appTitle, home: MyHomePage(title: appTitle), ); } } class MyHomePage extends StatelessWidget { final String title; MyHomePage({Key key, this.title}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(title), ), body: FutureBuilder<List<Post>>( future: fetchPosts(http.Client()), builder: (context, snapshot) { if (snapshot.hasError) print(snapshot.error); return snapshot.hasData ? PhotosList(photos: snapshot.data) : Center(child: CircularProgressIndicator()); }, ), ); } } class PhotosList extends StatelessWidget { final List<Post> photos; PhotosList({Key key, this.photos}) : super(key: key); @override Widget build(BuildContext context) { return ListView.builder( itemCount: photos == null ? 0 : photos.length, itemBuilder: (BuildContext context, i) { return new ListTile( title: new Text(photos[i].Last + " " + photos[i].First), subtitle: new Text(photos[i].Phone), leading: new CircleAvatar( backgroundImage: new NetworkImage(photos[i].Photo), ) ); } ); } } Test JSON data as such: [{ "Full": "Billy Bobbins", "First": "Billy", "Last": "Bobbins", "Photo": "", "Email": "[email protected]", "Phone": "18885551212" }, { "Full": "Darron Dragonborn", "First": "Darron", "Last": "Dragonborn", "Photo": "", "Email": "[email protected]", "Phone": "18005551111" }] A: Because you are using Future and async, you can use await for asynchronous operation. So your fetchPosts should be like this Future<List<Post>> fetchPosts(http.Client client) async { var url = "contacts.json"; var client = new http.Client(); var request = new http.Request('POST', Uri.parse(url)); var body = {'type': 'getContacts'}; request.bodyFields = body; var data = await http.post(url, body: {"type": "getContacts"}); print(data.body); return await compute(parsePosts, data.body); }
{ "pile_set_name": "StackExchange" }
Q: Swift NSUserDefaults NSArray using objectForKey I'm pretty new to Swift, and I've managed to get pretty stuck. I'm trying to retrieve data from NSUserDefaults and store it in an array (tasks): @lazy var tasks: NSArray = { let def = NSUserDefaults.standardUserDefaults() let obj: AnyObject? = def.objectForKey("tasks") return obj as NSArray }() All I'm getting is a warning: EXE_BAD_INSTRUCTION on line 3. Also to note that I haven't actually set any data yet, but what I'm aiming for is that if there is no data, I want the array to be empty. I'll be using the data to populate a table view. Now using a var instead of a constant: @lazy var tasks: NSArray = { let def = NSUserDefaults.standardUserDefaults() var obj: AnyObject? = { return def.objectForKey("tasks") }() return obj as NSArray }() The error has now moved to the return line. A: I think the problem here is that you are attempting to cast nil to a non-optional type and return it. Swift does not allow that. The best way to solve this would be the following: @lazy tasks: NSArray = { let defaults = NSUserDefaults.standardUserDefaults() if let array = defaults.arrayForKey("tasks") as? NSArray { return array } return NSArray() } Using Swift's if let syntax combined with the as? operator lets you assign and safe cast in one line. Since your method does not return an optional, you must return a valid value if that cast fails.
{ "pile_set_name": "StackExchange" }
Q: c++ Stop Enemy Sprites Moving Over Each Other I'm making a 2d game and I'm trying to stop enemy sprites moving over each other. I've implemented the following method that is supposed to check that enemies are not overlapping, then move one of them back in the direction they came. However this method seems to crash my game as only one enemy is ever rendered. This is my check method: size = enemys.size(); for (int i = 0; i<size; i++){ double x = enemys[i].getEnemyX(); double y = enemys[i].getEnemyY(); for (int s = 1; s<size; s++){ double enemyX = enemys[s].getEnemyX(); double enemyY = enemys[s].getEnemyY(); if (x >= enemyX-5.0 && x <= enemyX+5.0 && y >= enemyY-5.0 && y <= enemyY + 5.0){ double xDir = x - enemyX; double yDir = y - enemyY; double hyp = sqrt(xDir*xDir + yDir*yDir); xDir /= hyp; yDir /= hyp; x -= xDir * 5; y -= yDir * 5; enemys[s].setEnemyCoord(x,y); } } }* A: Your code will end up checking each enemy against itself. Make your inner loop start from s=i+1
{ "pile_set_name": "StackExchange" }
Q: Updating Ruby version to newer (latest) on production? We use Ubuntu 12.04 TLS, Ruby 1.9.3, Rails 3.2.12, and RVM on our production server. We want to upgrade Ruby from 1.9.3 to 2.2 (or whatever the latest one is), without updating Rails. I have three questions: Are there any caveats in doing that, any inconsistensies, deprecated methods? Is there any chance that site will stop working? Considering that we are using RVM, would it be possible to get back to the version we are using right now (if anything goes wrong)? Would it be necessary to re-install all the gems that we are using right now? Thanks in advance! A: Always presume the whole machine is going to be trashed beyond repair by this process. Prepare for the worst, hope for the best. If you don't have a test machine, you can build one with a tool like Vagrant. Once you have a procedure that works, repeat it on your production system. Ruby 2.1.1 is the current version. You'll also want to look at upgrading Rails itself to avoid a bunch of nasty vulnerabilities. 3.2.17 is the version to target here. RVM does make it easier to upgrade things, but you'll also need to upgrade your launcher (e.g. Passenger) to use the newer Ruby version. Yes, it is possible to back out, but this is not always convenient. One trick that might help rescue from disaster is checking your /etc directory into a local Git repository. This allows you to rollback any configuration changes you make, as well as see what changes you've actually made through the course of your upgrades. Any change to the base Ruby version does require re-installing all gems. If you're using Bundler or an automated deployment tool this should be fairly automatic.
{ "pile_set_name": "StackExchange" }
Q: Android - Listening for incoming TCP/Socket messages in background I am trying to write a little application which sends TCP messages (with a PrintWriter) to a JAVA Server running on PC. Now the Client should listen in background for incoming messages from the Server. How can I listen for incoming messages an update the GUI with the message from background-task? A: You'll want to spin up a background thread for this. Probably the easiest way to go is to use an AsyncTask and then use onPostExecute, or publishProgress, to safely display your message in the UI. Check out the Android docs on threads.
{ "pile_set_name": "StackExchange" }
Q: How do you use the gizmo for Café Sua Da? Vietnamese Iced Coffee or Café Sua Da is usually served with the little brew pot dripping coffee into a glass with sweetened condensed milk at the bottom. You then stir and add ice and enjoy. But what's the little screen with the screw for? Usually in restaurants I find it just sitting loose. Is it supposed to be screwed-on or loose? Is it supposed to constrain the expansion of the grounds or just help form the initial packed puck shape? Is the lid important? Bonus questions: How important is it to have chicory in the coffee? What's a good proportion? A: Here's a website that goes into it and includes this picture of the gizmo to which you refer: This little single serving device is meant to fit over a cup, hold about two tablespoons worth of coffee, and the required amount of water for brewing. There is a screen on the bottom, and a plunger with another screen on it that screws down on top of the coffee to smush it between the two filters. The tightness of this top filter controls the strength of the coffee. The tighter it is, the slower water flows, and the stronger the brew. EDIT: Regarding the "bonus question": I'm not aware of chicory as an ingredient in Vietnamese/Thai iced coffee, I'm only familiar with it as a traditional New Orleans addition, having migrated from France. It became a popular substitution during the French Revolution when coffee became prohibitively expensive. Certainly the website I linked to uses it, so it may be traditional for some. Certainly the French significantly influenced Vietnamese and Thai cuisine. I dug up a recipe for New Orleans chicory coffee: "Ingredients 1 lb. coarsely ground coffee, 1 1/2 oz. roasted and chopped chicory, 2 1/2 quarts water, 3 oz. simple syrup, Tools Large stockpot, Wooden spoon, Fine-mesh sieve, Large Mason jar, Combine the ground coffee, chicory and water in a stockpot. Stir with a wooden spoon, cover and let steep at room temperature for 8-12 hours. Carefully break the crust of the coffee grounds with a spoon and strain through a fine-mesh sieve into the Mason jar. Add simple syrup to concentrate and stir to combine. Serve over ice and add milk to taste—most people opt for about a 50/50 ratio of milk to chicory-coffee concentrate. Keep refrigerated and use within 1-2 days. Yields 4-5 cups of concentrate.
{ "pile_set_name": "StackExchange" }
Q: Multilevel JSON data using jquery can any one tell me how to access data from "item2" from the below json? JSON item1: [ { "location": [ {"latitude": value, "longitude": value, "fileName": value } ], "links": [ {"latitude": value, "longitude": value, "fileName": value }, {"latitude": value, "longitude": value, "fileName": value }, {"latitude": value, "longitude": value, "fileName": value } ] } ], item2: [ //repeat of above ] A: This will help you to iterate the item2 from your json <script language="javascript" > document.writeln("<h2>JSON array object</h2>"); var books = { "Java" : [ { "Name" : "Java is Simple", "price" : 500 }, { "Name" : "The Complete Reference", "price" : 600 } ], "Spring" : [ { "Name" : "Spring is mvc", "price" : 300 }, { "Name" : "Basics Spring", "price" : 200 } ] } var i = 0 document.writeln("<table border='2'><tr>"); for(i=0;i<books.Java.length;i++) { document.writeln("<td>"); document.writeln("<table border='1' width=100 >"); document.writeln("<tr><td><b>Name</b></td><td width=50>" + books.Java[i].Name+"</td></tr>"); document.writeln("<tr><td><b>Price</b></td><td width=50>" + books.Java[i].price +"</td></tr>"); document.writeln("</table>"); document.writeln("</td>"); } for(i=0;i<books.Spring.length;i++) { document.writeln("<td>"); document.writeln("<table border='1' width=100 >"); document.writeln("<tr><td><b>Name</b></td><td width=50>" + books.Spring[i].Name+"</td></tr>"); document.writeln("<tr><td><b>Price</b></td><td width=50>" + books.Spring[i].price+"</td></tr>"); document.writeln("</table>"); document.writeln("</td>"); } document.writeln("</tr></table>"); </script>
{ "pile_set_name": "StackExchange" }
Q: Transfer existing email to new postfix/dovecot server via POP3 I have to build a new email server with dovecot/postfix on CentOS because an existing supplier is becoming too erratic with their billing. I can do that but I am worried for a small problem. If I create a new server before I transfer the MX records and DNS, can I connect to the existing server via POP3 using the new server as a client and "download" all the email that way? A: Nevermind, I found dsync tool from Dovecot wiki. As alternative, you can also use imapsync.
{ "pile_set_name": "StackExchange" }
Q: Mapping a sequence of results from Slick monadic join to Json I'm using Play 2.4 with Slick 3.1.x, specifically the Slick-Play plugin v1.1.1. Firstly, some context... I have the following search/filter method in a DAO, which joins together 4 models: def search( departureCity: Option[String], arrivalCity: Option[String], departureDate: Option[Date] ) = { val monadicJoin = for { sf <- slickScheduledFlights.filter(a => departureDate.map(d => a.date === d).getOrElse(slick.lifted.LiteralColumn(true)) ) fl <- slickFlights if sf.flightId === fl.id al <- slickAirlines if fl.airlineId === al.id da <- slickAirports.filter(a => fl.departureAirportId === a.id && departureCity.map(c => a.cityCode === c).getOrElse(slick.lifted.LiteralColumn(true)) ) aa <- slickAirports.filter(a => fl.arrivalAirportId === a.id && arrivalCity.map(c => a.cityCode === c).getOrElse(slick.lifted.LiteralColumn(true)) ) } yield (fl, sf, al, da, aa) db.run(monadicJoin.result) } The output from this is a Vector containing sequences, e.g: Vector( ( Flight(Some(1),123,216,2013,3,1455,2540,3,905,500,1150), ScheduledFlight(Some(1),1,2016-04-13,90,10), Airline(Some(216),BA,BAW,British Airways,United Kingdom), Airport(Some(2013),LHR,Heathrow,LON,...), Airport(Some(2540),JFK,John F Kennedy Intl,NYC...) ), ( etc ... ) ) I'm currently rendering the JSON in the controller by calling .toJson on a Map and inserting this Vector (the results param below), like so: flightService.search(departureCity, arrivalCity, departureDate).map(results => { Ok( Map[String, Any]( "status" -> "OK", "data" -> results ).toJson ).as("application/json") }) While this sort of works, it produces output in an unusual format; an array of results (the rows) within each result object the joins are nested inside objects with keys: "_1", "_2" and so on. So the question is: How should I go about restructuring this? There doesn't appear to be anything which specifically covers this sort of scenario in the Slick docs. Therefore I would be grateful for some input on what might be the best way to refactor this Vector of Seq's, with a view to renaming each of the joins or even flattening it out and only keeping certain fields? Is this best done in the DAO search method before it's returned (by mapping it somehow?) or in the controller after I get back the Future results Vector from the search method? Or I'm wondering whether it would be preferable to abstract this sort of mutation out somewhere else entirely, using a transformer perhaps? A: You need JSON Reads/Writes/Format Combinators In the first place you must have Writes[T] for all your classes (Flight, ScheduledFlight, Airline, Airport). Simple way is using Json macros implicit val flightWrites: Writes[Flight] = Json.writes[Flight] implicit val scheduledFlightWrites: Writes[ScheduledFlight] = Json.writes[ScheduledFlight] implicit val airlineWrites: Writes[Airline] = Json.writes[Airline] implicit val airportWrites: Writes[Airport] = Json.writes[Airport] You must implement OWrites[(Flight, ScheduledFlight, Airline, Airport, Airport)] for Vector item also. For example: val itemWrites: OWrites[(Flight, ScheduledFlight, Airline, Airport, Airport)] = ( (__ \ "flight").write[Flight] and (__ \ "scheduledFlight").write[ScheduledFlight] and (__ \ "airline").write[Airline] and (__ \ "airport1").write[Airport] and (__ \ "airport2").write[Airport] ).tupled for writing whole Vector as JsAray use Writes.seq[T] val resultWrites: Writes[Seq[(Flight, ScheduledFlight, Airline, Airport, Airport)]] = Writes.seq(itemWrites) We have all to response your data flightService.search(departureCity, arrivalCity, departureDate).map(results => Ok( Json.obj( "status" -> "Ok", "data" -> resultWrites.writes(results) ) )
{ "pile_set_name": "StackExchange" }
Q: Problem autoexecuting yuicompressor in Vim (executing it from any directory) I made yuicompressor work from the command line. But the only thing I didn't understand from this tutorial is this part: You most install yuicompressor and make yuicompressor executable from any directory. How do I make it execute from any directory? A: You need to put it in your PATH environment variable in Windows or in similar one in other OS'es.
{ "pile_set_name": "StackExchange" }
Q: Why doesn't this play in Safari? <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Test</title> </head> <body> <audio controls="controls" > <source src="coin.mp3" type="audio/mp3" /> Your browser does not support the audio element. </audio> </body> </html`` This plays in Chrome without a hitch. A: It's most likely because Safari's HTML5 audio/video support relies on Quicktime, which means anyone using Safari will need to have Quicktime installed. A: should be mpeg, not mp3 for the file type <audio controls="controls" > <source src="coin.mp3" type="audio/mpeg" /> Your browser does not support the audio element. </audio>
{ "pile_set_name": "StackExchange" }
Q: Number of processors / Number of cores per processor Intel Core 2 Duo I'm confused about years, what is the correct setting for this processor Intel Core 2 Duo, here is the specification. I can set Number of processors to 2 and Number of cores to 1 or I can set Number of processors to 1 and Number of cores to 2 and both setting works. From my point of view the second option is right, because I have physically only one processor on the motherboard. Thank you for confirmation and comments. A: You must consider always the processor as the physical unit. So, Core2Duo is a SIngle Processor with 2 cores. For instance, the i7-4970 is a Single CPU with 4 cores in Hyperthreading (you may consider like 8 cores).
{ "pile_set_name": "StackExchange" }
Q: Config for Enabling SSI nginx? I want to do server side include and i have nginx server installed in my machine and i cant find a way to enable ssi in nginx.conf file? all i can find from the internet is syntax: ssi on | off; default: ssi off; context: http, server, location, if in location A: Enable ssi on the location context. In my case i want it on root location / { ssi on; } A: It looks like you were having the same problem I was having; finding a crystal clear explanation of how to enable SSI on NGINX. Crystal Clear entails not just which syntax to use, but the format, and exactly where to include it. I figured it out and it's not that difficult, but the lack of clear instructions on the internet was frustrating. You'll need to open up the nginx.conf file and look for the section that is formatted as follows (I've included the 'ssi on' syntax as well): location / { root E:\website\FinalJRLWeb; index index.html index.shtml; ssi on; } It took me a bit to realize the location, but it's really as simple as adding the line 'ssi on' right underneath the specified index file names (and it should be able to really go anywhere you'd like, I don't imagine the order matters, just as long as it's within the two brackets {}). After that, to verify that SSI is working on your NGINX server, add the following line anywhere in the 'body' tag of a blank html page <!--#echo var="DATE_LOCAL" --> and save it with the extension .shtml in your web server's root directory. You should see the server's local date and time displayed upon visiting your page. I realize this is almost a year old, but after my frustration trying to find clear instructions, I wanted to do my best to try and provide clear instructions for anyone else that may need them. So hopefully this will help someone out! Here's NGINX's documentation page on SSI (which honestly was not helping me as much as I would have liked, but it nonetheless is useful, and can only become more and more useful) http://nginx.org/en/docs/http/ngx_http_ssi_module.html#ssi_last_modified
{ "pile_set_name": "StackExchange" }
Q: Import function into jest.mock to avoid boilerplate code I assume this must be a pretty straightforward solution, but I am struggling to find a solution. I have a function at the top of my tests: jest.mock('../someFile', () => { const setWidth = () => { // lots of complex logic }; return { width: jest .fn() .mockImplementation(element => { setWidth(element); }; }; }; }; So, I understand that jest.mock is hoisted above the import statements in every test run, but say I would like to cut down on the boiler plate code I need in this file and as an example if setWidth was a really big function and I want to import it from another file, is there any way I could do this? If I move setWidth to another file and try the following it fails due to the hoisting import { setWidth } from ./setWidth jest.mock('../someFile', () => { return { width: jest .fn() .mockImplementation(element => { setWidth(element); }; }; }; }; The error received is: ● Test suite failed to run Invalid variable access: setWidth Thanks in advance for any possible solutions! A: jest.mock gets hoisted above the import, so that won't work. But what you can do is use requireActual jest.mock('../someFile', () => { const { setWidth } = jest.requireActual('./setWidth'); return { width: jest .fn() .mockImplementation(element => { setWidth(element); }; }; }; }; Looks like you’re starting to go a bit crazy with "testing infrastructure" though - try to consider if there's a more "real" way (less testing infrastructure) you can test your code. The most likely way to do this is to break the code your testing down into smaller functions/components.
{ "pile_set_name": "StackExchange" }
Q: html javascript, multiply the values of a dynamic row I've dynamically created rows in a table using javascript that I've altered to suit my needs, within this dynamically created table i want to multiply Qty with price and put that in the total box, html <table> <tbody id="plateVolumes"> <tr> <td><input type="checkbox" value="None" id="chk" name="chk[]" /></div></td> <td><input type='text' name='qty' id='qty' class="qty" placeholder='Qty' /></td> <td><select name="productdescription[]" class="productdescription" id="productdescription"> <option value="Product">Product</option> <option value="Product01" label="Product01">Product01</option> <option value="Product02" label="Product02">Product02</option> <option value="Product03" label="Product03">Product03</option> <option value="Product04" label="Product04">Product04</option> <option value="Product05" label="Product05">Product05</option> <option value="Product06" label="Product06">Product06</option> </select></td> <td><input type='text' name='price[]' id='price' class="price" placeholder='Price (&pound;)' onChange="WO()" /></td> <td><input type='text' name='totalprice[]' id='totalprice' class="price" placeholder='Total Price&nbsp;(&pound;)' /></td> </tr> </tbody> </table> I am using this javascript code in order to add the values together but this will only work with the first line that isn't created by the code: javascript <script> function WO() { var qty = document.getElementById('qty').value; var price = document.getElementById('price').value; answer = (Number(qty) * Number(price)).toFixed(2); document.getElementById('totalprice').value = answer; } </script> I'm pretty new with javascript so I'm wondering if there is a way to apply this to the dynamic rows also but keep them separate for when I pass them over to my php mailer. EDIT: I've been playing with the code and I'm a bit closer to getting the answer I need but I still don't know how to make this give me the answers that I want, function WO() { for (var i = 0; i < rowCount; i++) { var qty = document.getElementsByClassName('qty').value; var price = document.getElementsByClassName('price').value; var answer = (Number(qty) * Number(price)).toFixed(2); document.getElementsByClassName('totalprice[' + i + ']').innerHTML = answer; } } A: this helped, I've asked a friend who's created this, just thought I'd add it in case anyone else wondered function WO() { var tbody = document.getElementById("plateVolumes"); for(var i = 0; i < tbody.rows.length; i++) { var row = tbody.rows[i]; var qty = row.cells[1].childNodes[0].value; var price = row.cells[3].childNodes[0].value; var answer = (Number(qty) * Number(price)).toFixed(2); row.cells[4].childNodes[0].value = answer; } }
{ "pile_set_name": "StackExchange" }
Q: Are all billionaires also millionaires? Are all billionaires also millionaires? In other words, should the definition of millionaire be taken to include billionaires, or exclude them? A: No, billionaires are not called "millionaires", even though by definition they may actually be millionaires. The relevant conversational principle is the maxim of quantity: Grice's Maxims. The maxim of quantity, where one tries to be as informative as one possibly can, and gives as much information as is needed, and no more. ... The maxim of manner, when one tries to be as clear, as brief, and as orderly as one can in what one says, and where one avoids obscurity and ambiguity. (by googling "maxim of quantity")
{ "pile_set_name": "StackExchange" }
Q: Keystone: Pass mongoose connection into Keystone options Looking at the documentation, it is possible to pass an instance of Mongoose into the Keystone options: http://keystonejs.com/docs/configuration/ "mongoose Object: Instance of Mongoose to be used instead of the default instance." But how...? How do I get the instance from Mongoose? A: You need to require mongoose yourself, configure it, and then pass it to keystone under the mongoose key var yourMongoose = require('mongoose') // init mongoose keystone.init({mongoose: yourMongoose})
{ "pile_set_name": "StackExchange" }
Q: "killed" message from cron.daily, but not when run from command line On Fedora 17, I put a file into /etc/cron.daily with the following contents: cd / su dstahlke /home/dstahlke/bin/anacron-daily.sh exit 0 For some reason, I get a mail every day that just says /etc/cron.daily/dstahlke-daily: ...killed. I tried with and without the exit 0 line above (I noticed that some system scripts have that and others don't, I'm not sure of the purpose). Running /etc/cron.daily/dstahlke-daily from the command line as root produces no ...killed message. Other than the message, everything seems to work fine. Putting set -x in the above script, as well as in the /home/dstahlke/bin/anacron-daily.sh script shows that the ...killed message happens just after the latter script terminates (or perhaps just after the su command finishes). What causes the ...killed message? Or, is there a more acceptable way to have anacron run a user script daily? I figured that putting this in /etc/cron.daily would help the system coordinate all of the daily tasks rather than potentially running my task concurrently with the system tasks. A: I did some further investigation, and found that ...killed is indeed printed by the su program, although the print does not come from the upstream coreutils project, it is introduced by coreutils-8.5-pam.patch in the source rpm. There is some history about the origins for adding this on bugzilla (622700, 597928 and 240117). The relevant part of the code is static sig_atomic_t volatile caught_signal = false; ... /* Signal handler for parent process. */ static void su_catch_sig (int sig) { caught_signal = true; } ... static void create_watching_parent (void) { ... sigfillset (&ourset); if (sigprocmask (SIG_BLOCK, &ourset, NULL)) { error (0, errno, _("cannot block signals")); caught_signal = true; } if (!caught_signal) { ... action.sa_handler = su_catch_sig; ... || sigaction (SIGTERM, &action, NULL) ... if (caught_signal) { fprintf (stderr, _("\nSession terminated, killing shell...")); kill (child, SIGTERM); } cleanup_pam (PAM_SUCCESS); if (caught_signal) { sleep (2); kill (child, SIGKILL); fprintf (stderr, _(" ...killed.\n")); } exit (status); } So in some way (either directly/indirectly related to cleanup_pam or unrelated) the parent process receives SIGTERM between the second last and the last if tests, and thus only prints the ...killed message that obviously should have been a continuation of the fprintf above. All in all that double use of caught_signal as both a asynchronous signal handler means and as a local flow control variable inside the function feels like a really dirty hack and I did not like the code. I tested by splitting that up and introduced a kill_child boolean variable to use in the body of the function and then having if (caught_signal) { kill_child: kill_child = true; status = 1; } if (kill_child) { { fprintf (stderr, _("\nSession terminated, killing shell...")); kill (child, SIGTERM); } cleanup_pam (PAM_SUCCESS); if (kill_child) { sleep (2); kill (child, SIGKILL); fprintf (stderr, _(" ...killed.\n")); } exit (status); } at the end of the function. With that modification I do not get any ....killed spam from anacron any longer. So a long explanation, and possibly more information than you need. However. I also found out some more, which is good news for you since you do not have to make local modifications to the coreutils package. For cases like running su from cron you are supposed to run the program runuser instead. It is sort of "bad" news for me since it makes my findings above less important, but well well :).
{ "pile_set_name": "StackExchange" }
Q: If $|f(x)| \leq 1$ and $|f''(x)| \leq 1$, show $|f'(x)|\leq 2$ Given $f : \mathbb{R} \to \mathbb{R}$, such that $f'(x)$ and $f''(x)$ exist for all $x \in \mathbb{R}$ and for $x \in [0,2]$, the inequalities $|f''(x)| \leq 1$ and $|f(x)| \leq 1$ hold, I am asked to show that for all $x \in [0,2]$, $|f'(x)| \leq 2$. I am given a hint that says to write down the Taylor expansions of $f(0)$ and $f(2)$ about a point $a \in [0,2]$. With the remainder in Lagrange form, I get: $$ \begin{align} \exists \xi_0 \in [0,2]\;\;f(0) &= f(a) -af'(a) + \frac{1}{2}a^2f''(\xi_0) \\ \exists \xi_1 \in [0,2]\;\;f(2) &= f(a) +(2-a)f'(a) + \frac{1}{2}(2-a)^2f''(\xi_1) \end{align}$$ I'm not 100% sure on where to go from here. I have tried manipulating the Taylor expansions, using the fact $a \in [0,2]$ to apply the bounds I was given: $$ \begin{align} f(0) &\leq |f(a) -af'(a) + \frac{1}{2}a^2f''(\xi_0)| \\ &\leq |f(a)| + |af'(a)| + \frac{1}{2}a^2|f''(\xi_0)| \\ &\leq 1 + |af'(a)| + \frac{1}{2}a^2 \end{align} $$ Similarly for $f(2)$: $$ f(2) \leq 1 + |(a-2)f'(a)| + \frac{1}{2}(a-2)^2 $$ But how exactly do I use this to bound $|f'|$? It's probably right there and I've just missed it somehow. A: The trick is to subtract the two equations you got to get $$f'(a) = \frac{f(2) - f(0)}{2} + \frac{1}{4}[a^2f’’(\zeta_0) - (2-a)^2f’’(\zeta_1)]$$ Now using the conditions $|f| \leq 1$, $|f''| \leq 1$ and the triangle inequality we get the desired result $$|f'(a)| \leq \frac{1+1}{2} + \frac{1}{4}[a^2\cdot 1 + (2-a)^2\cdot 1] \leq 2$$ since $\max_{a\in[0,2]} [a^2 + (2-a)^2] = 4$. An example of a function satisfying $\max_{a\in[0,2]} |f(a)| = \max_{a\in[0,2]} |f''(a)| = 1$ and where $\max_{a\in[0,2]} |f'(a)| = 2$ is $$f(x) = \frac{x^2}{2} - 1$$
{ "pile_set_name": "StackExchange" }
Q: Random.choice Only Choosing from One Line of File Python novice here, very good at copy and pasting. I'm trying to sample one random word from my text file. It's working, but it's only sampling from a single line. How can I make it sample the entire file? lines = open("myfilehere").readlines() line = lines[0] words = line.split() print(random.choice(words)) Labely = random.choice(words) Label1 = Label(root, text=Labely) Label1.pack() A: You split and perform random.choice() on the variable words, which contains only your first line of text (lines[0]). If you want all the text you don't need to use the variable line, run words = lines.split() instead of words = line.split()
{ "pile_set_name": "StackExchange" }
Q: Wxpython Detect Caps Lock status I build a gui in wxpython (python-3). Someone knows how to detect if Caps Lock is on or off? Something like this code but with CapsLock. event.CmdDown() A: I found a nice way to check it: from win32api import GetKeyState from win32con import VK_CAPITAL def caps_on(): return GetKeyState(VK_CAPITAL) == 1
{ "pile_set_name": "StackExchange" }
Q: Multilabel classification of a sequence, how to do it? I am quite new to the deep learning field especially Keras. Here I have a simple problem of classification and I don't know how to solve it. What I don't understand is how the general process of the classification, like converting the input data into tensors, the labels, etc. Let's say we have three classes, 1, 2, 3. There is a sequence of classes that need to be classified as one of those classes. The dataset is for example Sequence 1, 1, 1, 2 is labeled 2 Sequence 2, 1, 3, 3 is labeled 1 Sequence 3, 1, 2, 1 is labeled 3 and so on. This means the input dataset will be [[1, 1, 1, 2], [2, 1, 3, 3], [3, 1, 2, 1]] and the label will be [[2], [1], [3]] Now one thing that I do understand is to one-hot encode the class. Because we have three classes, every 1 will be converted into [1, 0, 0], 2 will be [0, 1, 0] and 3 will be [0, 0, 1]. Converting the example above will give a dataset of 3 x 4 x 3, and a label of 3 x 1 x 3. Another thing that I understand is that the last layer should be a softmax layer. This way if a test data like (e.g. [1, 2, 3, 4]) comes out, it will be softmaxed and the probabilities of this sequence belonging to class 1 or 2 or 3 will be calculated. Am I right? If so, can you give me an explanation/example of the process of classifying these sequences? Thank you in advance. A: Here are a few clarifications that you seem to be asking about. This point was confusing so I deleted it. If your input data has the shape (4), then your input tensor will have the shape (batch_size, 4). Softmax is the correct activation for your prediction (last) layer given your desired output, because you have a classification problem with multiple classes. This will yield output of shape (batch_size, 3). These will be the probabilities of each potential classification, summing to one across all classes. For example, if the classification is class 0, then a single prediction might look something like [0.9714,0.01127,0.01733]. Batch size isn't hard-coded to the network, hence it is represented in model.summary() as None. E.g. the network's last-layer output shape can be written (None, 3). Unless you have an applicable alternative, a softmax prediction layer requires a categorical_crossentropy loss function. The architecture of a network remains up to you, but you'll at least need a way in and a way out. In Keras (as you've tagged), there are a few ways to do this. Here are some examples: Example with Keras Sequential model = Sequential() model.add(InputLayer(input_shape=(4,))) # sequence of length four model.add(Dense(3, activation='softmax')) # three possible classes Example with Keras Functional input_tensor = Input(shape=(4,)) x = Dense(3, activation='softmax')(input_tensor) model = Model(input_tensor, x) Example including input tensor shape in first functional layer (either Sequential or Functional): model = Sequential() model.add(Dense(666, activation='relu', input_shape=(4,))) model.add(Dense(3, activation='softmax')) Hope that helps!
{ "pile_set_name": "StackExchange" }
Q: Android Layout MinWidth I know I can set minWidth using xml but I want to know how to set it in code, because I'm adding Linear Layouts from code to View but when the content is too small all the layout's content I'm adding change and so, I need to set the minimun width from code. A: you have to use viewInstance.setMinimumWidth (int minWidth). you can read about it here
{ "pile_set_name": "StackExchange" }
Q: View activity stack in Android Is it possible to view the activity stack in Android for debugging purposes? A: To display the activity stack, run the following command : adb shell dumpsys activity activities
{ "pile_set_name": "StackExchange" }
Q: Dictionary app for ipod touch Is there a dictionary app that I can just click on a word anywhere (in any app) and it will automatically define it for me? A: With the release of iOS 5, this is now very simple. Dictionary functionality is available in any app that allows you to select text. Just highlight the text as if you were going to do a Copy and you will see a "Define" option next to "Copy". Tap "Define" and you get a pop-up window with the definition from the same dictionary built in to iBooks.
{ "pile_set_name": "StackExchange" }
Q: How to close a prompt form or dialogue upon a hardware event? I want to prompt the user to scan a bar code or RFID tag. That (I guess) means either MessageDlg() or a small form - I don't care which and invite advice. When I read a scan over serial port or HID (or timer or WM_xxxx), I want to close that prompt. What is the simplest way to go about that? Thankls A: We have this feature in our application with even 1 more integrated step to start with. I will describe it fully, as it might be useful to you. We have a modal dialog that allows the user to enter the Serial Id for a device by either keying it in with the keyboard or just scanning the barcode tag. Step 1. We have a menu item with a Hot Key (Shortcut Ctrl+Alt+N for instance). We have configured the scanner so that it sends this preamble whenever it scans a barcode. (Manual equivalent of keying in the shortcut). That opens the modal dialog. Step 2. The Focus is in a Edit box to get the Serial ID either from the user and the keyboard or from the scanner reading the barcode. Step 3. There are an [OK] and a [Cancel] buttons. The OK button has Default:=True and ModalResult:=mrOK. The Cancel button has Cancel:=True and ModalResult:=mrCancel. The scanner is set to postfix the scanned string with Enter which has the same effect as the user hitting the [Enter] key or clicking the OK button: it closes the modal dialog with mrOK in the ModalResult so we can read the Edit.text to get the SerialID. Step 3bis. The user presses [Esc] or click on Cancel or closes the dialog with the title bar close button: it closes the dialog with anything but mrOK and we discard whatever is in the Edit... Works very well in our case with any scanner working as an HID emulation (keyboard) and where we can configure the preamble. (sending Enter at the end was by default in all the scanners we tried).
{ "pile_set_name": "StackExchange" }
Q: How does mock-debugger control which line the debugger steps next? I'm unable to understand how the mock-debugger extension controls where the next step is. For example what if I'd like to step 2 lines if I find the word "banana" in my text? Also, I'd like to do something, like "Step In", where I can walk word-by-word - is it possible? I've seen the this._currentLine = ln; assign, which looks like it controls where the line is, but it's just a simple local variable. How could it ever control anything in the debugger? I can't find any other uses of the _currentLine varbiable where it passes to anything useful API (except for stack tracing, but I don't think it has any relation with the debugger line-control). A: The stack trace is the only source for the debugger step visualization. When the debugger gets a notification to pause it requests the current stack trace. The TOS determines where the next execution point will be located. Hence the debug adapter is reponsible to determine this position precisely.
{ "pile_set_name": "StackExchange" }
Q: Haskell data type and lists I created a datatype that is a list of other elements say data Tarr = Tarr [Int] deriving (Show) I would like to concatenate two of these Lists so Tarr [0,2,4,2] ++ Tarr [1] but I get an error <interactive>:43:1: Couldn't match expected type `[a0]' with actual type `Tarr' If there was a typeclass for (++) (Concat say) as there is for (==) (Eq) I could implement it as something like class Concat a where (+++) :: a -> a -> a instance Concat Tarr where (+++) (Tarr a) (Tarr b) = Tarr (a ++ b) 1) How should I solve my problem? 2) Any reason why (++) isn't defined in a typeclass? A: The ++ function applies to lists only, but the <> / mappend function from the Monoid typeclass generalizes it. In fact if you changed your data to a newtype instead, you could do this: {-# LANGUAGE GeneralizedNewtypeDeriving #-} import Data.Monoid newtype Tarr = Tarr [Int] deriving (Show, Monoid)
{ "pile_set_name": "StackExchange" }
Q: JPanel gradient background I googled but could find no correct answer. I have a JPanel and I want it to have a gradient that comes from top to bottom. I'm just going to use two colors. How can I achieve this? A: Here you go: import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class TestPanel extends JPanel { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); int w = getWidth(); int h = getHeight(); Color color1 = Color.RED; Color color2 = Color.GREEN; GradientPaint gp = new GradientPaint(0, 0, color1, 0, h, color2); g2d.setPaint(gp); g2d.fillRect(0, 0, w, h); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JFrame frame = new JFrame(); TestPanel panel = new TestPanel(); frame.add(panel); frame.setSize(200, 200); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } } A: hey Bebbie you can use this : JPanel contentPane = new JPanel() { @Override protected void paintComponent(Graphics grphcs) { super.paintComponent(grphcs); Graphics2D g2d = (Graphics2D) grphcs; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); GradientPaint gp = new GradientPaint(0, 0, getBackground().brighter().brighter(), 0, getHeight(), getBackground().darker().darker()); g2d.setPaint(gp); g2d.fillRect(0, 0, getWidth(), getHeight()); } }; hope that help; you can also back to this artical for more help: Gradient background to any jcomponent
{ "pile_set_name": "StackExchange" }
Q: Homebase extractor fan. How to remove the front cover? I bought an extractor fan from homebase. One of these: https://www.homebase.co.uk/humidity-controlled-extractor-fan_p594561 . I didn't get very far with fitting it though because step one is "Remove the front cover" but this is proving very difficult. I have made a little video of me explaining the problem (with a bit of help from a 3 year old!) On the top edge there is a clip which pops open with a screwdriver, and it start's coming open (I can pull it apart about 4 millimetres and start to see inside from the top), but at the bottom edge of the fan there is no clip, and the front cover does not want to come off at all. I can just about prise it apart by about a millimetre. I can push a knife blade in there along the whole bottom edge (see following photo), but something in the middle near the bottom (by the red light) is holding the front cover on tight. There are various holes which look to be mostly for the screws which will hold it to the wall (from the direction of inside-out, meaning I need to get inside of course). Near the middle there's an interesting looking screwdriver-sized hole you can see in the photo, but solid edges all around. No clips or moving parts to poke at. I can't see any other clips or screws, but I feel like I must be missing something. I could just pull harder, but it feels like I'm at the limit before plastic starts snapping. Oh I almost forgot the funniest part. The instructions have a sentence explaining how to do it! But it seems to be badly translated or something. Here it is word for word: "Remove the front cover. To remove the front cover, first remove the hole plug than using screw driver to remove the self tapping screw, then cover can be remove unclip" It's strange because the rest of the manual is well written. Just that one sentence... which is the sentence I need! Where is this "hole plug" / "self tapping screw"?? Maybe I could find out more from a manufacturer, but it's just generically homebase branded. "Homebase Extractor Fan. Humidity Control Model". There is a sticker on the fan itself with the numbers "SPA255 B141319" A: Took me a while but the red light is just a cover for the screw, use a small screwdriver to lift it out.
{ "pile_set_name": "StackExchange" }
Q: JavaFX - Drawing a line between two nodes I am busying writing a simple application using JavaFX2. The goal is just to plot 2 nodes (the nodes are movable by dragging them) and then have a function to draw lines between these nodes. I finished the functions to add and move nodes (at the moment I am just using Ellipse shapes but I am going to replace it later with my own node class) but now I am struggling with the connecting lines. The actions to add a node or a line is from a dropdown menu and I have the following code on the line function: private void drawLine(MenuItem line) { final BooleanProperty lineActive = new SimpleBooleanProperty(false); final BooleanProperty clickOne = new SimpleBooleanProperty(false); final BooleanProperty clickTwo = new SimpleBooleanProperty(false); line.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent t) { lineActive.set(true); } }); nodeGroup.setOnMousePressed(new EventHandler<MouseEvent>() { public void handle(final MouseEvent t1) { clickOne.set(true); if (lineActive.get()) { if (clickOne.get()) { //get x and y of first node x1 = ((Ellipse) t1.getTarget()).getCenterX(); y1 = ((Ellipse) t1.getTarget()).getCenterY(); clickOne.set(false); clickTwo.set(true); } if (clickTwo.get()) { nodeGroup.setOnMouseClicked(new EventHandler<MouseEvent>() { public void handle(MouseEvent t2) { //get x and y of second node x2 = ((Ellipse) t2.getTarget()).getCenterX(); y2 = ((Ellipse) t2.getTarget()).getCenterY(); //draw line between nodes final Line line = new Line(); line.setStartX(x1); line.setStartY(y1); line.setEndX(x2); line.setEndY(y2); canvas.getChildren().add(line); clickTwo.set(false); lineActive.set(false); } }); } } } }); } I just have the booleans to check for the first and second click to get the center of each node. My first question is when I click on the line function and add a line between 2 nodes, it doesn't seem to end the function, and any other nodes I click on gets a line to it. How can I prevent it from executing more than once. And my second question is how can I "connect" the line to the nodes that if the node moves, the line stays in the center of the node? Thanks. A: I think there is a couple of things which could make this simpler... Do not use booleans when you have more than two states (no click, click one, click two) use an enum instead. Then you only need one variable to look after. Only ever set one mouse listener on the nodeGroup and check which state you're in and have the appropriate code there instead of separate mouse listeners. I imagine that the program is setting the listener for the second click and not resetting it to the listener for the first click when it completes.
{ "pile_set_name": "StackExchange" }
Q: Operating room schedule probability (Statistics homework problem) I am trying to figure out the following homework problem from the textbook Applied Statistics and Probability for Engineers (6th Edition): Question: Suppose that an operating room needs to schedule 2 knee, 4 hip, and 5 shoulder surgeries. Assume that all schedules are equally likely. Find the probability that the schedule begins with a hip surgery, given that all of the shoulder surgeries are last. Attempted solution: If A is the event that a schedule begins with a hip surgery, then we have 3 other hip surgeries remaining. Let B is the event that shoulder surgeries are last. $$ \begin{align} P(A|B) & =\frac{P(A \cap B)}{P(B)}\\ & =\frac{\frac{5!}{1!4!}}{\frac{6!}{2!4!}}\\ & =\frac{5}{15}\\ & =\frac{1}{3} \end{align} $$ Does my attempted solution make sense? The number of schedule permutations in (A $\cap$ B) is $\frac{5!}{1!4!}$ because there are 5 operations that can be freely scheduled and we have 1 knee and 4 hip operations left to schedule. The number of schedule permutations in (B) is $\frac{6!}{2!4!}$ because there are 6 operations to schedule besides the shoulder operations and we have 2 knee and 4 hip operations left to schedule. $\therefore P(A|B) = \frac{1}{3}$. A: The number of schedule permutations in $(A ∩ B)$ is $\frac{5!}{1!4!}$ because there are $5$ operations that can be freely scheduled and we have $1$ knee and $4$ hip operations left to schedule. First of all, permutation implies ordered operations. Secondly, the number of scheduled permutations in $(A\cap B)$ is not equal to $P(A\cap B)$, because the latter is probability. Thirdly, the number of scheduled permutations in $(A\cap B)$ is not $\frac{5!}{1!4!}$ (it is ${4\choose 1}\cdot 5!\cdot 5!$). Your thought: $5$ operations to be freely scheduled: $K,H,H,H,H$, so $\frac{5!}{1!4!}$. However, you must consider $K,H_1,H_2,H_3,H_4$ and $KH_1H_2H_3H_4$ is different from $KH_2H_1H_3H_4$. Moreover, you must look at the general picture. Denote: $K_1,K_2,H_1,H_2,H_3,H_4,S_1,S_2,S_3,S_4,S_5$ the knee, hip and shoulder operations, respectively. First, allocate $5$ shoulder operations to the last $5$ positions, which can be done in $\color{green}{5!}$ ways. Second, select $1$ hip operation to the first position, which can be done in $\color{red}{{4\choose 1}}=4$ ways. (Note that here you are also confusing with knee operation) Third, once $5$ shoulder operations are set to the last and $1$ hip operation is set to the first positions, there remained overall $5$ operations ($2$ knee and $3$ hip) for the middle $5$ positions, which can be arranged in $\color{blue}{5!}$ ways. Hence, the number of scheduled permutations in $A\cap B$ is: $$\color{red}{{4\choose 1}}\cdot \color{green}{5!}\cdot \color{blue}{5!}$$ Similarly, the number of outcomes in $B$ is: $$5!\cdot 6!$$ because, there are $5!$ ways to arrange $5$ shoulder operations and then $6!$ ways to arrange the rest $6$ ($2$ knee and $4$ hip) operations. Hence, the required probability is: $$\frac{{4\choose 1}\cdot 5!\cdot 5!}{6!\cdot 5!}=\frac23.$$ Alternatively, since it is stated "given that all of the shoulder surgeries are last", the shoulder operations can be ignored and only $2$ knee and $4$ hip operations can be considered for having a hip operation first, which is: $$\frac{{4\choose 1}\cdot 5!}{6!}=\frac23.$$
{ "pile_set_name": "StackExchange" }
Q: jquery validation doesn't work for ajax loaded bootstrap modal dialog content I am using bootstrap with zend 2. The content of the modal is retrieved through ajax call. But the validation doesn't work at all, it submits without checking any field: Here is where the modal loads: <div class="modal fade" id="themesModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> </div> </div> </div> Here is the modal content: <div class="modal-body"> <div id="themesbox"> <div class="panel panel-info"> <div class="panel-heading"> <div class="panel-title">title</div> </div> <div style="padding-top: 30px" class="panel-body"> <?php $form = $this->form; $form->setAttribute('action', $this->url('user/default', array('controller' => 'users', 'action' => 'create'))); $form->prepare(); echo $this->form()->openTag($form); ?> <div id="mydiv" style="display: none" class="alert alert-danger"> <p>Error:</p> <span></span> </div> <div class="form-group"> <label for="name" class="col-md-3 control-label">user</label> <div class="col-md-9"> <?php echo $this->formElement($form->get('name'));?> </div> </div> <div class="form-group"> <label for="description" class="col-md-3 control-label">password</label> <div class="col-md-9"> <?php echo $this->formElement($form->get('password'));?> </div> </div> <div style="margin-top: 10px" class="form-group"> <!-- Button --> <div class="col-sm-12 controls"> <?php echo $this->formSubmit($form->get('submit'));?> <button id="cancel" class="btn btn-success" data-dismiss="modal">Cancel</button> </div> </div> <?php echo $this->form()->closeTag();?> </div> <!-- /.panel-body --> </div> <!-- /. panel panel-info --> </div> </div> Here is the jquery validation code: $('.form-validation').each(function () { $(this).validate({ errorElement: "span", errorClass: "help-block", highlight: function(element) { $(element).closest('.control-group').removeClass('success').addClass('error'); $(element).attr('style', "border-radius: 5px; border:#FF0000 1px solid;"); }, unhighlight: function(element) { $(element).addClass('valid').closest('.control-group').removeClass('error').addClass('success'); $(element).attr('style', "border-radius: 4px; border:1px solid #ccc;"); }, errorPlacement: function (error, element) { $(error).attr('style', "color: #FF0000;"); if ( element.prop('type') === 'checkbox') { error.insertAfter(element.parent()); } else { error.insertAfter(element); } } }); }); And here is the form code: $this->add(array( 'name' => 'name', 'attributes' => array( 'type' => 'text', 'id' => 'username', 'class' => 'form-control', 'required' => 'true', 'minlength' => '8', 'maxlength' => '20', ), 'options' => array( 'label' => 'name', ), )); $this->add(array( 'name' => 'description', 'attributes' => array( 'type' => 'password', 'id' => 'password', 'class' => 'form-control', 'required' => 'true', 'minlength' => '8', 'maxlength' => '20', ), 'options' => array( 'label' => 'Password', ), )); A: In a matter of fact all the server side validation mechanisms were in place and were working perfectly. I needed client side validations through jquery. Because the content of Bootstrap modal dialog is loading from ajax, it didn't consider the surrounding context as usual, I needed to insert jquery code in the ajax content. ZF2 doesn't permit inserting js code in its view files. So I did in the following way inserting the following line in the ajax content: <?php echo $this->inlineScript()->appendFile($this->basePath() . '/js/custom.js')?>
{ "pile_set_name": "StackExchange" }
Q: Access only by network name I have a win server 2003 on my network, I cannot access a web service on that server using local IP or real live IP, only I can use the network name . Thanks A: End of madness As far as I understand, The client was detecting a proxy and was trying to connect through it. simply don't use proxy at the client. but I am still don't get it, why it woks fine with HTTP and failed to work with HTTPS. HTTPS works only when those lines is added. Someone try to explain this to me!! ASP.net IWebProxy myProxy = GlobalProxySelection.GetEmptyWebProxy(); GlobalProxySelection.Select = myProxy;
{ "pile_set_name": "StackExchange" }
Q: Date expression in Oracle How will the following expression be evaluated to in Oracle? WHERE nvl(MODIFIEDDATE, TO_DATE('2030/01/01', 'YYYY/MM/DD HH24:MI:SS')) > TO_DATE('', 'YYYY/MM/DD HH24:MI:SS') Can anyone explain what this would do? I am not Oracle person. A: Let's walk through this in detail: NVL(MODIFIEDDATE, TO_DATE('2030/01/01', 'YYYY/MM/DD HH24:MI:SS')) This will return MODIFIEDDATE if it is not NULL. If MODIFIEDDATE is NULL then it will return a DATE value of 2030/01/01 00:00:00 (the time component will default to midnight because it's not specified in the time literal of '2030/01/01'). So this will always return a non-NULL DATE value. TO_DATE('', 'YYYY/MM/DD HH24:MI:SS') This will always return NULL. A zero-length string, in Oracle, means NULL. This is by design (it goes back to the very earliest days of Oracle), and is IMO one of the worst design decisions in the Oracle product. But it's what it is - a zero-length string in Oracle is NULL, always and forever. And NULLs are poison, so TO_DATE(NULL, 'YYYY/MM/DD HH24:MI:SS') will return NULL. So now we've got SOME_VALID_DATE_VALUE > NULL This will always return NULL, because any comparison with NULL returns NULL (remember - NULLs are poison). So the WHERE clause becomes WHERE NULL... And thus the query which uses this WHERE clause will return no rows. Share and enjoy.
{ "pile_set_name": "StackExchange" }
Q: Finding supremum of a sequence - i can't understand my instructor I have the sequence: $A = \{ 1 - \frac{1}{n} | n \in \mathbb{N}\}$ I need to find the surpremum with correct mathmatical notation. I got some help from my math instructor, i thought i understood it, but some of the steps i don't understand. I'll make the steps and write when the logic fails for me. First let's find an upper bound: $1 - \frac{1}{n} \leq 1$ Check of it is the lowest upper bound: pick and epsilon $\forall \epsilon > 0 $ or: $1 - \epsilon$ Now comes the step i don't understand. He said: $\exists n \in \mathbb{N} \space | \space 1 - \epsilon < 1 - \frac{1}{n} \leq 1$ This part i don't understand. Why should $1- \epsilon < 1 - \frac{1}{n} $? then it is not in the sequence.. Shouldn't we only check it is smaller than 1, and still be inside the sequence? the last steps he did was: $\Rightarrow n > \frac{1}{\epsilon}$ For $n > \frac{1}{\epsilon}$: $1 - \epsilon < 1 - \frac{1}{n} \leq 1$ and then this should be the conclusion.. But i'm not sure what we just concluded. I would very much appreciate your perspective.. A: So we know that $1-\frac1n ≤1$, hence $1$ is an upper bound of A. To show that $1$ is actually the lowest upper bound, we assume that there is a lower one and lead that to a contradiction. If there is a lower upper bound than $1$, it must be lower than $1$ and hence we can write it as $1-\epsilon$ for a (possibly very small) $\epsilon >0$. But then we can choose $n \in \Bbb N$ with $n>\frac1\epsilon$ and we see $$1-\frac1n>1-\frac{1}{\frac1\epsilon}=1-\epsilon.$$ So $1-\epsilon$ can't be an upper bound, because we just found a term of the sequence which is greater. Hence we conclude that there can't be an upper bound of the form $1-\epsilon$ for $\epsilon >0$ and thus 1 is the lowest upper bound of $A$.
{ "pile_set_name": "StackExchange" }
Q: SimonVT menudrawer I have an app that already many activities and class. Like Profile, Friends, Photos, News Feed, etc. I want to integrate that sliding drawer into my main activities. in the examples, they are just showing array list which is implement onClick. so my question is how to change that array list to become my activities like friends, profile, home and etc. A: You can use ListView with custom adapter. to adjust custom adapter you can link in your listView that adapter. and in adapter you can put custom icon public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflator = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View rowView = inflator.inflate(R.layout.row, parent, false); ImageView icon = (ImageView) rowView.findViewById(R.id.row_icon); TextView title = (TextView) rowView.findViewById(R.id.row_title); title.setText(proMenu[position]); String s = proMenu[position]; if(s.equalsIgnoreCase("Home")){ icon.setImageResource(R.drawable.icon_home); } else if(s.equalsIgnoreCase("Best Nearby")){ icon.setImageResource(R.drawable.specialss); }
{ "pile_set_name": "StackExchange" }
Q: Outlook receives PHP HTML e-mail as code? I made an HTML e-mail send with PHP, but my client receives this as pure code. Here is the PHP code to send the mail: $subject = 'HTML e-mail test'; $message = '<html> <body> <h1>TEST</h1> </body> </html>'; $headers = "MIME-Version: 1.0\r\n"; $headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; $headers .= "To: <".$to.">\r\n"; $headers .= "From: <".$email.">\r\n"; $mailb = mail($to, $subject, $message, $headers); It works fine for me, but they receive it as: Content-type: text/html; charset=iso-8859-1 To: <[email protected]> From: <[email protected]> <html> <body> <h1>TEST</h1> </body> </html> Is there something wrong with my headers? Or is it their Outlook? How can I fix this problem? Thanks in advance! A: I see: Content-typetext/html; charset=iso-8859-1 where I should see: Content-type: text/html; charset=iso-8859-1 Is that a cut/paste error? In your code, or in your result? Note that you probably want to include both text/plain and text/html types in a multipart message, since HTML-only mail often gets high spam scores (using SpamAssassin, SpamBouncer, etc). UPDATE #1: It appears that the \r\n is being interpreted as two newlines instead of one. Different platforms may have different bugs in their implementation of SMTP. It's possible that you can get away with changing your line endings to just \n. If that works with your system, don't rely on it, as it may not work on a different system. Also, consider switching to a different method for sending mail. phpMailer and SwiftMailer are both recommended over PHP's internal mail() function. UPDATE #2: Building on Incognito's suggestion, here's code you might use to organize your headers better, as well as create a plaintext part: filter_var($to, FILTER_VALIDATE_EMAIL) or die("Invalid To address"); filter_var($email, FILTER_VALIDATE_EMAIL) or die("Invalid From address"); $subject = 'HTML e-mail test'; $messagetext = 'TEST in TEXT'; $messagehtml = '<html> <body> <h1>TEST</h1> <p>in HTML</p> </body> </html>'; // We don't need real randomness here, it's just a MIME boundary. $boundary="_boundary_" . str_shuffle(md5(time())); // An array of headers. Note that it's up to YOU to insure they are correct. // Personally, I don't care whether they're a string or an imploded array, // as long as you do input validation. $headers=array( 'From: <' . $email . '>', 'MIME-Version: 1.0', 'Content-type: multipart/alternative; boundary="' . $boundary . '"', ); // Each MIME section fits in $sectionfmt. $sectionfmt = "--" . $boundary . "\r\n" . "Content-type: text/%s; charset=iso-8859-1\r\n" . "Content-Transfer-Encoding: quoted-printable\r\n\r\n" . "%s\n"; $body = "This is a multipart message.\r\n\r\n" . sprintf($sectionfmt, "html", $messagehtml) . sprintf($sectionfmt, "plain", $messagetext) . "--" . $boundary . "--\r\n"; $mailb = mail($to, $subject, $body, implode("\r\n", $headers)); I'm not saying this is The Right Way to do this by any means, but if the strategy appeals to you, and you think you can maintain code like this after not having looked at it for 6 or 12 months (i.e. it makes sense at first glance), then feel free to use or adapt it. Disclaimer: this is untested, and sometimes I make typos ... just to keep people on their toes. :)
{ "pile_set_name": "StackExchange" }
Q: Adding row in a table with javascript = strange result in Chrome and safari I've got to add a new row with it's content populated from an ajax query when I click on any row present. Everything is working well in ie8, ff3.6, opera11, but in chrome10 and safari5 the row are always shown as the first row even if the HTML code is well ordered. the javascript use is here: jQuery('.tx_tacticinfocours_pi1_cour_line').click(function (){ if(running==false){ running=true; jQuery('.cour_detail_temp_inner').slideUp(500, function () { jQuery(this).parents('.cour_detail_temp').remove(); }); var td=jQuery(this).after('<tr class="cour_detail_temp"><td colspan="8" style="padding: 0pt;"><div class="cour_detail_temp_inner" style="display: none;"></div></td></tr>'); td=td.next().find('.cour_detail_temp_inner'); var url=jQuery(this).find('.tx_tacticinfocours_pi1_detail_link a').attr('href'); td.load(url,function(){ jQuery(this).slideDown(500,function(){running=false;}); }); } }); and here is the HTML (it's typo3 template): <table class="tx_tacticinfocours_pi1_liste" border="0" cellspacing="0" cellpadding="0"> <tr> <th>###TITRE_WEB###</th> <th>###TITRE_PDF###</th> <th>###TITRE_DETAILS###</th> <th>###TITRE_SIGLE###</th> <th>###TITRE_TITRE###</th> <th>###TITRE_ENLIGNE###</th> <th>###TITRE_ENSEIGNANT###</th> <th>###TITRE_RESPONSABLE###</th> </tr> <!-- ###COURS### begin --> <tr class="tx_tacticinfocours_pi1_cour_line"> <td class="tx_tacticinfocours_pi1_link"><!-- ###COURS_LINK### begin -->###COURS_WEB_IMAGE###<!-- ###COURS_LINK### end --></td> <td class="tx_tacticinfocours_pi1_link"><!-- ###PDF_LINK### begin -->###PDF_IMAGE###<!-- ###PDF_LINK### end --></td> <td class="tx_tacticinfocours_pi1_link tx_tacticinfocours_pi1_detail_link"><!-- ###DETAILS_LINK### begin -->###DETAILS_IMAGE###<!-- ###DETAILS_LINK### end --></td> <td class="tx_tacticinfocours_pi1_sigle" nowrap>###COURS_SIGLE###</td> <td class="tx_tacticinfocours_pi1_titre">###COURS_TITRE###</td> <td class="tx_tacticinfocours_pi1_enligne">###COURS_ENLIGNE###</td> <td class="tx_tacticinfocours_pi1_enseignant" nowrap>###COURS_ENSEIGNANT###</td> <td class="tx_tacticinfocours_pi1_responsable" nowrap>###COURS_RESPONSABLE###</td> </tr> <!-- ###COURS### end --> have you got any idea why it's doing so or any work around? A: I'm not sure, but try turning: var td=jQuery(this).after(...) to: var td=jQuery('<tr class="cour_detail_temp"><td colspan="8" style="padding: 0pt;"><div class="cour_detail_temp_inner" style="display: none;"></div></td></tr>').appendTo(this); I think what you've got there is more of a css problem than a javascript problem.
{ "pile_set_name": "StackExchange" }
Q: Change JS regex to work in Java I came across this JS regex that retrieve ID from the Youtube URLs listed below. /(youtu(?:\.be|be\.com)\/(?:.*v(?:\/|=)|(?:.*\/)?)([\w'-]+))/i Youtube URLS tested on: http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I http://www.youtube.com/user/SilkRoadTheatre#p/a/u/2/6dwqZw0j_jY http://youtu.be/6dwqZw0j_jY http://www.youtube.com/watch?v=6dwqZw0j_jY&feature=youtu.be http://youtu.be/afa-5HQHiAs http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo?rel=0 http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I http://www.youtube.com/embed/nas1rJpm7wY?rel=0 http://www.youtube.com/watch?v=peFZbP64dsU How do I modify the regex to work in Java? Also, can it be altered to pick IDs from gdata URLs too? e.g https://gdata.youtube.com/feeds/api/users/Test/?alt=json&v=2 Update: This is the function where I intend to use the Regex. public static String getIDFromYoutubeURL(String ytURL ) { if(ytURL.startsWith("https://gdata")) { // This is my obviously silly hack, ytURL = ytURL.replace("v=\\d", ""); // I belive Regext should handle this. } String pattern = "(?i)(https://gdata\\.)?(youtu(?:\\.be|be\\.com)/(?:.*v(?:/|=)|(?:.*/)?)([\\w'-]+))"; Pattern compiledPattern = Pattern.compile(pattern); Matcher matcher = compiledPattern.matcher(ytURL); if(matcher.find()){ return matcher.group(3); } return null; } Currently, it works fine for the URLs listed above and for https://gdata.youtube.com/feeds/api/users/Test/?id=c. However, It doesn't not work well if the Gdata URL have the version parameter. e.g v=2, (https://gdata.youtube.com/feeds/api/users/Test/?id=c&v=2). In this case, it returns 2 as the ID. How can it be improved to return Test and not 2 as the ID in the Gdata URL? Thanks. A: I fixed it! Use replaceAll instead: import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test2 { public Test2() { // TODO Auto-generated constructor stub } public static void main(String[] args) { String toTest = getIDFromYoutubeURL( "https://gdata.youtube.com/feeds/api/users/Test/?id=c&v=2"); System.out.println(toTest); } public static String getIDFromYoutubeURL(String ytURL ) { if(ytURL.startsWith("https://gdata")) { // This is my obviously silly hack, ytURL = ytURL.replaceAll("v=\\d", ""); // I belive Regext should handle this. } String pattern = "(?i)(https://gdata\\.)?(youtu(?:\\.be|be\\.com)/(?:.*v(?:/|=)|(?:.*/)?)([\\w'-]+))"; Pattern compiledPattern = Pattern.compile(pattern); Matcher matcher = compiledPattern.matcher(ytURL); if(matcher.find()){ return matcher.group(3); } return null; } }
{ "pile_set_name": "StackExchange" }
Q: Issues while connecting to mysql using ruby require 'rubygems' require 'mysql' db = Mysql.connect('localhost', 'root', '', 'mohit') //db.rb:4: undefined method `connect' for Mysql:Class (NoMethodError) //undefined method `real_connect' for Mysql:Class (NoMethodError) db.query("CREATE TABLE people ( id integer primary key, name varchar(50), age integer)") db.query("INSERT INTO people (name, age) VALUES('Chris', 25)") begin query = db.query('SELECT * FROM people') puts "There were #{query.num_rows} rows returned" query.each_hash do |h| puts h.inspect end rescue puts db.errno puts db.error end error i am geting is: undefined method `connect' for Mysql:Class (NoMethodError) OR undefined method `real_connect' for Mysql:Class (NoMethodError) EDIT return value of Mysql.methods ["private_class_method", "inspect", "name", "tap", "clone", "public_methods", "object_id", "__send__", "method_defined?", "instance_variable_defined?", "equal?", "freeze", "extend", "send", "const_defined?", "methods", "ancestors", "module_eval", "instance_method", "hash", "autoload?", "dup", "to_enum", "instance_methods", "public_method_defined?", "instance_variables", "class_variable_defined?", "eql?", "constants", "id", "instance_eval", "singleton_methods", "module_exec", "const_missing", "taint", "instance_variable_get", "frozen?", "enum_for", "private_method_defined?", "public_instance_methods", "display", "instance_of?", "superclass", "method", "to_a", "included_modules", "const_get", "instance_exec", "type", "<", "protected_methods", "<=>", "class_eval", "==", "class_variables", ">", "===", "instance_variable_set", "protected_instance_methods", "protected_method_defined?", "respond_to?", "kind_of?", ">=", "public_class_method", "to_s", "<=", "const_set", "allocate", "class", "new", "private_methods", "=~", "tainted?", "__id__", "class_exec", "autoload", "untaint", "nil?", "private_instance_methods", "include?", "is_a?"] return value of Mysql.methods(false) is []... blank array EDIT2 mysql.rb file # support multiple ruby version (fat binaries under windows) begin require 'mysql_api' rescue LoadError if RUBY_PLATFORM =~ /mingw|mswin/ then RUBY_VERSION =~ /(\d+.\d+)/ require "#{$1}/mysql_api" end end # define version string to be used internally for the Gem by Hoe. class Mysql module GemVersion VERSION = '2.8.1' end end A: I had this same problem and solved this way: make sure you have installed only the gem ruby-mysql and not the gem mysql. For me, now: $ gem list --local | grep mysql ruby-mysql (2.9.2) If that is not the case, uninstall $ sudo gem uninstall mysql (I uninstalled every gem with mysql in its name) and then reinstalled ruby-mysql. In my case, because I have mysql installed in a usb disk the installation command was: sudo env ARCHFLAGS="-arch i386" gem install ruby-mysql -- --with-mysql-config=/Volumes/usb/opt/bin/osx/mysql/bin/mysql_config --with-mysql-lib=/Volumes/usb/opt/bin/osx/mysql/lib/ --with-mysql-dir=/Volumes/usb/opt/bin/osx/mysql (and I was using the 32bits binary for MacOs, don't know if that applies for you) Finally, my ruby test program was require 'rubygems' require 'mysql' dbh = Mysql.real_connect('localhost', 'root', 'your password', 'TEST') res = dbh.query("select * from Persons;"); puts res.class res.each do |row| puts row.join(" ") end
{ "pile_set_name": "StackExchange" }