source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0018944677.txt" ]
Q: I can just use snippets from all.snippets It seems that I can't use snippets from *.snippets files except all.snippets. For example I can not use snippets from c.snippets or python.snippets. If i try to define a custom snippets in all.snippets it works but not in c.snippets when I create a .c file. But if I add the command on vim: :UltiSnipsAddFiletypes types it takes the types into account. Why it doesn't take the type in account? A: After asking here https://answers.launchpad.net/ultisnips/+question/236140, it seems that scripts from ftdetect are not properly run. I have to copy UltiSnips.vim into ~/vim/ftdetect repository.
[ "stackoverflow", "0019550488.txt" ]
Q: GLKit masking or blending 2 textures both from jpegs no alphas I am using GLKit, and at 24 fps I need to take a CGImageRef (no alpha layer) and apply another CGImageRef (no alpha layer) as a mask to it (black and white image) and render the result as a GLKit texture. At first I tried this approach: CGImageRef actualMask = CGImageMaskCreate(CGImageGetWidth(maskRef), CGImageGetHeight(maskRef), CGImageGetBitsPerComponent(maskRef), CGImageGetBitsPerPixel(maskRef), CGImageGetBytesPerRow(maskRef), CGImageGetDataProvider(maskRef), NULL, false); CGImageRef masked = CGImageCreateWithMask(imgRef, actualMask); And although would work when assigning the resulting UIImage to a UIImageView, this would not work as a GLKit texture (the mask would not be applied). However, if I redraw the image using: UIImage *maskedImg = [UIImage imageWithCGImage:masked]; UIGraphicsBeginImageContext(maskedImg.size); [maskedImg drawInRect:CGRectMake(0, 0, maskedImg.size.width, maskedImg.size.height)]; UIImage* resultImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); The resulting image would be masked and render correctly in the GLKit texture. However, this lowers the performance to about 6 fps on an iPhone 4S. I have tried this masking approach without success. I have tried doing this without Core Graphics and using GLKit blending as shown in this example by Ray Wenderlich. However, this requires an alpha transparency on the mask and this is a deal breaker for me. I also found an interesting example of doing exactly what I want to do with a library called AVAnimator and an example called KittyBoom. Here they are replacing pixels manually. I want to get this same result using GLKit. Any further direction or guidance would be helpful here. Thanks in advance. A: GLKit is a framework with four major components that may be used together or separately: view/view controller, math library, texture loader, and effects. I presume from your question that the issue your having concerns GLKBaseEffect. One might say GLKBaseEffect's purpose in life is to make routine things easy. It's primarily a replacement for the OpenGL ES 1.1 fixed-function pipeline and some of the common tricks done with it. What you're after isn't a routine fixed-function pipeline task, so to do it well means stepping beyond the basic functionality of GLKBaseEffect and writing your own shaders. That's the bad news. The good news is that once you're into the shader world, this is pretty easy. The other good news is that you can expect great performance -- instead of using the CPU to do CoreGraphics blending, you can do it on the GPU. The "hard" part, if you're unfamiliar with OpenGL ES 2.0 (or 3.0) shaders, is replacing the client OpenGL ES code and vertex shader provided by GLKBaseEffect with with custom code that does the same. There's lots of example code and tutorials for this, out there, though. (Since you've been following Ray Wenderlich's site, I'm sure you'll find some good ones there.) The main things you need to do here are: Transform vertices from the coordinate space you're using for your glDraw commands into clip space. For 2D stuff this is pretty easy, since you can use the same matrix setup you were doing for GLKBaseEffect's transform property. Load your two textures (GLKTextureLoader can help you a lot here) and bind them to two texture units. In your client code, associate each vertex with some texture coordinates. (You're probably doing this already.) In your vertex shader, take the texture coordinates from a uniform input and pass them to a varying output. (You don't have to do anything else unless you want to transform the coordinates for some reason.) After all that setup, the part that actually accomplishes the effect you're after is pretty easy, and it's all in your fragment shader: // texture units bound in client code uniform sampler2D colorTexture; uniform sampler2D maskTexture; // texture coordinate passed in from vertex shader // (and automatically interpolated across the face of the polygon) varying mediump vec2 texCoord; void main() { // read a color from the color texture lowp vec3 color = texture2D(colorTexture, texCoord).rgb; // read a gray level from the mask texture // (the mask is grayscale, so we only need one component // of its color because the others are the same) lowp float maskLevel = texture2D(maskTexture, texCoord).r; // use the gray level from the mask as the alpha value in the output color gl_FragColor = vec4(color, maskLevel); } Also, since you mention doing this at 24 fps, it suggests you're working with video. In that case, you can cut out the middleman -- video frames are already being handled on the GPU, and putting them in CGImages on the CPU just slows you down. Take a look at the CVOpenGLESTexture class and the GLCameraRipple sample code for help getting video into a texture.
[ "stackoverflow", "0062807785.txt" ]
Q: Trying to calculate the difference between 2 time and dates using moment.js I'm using a date/time picker that I found on https://material-ui-pickers.dev/ and wanted to use it with the moment.js library. I'm having some issues. I have a form that collects a start time and an end time. I wanted to use the moment.js "diff" method to calculate the difference in hours. I keep getting "20.4234254" or similar, regardless of what dates & times I enter. The format of the date as it's being held in state and managed by moment.js is: "Wed Jul 08 2020 21:51:23 GMT-0700 (Pacific Daylight Time)". import React, { useState, useEffect } from 'react'; import MomentUtils from '@date-io/moment'; import { DatePicker, TimePicker, DateTimePicker, MuiPickersUtilsProvider, } from '@material-ui/pickers'; import moment from 'moment'; function DateFormField() { const [startDate, startTime] = useState(new Date()); const [endDate, endTime] = useState(new Date()); const [duration, setDuration] = useState(""); const timeCalc = (startDate, endDate) => { var start = moment(startDate); var end = moment(endDate); console.log(end.diff(start, "hours", true) + ' hours'); } return ( <MuiPickersUtilsProvider utils={MomentUtils}> <DateTimePicker value={startDate} onChange={startTime} helperText="Start Time" /> <DateTimePicker value={endDate} onChange={endTime} helperText="End Time" /> <button onClick={timeCalc}>Time Duration: {duration}</button> </MuiPickersUtilsProvider> ); } export default DateFormField; A: Issue I can't get this code to run in a sandbox (interacting with the DateTimePicker for some reason throws a utils.getYearText is not a function TypeError), but I think I know what the issue is. You define timeCalc to consume two arguments, startDate and endDate const timeCalc = (startDate, endDate) => { var start = moment(startDate); var end = moment(endDate); console.log(end.diff(start, "hours", true) + ' hours'); } but in the button to trigger it you simply attach the function to the onClick handler, so it is actually only passed the event object as the first argument and undefined for the second. <button onClick={timeCalc}>Time Duration: {duration}</button> I then tested timeCalc manually in the function body by passing it the startDate and endDate state values and it (presumably) correctly returns 0 hours, as would be expected from two nearly identical timestamps. const timeCalc = (startDate, endDate) => { var start = moment(startDate); var end = moment(endDate); console.log(end.diff(start, "hours", true) + " hours"); }; timeCalc(new Date(), new Date()); <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script> Solution Either remove the arguments to timeCalc so the referenced startDate and endDate values will be the ones in global component scope const timeCalc = () => { var start = moment(startDate); var end = moment(endDate); console.log(end.diff(start, "hours", true) + ' hours'); } Or explicitly pass the state values to the callback <button onClick={() => timeCalc(startDate, endDate)}> Time Duration: {duration} </button>
[ "stackoverflow", "0018343873.txt" ]
Q: SQL Query Into Delimited String In Stored Procedure I have the table: CREATE TABLE [address_tabletype] ( [CONTROL_NUMBER] [varchar](12) NULL, [ADDRESS1] [varchar](50) NULL, [ADDRESS2] [varchar](50) NULL, [CITY] [varchar](50) NULL, [STATE] [varchar](2) NULL, [ZIP] [varchar](10) NULL ) GO and, say I have the following rows: 2506387 1 2 3 4 5 2506394 1 2 3 4 5 2506403 1 2 3 4 5 I would like to to look like: 2506387|1|2|3|4|5~2506394|1|2|3|4|5~2506403|1|2|3|4|5 I haven't tried anything because I honestly have no idea where to start. I am using SQL Server 2008 R2, and will be using a temp table to build this string. EDIT I am using this to pass to a 3rd party CLR Function that absolutely needs a delimited string in this fashion. I planned to send it over to the function, return it to the SP, break it down to its original form, and then return the results to the caller of the SP. Thank you. A: Try following: SELECT STUFF((select ( SELECT '~' + ( CONTROL_NUMBER+'|'+ ADDRESS1 +'|'+ ADDRESS2 + '|'+ CITY + '|'+ [States] + '|'+ ZIP) FROM address_tabletype FOR XML PATH(''), type ).value('text()[1]', 'varchar(max)')), 1, 1, '')
[ "stackoverflow", "0046658003.txt" ]
Q: Error "AttributeError: 'NoneType' object has no attribute 'append'" I saw a lot of questions about the same error, but I didn't find anyone that seems to be about the same thing. A part (that seems relevant to me) of my code is: falta = [0] x = 0 o = 0 aux = a while a in range(aux, len(repetido)): print("a %s" %a) x = 0 while int(repetido[a].academia) != int(vetor[x].academia): print("repetido %s" % repetido[a].academia) print("vetor %s" %vetor[x].academia) x = x + 1 if a == aux: falta[0] = int(vetor[x].inscricao) print("este eh o primeiro falta: %s" %falta[0]) else: falta.append(int(vetor[x].inscricao)) falta = random.shuffle(falta) a = a + 1 I get this error message: File "C:/Users/vivia/PycharmProjects/karate/Teste posicoes repetidas.py", line 60, in posicionaAcademiaIgual falta.append(int(vetor[x].inscricao)) AttributeError: 'NoneType' object has no attribute 'append' I don't use this falta list on any other place in the program. Sorry about my poor English. A: Just making my comment an official answer. When you perform the assignment falta = random.shuffle(falta), falta becomes None, since random.shuffle operates in place and returns None. When you come around on your next iteration, falta has become none, and the AttributeError is thrown when you call falta.append. Instead of falta = random.shuffle(falta) try random.shuffle(falta) And read this.
[ "stackoverflow", "0024691332.txt" ]
Q: How can I compare two source locations in clang? this seems to be more a C++ problem rather than a Clang problem... I have to use C++ in order to write an OCLint (static code analyzer) rule. I wish to compare two objects from the Clang library that have the type "SourceLocation". This type provides informations about the location (basically line & column) of an object (statement, declaration etc.) in the code. Basically, I would like to know if the statement A begins and ends before, or after a statement B. In pseudo-code, that means I would like to get a boolean from : ( stmt_A->getLocBegin() < stmt_B->getLocBegin() ), for example. Of course, this does not compile because the "<" operator is not defined between two objects of type "SourceLocation". I found a method in the Clang documentation, but, as I am no frequent user of C++, I don't find a way to use it, here is this method : http://clang.llvm.org/doxygen/classclang_1_1BeforeThanCompare_3_01SourceLocation_01_4.html clang::BeforeThanCompare<SourceLocation>::BeforeThanCompare (SourceManager &SM) bool clang::BeforeThanCompare< SourceLocation >::operator()(SourceLocation LHS, SourceLocation RHS) const [inline] I do not know how to use SourceManager, or simply how to get this boolean above. A: Here is the final code that shows how to use SourceManager in Clang library, and how to compare two SourceLocation : // Declaration of a SourceManager SourceManager & loc_SM = _carrier->getSourceManager(); // Declaration of an object BeforeThanCompare<SourceLocation> BeforeThanCompare<SourceLocation> isBefore(loc_SM); SourceLocation stmt_A, stmt_B; // Get whether stmt_A is before or after Stmt_B bool A_before_B = isBefore(stmt_A,stmt_B);
[ "math.stackexchange", "0000628857.txt" ]
Q: What are the conditions for $n^2 \nmid(n-1)!$ Q: What are the conditions for $n^2 \nmid (n-1)!$, given that $2\le n \le 100$ and $n\in \mathbb{N}$? According to me the two conditions must be: 1. $n$ is a prime number (since the factorization of $(n-1)!$ will not have a $n$ when n is prime). 2. $n = 2\times$(prime number). (Because if $p$ is the prime number such that $n=2p$, then $(2p-1)!$ will have only one $p$ in the prime factorization, but we need two.) Is there any other condition for $n^2\text{does not divide} ((n-1)!)$ ? A: If $n$ has (at least) two distinct prime factors -- say $p$ and $q$ -- then notice that the factors $\frac{n}{p}$, $\frac{n}{q}$, $p$, and $q$ multiply to get $n^2$. So we would like to write $$ n^2 = \frac{n}{p} \cdot \frac{n}{q} \cdot p \cdot q \; \mid \; (n-1)! $$ (since $p,q, \frac{n}{p}, \frac{n}{q} < n$ are contained in the expansion of $(n-1)!$.) But a few things could go wrong: $n$ does not have at least two distinct prime factors. Then either $n$ is a power of a prime, or $n = 1$. If $n = 1$, in fact $n^2$ does divide $(n-1)! = 1$. Otherwise, let $n = p^k$, $k > 0$. 1a. If $k = 1$, then this is one exception (which you list): $\boxed{n \text{ is prime}}$. 1b. If $p^{k-1} > 2k$, then we can write $$ n^2 = p^{2k} \; \mid \; p^{p^{k-1} - 1} \; \mid \; (p)(2p)(3p)\cdots ((p^{k-1} - 1)p) \; \mid \; (n-1)! $$ 1c. Either (1a) or (1b) applies unless $(p,k) = (2,2), (2,3), (2,4), (3,2)$. These correspond to $n = 4, 8, 16, 9$, of which $\boxed{n = 4, 8, 9}$ are genuine exceptions. $\frac{n}{p}$ could equal $p$ (or $\frac{n}{q}$ could equal $q$). In this case, $n = p^2$, which is not divisible by $q$ (so this case never happens). $\frac{n}{p}$ could equal $q$ (or $\frac{n}{q}$ could equal $p$). In this case, $n = pq$. If $p,q > 2$, then we write $$ n^2 = p^2q^2 \; \mid \; p \cdot q \cdot 2p \cdot 2q \; \mid \; (n-1)! $$ because $p,q, 2p, 2q < pq = n$. Otherwise, we have the exception $\boxed{n \text{ is 2 times a prime}}$. (This exception also encompasses $n = 4$ from case 1.) So: besides $n = 8,9$, your two conditions are correct (and you don't need the restriction $2 \le n \le 100$).
[ "stackoverflow", "0015586167.txt" ]
Q: Send mail using VB Script? I have the following code to monitor a drive. Now I an getting Echo for each file creation or deletion event. Is there and way to modify the WScript.Echo to send a mail notification? strDrive = "c" arrFolders(0) = strDrive & "\\\\" strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2") 'Loop throught the array of folders setting up the monitor for Each i = 0 For Each strFolder In arrFolders 'Create the event sink strCommand = "Set EventSink" & i & " = WScript.CreateObject" & "(""WbemScripting.SWbemSink"", ""SINK" & i & "_"")" ExecuteGlobal strCommand 'Setup Notification strQuery = "SELECT * FROM __InstanceOperationEvent WITHIN 1 " & "WHERE Targetinstance ISA 'CIM_DirectoryContainsFile'" & " and TargetInstance.GroupComponent = " & "'Win32_Directory.Name=""" & strFolder & """'" strCommand = "objWMIservice.ExecNotificationQueryAsync EventSink" & i & ", strQuery" ExecuteGlobal strCommand 'Create the OnObjectReady Sub strCommand = "Sub SINK" & i & "_OnObjectReady(objObject, " & "objAsyncContext)" & VbCrLf & vbTab & "Wscript.Echo objObject.TargetInstance.PartComponent" & VbCrLf & "End Sub" WScript.Echo strCommand ExecuteGlobal strCommand i = i + 1 Next WScript.Echo "Waiting for events..." i = 0 While (True) Wscript.Sleep(1000) Wend Instead of Echoing like below: strCommand = "Sub SINK" & i & "_OnObjectReady(objObject, " & "objAsyncContext)" & VbCrLf & vbTab & "Wscript.Echo objObject.TargetInstance.PartComponent" & VbCrLf & "End Sub" I want to send a mail like this: strCommand = "Sub SINK" & i & "_OnObjectReady(objObject, " & "objAsyncContext)" & VbCrLf & vbTab & " Set outobj = CreateObject("Outlook.Application") Set mailobj = outobj.CreateItem(0) With mailobj .To = toAddress .Subject = Subject .HTMLBody = strHTML .Send End With " & VbCrLf & "End Sub" Is it possible or is there an other way to do this..? A: I don't know what server do you use, but on Windows 2003 and 2008 e.g. you can use CDO object to create a email. You might use a smart host to send your email to. Check this link: http://www.paulsadowski.com/wsh/cdo.htm Also you can choose any free email component to create a email and use a smtp server to send your email. Or check this side where you can use a component including many examples how to do it: http://www.chilkatsoft.com/email-activex.asp. ** UPDATED ** This Script checks and send a email as you requestted: strDrive = "d:" Dim arrFolders(0) : arrFolders(0) = strDrive & "\\\\" strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2") 'Loop throught the array of folders setting up the monitor for Each i = 0 For Each strFolder In arrFolders 'Create the event sink WScript.Echo "setup for folder: " & strFolder & vbLf strCommand = "Set EventSink" & i & " = WScript.CreateObject" & "(""WbemScripting.SWbemSink"", ""SINK" & i & "_"")" ExecuteGlobal strCommand 'Setup Notification strQuery = "SELECT * " _ & "FROM __InstanceOperationEvent " _ & "WITHIN 1 " _ & "WHERE Targetinstance ISA 'CIM_DirectoryContainsFile'" _ & " AND TargetInstance.GroupComponent = " & "'Win32_Directory.Name=""" & strFolder & """'" strCommand = "objWMIservice.ExecNotificationQueryAsync EventSink" & i & ", strQuery" ExecuteGlobal strCommand 'Create the OnObjectReady Sub strCommand = "Sub SINK" & i & "_OnObjectReady(objObject, " & "objAsyncContext)" & vbLf _ & " Wscript.Echo objObject.TargetInstance.PartComponent" & vbLf _ & " SendMail(objObject.TargetInstance.PartComponent)" & vbLf _ & "End Sub" 'WScript.Echo strCommand ExecuteGlobal strCommand i = i + 1 Next WScript.Echo "Waiting for events..." i = 0 While (True) Wscript.Sleep(1000) Wend Function SendMail(vBody) Dim oMail : Set oMail = CreateObject("CDO.Message") 'Name or IP of Remote SMTP Server oMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 oMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "your.smtp.server" oMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 oMail.Configuration.Fields.Update oMail.Subject = "Email Watch Info Message" oMail.From = "[email protected]" oMail.To = "[email protected]" oMail.TextBody = vBody oMail.Send End Function Correct the settings in the send mail function and your are fine.
[ "stackoverflow", "0047788396.txt" ]
Q: Vue js : Call a chid method from the parent component I tried to make communicate to components with vuejs and vuex : First component is a menu Second component, inside the first, is an hamburgerButton. In this very current case, when I click the hamburgerButton, this one is animated and the menu too. With this code, after the button click, the menu is animated with vueTransition and the hamburgerButton too. Note that i use vuex to manage a menuIsOpen state. My problem is when i click an item of the menu, I would like fired the hamburgerButton animation. hamburgerButtonanimation method, call animButtonHandler(), is encapsulated in a @click event. Actually i understand why it doesn't work right know, but I don't perceive how to handle this method to the click of a Parent element (item of the menu). So my question is, how can I access a method to a child component from a parent component ? Or is there an another workaround methodology to achieve this ? parent component - menu.vue : <template> <div class="menu"> <!-- import hamburgerButton component --> <hamburger-button></hamburger-button> <transition v-on:enter="enterMenuHandler" v-on:leave="leaveMenuHandler"> <div class="menu_wrapper" v-if="this.$store.state.menuIsOpen"> <ul class="menu_items"> <li class="menu_item" @click="$store.commit('toggleMenu')"> <router-link class="menu_link" to="/">home</router-link> <router-link class="menu_link" to="/contact">contact</router-link> </li> </ul> </div> </transition> </div> </template> <script> import hamburgerButton from "hamburgerButton.vue"; export default { components: { 'hamburger-button': hamburgerButton, }, methods: { enterMenuHandler(el, done){ TweenLite.fromTo(el, 0.5, { opacity: '0', },{ opacity: '1', onComplete: done }); }, leaveMenuHandler(el, done){ TweenLite.to(el, 0.5, { opacity: '0', onComplete: done }); }, } } </script> child component : hamburgerButton.vue : <template> <div class="hamburgerButton" @click="animButtonHandler()"> <div class="hamburgerButton_inner" ref="hamburgerButtonInner"> <i class="hamburgerButton_icon></i> </div> </div> </template> <script> export default { methods: { animButtonHandler (){ // toggle the state of menu if button clicked this.$store.commit('toggleMenu'); const isOpen = this.$store.state.menuIsOpen === true; // anim the button TweenLite.to(this.$refs.hamburgerButtonInner, 0.5, { rotation: isOpen ? "43deg" : '0', }); }, } } </script> store.js (imported in the main.js) : let store = new Vuex.Store({ state : { menuIsOpen : false, }, mutations: { toggleMenu(state) { state.menuIsOpen = !state.menuIsOpen } } }); A: I have added basic Example of event bus. you can now compare it with and do changes like wise. if find any difficulties please comment. <!DOCTYPE html> <html> <head> <script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div id="app"> <h2>event bus</h2> <button @click="callChildAnimateMethod"> Button On Parent Call Child </button> <childcmp><childcmp /> </div> <script> var EventBus = new Vue(); Vue.component('childcmp', { template: `<div>child demo - {{ message }}</div>`, data: function() { return { message: 'hello' } }, mounted: function() { // listen for event EventBus.$on('animate', this.animButtonHandler); }, destroyed: function(){ // remove listener EventBus.$off('animate', this.animButtonHandler); }, methods: { animButtonHandler: function() { console.log('this is child method'); this.message = 'I am changed.' } } }); new Vue({ el: '#app', data: function() { return { } }, methods: { callChildAnimateMethod: function() { EventBus.$emit('animate'); } } }); </script> </body> </html> Update you need to define EventBus eventbus.js import Vue from 'vue'; const EventBus = new Vue(); export default EventBus; parent component - menu.vue import EventBus from './eventbus.js' ... your code child component : hamburgerButton.vue : import EventBus from './eventbus.js' ... your code now EventBus will be available to your code.
[ "stackoverflow", "0005439843.txt" ]
Q: Does XAML contain a subset of html tags? I know that there are lot of tags in XAML that have simmilar names in html. Is this because XAML contains all of the tags that html does, or is it just coincidence? A: No XAML and HTML are completely different. XAML tags map to .NET objects and properties. There are some XAML tags named similarly to mimic document functionality, like <Paragraph>, <Bold>, but the top of my head, I actually can't think of many that are exactly the same. Are you sure you aren't refering to XHTML?
[ "stackoverflow", "0025926810.txt" ]
Q: After the launch of iOS 8, already released app is behaving abnormally As soon as I updated to iOS 8, i found that my already released app is not properly showing the orientations, my app only support landscape orientations, but when i checked it on iOS 8, the first navigation controller is in Portrait orientation. It automatically goes fine after it goes to background, but on fresh launch it behaves in the same way. All orientation methods are implemented properly and working fine on iOS 7 and later. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation - (BOOL)shouldAutorotate - (NSUInteger)supportedInterfaceOrientations - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation - (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window A: Here it is Documentation of deprecated Method in iOS 8 about Orientation and other Methods
[ "stackoverflow", "0011412412.txt" ]
Q: Lotus Domino Designer 8.5 Web Preview Port Number Is it possible to change the port number and host in Designer 8.5? A: Prior to Domino Designer 8.5.3, the answer is no. In 8.5.3, IBM implemented a setting in the Domino Designer pane of the Preferences dialog. See here for more info.
[ "biology.stackexchange", "0000028621.txt" ]
Q: How close to Earth's core can organisms live? We don't to know much about organisms living deep below the Earth's crust. Recently a team led by S. Giovanni discovered some microbes 300 m below the ocean floor. The microbes were found to be a completley new and exotic species and apparently they feed off hydrocarbons like methane and benzene. Scientists speculate that life may exist in our Solar System far below the surface of some planets or moons. This raises some questions: What is the theoretical minimum distance from Earth's core where life can still exist. Please explain how you came up with this number. For example, there are temperature-imposed limits on many biochemical processes. Is there the potential to discover some truly alien life forms in the Earth's mantle (by this I mean, life which is not carbon based, or life which gets its energy in ways we have not seen before, or non DNA-based life, or something along these lines)? What is the greatest distance below the Earth's crust that life has been discovered? I believe it is the 300 m I cited above, but I am not 100% sure. A: There's a lot we don't know about life in deep caves, but we can bound the deepest living organism to at least 3.5 kilometers down, and probably not more than 30 kilometers down. The worms recovered from deep mining boreholes are not particularly specifically adapted to live that far down: they have similar oxygen/temperature requirements as surface nematodes. The Tau Tona mine is about 3.5 kilometers deep and about 60˚ C at the bottom. Hydrothermal vent life does just fine up to about 80˚C, and the crust gets warmer at "about" 25˚C per kilometer. It's entirely reasonable to expect life to about 5 kilometers down, but further than that is speculation. Increasing pressure helps to stabilize biological molecules that would otherwise disintegrate at those temperatures, so it's not impossible there could be life even deeper. It may even be likely, given that the Tau Tona life breathes oxygen. I am certain no life we might recognize as life exists in the upper mantle.
[ "stackoverflow", "0052648754.txt" ]
Q: How to enlarge the clickable of CSS button? I used NavLink for my route, then added some padding, and background color and etc according to the design I want. Then added a border-left style to the active css button to let user easily know where they are. But for some reason I am not able to make the border/background of my css button clickable and, the border-left is only beside of the text instead of the background. Anyone can help me with that? Here is the css: .tab-selections { background-color: rgb(242, 242, 242); padding: 1.4em 6em; height: 1.7em; display: inline-block; margin: .3em; vertical-align: top; align-items: center; text-align: center; color: rgb(75, 75, 75); font-size: 15px; } .active { display: inline-block; background-color: rgb(205, 221, 255); border-left: .6em solid; border-left-color: rgb(87, 0, 255); text-align: center; } Here is the HTML (ReactJS): <div className="article container"> <div className="flex container parent"> <div className="tab-selections"> <NavLink to="/sample/article" style={{ color: '#4b4b4b', textDecoration: 'none' }} > ARTICLES </NavLink> </div> <div className="tab-selections"> <NavLink to="/sample/casestudies" style={{ color: '#4b4b4b', textDecoration: 'none' }} > CASE STUDIES /<br /> WHITEPAPERS </NavLink> </div> <div className="tab-selections"> <NavLink to="/sample/news" style={{ color: '#4b4b4b', textDecoration: 'none' }} > NEWS/EVENTS </NavLink> </div> </div> Here's what the active button looked like Here's what it should looked like A: In your example code padding is used to space the container of the NAV-LINK, the solution is instead to apply the padding directly to the NAV-LINK that constitutes your "clickable surface" so i will change: style={{ color: '#4b4b4b', textDecoration: 'none' }} to: style={{ color: '#4b4b4b', textDecoration: 'none', padding: '1.4em 6em'}} however consider to put it inside a css class for better handle
[ "stackoverflow", "0055534286.txt" ]
Q: Firebase: Querying data inside an unknown name key (child inside another child) I'm developing a React Native app and having a query doubts. I need to return all groups (eg "group-id-01"), where the provided UID exists within members. This code return all groups: const memberGroup = firebase.database().ref('groups') memberGroup.once('value') .then((snapshot) => { console.log('snapshot'); console.log(snapshot.val()); }) .catch((error) => { console.log('Erro'); console.log(error); }); Result I'm having: "group-id-01" "members" "no-uid-provided":"Belem" "oZlTzlbCTGaZfsrzyxqABlnxt2e2":"Julia" "name":"Rolling Stones" Result I want: "group-id-01" "members" "oZlTzlbCTGaZfsrzyxqABlnxt2e2":"Julia" "name":"Rolling Stones" Whell... I've tried some queries with .orderByChild and .equalTo, but the result is null. const memberGroup = firebase.database().ref('groups') .orderByChild('oZlTzlbCTGaZfsrzyxqABlnxt2e2') .equalTo('Julia') memberGroup.once('value') .then((snapshot) => { console.log('snapshot'); console.log(snapshot.val()); }) .catch((error) => { console.log('Erro'); console.log(error); }); I'm new in Firebase and I don't know if is possible to query a child inside another child with unknown name. Appreciate all the help :D A: Your current structure allows you to easily look up the members for a given group. It does not allow you to easily look up the groups for a given user. To allow the latter, you will need to add an additional data structure (often called a reverse index) mapping users back to groups. userGroups uid1 groupid1: true groupid2: true uid2 groupid2: true groupid3: true This means that you're duplicating data to allow for the additional use-case, which is quite common in NoSQL databases. Also see: Firebase Query Double Nested Firebase query if child of child contains a value Many to Many relationship in Firebase
[ "stackoverflow", "0059380393.txt" ]
Q: HackerRank- Method calculateSum in class Solution cannot be applied to given types I read many different posts and still don't understand why I get this error when running the below: import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class Solution { private static final Scanner scanner = new Scanner(System.in); public static void calculateSum(int n){ for (int i=1;i>11;i++){ int result=n*i; System.out.println(result); } } public static void main(String[] args) { int n = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); scanner.close(); calculateSum(); } } I get the below error: Compile Message Solution.java:26: error: method calculateSum in class Solution cannot be applied to given types; calculateSum(); ^ required: int found: no arguments reason: actual and formal argument lists differ in length 1 error Exit Status 1 I passed a value in the calculateSum() method within the main method and it ran successfully but then it prints no output. Please help me to understand what I'm doing wrong. Thanks. A: You have given argument in called int n in public static void calculateSum(int n). When you call that function into your main function you keep calculateSum function as empty. You cannot call like that. There for you have to fill that function with an integer value. You have used to input int n in main function. There for use calculateSum(n); instead of calculateSum(); I found another error on your code you have used for (int i=1;i>11;i++). In here i > 11 need correction. It should be for (int i=1;i<11;i++) like this
[ "stackoverflow", "0022363867.txt" ]
Q: Predefine for Windows 8 || Windows 8.1 Is there a predefine when we are building for Windows 8 and Windows 8.1 store applications, we need to detect which is selected so that we can disable some features. I ask this because we're porting Windows 8.1 app to Windows 8. In Windows 8 some features are not available so we need to override them and implement something else. (Two projects, same code) A: Have a look at the NTDDI_VERSION macro. #if NTDDI_VERSION == 0x06030000 // NTDDI_WINBLUE /* Windows 8.1 */ #elif NTDDI_VERSION == 0x06020000 // NTDDI_WIN8 /* Windows 8 */ #endif Make sure you've included SdkDdkVer.h, but it I believe most Windows projects already do that by default.
[ "stackoverflow", "0007507257.txt" ]
Q: Getting 405 Method Not Allowed on a GET Clicking the following link in my webapp produces a 405: <a href="/unsubscribe/confirm?emailUid=<%= ViewData["emailUid"] %>&hash=<%= ViewData["hash"] %>" class="button">Yes, unsubscribe me.</a> Here's the Confirm Action being called from the Unsubscribe Controller: [HttpGet] public ActionResult Confirm( string emailUid, string hash) { using ( UnsubscribeClient client = new UnsubscribeClient() ) { UnsubscribeResponse response = client.Unsubscribe( emailUid, hash ); return View( response ); } } Simple stuff. It works when I F5 it, but when I host it in IIS (both 7.5 and 6), I get the error. I'm pretty lost with this. I've scoured the net, but can't seem to find any reason as to why this is happening. A: <%= Html.ActionLink( "Yes, unsubscribe me.", "Confirm", "Unsubscribe", new { emailUid = ViewData["emailUid"], hash = ViewData["hash"] }, new { @class = "button" } ) %> Also ViewData?! Please, remove this as well in favor of strongly typed views and view models. Everytime I see someone using ViewData I feel obliged to say that. A: Well, I found my issue. It turns out to be a problem with my IIS configuration. In IIS 6, I didn't allow scripts to be executed in the directory, so my .svc would never run for my service host. Once I changed that setting, I no longer received the 405 error... Many thanks to the other answers. I'll be sure to use the Html helper.
[ "gaming.stackexchange", "0000233000.txt" ]
Q: Why is Dark Souls showing double health bars on bosses? When I fight bosses I see 2 health bars (for each boss) along the bottom. One is yellow and uses most of the bottom of the screen, the other is red and is below the yellow one and in the left quarter of the screen. It is about 1/4 the size of the yellow bar. I have DSFix installed. Is this an issue with that? Any ideas how to fix so that only one bar displays? Screen shot from http://www.neogaf.com/forum/showthread.php?t=488240&page=119 A: I figured it out. DSFix has a feature called HUD scaling that was causing it. The scaling was at 75%, when I turned it off, the artifacts went away. Also, the hotkey for toggling HUD changes on and off is RightShift (at lest by default) as seen in the DSFixKeys.config
[ "stackoverflow", "0015204581.txt" ]
Q: How to change autolink in my forum, I'm trying to stop links from converting into clickbale links and place a custom text language instead that says Links Not Allowed. This seems to be the code that creates the clickable links. My question, is it possible to convert the urls to non-clickable text that says "Spam - Links Not Allowed" public function parseUrl($params) { $url = $params['url']; $text = $params['text']; If I remove this last line, it seems to make the links disappear, however I would like to display a custom message instead. Sorry if this is a basic question, my code knowledge is at a beginner level. A: It's not just server side action, for this reason you should call JS function, so, at first change your php code to this : $url = $params['javascript:myfunction();']; and then in client side for javascript write this : function myfunction(){ alert('not allowed!'); }
[ "stackoverflow", "0055249898.txt" ]
Q: How to convert a list to dictionary where some keys are missing their values? I have a list of objects with their counts associated after a semicolon. Trying to convert this list into a dictionary but some keys will be missing their values once converted. Tried using try/except but not sure how to store the value individually into the dictionary. Example: t = ['Contact:10', 'Account:20','Campaign:', 'Country:', 'City:'] The Campaign and Country objects would have no values when converting. I would like to either pass or assign a NaN as the dictionary value. I tried something like this but with no avail. for objects in t: try: dictionary = dict(objects.split(":") for objects in t) except: pass Any suggestion is appreciated. A: You do not really need to try/catch: t = ['Contact:10', 'Account:20','Campaign:', 'Country:', 'City:'] { a: b for a,b in (i.split(':') for i in t) } this yields: {'Account': '20', 'Campaign': '', 'City': '', 'Contact': '10', 'Country': ''} If you want None instead of empty string: { a: b if b else None for a,b in (i.split(':') for i in t) } A: You can use a generator expression with a split of each item and pass the output to the dict constructor: dict(i.split(':') for i in t) This returns: {'Contact': '10', 'Account': '20', 'Campaign': '', 'Country': '', 'City': ''} If you would like the assign NaN as a default value you can do it with a dict comprehension instead: {a: b or float('nan') for i in t for a, b in (i.split(':'),)} This returns: {'Contact': '10', 'Account': '20', 'Campaign': nan, 'Country': nan, 'City': nan}
[ "stackoverflow", "0058208103.txt" ]
Q: Join 2 dataframes with column of dateTime in df.x filtered on dateStart dateEnd in df.y? I have a dataset with start and end times for events (called df_time), and another dataset with when an event happened (df_val). I want to do an inner join the two dataframes on whether df_val took place within the 2 columns of df_time. start = c(1, 5, 7, 4) end = c(2, 7, 11, 7) event_id = c('a', 'b', 'c', 'd') df_time = data.frame(start, end, event_id) time = c(3, 6, 2, 10, 11) val = c(100, 20, 30, 40, 50) df_val = data.frame(time, val) I am aware of map2_dfr, and am using it as such: library(tidyverse) unique( map2_dfr( df_time$start, df_time$end, ~filter(df_val, time >= .x, time <= .y) ) ) However, this gives me back only columns in df_val; is there any way to get back the columns from df_time for an output like: time val start end event_id 1 2 30 1 2 'a' 2 6 20 5 7 'b' 3 10 40 7 11 'c' 4 6 50 4 7 'd' Edit: setDT is very close to the correct answer! However, df_time has na values for val and time for rows that had no corresponding values in df_val instead of being omitted altogether. For example, considering the below to be Case 2: Case 2 time=c(3,6,10,11) val=c(100,20,40,50) df_val=data.frame(time,val) start = c(1, 5, 7, 4) end = c(2, 7, 11, 7) event_id = c('a', 'b', 'c', 'd') df_time = data.frame(start, end, event_id) setDT(df_time)[df_val, c("val", "time") := .(val, time) , on = .(start <= time, end >= time)] df_time Output: df_time start end event_id val time 1 2 a NA NA 5 7 b 20 6 7 11 c 50 11 4 7 d 20 6 expected/correct output: start end event_id val time 5 7 b 20 6 7 11 c 50 11 4 7 d 20 6 A: An option is a non-equi join in data.table. Convert the 'data.frame' to 'data.table' (setDT(df_time)), join with 'df_val' on non-equi (<=, >=) columns, and assign (:=) the corresponding 'val' and 'time' that matches to new columns in the 'df_time' library(data.table) na.omit(setDT(df_time)[df_val, c("val", "time") := .(val, time) , on = .(start <= time, end >= time)]) #. start end event_id val time #1: 5 7 b 20 6 #2: 7 11 c 50 11 #3: 4 7 d 20 6
[ "stackoverflow", "0028629937.txt" ]
Q: Set Collection for mutable objects in Java In Java, a set only checks for equality of an object with objects already in the set only at insertion time. That means that if after an object is already present in the set, it becomes equal to another object in the set, the set will keep both equal objects without complaining. EDIT: For example, consider a simple object, and assume that hashCode and equals are defined following best practices/ class Foo { int foo; Foo(int a){ foo = a; } //+ equals and hashcode based on "foo" } Foo foo1 = new Foo(1); Foo foo2 = new Foo(2); Set<Foo> set = new HashSet<Foo>(); set.add(foo1); set.add(foo2); //Here the set has two unequal elements. foo2.foo = 1; //At this point, foo2 is equal to foo1, but is still in the set //together with foo1. How could a set class could be designed for mutable objects? The behavior I would expected would be the following: If at any time one of the objects in the set becomes equal to another object in the set, that object is deleted from the set by the set. Is there one already? Is there a programming language that would make this easier to accomplish? A: I don't think this can be reliably done in Java in the general sense. There is no general mechanism for ensuring a certain action on mutation of an object. There a few approaches for solutions that may be sufficient for your use case. 1. Observe elements for changes You need to have control over the implementation of the types that go into the set Small performance cost whenever an object in your set updates You could try to enforce an observer like construction where your Set class is registered as an Observer to all its items. This implies you'd need to control the types of objects that can be put into the Set (only Observable objects). Furthermore, you'd need to ensure that the Observables notify the observer for every change that can affect hashcode and equals. I don't know of any class like this that exists already. Like Ray mentions below, you'll need to watch out for potential concurrency problems as well. Example: package collectiontests.observer; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Observable; import java.util.Observer; import java.util.Set; public class ChangeDetectingSet<E extends Observable> implements Set<E>, Observer { private HashSet<E> innerSet; public void update(Observable o, Object arg) { innerSet.remove(o); innerSet.add((E)o); } public int size() { return innerSet.size(); } public boolean isEmpty() { return innerSet.isEmpty(); } public boolean contains(Object o) { return innerSet.contains(o); } public Iterator<E> iterator() { return innerSet.iterator(); } public Object[] toArray() { return innerSet.toArray(); } public <T> T[] toArray(T[] a) { return innerSet.toArray(a); } public boolean add(E e) { e.addObserver(this); return innerSet.add(e); } public boolean remove(Object o) { if(o instanceof Observable){ ((Observable) o).deleteObserver(this); } return innerSet.remove(o); } public boolean containsAll(Collection<?> c) { return innerSet.containsAll(c); } public boolean addAll(Collection<? extends E> c) { boolean result = false; for(E el: c){ result = result || add(el); } return result; } public boolean retainAll(Collection<?> c) { Iterator<E> it = innerSet.iterator(); E el; Collection<E> elementsToRemove = new ArrayList<E>(); while(it.hasNext()){ el = it.next(); if(!c.contains(el)){ elementsToRemove.add(el); //No changing the set while the iterator is going. Iterator.remove may not do what we want. } } for(E e: elementsToRemove){ remove(e); } return !elementsToRemove.isEmpty(); //If it's empty there is no change and we should return false } public boolean removeAll(Collection<?> c) { boolean result = false; for(Object e: c){ result = result || remove(e); } return result; } public void clear() { Iterator<E> it = innerSet.iterator(); E el; while(it.hasNext()){ el = it.next(); el.deleteObserver(this); } innerSet.clear(); } } This incurs a performance hit every time the mutable objects change. 2. Check for changes when Set is used Works with any existing object you want to put into your set Need to scan the entire set every time you require info about the set (performance cost may get significant if your set gets very large). If the objects in your set change often, but the set itself is used rarely, you could try Joe's solution below. He suggests to check whether the Set is still correct whenever you call a method on it. As a bonus, his method will work on any set of objects (no having to limit it to observables). Performance-wise his method would be problematic for large sets or often used sets (as the entire set needs to be checked at every method call). Possible implementation of Joe's method: package collectiontests.check; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; public class ListBasedSet<E> { private List<E> innerList; public ListBasedSet(){ this(null); } public ListBasedSet(Collection<E> elements){ if (elements != null){ innerList = new ArrayList<E>(elements); } else { innerList = new ArrayList<E>(); } } public void add(E e){ innerList.add(e); } public int size(){ return toSet().size(); } public Iterator<E> iterator(){ return toSet().iterator(); } public void remove(E e){ while(innerList.remove(e)); //Keep removing until they are all gone (so set behavior is kept) } public boolean contains(E e){ //I think you could just do innerList.contains here as it shouldn't care about duplicates return innerList.contains(e); } private Set<E> toSet(){ return new HashSet<E>(innerList); } } And another implementation of the check always method (this one based on an existing set). This is the way to go if you want to reuse the existing sets as much as possible. package collectiontests.check; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.NavigableSet; import java.util.SortedSet; import java.util.TreeSet; public class ChangeDetectingSet<E> extends TreeSet<E> { private boolean compacting = false; @SuppressWarnings("unchecked") private void compact(){ //To avoid infinite loops, make sure we are not already compacting (compact also gets called in the methods used here) if(!compacting){ //Warning: this is not thread-safe compacting = true; Object[] elements = toArray(); clear(); for(Object element: elements){ add((E)element); //Yes unsafe cast, but we're rather sure } compacting = false; } } @Override public boolean add(E e) { compact(); return super.add(e); } @Override public Iterator<E> iterator() { compact(); return super.iterator(); } @Override public Iterator<E> descendingIterator() { compact(); return super.descendingIterator(); } @Override public NavigableSet<E> descendingSet() { compact(); return super.descendingSet(); } @Override public int size() { compact(); return super.size(); } @Override public boolean isEmpty() { compact(); return super.isEmpty(); } @Override public boolean contains(Object o) { compact(); return super.contains(o); } @Override public boolean remove(Object o) { compact(); return super.remove(o); } @Override public void clear() { compact(); super.clear(); } @Override public boolean addAll(Collection<? extends E> c) { compact(); return super.addAll(c); } @Override public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { compact(); return super.subSet(fromElement, fromInclusive, toElement, toInclusive); } @Override public NavigableSet<E> headSet(E toElement, boolean inclusive) { compact(); return super.headSet(toElement, inclusive); } @Override public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { compact(); return super.tailSet(fromElement, inclusive); } @Override public SortedSet<E> subSet(E fromElement, E toElement) { compact(); return super.subSet(fromElement, toElement); } @Override public SortedSet<E> headSet(E toElement) { compact(); return super.headSet(toElement); } @Override public SortedSet<E> tailSet(E fromElement) { compact(); return super.tailSet(fromElement); } @Override public Comparator<? super E> comparator() { compact(); return super.comparator(); } @Override public E first() { compact(); return super.first(); } @Override public E last() { compact(); return super.last(); } @Override public E lower(E e) { compact(); return super.lower(e); } @Override public E floor(E e) { compact(); return super.floor(e); } @Override public E ceiling(E e) { compact(); return super.ceiling(e); } @Override public E higher(E e) { compact(); return super.higher(e); } @Override public E pollFirst() { compact(); return super.pollFirst(); } @Override public E pollLast() { compact(); return super.pollLast(); } @Override public boolean removeAll(Collection<?> c) { compact(); return super.removeAll(c); } @Override public Object[] toArray() { compact(); return super.toArray(); } @Override public <T> T[] toArray(T[] a) { compact(); return super.toArray(a); } @Override public boolean containsAll(Collection<?> c) { compact(); return super.containsAll(c); } @Override public boolean retainAll(Collection<?> c) { compact(); return super.retainAll(c); } @Override public String toString() { compact(); return super.toString(); } } 3. Use Scala sets You could cheat and do away with mutable objects (in the sense that instead of mutating, you'd create a new one with one property changed) in your set. You can look at the set in Scala (I thought it was possible to call Scala from Java, but I'm not 100% sure): http://www.scala-lang.org/api/current/scala/collection/immutable/IndexedSeq.html A: You will not find a general datastructure that can take just any object for this purpose. That kind of set would have to constantly monitor its elements, which among other things would lead to a lot of questions on concurrency. However, I can imagine something based on the practically unknown class java.util.Observable. You could e.g. write a class ChangeAwareSet implements Set<? extends Observable>, Observer. When an element is added to this Set, it would register as an Observer and so be notified on all changes to that object. (But don't expect this to be very efficient, and you might encounter concurrency problems in this scenario as well.) A: You can get the behaviour you're after by using another collection, such as an ArrayList. The contains and remove methods for a List make no assumptions about objects remaining unchanged. Since changes can happen at any time, there isn't much room for optimisation. Any operations would need to perform a full scan over all contents, as any object could have changed since the last operation. You may or may not wish to override add to check whether the object currently appears to be present. Then, when using or printing, use new HashSet(list) to eliminate objects which are currently duplicate.
[ "stackoverflow", "0051873626.txt" ]
Q: TypeScript foreach return I wonder if there is a better way of doing this - looks like returning out of a foreach doesn't return out of the function containing the foreach loop, which may be an expectation from C# devs. Just wondering if there is a cleaner way of doing this: example() { var forEachReturned; this.items.forEach(item => { if (true) { forEachReturned = true; return; } }); if (forEachReturned) { return; } // Do stuff in case forEach has not returned } A: The cleaner way would be to not use .forEach. It's almost never needed if you're using TypeScript: example() { for (let item of this.items) { if (true) { return; } } // Do stuff in case forEach has not returned } If the code inside your loop doesn't have any side-effects and you're just checking for a condition on each item, you could also use a functional approach with .some: example() { if (this.items.some(item => item === 3)) { return; } // Do stuff in case we have not returned }
[ "stackoverflow", "0010707421.txt" ]
Q: No class definition found while using Generic Motion listener My code was set on API 7 then i changed it to API 15 so that i can get onGenericMotionListener Now i am defining my activity as follow : newGame.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { vibe.vibrate(vibValue); if (levelStage == 1 && levelId == 1) { Intent myIntent = new Intent(v.getContext(), Level.class); startActivity(myIntent); } else displayAlertForNewGame(v.getContext()); } }); Whenever i try to launch this activity i get error java.lang.NoClassDefFoundError using this code to start activity Intent myIntent = new Intent(v.getContext(),myActivity.class); startActivity(myIntent); 05-22 22:49:20.416: E/AndroidRuntime(6327): FATAL EXCEPTION: main 05-22 22:49:20.416: E/AndroidRuntime(6327): java.lang.NoClassDefFoundError: com.code.global.Level 05-22 22:49:20.416: E/AndroidRuntime(6327): at com.umar.regGame.MainMenu$1.onClick(MainMenu.java:67) 05-22 22:49:20.416: E/AndroidRuntime(6327): at android.view.View.performClick(View.java:2449) 05-22 22:49:20.416: E/AndroidRuntime(6327): at android.view.View$PerformClick.run(View.java:9027) 05-22 22:49:20.416: E/AndroidRuntime(6327): at android.os.Handler.handleCallback(Handler.java:587) 05-22 22:49:20.416: E/AndroidRuntime(6327): at android.os.Handler.dispatchMessage(Handler.java:92) 05-22 22:49:20.416: E/AndroidRuntime(6327): at android.os.Looper.loop(Looper.java:123) 05-22 22:49:20.416: E/AndroidRuntime(6327): at android.app.ActivityThread.main(ActivityThread.java:4627) 05-22 22:49:20.416: E/AndroidRuntime(6327): at java.lang.reflect.Method.invokeNative(Native Method) 05-22 22:49:20.416: E/AndroidRuntime(6327): at java.lang.reflect.Method.invoke(Method.java:521) 05-22 22:49:20.416: E/AndroidRuntime(6327): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 05-22 22:49:20.416: E/AndroidRuntime(6327): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 05-22 22:49:20.416: E/AndroidRuntime(6327): at dalvik.system.NativeStart.main(Native Method) Best Regards A: The problem comes from the class com.code.global.Level. Where does this class come from ? Is it in a jar, do you include it in the right way in your build path ?
[ "math.stackexchange", "0001443487.txt" ]
Q: Example where $x^2 = e$ has more than two solutions in a group Show by means of an example that it is possible for the quadratic equation $x^2 = e$ to have more than two solutions in some group $G$ with identity $e$. A: Hint: Try $S_3$. Here $(1\:2), (1\:3), (2\:3)$ are solutions of $x^2=e$. A: In $S_n$, any transposition $\tau$ satisfies $\tau^2=e$. There are $\dbinom n2$ transpositions in $S_n$. A: Try $(\mathbb Z/2\mathbb Z)^n$ for $n\ge 2$.
[ "stackoverflow", "0019451140.txt" ]
Q: From code can I determine if glimpse is active for the current request? I want to add some custom plugins to glimpse. However the profiling I want to do is expensive so I only want to do it if glimpse id turned on for the current request. Can I access a property in code to tell me if glimpse is currently on. Something like: if(GlimpseConfig.IsGlimpseActive) { } A: First of all if you're creating a plugin for Glimpse like a custom tab then your tab will only be asked for data if Glimpse is active for the given request. So to be clear, if you want to make a check like you mentioned above inside your tab, then that is not necessary since Glimpse will not call you in the first place. But if you are talking about enabling/disabling some profiling code that will be accessed by your custom tab and which might be expensive, then I guess a check might indeed by helpful. Unfortunately there is currently no way to do this without some kind of abuse of Glimpse internals. Your question seems to have the same requirement as this question so I'm not going to paste the same answer here, but I'll paste the code sample for completeness of this answer. But in short you could do the following if you keep in mind that there are no guarantees on whether this will continue to work in upcoming releases, but check the other question for more details. public static class CurrentGlimpseStatus { private const string GlimpseCurrentRuntimePolicyKey = "__GlimpseRequestRuntimePermissions"; public static bool IsEnabled { get { RuntimePolicy currentRuntimePolicy = RuntimePolicy.Off; if (System.Web.HttpContext.Current.Items.Contains(GlimpseCurrentRuntimePolicyKey)) { currentRuntimePolicy = (RuntimePolicy)System.Web.HttpContext.Current.Items[GlimpseCurrentRuntimePolicyKey]; } return !currentRuntimePolicy.HasFlag(RuntimePolicy.Off); } } }
[ "rpg.stackexchange", "0000076561.txt" ]
Q: How deep information should players have in a political negotiation-focused edu-larp? I am considering an educational larp, perhaps even suitable for a lesson of one and half an hour in length at gymnasium (roughly: high school) level or at yläkoulu (roughly: middle school) level, supposing the class is not too large. The game should be playable in other contexts. Probably 6-30 players, with focus on 8-20 players. The time limit is not a necessary feature, but it would be nice. The players are divided into two teams. Each player will have a short description of their character, which communicates some of their social context, their goals, and maybe personality or other such traits for inspiration. The description will also contain historical/setting information. The groups are decision-making bodies that oppose each other. Both will decide how aggressively they will act towards the other. At the end, everyone will gather in the same space, the decisions of both groups will be compared in a prisoner's dilemma -kind of way to see how history unfolds in this case. There will be no other contact between the groups. Restrictions and limits Players will not have prepared for the game and are not assumed to be familiar with the initial situation. There will be a short common introduction (maybe 5 or 10 minutes). Most of the facts and rumours regarding the setting and the conflict will only be given to specific players through their character descriptions / info sheets. Players should not have to read very much - the game should teach by play, not by studying for play. Question How many layers of information, or how deep information, should the players have? The main educational goals are to give a sense of the event and the political issues of the time, and to give a sense of political decision-making. Here, political decision making means making decisions under uncertainty (already provided by the other team) when the involved people have somewhat different personal goals and various opinions on the proper methods for reaching those goals. Example of layers of information One layer of information: The communist revolution in the east is likely to succeed. Two layers of information: The communist revolution in the east is likely to succeed, since they defeated the troops sent against them. Three layers of information: The communist revolution in the east is likely to succeed, since they defeated the troops sent against them. Many of the defeated joined the communist revolution and the rest were killed. The situation (In case anyone is interested.) The situation is likely to be one of the following: the beginning of Finnish civil war, a decisive moment in the history of IKL or Lapuan liike, or a decisive moment in the history of SMP and Maalaisliitto. Answers I am interested in best practices and experiences of negotiation-focused larps. My experience is mostly on the tabletop side. I also have some experience as a teacher (of mathematics, not history). A: What you are trying to do is called a "Planspiel" in German. An educational role playing game that involves a conflict. The Planspiel has derived from military simulations, i.e. maneuvers at the green table with decision-making involving also the problem of having to act on incomplete information. The educational Planspiel is focused on decision-making and - mostly-negotiations. In a Planspiel you should hand out a scenario description of about half a page to all participants. Illustrations help. The scenario describes the conflict, gives a list of conflicting groups and defines the way of deciding the outcome of the conflict. This can be a treaty, a ballot, or - as in your case an outcome defined by a game master considering all actions taken by the players. There are scores of Planspiele around. Here is a link to an english site of a professional group of educators focussing on creating this kind of simulation games. A simple form I use for school (I am a history and politics teacher) is to hand out a role description to each group with their goals and ressources, written in a very subjective language so that each group gets the impression to be the only legitimate group in the game. I write descriptions of one half to one page. You can add secret individual roles to these group briefings, involving special interests and additional information as you see fit. The time schedule you set is tight. I normally reckon 1 and half an hour to introduce the game, have the students find their roles, let them prepare for the first exchange of opinions and let them exchange their viewpoints. Then normally 1 and half an hour have passed. My games normally really start after this first exchange, when a round of negotiations and actions goes afloat. But the limited scope of your project, i.e. one round of decision-making, no negotiation, probably allows for the decisions to take place at the end of 1 and half an hour. But still: If you want to discuss the results with your students (and everything we know about eductional role playing games and learning suggests, that reflecting the experience is what makes the difference) you will need more time or a second lesson. A: A game suitable for that age level, designed explicitly for educational purposes, is Dangerous Parallel. See if your school can get a copy of that game and use it as a template for how deep to go. I recall that the game went a little deeper than your third level. There is both open information and secret information that only certain players got. The game can accommodate 6-30 players, and can work at the junior high level as well. There are multiple roles on each team. If your time limit is one to two hours, you are right to be concerned about complexity and depth. If you want all of the players to participate, level 3 might be the limit, maybe level 2. We played Dangerous Parallel in high school (with two teachers as moderators/referees) in 1974/1975 as a part of our class on government/international relations. It covered more than one class session. The scenario we played modeled a similar problem to the Korean War. Interactions focused on international relations, decision making, and negotiation. It had opposing parties, neutral parties, and an international body like the UN. There are a variety of possible outcomes -- it may not be as free form as you'd like, so it may not be the game for you, but it's structure should provide a good guide for depth. There were some outcomes that would make the war worse, and some that would resolve the war -- all of which relied on decisions made by the players. There were victory conditions for neutral parties who successfully convinced the opposing parties to either not fight, or to stop fighting. If you are not interested in things like "victory conditions," that's easy to remove. You can just focus on process and the uncertainty factor leading to different outcomes. Role playing was key. I don't have a copy of the game at hand, so I can't give more definition to you on "how many layers of information, or how deep information, should the players have?" It took very little time to pass out the packets and get to playing. Each team had 4-6 players. The main educational goals are to give a sense of the event and the political issues of the time, and to give a sense of political decision-making. Here, political decision making means making decisions under uncertainty (already provided by the other team) when the involved people have somewhat different personal goals and various opinions on the proper methods for reaching those goals. Dangerous Parallel does that very well. While it's a good model, it is a multi-party game: there are multiple major factions (6) not two. The materials will give you a sense of the depth necessary to get the gameplay to the detail that you desire, and to get playing quickly. (Sadly, I do not have experience in modding that game for fewer parties). A review at boardgame.geek.com is here. A: I've run a great number of political larps. For one-shots, you have to strike a very important balance: giving people enough leads where they never feel they're lost for something to do, and not overwhelming them with too much information. Given your examples were all very short - you could give way more than that. About half a page of total background reading material (not in a text wall and easy to reference) is usually what I've found that players can quickly and easily digest. You could go level three with two-three different issues at that level. I also recommend that adding in a "Complication" and absolutely a personal connection. Ex: Communists are winning the war in the East, after having defeated the army sent against them. All of the survivors have either joined the Communists, or been killed. However many of the turncoats only joined from fear, and may be willing to sell out their comrades. You know your brother survived, but you don't know where his loyalties lie, and getting in contact with him through the wrong channels (loyalist spies in the Communists, or Communist spies in your camp) could be risky, until you know more. If only there was another way... I also recommend making sure everybody has a sense of which faction they are in (so they know they have people they can work with). Factions should be largely coherent, though with everybody having a personal agenda which might conflict with the faction agenda. Essentially, from reading about a page (at most) of information, everybody should have a clear idea of What they want What they fear What they have to offer Who they can work with Some idea of who might be working against them Usually, one of these overlaps with something along the lines of "A secret that is worth protecting from the wrong people, but very valuable if shared with the right person."
[ "meta.stackexchange", "0000258480.txt" ]
Q: Should reputation be earned on questions that get closed? The current situation Let me start of with two a priori observations: Due to the way StackExchange is designed the easier a question is, the more reputation one will earn. This simply a consequence of the fact that more people will visit a simple question. Simple questions have often been asked before, so a lot of simple questions are actually duplicates. The combined consequence of this is that a lot of reputation is earned by quickly answering simple duplicate questions, here is a typical example: How to slice (in Python) "all but the last n" items when n may be zero? from 10 minutes ago at the time of writing with 3 upvotes on the answer whilst it got closed in 3 minutes. Beyond that people are also often answering questions that are clearly off topic, and yet earning reputation for it none the less. A not so typical example from 2 hours ago can be found here: Are new and delete still useful in C++14? with the answer scoring 9 upvotes. A more typical example is when a question is asking for a library, plugin or opinion, but couldn't find a link as my SE-search-fu skills aren't that great and I used to see this all the time when I was quick answering questions, but nowadays that's not my kinda thing anymore. Either way, the point I am getting to as you might have guessed based on the title is that it doesn't seem to make any sense to reward reputation for duplicate and closed answers. An even stronger case of this is when questions that are supposed to get closed are bountied and then users knowingly1 answer it despite everything as the bounty is so tempting (and no, flagging for it to get closed doesn't work half the time... I have been trying and I have pending flags from weeks ago). If the question could simply get closed after the bounty finishes this would take a lot of time pressure away from these kind of situations. The proposal So, my proposal would be as follows: Allow voting on anything just as it is now Do not count reputation for answers (including bounties) that are on a question that is currently closed If a question gets reopened then of course any upvotes and bounties get applied again. Advantages Users will be less likely to answer questions that are off topic If you don't have a reason anymore to answer the question for some quick rep, you will be all the more likely to flag or vote for the question to be closed (minor) And maybe users will be less motivated to ask such questions as well if they won't get answers Dangers Users might be motivated to vote for reopening a question just for the reputation. Possibly that would mean that voting for reopening should not be possible for people who already posted an upvoted answer, but that's up for debate, as those same users are the users that most likely understand the question best in other situations. 1 I actually discussed this with a couple of users on chat after we got into a discussion about it once. If you want to read the full story read all the edits, comments and chat in chronological order here, but mind you, it's a mess... (I tried to edit the question to make it on topic, as flagging it isn't quick enough most of the time and the bounty was so big, but the user really actually meant his original off topic version (my bad) so he accepted an answer that doesn't fit the edit, but he didn't revert the edit, so voting to close based upon the current version doesn't make sense) A: Too much collateral damage. Lots of questions asked and answered in good faith end up getting closed -- a non-obvious duplicate gets discovered later or a site's scope shifts. (Maybe there are other reasons too, but those are the two I've seen enough to matter.) The solution to people earning reputation from questions that shouldn't have been asked is to delete the questions within 60 days.
[ "stackoverflow", "0005769148.txt" ]
Q: scrollTop and doctype I'm looking for at solution to make document.body.scrollTop return the right values when using a doctype <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> now this only works with chrome and not in ff and ie alert('scrollTop = '+document.body.scrollTop); A: I think these are the two alternatives: var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
[ "math.stackexchange", "0001245513.txt" ]
Q: How can you find $P(\frac{X}{Y-X}<0)$ if $X\sim Geometric(p)$ and $Y\sim Bernoulli(p)$ Let the independent random variables $X\sim Geometric(p)$ and $Y\sim Bernoulli(p)$, I want to prove that $P(\dfrac{X}{Y-X}<0)=(p-1)^{2}(p+1)$. Do I need the joint probability mass function for this or should it be proven in some other way? Any help or hints will be appreciated A: Given that $Y$ is Bernoulli distributed, it will have probability mass function $P(Y=0)=(1-p)$ and $P(Y=1)=p$. As Frank has helpfully commented, we can condition on $Y$. When $Y=0$, we have $P(\frac{X}{Y-X}<0|Y=0)=P(-X<0|Y=0)=P(X>0|Y=0)$ When $Y=1$, we $P(\frac{X}{Y-X}<0|Y=1)=P(\frac{X}{1-X}<0|Y=1)=P(X>1|Y=1)$ Thus, we have the following (the third line being a consequence of the independence between $X$ and $Y$) $$\begin{align}P\left(\frac{X}{Y-X}<0\right)&=P\left(\frac{X}{Y-X}<0|Y=0\right)P(Y=0)+P\left(\frac{X}{Y-X}<0|Y=1\right)P(Y=1)\\&=P(X>0|Y=0)P(Y=0)+P(X>1|Y=1)P(Y=1)\\&=P(X>0)P(Y=0)+P(X>1)P(Y=1)\\&=\left(\sum_{k=1}^{\infty}p(1-p)^k\right)(1-p)+\left(\sum_{k=2}^{\infty}p(1-p)^k\right)(p)\\&=(1-p)^2+p(1-p)^2\\&=(p-1)^2(1+p)\end{align}$$
[ "electronics.stackexchange", "0000430559.txt" ]
Q: Does SysTick_Handler() have to be in main file? Does the CMSIS SysTick_Handler() have to be placed in the main file (i.e. same file where it is configured)? If not, how would I go about placing it elsewhere? Is it just a matter of defining the function in another .cpp file, and including "LPC17xx.h"? A: You can put it anywhere, as long as it has the right linkage spec the linker will take care of it for you. You don't need any header included, just extern "C" void SysTick_Handler(){ ... } in an implementation file.
[ "stackoverflow", "0060938171.txt" ]
Q: C# - how to decompress an ISO-8859-1 string I have C# program that received zipped bitstream received in iso-8859-1 character set. I need to get the string that was compressed. It should be equivalent to the this python code: zlib.decompress(bytes(bytearray(json_string, 'iso8859')), 15+32). I tried this code for decompress: Encoding iso_8859_1 = Encoding.GetEncoding("iso-8859-1"); byte[] isoBytes = iso_8859_1.GetBytes(inputString); // then do GZip extract MemoryStream objMemStream = new MemoryStream(); objMemStream.Write(isoBytes, 0, isoBytes.Length); objMemStream.Seek(0, SeekOrigin.Begin); GZipStream objDecompress = new GZipStream(objMemStream, CompressionMode.Decompress); But, objDecompress.Read failed, so I did something wrong. ***** Edit 31/03 The Java code which do the compression is: ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream gzip = new GZIPOutputStream(out); gzip.write(JsonStr.getBytes()); gzip.close(); return out.toString("ISO-8859-1"); I need a C# code to get the JsonStr. Would like to get some help. A: There are build in DeflateStream GZipStream classes, but I couldn't manage to reverse this probably because ZLibNative has default constants like public const int Deflate_DefaultWindowBits = -15. There are discussions on this subject like in this DotNet runtime issue "System.IO.Compression to support zlib thin wrapper over DEFLATE?" There is zlib.net NuGet package which you can use to decompress the data. You can read of a simple compress/decompress implementation here Compression and decompression problem with zlib.Net. Python compress import zlib import binascii json_string = '{"aaaaaaaaaa": 1111111111, "bbbbbbbbbbb": "cccccccccccc"}' compressed_data = zlib.compress(bytes(bytearray(json_string, 'iso8859')), 2) decompressed_data = zlib.decompress(compressed_data, 15+32) print('Compressed HEX data: %s' % (binascii.hexlify(compressed_data))) print('Decompressed data: %s' % (decompressed_data)) Will output: Compressed HEX data: b'785eab564a8403252b054338d051504a4200a09452321250aa0500e4681153' Decompressed data: b'{"aaaaaaaaaa": 1111111111, "bbbbbbbbbbb": "cccccccccccc"}' C# decompress static void Main(string[] args) { var extCompressedHex = "785eab564a8403252b054338d051504a4200a09452321250aa0500e4681153"; var extCompressed = HexStringToByteArray(extCompressedHex); byte[] extDecompressedData; DecompressData(extCompressed, out extDecompressedData); string extDecompressedJson = Encoding.GetEncoding("ISO-8859-1").GetString(extDecompressedData); Console.WriteLine("Hex ext compressed: {0}", ByteArrayToHex(extCompressed.ToArray())); Console.WriteLine("Raw ext decompressed: {0}", extDecompressedJson); } void DecompressData(byte[] inData, out byte[] outData) { using (MemoryStream outMemoryStream = new MemoryStream()) using (ZOutputStream outZStream = new ZOutputStream(outMemoryStream)) using (Stream inMemoryStream = new MemoryStream(inData)) { CopyStream(inMemoryStream, outZStream); outZStream.finish(); outData = outMemoryStream.ToArray(); } } // Helper functions ___________________________________________________ string ByteArrayToHex(byte[] bytes) { StringBuilder sw = new StringBuilder(); foreach (byte b in bytes) { sw.AppendFormat("{0:x2}", b); } return sw.ToString(); } void CopyStream(System.IO.Stream input, System.IO.Stream output) { byte[] buffer = new byte[2000]; int len; while ((len = input.Read(buffer, 0, 2000)) > 0) { output.Write(buffer, 0, len); } output.Flush(); } byte[] HexStringToByteArray(string hex) { return Enumerable.Range(0, hex.Length) .Where(x => x % 2 == 0) .Select(x => Convert.ToByte(hex.Substring(x, 2), 16)) .ToArray(); } Will output: Hex ext compressed: 785eab564a8403252b054338d051504a4200a09452321250aa0500e4681153 Raw ext decompressed: {"aaaaaaaaaa": 1111111111, "bbbbbbbbbbb": "cccccccccccc"} You can check it working in this .NET Fiddle.
[ "stats.stackexchange", "0000338680.txt" ]
Q: Can LSTMs have weight dimensions bigger than (num_class,num_classes)? I am working on an LSTM but am confused about the weight dimensions. Since the output must be one hot (num_classes,1), is it wrong to say that the weights can only be of size (num_classes ,num_classes)? If weights have dimensions of (100, num_classes), the final layer ht would have a size of (100,1) rather than (num_classes,1). Am I reading this the wrong way? It seems that because the final layer has elementwise multiplication, it is not possible to do a final dot product to achieve an output vector size of (num_classes,1). How can I increase the number of parameters in my model without adding more layers? Thanks! A: It’s typical to have a layer projecting down to the number of classes if the previous layer is larger.
[ "superuser", "0000998705.txt" ]
Q: How can I click on an inactive Excel window and have Excel move to the cell I clicked on? Can I customize Excel so that when the Excel window is not active, and I click on a cell, Excel will move to that cell? Clicking on a cell activates the window, but Excel does not move to the cell. I must click a second time on the cell to cause Excel to move to the cell. This seems to be a special case of a more general behavior of Excel. Excel ignores mouse clicks on inactive windows. For example, clicking a ribbon button does nothing (except the window becomes active). Other Windows applications have the opposite behavior. They do not ignore clicks on inactive windows. The click activates the window but also does whatever a click normally would do. Clicking in an inactive Notepad window in the main text buffer activates the window but also moves the cursor to the clickpoint, clicking a menu button activates the menu, and so on. I have looked through the choices available under File ... Options, and tried several Google searches for the answer. I did not find any relevant information. A: You probably can't change Excel, but you can change the behavior of window to move the focus always to the window the mouse is over (control panel, 'ease of use'). That way, when you move your mouse over an (previously inactive) Excel window, it becomes active by itself, and your click will then be recognized and acted upon. Note that such a change affects all your windows in all programs. Some people find it very useful, but some hate it.
[ "stackoverflow", "0059296834.txt" ]
Q: How to understand the rules of partial ordering about T& and T const& template <typename T> void show(T&); // #1 template <typename T> void show(T const&); // #2 int main() { int a = 0; show(a); // #1 to be called } I'm confused about these partial ordering rules. Here are some quotes: [temp.deduct.partial]/5 Before the partial ordering is done, certain transformations are performed on the types used for partial ordering: If P is a reference type, P is replaced by the type referred to. If A is a reference type, A is replaced by the type referred to. [temp.deduct.partial]/6 If both P and A were reference types (before being replaced with the type referred to above), determine which of the two types (if any) is more cv-qualified than the other; otherwise the types are considered to be equally cv-qualified for partial ordering purposes. The result of this determination will be used below. [temp.deduct.partial]/7 Remove any top-level cv-qualifiers: If P is a cv-qualified type, P is replaced by the cv-unqualified version of P. If A is a cv-qualified type, A is replaced by the cv-unqualified version of A. Firstly, both void show(T&) and void show(T const&) could be called by passing an int lvalue, so we need to use partial order rules to decide which function is more matched. Then, according to the above quotes, we do some transformations. Step 1: T& => T #3 T const& => T const #4 Step 2: T => T #5 T const => T #6 #5 => #6, #6 => #5, deduction succeeds in both directions. Then the following rules work: [temp.deduct.partial]/9 If, for a given type, deduction succeeds in both directions (i.e., the types are identical after the transformations above) and both P and A were reference types (before being replaced with the type referred to above): if the type from the argument template was an lvalue reference and the type from the parameter template was not, the parameter type is not considered to be at least as specialized as the argument type; otherwise, if the type from the argument template is more cv-qualified than the type from the parameter template (as described above), the parameter type is not considered to be at least as specialized as the argument type. So #4 is more specialized then #3. For a given value a, #2 function should be called, but actually #1 function is called. Why? Is there something wrong with my understanding? A: In this case, the "more specialized" rule is not used, which is a tiebreaker in case ranking implicit conversion sequences does not determine the order of the functions: [over.match.best]/1 Define ICSi(F) as follows: [...] Given these definitions, a viable function F1 is defined to be a better function than another viable function F2 if for all arguments i, ICSi(F1) is not a worse conversion sequence than ICSi(F2), and then (1.3) for some argument j, ICSj(F1) is a better conversion sequence than ICSj(F2), or, if not that, [...] (1.7) F1 and F2 are function template specializations, and the function template for F1 is more specialized than the template for F2 according to the partial ordering rules described in [temp.func.order], or, if not that, [...] In this case, ranking implicit conversion sequences alone is enough to determine the ordering, so everything following the "or, if not that" is ignored. Deduction results in (int&) for #1 and (int const&) for #2, so in both cases, reference binding (a to int& and a to int const&) results in the Identity Conversion, regardless of the cv-qualification: [over.ics.ref]/1 When a parameter of reference type binds directly to an argument expression, the implicit conversion sequence is the identity conversion, unless the argument expression has a type that is a derived class of the parameter type, in which case the implicit conversion sequence is a derived-to-base Conversion ([over.best.ics]). [...] However, ICS1(#1) is a better conversion sequence than ICS1(#2) because of [over.ics.rank]/3: Two implicit conversion sequences of the same form are indistinguishable conversion sequences unless one of the following rules applies: [...] (3.2) Standard conversion sequence S1 is a better conversion sequence than standard conversion sequence S2 if [...] (3.2.6) S1 and S2 are reference bindings ([dcl.init.ref]), and the types to which the references refer are the same type except for top-level cv-qualifiers, and the type to which the reference initialized by S2 refers is more cv-qualified than the type to which the reference initialized by S1 refers. [...] Therefore, ICS1(F1) is a better conversion sequence than ICS1(F2), thus F1 is better than F2 according to [over.match.best]/(1.3) (above). The [over.match.best]/(1.7) rule is not used. The "more specialized" rule is used in the reverse situation: int const a = 0; show(a); // #2 should be called for a const lvalue This time, deduction results in int const& and int const&, so [over.match.best]/(1.7) kicks in. The result, as you observed, is that #2 is a better function than #1. (Emphasis mine, for all quotes)
[ "stackoverflow", "0008733366.txt" ]
Q: Setting MS C# compiler options via environmental variables? Is there any way to set default options passed to csc.exe? In particular, I'm interested in supressing copyright messages. For example, for cl.exe and ml.exe I have CL = /nologo ML = /nologo A: rewrite csc.rsp Added /nologo csc.rsp location is same folder of csc.exe E.g. C:\Windows\Microsoft.NET\Framework64\v4.0.30319
[ "stackoverflow", "0020299390.txt" ]
Q: Error - "UNION operator must have an equal number of expressions" when using CTE for recursive selection At this moment I have a table tblLocation with columns ID, Location, PartOfID. The table is recursively connected to itself: PartOfID -> ID My goal is to have a select output as followed: > France > Paris > AnyCity > Explanation: AnyCity is located in Paris, Paris is located in France. My solution that I found until now was this: ; with q as ( select ID,Location,PartOf_LOC_id from tblLocatie t where t.ID = 1 -- 1 represents an example union all select t.Location + '>' from tblLocation t inner join q parent on parent.ID = t.LOC_PartOf_ID ) select * from q Unfortunately I get the following error: All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists. If you have any idea how I could fix my output it would be great. A: The problem lays here: --This result set has 3 columns select LOC_id,LOC_locatie,LOC_deelVan_LOC_id from tblLocatie t where t.LOC_id = 1 -- 1 represents an example union all --This result set has 1 columns select t.LOC_locatie + '>' from tblLocatie t inner join q parent on parent.LOC_id = t.LOC_deelVan_LOC_id In order to use union or union all number of columns and their types should be identical cross all result sets. I guess you should just add the column LOC_deelVan_LOC_id to your second result set A: The second result set have only one column but it should have 3 columns for it to be contented to the first result set (columns must match when you use UNION) Try to add ID as first column and PartOf_LOC_id to your result set, so you can do the UNION. ; WITH q AS ( SELECT ID , Location , PartOf_LOC_id FROM tblLocation t WHERE t.ID = 1 -- 1 represents an example UNION ALL SELECT t.ID , parent.Location + '>' + t.Location , t.PartOf_LOC_id FROM tblLocation t INNER JOIN q parent ON parent.ID = t.LOC_PartOf_ID ) SELECT * FROM q A: Then number of columns must match between both parts of the union. In order to build the full path, you need to "aggregate" all values of the Location column. You still need to select the id and other columns inside the CTE in order to be able to join properly. You get "rid" of them by simply not selecting them in the outer select: with q as ( select ID, PartOf_LOC_id, Location, ' > ' + Location as path from tblLocation where ID = 1 union all select child.ID, child.PartOf_LOC_id, Location, parent.path + ' > ' + child.Location from tblLocation child join q parent on parent.ID = t.LOC_PartOf_ID ) select path from q;
[ "math.stackexchange", "0001448792.txt" ]
Q: Reference for Poisson geometry Is there any good reference for Poisson geometry/Poisson manifolds out there? I would like to give a deep look to the subject, but all I seem to be able to find are short chapters or interludes in text about symplectic geometry. Looking a bit around on the web, the only thing I found is this book. Has anybody read it? And if so, is it good or is there something better? For those left wondering: the book in the link above seems a good introduction. A more advanced text is given by the book Poisson Geometry, Deformation Quantisation and Group Representations (Cambridge University Press). A: Wiki give some references depending on which kind of book you are looking for https://en.wikipedia.org/wiki/Poisson_manifold or to have a look on scanned book : http://gen.lib.rus.ec/search.php?req=poisson+geometry&lg_topic=libgen&open=0&view=simple&phrase=1&column=def
[ "stackoverflow", "0061098036.txt" ]
Q: Alfresco Messages conventions I know Alfresco stores messages and i18n labels for the UI in ".properties" files, I would like to know what are the Alfresco conventions to write those files How it is better to write those key? It is correct to write form.form-id.title=myTitle or should I use another convention? Do you use another prefix like the namespace (myc.form.form-id.title=myTitle) Thanks to all A: Indeed, if you want to set labels in properties files for a custom form, you have to keep Alfresco standards. See comments in tomcat/shared/classes/alfresco/web-extension/share-config-custom.xml : If a type has been specified without a title element in the content model, or you need to support multiple languages, then an i18n file is needed on the Repo AMP/JAR extension side for the type to be visible when creating rules: custom_customModel.type.custom_mytype.title=My SubType Used by the "Change Type" action. For the type to have a localised label add relevant i18n string(s) in a Share AMP/JAR extension: type.custom_mytype=My SubType But if you define your own properties in custom Java code and spring beans, maybe could you keep choose the most comprehensive name for a user or admin sys which will have to configure your properties. To answer to your question, I don't know any standard for these new properties. Hope it helps
[ "stackoverflow", "0018602049.txt" ]
Q: Javascript - Omitting Return False I recently realized that when I use a function to loop over an array and return a match, I actually don't need the return false/null at the end. For example, if I have: *Edited example. Original example was from a function I tried to simplify but forgot to change the name/context of. Sorry for the confusion. Here is a better example fitting the title of my question: var hasKey = hasKeyMatch(key); function hasKeyMatch(key) { for (var i = 0; i < array.length) { if (array[i].key === key) { return true; } } }; I don't actually need a return false, as if there is no return of key, hasKey will be undefined. So I can still use hasKey as a boolean. But is this considered good style? I realize having a 'back-up' return is a necessity in languages like Java, and so some people bring the habit to JS. But I think minimizing unnecessary returns would be ideal, though I have no idea of the actual cost of returning. And I when I look at the answer to the below question, I am confused on why he chooses to return a variable that is already pushed to the desired array. I assume his return is intentional, and he isn't intended to store the returned variable anywhere. Are there benefits (like say garbage collection) of returning a variable at the end of a function? drawImage using toDataURL of an html5 canvas A: This is a matter of code solidity and you should always return false instead of undefined if the method name suggest that as a result. As everything which has to do with code style it is not a matter of right or wrong (http://www.youtube.com/watch?v=zN-GGeNPQEg) but it is important if you intent others to understand what you are doing and avoiding stupid bugs. Solid code avoids the possibility of doing stupid things by behaving as expected. For example: isA() && isB() || !isA() && !isB() can be written more shortly as isA() == isB(). If you had these two functions defined as one (isA) returning false and one (isB) returning undefined the second expression would not behave as one might suspect. See: http://jsfiddle.net/wDKPd/1/
[ "stackoverflow", "0055101052.txt" ]
Q: to list the operations that belong to a database in mysql - (SHOW PROCESSLIST) I would like to list the processes in Mysql. I have multiple databases for in my connection. When I say Show process list, the processes of all databases come. How do I view processes for a single database? A: This is a job for the information_schema. That's where SHOW PROCESSLIST gets its information. SELECT * FROM information_schema.processlist WHERE DB = DATABASE() Of course, the function DATABASE() returns the current database, as chosen by USE DATABASE or by your login default database. If for some reason that is not set, and you know the name of your database, try this. SELECT * FROM information_schema.processlist WHERE DB = 'my_database_name'
[ "stackoverflow", "0008500838.txt" ]
Q: jQuery: Slide Toggle || Any optimizations to the code? Hi Im new to programming jQuery and i have a quick code snippet that I would love someone to test for me. I think it works well.. but i dont know if its the best way to handle it. working example: http://jsfiddle.net/zWnLv/29/ //hide wrapper at document ready $('#newsbox_content_wrapper').hide(); //toggle visiblility of newsbox and slide down to scroll window to newsbox $('.newsbox_toggle').bind('click', function () { //define speed for effect var $speed = 400; //check to see if the class 'open' exists then run if ($('.newsbox_toggle').hasClass('open')) { //scroll to the top of the newsbox $('html, body').animate({scrollTop: $('#header_lower').offset().top}, $speed); $('#newsbox_content_wrapper').slideDown($speed); $('.newsbox_toggle').removeClass('open'); //delay HTML replacement to sync with animation $('.newsbox_expand').delay($speed).queue(function(n) { $(this).html('Click to Close News Feature.'); $(this).addClass('rotate'); n(); }); } else { //scroll back to top of body $('html, body').animate({ scrollTop: 0 }, $speed); $('#newsbox_content_wrapper').slideUp($speed); $('.newsbox_toggle').addClass('open'); //delay HTML replacement to sync with animation $('.newsbox_expand').delay($speed).queue(function(n) { $(this).html('Click to Read More.'); $(this).removeClass('rotate'); n(); }); } }); A: The only way you could "optimize" this is using callbacks instead of manually delaying functions. .slideUp() and .slideDown() accept callbacks to be executed after the animation finishes. Using chaining is a best practice, so you don't have to recreate objects (see the callback functions). Also, I've changed the bind() function with the new on(), which was added in jQuery 1.7. $('.newsbox_toggle').on('click', function () { //define speed for effect var $speed = 400; //check to see if the class 'open' exists then run if ($('.newsbox_toggle').hasClass('open')) { //scroll to the top of the newsbox $('html, body').animate({scrollTop: $('#header_lower').offset().top}, $speed); $('#newsbox_content_wrapper').slideDown($speed, function() { $('.newsbox_expand').html('Click to Close News Feature.').addClass('rotate'); }); $('.newsbox_toggle').removeClass('open'); } else { //scroll back to top of body $('html, body').animate({ scrollTop: 0 }, $speed); $('#newsbox_content_wrapper').slideUp($speed, function() { $('.newsbox_expand').html('Click to Read More.').removeClass('rotate'); }); $('.newsbox_toggle').addClass('open'); } }); If you're on jQuery < 1.7, use .click(), which is a shorthand for .bind(). $('.newsbox_toggle').click(function () { // ... });
[ "stackoverflow", "0028487984.txt" ]
Q: Find number of elements inside ng-repeat template, before I have any items in the array? We are using AngularJS, and I have a server generated template like this: <div ng-repeat='data in lazyContentFactory.items'> <my-element data="data[0]"></my-element> <my-element data="data[1]"></my-element> <my-element data="data[2]"></my-element> </div> Here, each item has a property data that is an array with dynamically set number of posts from the server. In this case I need to fetch 3 data-items from an API. This number may vary, depending on the settings on the server. How can I find the number of "my-element" elements while lazyContentFactory.items have length = 0, so I know how many data items I need to fetch? The elements are not rendered in the DOM, so it seems I can not fetch them with angular.element.find, nor register them via directive compile pre or post functions. Is this possible? Is my question clear enough? A: As I learned more about the way Angular executes code, I found a method you can call on modules called .run. These run-blocks will be executed after all your services has been created, but most importantly in my case, before the DOM has been altered by Angular, and thus all my initial elements are accessible. In the run-block I could therefore count all my elements that would be hidden by the ng-repeat directive, before they are hidden! NB: This is not optimal use of Angular, because I have to check the DOM for elements before Angular traverses the DOM. Maybe another framework could have been used, because we do need the flexibility on the back-end. angular.module('myModule',[]) .run(function (elementService, cacheService, myConstants) { var initialNrOfMyElements = elementService .getNrOfElementsInDomWithAttribute('my-element', 'some-attr'); cacheService.put( myConstants.initialNrOfMyElements, initialNrOfMyElements );
[ "stackoverflow", "0049341798.txt" ]
Q: Parse error at '=': usage might be invalid Matlab syntax Why can't I do this loop this way ? for i=1:N (Teta(2,i)-Teta(1,i))/dY=0; end I am getting this error : Parse error at '=': usage might be invalid Matlab syntax A: You cannot make calculations in the left side of the equals sign. Calculations can only be made in the right-hand side. For example, like this: for i=1:N Teta(2,i) = 0 * dY + Teta(1,i); end Without knowing anything about the application of you problem, I just moved everything but the Teta(2,i) from the left to the right. This will not give that error. But probably isn't the result you wish wither...
[ "stackoverflow", "0021154066.txt" ]
Q: Saving command into variable I've question about this variables.How can I store result of a command into a variable? For example: saving drive serial into location variable. thanks. E.g: @ECHO OFF SET location=vol ECHO We're working with %location% A: for /f "delims=" %%x in ('your command and parameters') do set "var=%%x" where the 'single quotes' are required around the command from which you wish to save output. Edit - now we know which command. Comment - one variable can contain up to ~8,000 characters. Here's a routine that will set the values in $1...$whatever and the entire set in $all with each field enclosed in angle-brackets. @ECHO OFF SETLOCAL SET "$all=" FOR /f "tokens=1*delims=:" %%a IN ( 'systeminfo 2^>nul^|findstr /n /r "$"' ) DO ( SET "$%%a=%%b" FOR /f "tokens=*" %%c IN ("%%b") DO CALL SET "$all=%%$all%%<%%c>" SET /a max=%%a ) SET $ pause FOR /l %%z IN (1,1,%max%) DO CALL ECHO %%$%%z%% GOTO :EOF
[ "stackoverflow", "0010264457.txt" ]
Q: Facebook Share only works if user is logged in? I'm hoping this isn't a duplicate, but I haven't seen this explained before. I've got a very basic Facebook Share implementation that I'm trying to use: <a name="fb_share" type="button" share_url="http://www.google.com"></a> <script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"> </script> The problem is: the FIRST time I click my "share" button, it prompts me to login to facebook. When I login in, it takes me straight to my news feed and does not show the link I'm trying to share. But if I login, close the window and then re-click my "share" button, it shows the link I'm trying to share. Is there something I'm missing from my code? I'm using IE9 if that makes a difference. EDIT: It appears to work fine in Chrome, but does NOT work in Safari either. EDIT 2: After trying to use Juicy Scripter's solution with the Feed Dialog, I am now having trouble with the following code. After I'm prompted to Login to Facebook, I get a red error message that just says "An error has occurred, please try again later." Can anyone see what I might be doing wrong with the following code? Also, is there a "best practice" in getting my link to be the actual Facebook button (like it was for the Share option?) <a onclick='postToFacebook(); return false;'>FB post</a> <script type="text/javascript"> function postToFacebook() { FB.init(); FB.ui({ method: 'feed', link: "http://www.google.com" }); } </script>` Many thanks in advance! A: As already noted by other answer Share Button is deprecated so it's better to avoid it. Use Feed Dialog to publish content on user's feed. For general purposes next code may be used to share current page link (consult documentation for additional parameters): FB.ui({method: 'feed', link: document.location.href});
[ "stackoverflow", "0014278488.txt" ]
Q: Amount of memory used by each thread I am developing an app that is crashing due to an excess of memory usage. I would like to know the amount of memory that is being used by each active thread so that I can decide which allocated or drawn in screen elements release or remove from view. Is there a way to obtain it? I have tried using mach.h library but with mach_task_self() I can only access the memory used by the whole application. Thanks in advance A: I think what you want is logMemUsage(). You can check the Answer from this Question : Watching memory usage in iOS I think you can get something from this Documentation also : Understanding and Analyzing iOS Application Crash Reports If you want to check Memory Usage While Application is Running then use Instruments. : Using Instruments you can check how much memory your app is using. In Xcode4, use 'Profile' build, choose Leaks, then click the Library button in the toolbar and add the Memory Monitor instrument. If you really don't want to use Instruments then you can use Custom Class UIDeviceAdditions : Get current Memory usage Hope it's Enough. A: You can't because threads share the heap. Threads are created with a 512KB stack space, with memory pages allocated as needed. Other than that, there is no memory per thread value stored anywhere.
[ "stackoverflow", "0029090583.txt" ]
Q: JavaFX TableView how to get cell's data? I'm using that method to get whole object. tableView.getSelectionModel().getSelectedItem() How can I get data from single cell? I mean like get S20BJ9DZ300266 as String? A: Assuming you know something is selected, you can do TablePosition pos = table.getSelectionModel().getSelectedCells().get(0); int row = pos.getRow(); // Item here is the table view type: Item item = table.getItems().get(row); TableColumn col = pos.getTableColumn(); // this gives the value in the selected cell: String data = (String) col.getCellObservableValue(item).getValue();
[ "stackoverflow", "0003801865.txt" ]
Q: Why is there one of my select options that put nothing in the query string at form submission? This is my HTML: <select name="results"> <option value="0">Vis alle</option> <option value="10">10 resultater per side</option> <option value="20">20 resultater per side</option> <option value="30">30 resultater per side</option> <option value="40">40 resultater per side</option> <option value="50">50 resultater per side</option> <option value="75">75 resultater per side</option> <option value="100">100 resultater per side</option> </select> When the topmost option is selected and form submitted, the get variable "results" disappears from the URL. I've tried switching out the 0 with strings "*" and "x" to no avail. A: A value of zero will get interpreted as "nothing" and therefore disappear from your $_GET. But that should be no problem in your case. You could also just test of the "results" is in the array to check if someone wants to see all. Or you change the zero to the string "all" and test for that. if (!isset($_GET['results']) { //logic for building your query without a LIMIT }
[ "stackoverflow", "0029330200.txt" ]
Q: How do I auto populate jRadioButtons with information? I have been having an issue and I dont know how to solve it. In my code below you can see that I am trying to create a GUI that auto populates 20 jRadioButtons with the information provided, but when I run the program there are no buttons visible. Can someone please point me to what I am doing incorrectly? package person; import java.util.ArrayList; import java.util.List; import javax.swing.*; public class PersonInfoUI extends javax.swing.JFrame { public PersonInfoUI() { initComponents(); ButtonGroup buttonGroup1 = new ButtonGroup(); JRadioButton jRadioButton1 = new JRadioButton(); personSelectorUI.add(jRadioButton1); personSelectorUI.revalidate(); personSelectorUI.repaint(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { personSelectorUI = new javax.swing.JPanel(); exitButton = new javax.swing.JButton(); clearButton = new javax.swing.JButton(); personInfoOutput = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); exitButton.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N exitButton.setText("Exit"); exitButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exitButtonActionPerformed(evt); } }); clearButton.setFont(new java.awt.Font("Times New Roman", 1, 18)); // NOI18N clearButton.setText("Clear"); clearButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { clearButtonActionPerformed(evt); } }); javax.swing.GroupLayout personSelectorUILayout = new javax.swing.GroupLayout(personSelectorUI); personSelectorUI.setLayout(personSelectorUILayout); personSelectorUILayout.setHorizontalGroup( personSelectorUILayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEA DING) .addGroup(personSelectorUILayout.createSequentialGroup() .addContainerGap() .addGroup(personSelectorUILayout.createParallelGroup(javax.swing.GroupLayout.Ali gnment.LEADING) .addComponent(personInfoOutput, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, personSelectorUILayout.createSequentialGroup() .addComponent(exitButton, javax.swing.GroupLayout.DEFAULT_SIZE, 344, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(clearButton, javax.swing.GroupLayout.PREFERRED_SIZE, 349, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); personSelectorUILayout.setVerticalGroup( personSelectorUILayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEA DING) .addGroup(personSelectorUILayout.createSequentialGroup() .addGap(151, 151, 151) .addComponent(personInfoOutput, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(personSelectorUILayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(exitButton, javax.swing.GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE) .addComponent(clearButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(personSelectorUI, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(personSelectorUI, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); pack(); }// </editor-fold> private void clearButtonActionPerformed(java.awt.event.ActionEvent evt) { personInfoOutput.setText(""); } private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) { System.exit(0); } public static void main(String args[]) { ButtonGroup buttonGroup1 = new ButtonGroup(); List<Person> people = new ArrayList<>(); people.add(new Person ("Nate Stoll", true, true, 1981)); people.add(new Person ("Ashley Stoll", true, true, 1985)); people.add(new Person ("Brooke Jackson", true, true, 1972)); people.add(new Person ("Reed Stoll", true, true, 1983)); people.add(new Person ("Reeda Stoll", true, true, 1942)); people.add(new Person ("John Stoll", true, true, 1940)); people.add(new Person ("Clark Kent", true, true, 1912)); people.add(new Person ("Reed Richards", true, true, 1992)); people.add(new Person ("Peter Parker", true, true, 1924)); people.add(new Person ("Charles Xavier", true, true, 1905)); people.add(new Person ("Bruce Banner", true, true, 1980)); people.add(new Person ("Cheri Monaghan", true, true, 1979)); people.add(new Person ("Matthew Groathouse", true, true, 1949)); people.add(new Person ("John Williams", true, true, 1958)); people.add(new Person ("Jake Holmes", true, true, 1998)); people.add(new Person ("Bradley Cooper", true, true, 2015)); people.add(new Person ("Shirley Temple", true, true, 1907)); people.add(new Person ("Natalie Stoll", true, true, 1900)); people.add(new Person ("Lindsay Gonzalez", true, true, 1970)); people.add(new Person ("Tommy Chong", true, true, 1957)); for(Person aPers : people){ final JRadioButton jRadioButton1 = new JRadioButton(aPers.getName()); jRadioButton1.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent evt) { if (jRadioButton1.isSelected()){ personInfoOutput.setText(jRadioButton1.getText()); } } }); buttonGroup1.add(jRadioButton1); } new PersonInfoUI().setVisible(true); java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { new PersonInfoUI().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton clearButton; private javax.swing.JButton exitButton; private static javax.swing.JTextField personInfoOutput; private static javax.swing.JPanel personSelectorUI; // End of variables declaration } Thanks! A: You never add your newly created JRadioButton to any container whose ancestor hierarchy leads to a top level window. In other words, for your JRadioButtons to be displayed in the GUI, the need to be added to something, usually a JPanel, and that JPanel has to be displayed on your GUI -- you're not doing this. Myself, I'd create a JPanel that uses a GridLayout, perhaps one with 1 column and variable rows, I'd add my JRadioButtons to this, I'd add the JPanel to a JScrollPane and I'd add the JScrollPane somewhere to my GUI. I recommend avoiding use of GroupLayout and NetBeans drag-and-drop GUI creation for creating something like this, since GroupLayout doesn't like your adding new components at run-time. I'm also not sure why you're trying to add your JRadioButtons in the static main method, which adds its own unnecessary complexity. If you're hard-coding the Strings, why not do this in a constructor? To understand how to do this, you'll need to read the tutorials on use of JPanels and layout managers. You can find links to the Swing tutorials and to other Swing resources here: Swing Info. As an aside -- it looks like what you really want to use is a JTable, one that has names in a column and that has a checkbox in a column.
[ "stackoverflow", "0042480171.txt" ]
Q: Use value in another method I am trying to use value in another method, for example in the code below I have this value userPostedFile.FileName: public partial class _WebForm1 : System.Web.UI.Page { public void Button1_Click(object sender, EventArgs e) { string filepath = Server.MapPath("\\Upload"); HttpFileCollection uploadedFiles = Request.Files; Span1.Text = string.Empty; for (int i = 0; i < uploadedFiles.Count; i++) { HttpPostedFile userPostedFile = uploadedFiles[i]; if (userPostedFile.ContentLength > 0) { userPostedFile.SaveAs(filepath + "\\" + Path.GetFileName(userPostedFile.FileName)); Span1.Text += "Location where saved: " + filepath + "\\" + Path.GetFileName(userPostedFile.FileName) + "<p>"; }}} and I want to use it in the code below, but I am getting an error which is: the name doesn't exist in the current context: private int get_pageCcount(string file) { using (StreamReader sr = new StreamReader(Server.MapPath(userPostedFile.FileName))) { Regex regex = new Regex(@"/Type\s*/Page[^s]"); MatchCollection matches = regex.Matches(sr.ReadToEnd()); return matches.Count; }}} A: the name doesn't exist in the current context: A context or scope is defined within the curly brackets: { and }. This is where the variable "lives" and can be found. userPostedFile is declared as a local variable in the scope of the for-loop. It will neither be accessible outside of the loop, nor outside of the method! For more information please read Scopes C# Inside the loop the assignment of this variable changes in each iteration: HttpPostedFile userPostedFile = uploadedFiles[i]; So even if you would declare the variable userPostedFile on class level, which would make it accessible in the get_pageCcount method, it would be unclear which instance you would use in the line: using (StreamReader sr = new StreamReader(Server.MapPath(userPostedFile.FileName))) Lets say you would declare the variable in the scope of the class like you have done with filepath and uploadedFiles public partial class _WebForm1 : System.Web.UI.Page { HttpPostedFile userPostedFile; string filepath = Server.MapPath("\\Upload"); HttpFileCollection uploadedFiles = Request.Files; Span1.Text = string.Empty; public void Button1_Click(object sender, EventArgs e) { for (int i = 0; i < uploadedFiles.Count; i++) { userPostedFile = uploadedFiles[i]; The variable userPostedFile will now be accessible in the get_pageCcount method. But it depends now strongly on when you call the method. If you call it before the button click. You will get a NullReferenceException because userPostedFile has not been given any value yet. If you call it after the button click you will get the last value of uploadedFiles because it will have the value that was assigned at the end of the loop.
[ "stackoverflow", "0036866837.txt" ]
Q: Request Mapping with a dot (.) in last path I have following request mapping. @RequestMapping(value = "/{userId}", produces = { MediaTypes.HAL_JSON_VALUE }) @ResponseStatus(HttpStatus.OK) public Resource<UserDTO> findUser(@PathVariable final String userId) { User user = administrationService.getSecurityUserById(userId); return userResourceAssembler.toResource(modelMapper.map(user, UserDTO.class)); } I use RestTemplate to get the resource. The user ids passed in the url contain a dot (.) like: john.doe -> request URL: http://mysite/users/john.doe When the above method gets called I only get john in @PathVariable userId. How can this be fixed? to get john.doe Thx. A: anything that goes after a dot in RequestMapping is considered an extension and therefore ignored, if you want to be able to read along with the dot and the rest of the string I recommend using a regex in your Request mapping such as: /{userId:.+} more detailed explanation can be found here: Spring MVC @PathVariable with dot (.) is getting truncated
[ "stackoverflow", "0042100534.txt" ]
Q: Gradient descent function with output plot and regression line I've been running the following code which returns the correct coefficients. However, no matter where I put a plot call, I can't get any plot output. I'm not sure if a reproducible example is needed here, as I think this can be solved by looking at my gradientDescent function below? It's my first attempt at running this algorithm in R: gradientDescent <- function(x, y, learn_rate, conv_threshold, n, max_iter) { m <- runif(1, 0, 1) c <- runif(1, 0, 1) yhat <- m * x + c cost_error <- (1 / (n + 2)) * sum((y - yhat) ^ 2) converged = F iterations = 0 while(converged == F) { m_new <- m - learn_rate * ((1 / n) * (sum((yhat - y) * x))) c_new <- c - learn_rate * ((1 / n) * (sum(yhat - y))) m <- m_new c <- c_new yhat <- m * x + c cost_error_new <- (1 / (n + 2)) * sum((y - yhat) ^ 2) if(cost_error - cost_error_new <= conv_threshold) { converged = T } iterations = iterations + 1 if(iterations > max_iter) { converged = T return(paste("Optimal intercept:", c, "Optimal slope:", m)) } } } A: It's unclear what you have been doing that was ineffective. The base graphics functions plot and abline should be able to produce output even when used inside functions. Lattice and ggplot2 graphics are based on grid-grpahics and would therefore need a print() wrapped around the function calls to create output (as described in the R-FAQ). So try this: gradientDescent <- function(x, y, learn_rate, conv_threshold, n, max_iter) { ## plot.new() perhaps not needed plot(x,y) m <- runif(1, 0, 1) c <- runif(1, 0, 1) yhat <- m * x + c cost_error <- (1 / (n + 2)) * sum((y - yhat) ^ 2) converged = F iterations = 0 while(converged == F) { m_new <- m - learn_rate * ((1 / n) * (sum((yhat - y) * x))) c_new <- c - learn_rate * ((1 / n) * (sum(yhat - y))) m <- m_new c <- c_new yhat <- m * x + c cost_error_new <- (1 / (n + 2)) * sum((y - yhat) ^ 2) if(cost_error - cost_error_new <= conv_threshold) { converged = T } iterations = iterations + 1 if(iterations > max_iter) { abline( c, m) #calculated dev.off() converged = T return(paste("Optimal intercept:", c, "Optimal slope:", m)) } } }
[ "stackoverflow", "0043598736.txt" ]
Q: Julia's speed advantage over R I have been using R for my research in corporate finance and asset pricing, and really like it due to my background in Math and Statistics. Until now, I encountered 2 main constrains in R. The first one is handling big data files, but I have kind of circumvented it by combining R with PostgreSQL and Spark, and I believe I can get more RAM from high performance computer or AWS cloud in the future. The second constrain is executing speed (important for handling tick by tick security quote data), and I was recommended that Julia has huge speed advantage over R. My question is that since Rcpp offers a really fast execution, does the speed advantage of Julia still hold? I am considering if I should learn Julia. In addition, R provides a perfect database connection with WRDS, Quandl, TrueFX, and TAQ, and I am really used to Hadley Wickham style data cleaning. As a academic guy, I kind of like the fact that R has support from peer review journals like Journal of Stat Software. I will try Julia and see how it works. Thanks for all the answers and comments! A: Rcpp and Julia will get you to the same place in the end performance-wise. In fact, type-stable Julia will compile to the essentially the same LLVM IR as clang compiled C++. Design-wise there's nothing that stops it from being the same (in the type-stable case), other than a few missing optimizations because the language is young (example, @fastmath doesn't add FMA by default, so you'd have to add FMA calls yourself, whereas I believe C++ compiled with fastmath will FMA). But you can play around check that @code_llvm and @code_native outputs the same code, given type-stability. However, Rcpp would require that you write a bunch of C++ code and test/maintain that code along with your R code. C/C++ is much lower level and can be more difficult to maintain (the "two language problem"). If you choose to go with Julia, you can write it all in Julia. That's the main difference. (As for the whole "Julia is 2x slower than C", should probably be mentioned here. Normally it's due to having small parts of type-unstable code, not turning off array bounds checking with @inbounds (the language comparison from the comments notably doesn't do this, which can cause a pretty large difference in a tight loop), and relying on vectorization styles (a la R/MATLAB/Python). The last part is much better in Julia v0.6, but it will always have a small cost over looping. In the end, it's opt-in/opt-out choices for concise code and additional safety checks that causes the difference.)
[ "stackoverflow", "0002506230.txt" ]
Q: Drupal: installing it in a subfolder this is a question about drupal installation on server. I usually upload my drupal into a subfolder "drupal" and I ask my customers to check the website in such subfolders until when it is ready. Then I asl to change the default folder in Apache to the "drupal" one. Sometimes my customer cannot change Apache configuration, so I was wondering if I can use a php script to forward users from root folder to the drupal one, or I should move the website to the root folder (which I would prefer to avoid, because is time consuming). thanks A: See Taking your site live
[ "stackoverflow", "0050096121.txt" ]
Q: Vue pwa with firebase cloud messaging not working properly im trying the following code: navigator.serviceWorker.register('service-worker.js') .then((registration) => { const messaging = firebase.messaging().useServiceworker(registration) console.log(messaging) messaging.requestPermission().then(function () { console.log('Notification permission granted.') messaging.getToken().then(function (currentToken) { if (currentToken) { console.log(currentToken) } }) }) }) my manifest: { "name": "Herot-Eyes", "short_name": "herot-eyes", "gcm_sender_id": "103953800507", "icons": [ { "src": "/static/img/icons/herot-eyes-192x192.png", "sizes": "192x192", "type": "image/png" }, { "src": "/static/img/icons/herot-eyes-512x512.png", "sizes": "512x512", "type": "image/png" }, { "src": "/static/img/icons/apple-touch-icon-180x180.png", "sizes": "180x180", "type": "image/png" } ], "start_url": "/", "display": "fullscreen", "orientation": "portrait", "background_color": "#000000", "theme_color": "#2196f3" } what is going wrong? my console.log(messaging) is returning a factory error, the following: bad-push-set : "The FCM push set used for storage / lookup was not not a valid push set string." bad-scope "The service worker scope must be a string with at least one character." bad-sender-id "Please ensure that 'messagingSenderId' is set correctly in the options passed into firebase.initializeApp()." bad-subscription "The subscription must be a valid PushSubscription." bad-token : "The FCM Token used for storage / lookup was not a valid token string." bad-vapid-key "The public VAPID key is not a Uint8Array with 65 bytes." bg-handler-function-expected "The input to setBackgroundMessageHandler() must be a function." delete-scope-not-found "The deletion attempt for service worker scope could not be performed as the scope was not found." delete-token-not-found "The deletion attempt for token could not be performed as the token was not found." failed-delete-vapid-key "The VAPID key could not be deleted." failed-serviceworker-registration "We are unable to register the default service worker. {$browserErrorMessage}" failed-to-delete-token "Unable to delete the currently saved token." get-subscription-failed "There was an error when trying to get any existing Push Subscriptions." incorrect-gcm-sender-id "Please change your web app manifest's 'gcm_sender_id' value to '103953800507' to use Firebase messaging." invalid-delete-token "You must pass a valid token into deleteToken(), i.e. the token from getToken()." invalid-public-vapid-key "The public VAPID key must be a string." invalid-saved-token "Unable to access details of the saved token." no-fcm-token-for-resubscribe "Could not find an FCM token and as a result, unable to resubscribe. Will have to resubscribe the user on next visit." no-sw-in-reg "Even though the service worker registration was successful, there was a problem accessing the service worker itself." no-window-client-to-msg "An attempt was made to message a non-existant window client." notifications-blocked "Notifications have been blocked." only-available-in-sw "This method is available in a service worker context." only-available-in-window "This method is available in a Window context." permission-blocked "The required permissions were not granted and blocked instead." permission-default "The required permissions were not granted and dismissed instead." public-vapid-key-decryption-failed "The public VAPID key did not equal 65 bytes when decrypted." should-be-overriden "This method should be overriden by extended classes." sw-reg-redundant "The service worker being used for push was made redundant." sw-registration-expected "A service worker registration was the expected input." token-subscribe-failed "A problem occured while subscribing the user to FCM: {$message}" token-subscribe-no-push-set "FCM returned an invalid response when getting an FCM token." token-subscribe-no-token "FCM returned no token when subscribing the user to push." token-unsubscribe-failed "A problem occured while unsubscribing the user from FCM: {$message}" token-update-failed "A problem occured while updating the user from FCM: {$message}" token-update-no-token "FCM returned no token when updating the user to push." unable-to-resubscribe "There was an error while re-subscribing the FCM token for push messaging. Will have to resubscribe the user on next visit. {$message}" unsupported-browser "This browser doesn't support the API's required to use the firebase SDK." use-sw-before-get-token "You must call useServiceWorker() before calling getToken() to ensure your service worker is used." A: Configure to server to receive notifications Add the following files to the public folder: manifest.json { "gcm_sender_id": "103953800507" } firebase-messaging-sw.js importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js'); var config = { messagingSenderId: <Sender ID> }; firebase.initializeApp(config); let messaging = firebase.messaging(); In your main.js file add the following code var config = { apiKey: <API_KEY>, authDomain: <DOMAIN>, databaseURL: <DATABASE_URL>, projectId: <PROJECT_ID>, storageBucket: <STORAGE_BUCKET>, messagingSenderId: <SENDER_ID> }; firebase.initializeApp(config); Vue.prototype.$messaging = firebase.messaging() navigator.serviceWorker.register('/firebase-messaging-sw.js') .then((registration) => { Vue.prototype.$messaging.useServiceWorker(registration) }).catch(err => { console.log(err) }) Receive notifications Then in your App.vue, add this code to the created() function created() { var config = { apiKey: <API_KEY>, authDomain: <DOMAIN>, databaseURL: <DATABASE_URL>, projectId: <PROJECT_ID>, storageBucket: <STORAGE_BUCKET>, messagingSenderId: <SENDER_ID> }; firebase.initializeApp(config); const messaging = firebase.messaging(); messaging .requestPermission() .then(() => firebase.messaging().getToken()) .then((token) => { console.log(token) // Receiver Token to use in the notification }) .catch(function(err) { console.log("Unable to get permission to notify.", err); }); messaging.onMessage(function(payload) { console.log("Message received. ", payload); // ... }); } Send notification UPDATE const admin = require("firebase-admin") var serviceAccount = require("./certificate.json"); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), }); const Messaging = admin.messaging() var payload = { webpush: { notification: { title: "Notification title", body: "Notification info", icon: 'http://i.imgur.com/image.png', click_action: "http://yoursite.com/redirectPage" }, }, topic: "Doente_" + patient.Username }; return Messaging.send(payload) Older version Then, in postman you do the following request POST /v1/projects/interact-f1032/messages:send HTTP/1.1 Host: fcm.googleapis.com Authorization: Bearer <SENDER_TOKEN> Content-Type: application/json { "message":{ "token" : The token that was in the console log, "notification" : { "body" : "This is an FCM notification message!", "title" : "FCM Message" } } } Sender Token In your backend, use the following code, where the file "certificate.json" was got in the firebase dashboard (https://firebase.google.com/docs/cloud-messaging/js/client - Generate pair of keys) const {google} = require('googleapis'); function getAccessToken() { return new Promise(function(resolve, reject) { var key = require('./certificate.json'); var jwtClient = new google.auth.JWT( key.client_email, null, key.private_key, ["https://www.googleapis.com/auth/firebase", "https://www.googleapis.com/auth/cloud-platform"], null ); jwtClient.authorize(function(err, tokens) { if (err) { reject(err); return; } resolve(tokens.access_token); }); }); } getAccessToken().then(senderToken => console.log(senderToken)) The senderToken is used on the Authorization header to send a notification
[ "academia.stackexchange", "0000019295.txt" ]
Q: Should I answer students' questions immediately or teach them to ask better questions? I'm teaching an online lab (to accompany an in-person course) to undergrads in their 3rd or 4th year of an engineering curriculum this semester. The aim of the lab is not to teach them any particular technical skills. It's only meant to supplement the content of the course by exposing them to some more advanced concepts in a hands-on way. The lab itself is the means, not the goal. So beyond a single "orientation" lab, they don't get a whole lot of training in debugging things that go wrong in the lab, and I don't expect them to become advanced users of the lab infrastructure. They're encouraged to post questions on a course forum if they have trouble running a lab exercise, and I answer their questions there. Having said that, some students post questions that would be closed immediately on a Stack Exchange site for lack of detail, and for good reason. Questions like: I can't log in to the website, please help. or When I run the experiment, it gives me an error. Can somebody help me??? or I can't see the results of the experiment. with no further details. These are perfectly reasonable things to ask about, but the student hasn't even attempted to give me any details as to what went wrong. In the "real world," people that ask questions like this won't usually get help. Since I operate the computing infrastructure for the lab, I can actually find out the specifics of what happened by checking the student's username against the server logs. So I can give them an answer even if they ask a really incomplete question (e.g., I can check the server logs and see that their experiment failed because they mistyped a command). But I'm not sure if I should answer their questions (because I can, and I want to encourage them to ask questions if they have trouble), or if I should try to train them to ask better questions. On the one hand: it seems like I am doing them a disservice by not teaching them how to ask for help properly. On the other hand: students are (legitimately) frustrated when they're using infrastructure they haven't been extensively trained in, and they can't get it to work. If I try to get them to ask better questions, they'll feel like I'm being deliberately unhelpful and making them jump through hoops to get an answer to their question. (I know this because that's been their reaction the few times I tried this.) They may stop asking questions and just give up on the lab exercises. Should I risk the actual course goal (delivering content to the students) in favor of a general educational goal (teaching them how to ask questions)? Is there a way to train students to ask better questions without making them feel like I'm not helping them? Just to clarify: I already provide answers to commonly asked questions, and a lot of material to help students formulate better questions before they ask. Some students ignore that material and ask very non-specific questions anyways. My question is how to address this once they've asked the question: should I walk them through the process of reformulating it before I answer? Is there a way to do so without frustrating them further? A: Being a student myself I know how frustrating it can be to work with technics or facilities you don't know enough about. Sometimes this means asking fully detailed questions can be tricky. But there is a difference between a student that tries to ask a question to get help with their problem, and one that just declares that they have a problem and thinks it is another persons business to deal with it. What you posted above is the latter. They have encountered a problem and instead of trying to get help to solve it they try to make you solve it. That might even be clever, because as long as you DO solve the problem, they get maximum effect with a minimum of effort. And as soon as students realise that, even the good students won't bother to read your FAQs anymore, because it is a waste of time, when you obviously can identify and solve a problem as soon as they write "Help, I have a problem." Additionally you have to keep in mind, that as a student you often take from the experience that people don't respond to your question of, "can anyone help me" as indicating that this person is just checking, whether someone responds. It is not meant to be a question, but a phrase to start a communication about the problem. That is something adapted from face to face communication. In the real world you don't go to people and start with a 5 minute monologue to your problem, you ask "Hey would you help me?" Wait for a "Sure what is it." And than give your monologue. So what I read above is not a question it is the reflex of a student to a problem. Before even thinking they are posting (in my generation a common reflex in every situation - we are the tldr - too long didn't read generation). If I were you I would respond with a reflex. Just answer with a standard answer that explains, that you need more detail to help. Students who get frustrated by this are already frustrated and beyond your reach. If on the other hand a student tried to ask a proper question and just failed, you should provide the answer and give a hint on how his question could have been better. How frustrated your student will be is less a question of what you respond, than of how you respond. "I could solve your problem, but I wont because of your stupid question" is of course frustrating. But even in a standard answer you can demonstrate that you care, that you take the other person and his time serious, that you would like to help and that you need more information in order to do so. I would try to phrase it, but as you undoubtedly realised I'm not a native English speaker, so I leave that to you. Just don't advertise the fact that you are trying to teach them something. A: To me it seems pretty simple. Stop beating around the bush and tell them to not waste your time. If they want a specific answer then they have to give you a specific question. Or as an alternative you can ask equally bad questions until they ask you more in detail. In your examples above: Q - I can't log in to the website, please help. A - How did you try to log in? Please help. Q - When I run the experiment, it gives me an error. Can somebody help me??? A - Help me first? What experiment and what error? Q - I can't see the results of the experiment. A - What experiment? What steps did you take? After going back and forth a few times even "slow" students will catch on to that to loose less time emailing back and forth, they have to ask more specific questions from the start. Keep your answers equally short, and use "their" language. When they give you more information, ask more detailed questions. They will find out the answer in time. A: Nobody replies with RTFM and STFW anymore, we are losing the traditions of the Internet and that is only bad. Students should learn to make better questions, but they should also learn something much more important how to answer their own questions, because at some point they will not be students anymore and they may not have anyone to ask their questions (specially in research, where people are meant to find knowledge beyond the state of the art). There are some related readings (I can think of now) in this context: How to ask questions How not to ask questions Ask the duck How to ask Also, don't give a man a fish, teach him to fish. In general I agree with this: Rubber duck problem solving But... (there is always a but, nothing is ever so simple not to have it), additionally to giving students the tools for them to answer their own questions it's important to give them the information so that they can do that. There are a number of things that work quite well in that sense. Clear definitions, terms, pointers, references and maybe even a glossary. It's much easier to search on the Internet for additional information when you can write a few words on a search box. Detailed step-by-step instructions of the set-up and all the things they should do to get their work done. (RTFM is quite pointless if there is no manual in the first place). A FAQ. If you are getting the same question repeatedly, then it's likely that something is not clear (which we could say it's your fault...) and it may be good to have a FAQ. If the FAQ deals not only with singular and particular questions but groups of questions then that's even better. E.g.(@cs): "I have an error in the code, how can I solve it?" There are many possible errors and the way to solve most of them is debugging, some instructions about how to debug would be very useful to solve many questions. About your final questions: should I walk them through the process of reformulating it before I answer? Is there a way to do so without frustrating them further? Yes, definitively. I would consider forcing them to reformulate the question is good for them and helping them to do so is very kind. Frustration may be good as well, as long as it is not desperation. Desperation could be good, but it's not for everyone (sorry, I've to link this). I'd personally suggest to help them to improve their questions by asking your own, which very likely you can copy and paste from a template, because there should be a pattern in those questions. Allegedly, Socrates didn't make many friends by asking questions, so try not to ask more than necessary. In any case, this "template" or process is something they should be able to learn and do by themselves, to make better questions and (if possible) to answer their own questions by themselves. Answering in this way would be teaching by example. You can also make the template explicit and part of the FAQ or a sticky post, teaching by example is not incompatible with other forms of teaching.
[ "stackoverflow", "0007234292.txt" ]
Q: Modifying text inside html nodes - nokogiri Let's say i have the following HTML: <ul><li>Bullet 1.</li> <li>Bullet 2.</li> <li>Bullet 3.</li> <li>Bullet 4.</li> <li>Bullet 5.</li></ul> What I wish to do with it, is replace any periods, question marks or exclamation marks with itself and a trailing asterisk, that is inside an HTML node, then convert back to HTML. So the result would be: <ul><li>Bullet 1.*</li> <li>Bullet 2.*</li> <li>Bullet 3.*</li> <li>Bullet 4.*</li> <li>Bullet 5.*</li></ul> I've been messing around with this a bit in IRB, but can't quite figure it out. here's the code i have: html = "<ul><li>Bullet 1.</li> <li>Bullet 2.</li> <li>Bullet 3.</li> <li>Bullet 4.</li> <li>Bullet 5.</li></ul>" doc = Nokogiri::HTML::DocumentFragment.parse(html) doc.search("*").map { |n| n.inner_text.gsub(/(?<=[.!?])(?!\*)/, "#{$1}*") } The array that comes back is parsed out correctly, but I'm just not sure on how to convert it back into HTML. Is there another method i can use to modify the inner_text as such? A: What about this code? doc.traverse do |x| if x.text? x.content = x.content.gsub(/(?<=[.!?])(?!\*)/, "#{$1}*") end end The traverse method does pretty much the same as search("*").each. Then you check that the node is a Nokogiri::XML::Text and, if so, change the content as you wished.
[ "puzzling.stackexchange", "0000020082.txt" ]
Q: Regain your bearings from the logicians You have landed on an island of fun-loving logicians (hmmm ...) and don't know how to find your way home. After asking the first person you meet for directions, you are led to a secret, mystical place with a large stone engraved with the following drawing replete with directions: "I want to go south," you explain. "Is this drawing correct?" "Judge for yourself," answers the native. "I can only tell you that one of the arrows points south, but I cannot tell you which one. I cannot tell you how many arrows point in the right direction either, or you would know which way to go." Show that you are bright enough to regain your bearings (whilst keeping your marbles) by working out which arrow points south. [First fully explained answer carries the day.] The "Pet Shop Boys" could help you too, if only you knew how. A: South is to the left. Proof: the key observation is the statement "I cannot tell you how many arrows point in the right direction either, or you would know which way to go." This tells us that the correct configuration, which say has $n$ arrows pointing in the right direction, is the only one with $n$ arrows pointing in the right direction. If N is in the right direction, then none of the other arrows are. If S is in the right direction, then none of the other arrows are. If W is in the right direction, then none of the other arrows are. If any of E, NE, SW is in the right direction, then so are the other two (and no others). If NW is in the right direction, then none of the other arrows are. If SE is in the right direction, then none of the other arrows are. If none of the arrows are in the right direction, then south could be in either of the directions labelled N or NE. So the native telling us that 0 or 1 arrows point in the right direction wouldn't enable us to know which way to go; any other number except 3 is impossible; and if 3 arrows point in the right direction, then they're E, NE, and SW and south is to the left. QED. A: If NE is correct then E and SW are also correct - you need to go W If NW correct then go SW If S then go S If SE then go NW If N then go SE If W then go E The only unique number of correct arrows is the first option, so you need to go west (as in the title of the song by the Pet Shop Boys)
[ "stackoverflow", "0039605738.txt" ]
Q: Organising template functionality Short and sweet, I have a controller extending Page_Controller and within contains loads of custom template functionality that I would like to "organise" and put this functionality into other files. class BookingPage extends Page { } class BookingPage_Controller extends Page_Controller { public function getMyTemplateVar() {} public function MyTemplateVar2($param) {} // x 1000~ more } My question here, is there any way to create template functionality globally and not just within a particular Page_Controller? My OCD is having a fit putting everything in a single file (controller is already 3432 lines long) A: I managed to accomplish this like so: class BookingPage extends Page {} class BookingPage_Controller extends \MyNamespace\Template\Functionality {} \MyNamespace\Template\Functionality namespace MyNamespace\Template; class Functionality extends \Page_Controller { public function ExternalAPI() { return new \MyNamespace\Rooms\ExternalRoomDataAPI(); } } \MyNamespace\Rooms\ExternalRoomDataAPI namespace MyNamespace\Rooms; class ExternalRoomDataAPI { public function HelloWorld() { $html = "Hello World"; return $html; } } MyTemplate.ss $ExternalAPI.HelloWorld // result: Hello World Am interested in knowing whether or not there is a cleaner way, you can literally extend and extend and extend to organise your functionality this way as long as your final class extends Page_Controller or create new objects and return them as their methods/variables are chainable indefinitely
[ "stackoverflow", "0028465670.txt" ]
Q: Get JSON Object from a nested JSON result I have the following JSON result: This is a weather result. My aim here is to get the cities names first. then according to a city in the list, request a property { "response": { "version":"0.1", "termsofService":"http://www.wunderground.com/weather/api/d/terms.html", "features": { "hourly": 1 , "lang": 1 } , "results": [ { "name": "Al-Arz", "city": "Al-Arz", "state": "", "country": "LB", "country_iso3166":"LB", "country_name":"Lebanon", "zmw": "00000.1.40105", "l": "/q/zmw:00000.1.40105" } , { "name": "Beirut", "city": "Beirut", "state": "", "country": "LB", "country_iso3166":"LB", "country_name":"Lebanon", "zmw": "00000.1.40100", "l": "/q/zmw:00000.1.40100" } , { "name": "Dahr Baidar", "city": "Dahr Baidar", "state": "", "country": "LB", "country_iso3166":"LB", "country_name":"Lebanon", "zmw": "00000.1.40110", "l": "/q/zmw:00000.1.40110" } , { "name": "Houche-Al-Oumara", "city": "Houche-Al-Oumara", "state": "", "country": "LB", "country_iso3166":"LB", "country_name":"Lebanon", "zmw": "00000.1.40101", "l": "/q/zmw:00000.1.40101" } , { "name": "Merdjayoun", "city": "Merdjayoun", "state": "", "country": "LB", "country_iso3166":"LB", "country_name":"Lebanon", "zmw": "00000.1.40104", "l": "/q/zmw:00000.1.40104" } , { "name": "Rayack", "city": "Rayack", "state": "", "country": "LB", "country_iso3166":"LB", "country_name":"Lebanon", "zmw": "00000.1.40102", "l": "/q/zmw:00000.1.40102" } , { "name": "Tripoli", "city": "Tripoli", "state": "", "country": "LB", "country_iso3166":"LB", "country_name":"Lebanon", "zmw": "00000.1.40103", "l": "/q/zmw:00000.1.40103" } ] } } How can i get the names of all cities? Thanks in advance. A: JSONObject rootObject = (JSONObject)new JSONTokener(yourJsonString).nextValue(); JSONObject responseObject = rootObject.getJSONObject("response"); JSONArray cityArray = responseObject.getJSONArray("results"); List<String> listWithCityNames = new ArrayList<String>(); for(int i = 0; i< cityArray.lenght();i++){ listWithCityNames.add(cityArray.getJSONObject(i).getString("name")); } for(String city:listWithCityNames){ System.out.println(city); } This snippet parses the json string in the var yourJsonString and collects the attribute name in the results array inside the response object of your json. Add Try/Catch blocks if needed.
[ "stackoverflow", "0032050016.txt" ]
Q: Views getting flagged inside CardView Everything with my android studio was working fine until I came across this weird thing that when I add Views inside a CardViewthe IDE is warning me telling that for example "TextView is not allowed here". I have done this a thousand times before and It was absolutely fine. Here is a List of the things I have tried 1. Restarted the IDE. 2. Restarted the entire system. 3. Tried the Invalidate Caches/Restart thing. 4. Cleaned the peoject. 5. Verified the support library version and files 6. Banged my head against the wall. Nothing worked, here are some additional details IDE version 1.3.1, SDK tools is using API 22 fully updated And one more thing is suggestions are not shown under the CardView in XML, i guess both these problems are related. I have seen a similar question here, but unfortunately it didn't help me.... Please someone find a fix for this problem... A: Well after spending a day searching around in the Intelli J IDEA docs, I was able to find a solution for this problem. It has to do with the corrupted project metadata and other project related data that is common across projects loaded into Android Studio, so naturally I just opened a backup of my project that I had backed up when the problem did not exist. And I solved it.... Hope this'll help you...
[ "stackoverflow", "0006449225.txt" ]
Q: Using existing shared library (.so) in Android application I have the follow scenario to work on. I was given a shared library (libeffect.so) to use in a Android project i am working for a client. I dont have the shared library source code, i have just the .so file with me. The library is pre-compiled to work on android devices. Along with the shared library I have the method signature public static native void doEffect(int param1, IntBuffer intBuffer); So now I have some questiosn on how to make the call to this native method, of source, if this is possible having just the .so file, so there they are: Do I need to place the native method signature in the same package/class as those defined when the .so was or I can use this signature in any package/class in my project that during runtime the jvm will be able to find the method in the shared library? For example, if this shared library was firstly used in a class mypackage.MyClass, do I need to create the same package, class and then put the method signature there? Where do I need to place this .so file inside my eclipse android project to get this file deployed inside my apk file? These question might sound noob, but I have never worked with jndi before so I am a bit concerned if calling the method doEffect without any error can be achieve. Any answer that can guide me is very welcome. Many Thanks Thiago A: Do I need to place the native method signature in the same package/class as those defined when the .so was or I can use this signature in any package/class in my project that during runtime the jvm will be able to find the method in the shared library? For example, if this shared library was firstly used in a class mypackage.MyClass, do I need to create the same package, class and then put the method signature there? No need to create same package/class. You can put the method signature in any package. public class NativeLib { static { System.loadLibrary("so_file"); } public static native void doEffect(int param1, IntBuffer intBuffer); } 2.Where do I need to place this .so file inside my eclipse android project to get this file deployed inside my apk file? You have put this .so file in lib folder of your application . IF lib folder is not there then you can create a lib folder and put the .so file. you can call it by using System.loadLibrary("so_ file");
[ "stackoverflow", "0043836417.txt" ]
Q: How to change UImage in UICollection UIImageView? I have a UICollectionView which contains a UIImageView and is only one row. I am trying to change the image to a selected image when tapped but the image will not update for some reason. The UIImage is set when the UICollectionView calls: - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath but it will not update when it calls: (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath Here is the code, as you can see I already tried setNeedsDisplay , reloadData, setImage and nullifying the UImageView itself, not setting it in the cellForItemAtIndexPath ... None of it has worked. - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { UICollectionViewCell *cell; UIImage *curImage; static NSString *cellAvatarMediaIdentifier = @"cvAvatarCell"; cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellAvatarMediaIdentifier forIndexPath:indexPath]; Child *currentChild = [self.children objectAtIndex:indexPath.row]; curImage = [UIImage imageNamed:@"male.png"]; UIImageView *childSilhouetteView = (UIImageView *)[cell viewWithTag:300]; if (curImage != nil) { // this WORKS !!!! [childSilhouetteView setImage:curImage]; } return cell; } - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { UIImage *selectedImage; Child *currentChild = [self.children objectAtIndex:indexPath.row]; UIImageView *childSilhouetteView = (UIImageView *)[collectionView viewWithTag:300]; selectedImage = [UIImage imageNamed:@"male_selected.png"]; if (selectedImage != nil) { // This does NOT work, image is never updated NSLog(@"Before setting image"); childSilhouetteView = nil; [childSilhouetteView setImage:selectedImage]; [childSilhouetteView setNeedsDisplay]; [collectionView reloadData]; } } A: You also need to find the corresponding child in didSelectItemAtIndexPath:, currently you're accessing the collectionView's view with tag. - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { UIImage *selectedImage; Child *currentChild = [self.children objectAtIndex:indexPath.row]; UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath]; UIImageView *childSilhouetteView = (UIImageView *)[cell viewWithTag:300]; selectedImage = [UIImage imageNamed:@"male_selected.png"]; if (selectedImage != nil) { // This does NOT work, image is never updated NSLog(@"Before setting image"); // childSilhouetteView = nil; [childSilhouetteView setImage:selectedImage]; [childSilhouetteView setNeedsDisplay]; // [collectionView reloadData]; } } If you call reloadData, your collectionView will be redrawn so you will see the default images on your views.
[ "stackoverflow", "0048093906.txt" ]
Q: Django rest ModelViewSet filtering objects I have two models: Library and a Book. A Library will have Many Books. class Library(models.Model): library_id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) city = models.CharField(max_length=30) address = models.CharField(max_length=80) phone = models.CharField(max_length=30, blank=True, null=True) website = models.CharField(max_length=60, blank=True, null=True) class Book(models.Model): book_id = models.AutoField(primary_key=True) title = models.CharField(max_length=30) # A library has many books which_library = models.ForeignKey('Library', related_name='books', on_delete=models.CASCADE) reader = models.ManyToManyField('Reader', related_name='wishlist') my serializers: class LibrarySerializer(serializers.ModelSerializer): class Meta: model = Library fields = '__all__' class BookSerializer(serializers.ModelSerializer): wishlist = ReaderSerializer(many=True, read_only=True) class Meta: model = Book fields = '__all__' And my view: class LibraryViewSet(viewsets.ModelViewSet): queryset = Library.objects.all() serializer_class = LibrarySerializer class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.filter(which_library=library_id) serializer_class = BookSerializer My Urls: router = routers.DefaultRouter() router.register(r'libraries', LibraryViewSet) router.register(r'books/(?P<library_id>[0-9]+)', BookViewSet) urlpatterns = router.urls my Library routes work correct. However for Books, I need to return the books only belonging to specific library. The default URL and all() returns all the books in database and can retrieve single by hitting books/1. How can I achieve this? I could do it previously with : @api_view(['GET', 'POST']) def books(request, library_id): but now I want to do it with ModelViewSet. A: Override get_queryset method of you viewset where you can define to return specific books. This works like this. class BookViewSet(viewsets.ModelViewSet): serializer_class = LibrarySerializer def get_queryset(self): user = self.request.user books = Book.objects.filter(which_library=self.kwargs['library_id']) return books You can also define list and detail methods where you can define your custom queries for Books. This is shown here. Base name should be set like this. router.register(r'books/(?P<library_id>[0-9]+)', BookViewSet, base_name='books')
[ "stackoverflow", "0020640373.txt" ]
Q: KendoUI PanelBar: unselect item on collapse How do I automatically unselect a PanelBar item when it is collapsed? I'm using 2013.3.1119, and creating the PanelBar from JavaScript. I found this thread from 2009, and tried plugging it in, but the parameters didn't match and it didn't work for me. I looked in the API Reference to wire up the collapse event handler, and put them together like this: <script type="text/javascript"> var panelBar; var onCollapse = function (e) { // access the collapsed item via e.item (HTMLElement) if (!e) { console.log('Error - e is ' + e); return; } if (!e.item) { console.log('Error - e.item is ' + e.item); return; } if (!e.item.unSelect) { console.log('Error - e.item.unSelect is ' + e.item.unSelect); return; } e.item.unSelect(); }; $(document).ready(function () { panelBar = $("#bids").kendoPanelBar({ collapse: onCollapse }); }); </script> But this still doesn't work, it says e.item.unSelect is undefined. I've looked on both e.item and the panelBar object, and can't find any method that appears related to unselecting. How do I do this? Is it still supported? Thanks A: Define your onCollapse as: function onCollapse(e) { $(".k-state-selected", e.item).removeClass("k-state-selected k-state-focused"); } Example here: http://jsfiddle.net/OnaBai/htmFG/
[ "stackoverflow", "0028321083.txt" ]
Q: ClickOnce – Redemption.dll - No such interface supported Problem: I’m changing an application (Project A) we developed to use the ClickOnce deployment method. I have a VB DLL project that uses Redemption. This has been running on the client site for 3+ years. We are currently using Install Shield as the installer. Redemption works fine when installed via this method. We are using VS2013 and the application uses .NET 3.5. After installing the application from a ClickOnce build the application runs but it errors when it tries to use Redemption: Unable to cast COM object of type 'System.__ComObject' to interface type 'Redemption.IRDOItems'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{F8408EB8-6B65-4704-810C-29795E67C0DD}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)). I have another application (Project B) that’s deployed using ClickOnce which also uses Redemption and it works fine. In this project the difference with Redemption is that it is referenced and used in the main project, not a DLL project within the solution. In this project Redemption is listed under Application Files. This application uses .NET 4.0. To get Project A to work I copied the setting employed in Project B. In Project B Redemption was marked as: Isolated = True Embed Interop Types = True In Project A Redemption was marked as: Isolated = True Copy Local = True Embed Interop Types doesn’t exist because it’s .NET 3.5 The Redemption.DLL isn’t listed in the Application Files in Project A, however if I look at the published files it is included and it’s also deployed on the client machine. The Native manifest for the VB DLL has all the interface entries as they are in Project B’s manifest. I found several suggestions after a bing/google search but I couldn’t find someone who had the exact same issue with a COM file. This is what I’ve tried but failed with: Add the Redemption file to the main project (not referenced to it) and set the Build Action = Content and Copy to Output Directory = Copy Always. This gave me an error when publishing, stating that the manifest for Redemption has already been done (i.e. The native manifest for the VB DLL). Changing the Redemption reference in VB DLL so it wasn’t isolated allowed the build to work but still received the original error. Different combinations of the Build Action and Isolation on Redemption in the VB DLL yielded the same results. Add the Redemption file to the main project but this time referencing it. Set isolated = true in the main project and set to false in the VB DLL. Also tried various combinations of isolated and copy local in the main project and VB DLL. Edit the main project file and add an Item Group to deploy manifest as described here: http://blogs.msdn.com/b/mwade/archive/2008/06/29/how-to-publish-files-which-are-not-in-the-project.aspx I changed Project A to use .NET 4.0 so I could have the exact same settings on Redemption as per Project B. All with same net result. Summary: The Redemption.DLL seems to be deployed but not registering in a way for the VB DLL to see it. Any suggestions would be most welcome. A: To get this working I ended creating Redemption as prerequisite. I created setup project to install Redemption. To make the bootstrapper so it could be used as a prequisite I followed the instructions here https://msdn.microsoft.com/en-us/library/h4k032e1.aspx
[ "stackoverflow", "0060416996.txt" ]
Q: How to write an UPDATE Query for multiple tables in Common Table Expressions (CTE's) format? Ho do I rewrite the following UPDATE statement into a Common Table Expressions (CTE's) format? DB::statement('UPDATE taggables, threads SET taggables.created_at = threads.created_at, taggables.updated_at = threads.updated_at WHERE taggables.thread_id = threads.id'); A: I don't really see the point for using a CTE here. Since it seems like your purpose is to update taggables from threads, I would suggest simply using Postgres' update/join syntax, which goes like: update taggables ta set created_at = th.created_at, updated_at = th.updated_at from threads th where ta.thread_id = th.id
[ "stackoverflow", "0014762873.txt" ]
Q: PHP is updating a database index that doesn't exist On my main page, when someone signs-in, i have jQuery using AJAX to 'talk' to a PHP file, and the same for when they sign-out. But, when they sign out, it is supposed to update a database index with the time they left. If they database entry for their last name doesn't exist (meaning, they didn't sign-in), it is supposed to return an error. Instead, the PHP file is saying that it IS updating a non-existant database index. i am using IF statements to achieve this. and for some reason it thinks the index does exist. I've checked the database that it is writing to and the indexes it's supposed to be updating don't exist. Here's my code: if ($Type == 1) { $mysqli = new mysqli("localhost","----","----", "----"); if (!$mysqli) $Type = 3; $Select = $mysqli->query("SELECT Time_Out FROM " . $Date . " WHERE Last_Name = '" . $LName . "'"); $Row = $Select->fetch_assoc(); $Row2 = $Row['Time_Out']; if ($Row2 !== "-1") $Type = 4; if ($Type == 1) {if ($mysqli->query("UPDATE " . $Date . " SET Time_Out='" . $Time . "' WHERE Last_Name='" . $LName . "'")) {} else {$Type = 5;} } $Select = $mysqli->query("SELECT Time_In FROM " . $Date . " WHERE Last_Name='" . $LName . "'"); $Row = $Select->fetch_assoc(); $Row2 = $Row['Time_In']; $Time2 = explode(":",$Row2); $Hour2 = $Hour - $Time2[0]; if ($mysqli->query("SELECT Hours FROM Names WHERE Last_Name='" . $LName . "'")) {$Select = $mysqli->query("SELECT Hours FROM Names WHERE Last_Name='" . $LName . "'"); $Row = $Select->fetch_assoc(); $Row3 = $Row['Hours']; $Auto += 1;} $Time3 = 60-$Time2[1]; if ($Hour != 21) $Time4 = $Min; $Time5 = $Time3+$Time4; if ($Time2[0]+1 != $Hour) {$Time5 = $Time5+60;} $Total = $Time5+intval($Row3); if ($Type == 1) { if ($mysqli->query("UPDATE Names SET Hours = '" . $Total . "' WHERE Last_Name = '" . $LName . "'")) {$Auto += 1;} else {$mysqli->query("INSERT INTO Names (Last_Name, First_Name, Hours) VALUES ('" . $LName . "', '" . $FName . "', '" . $Total . "')");} } $mysqli->close(); } if ($Type == 1) echo "Thank you " . $FName . " " . $LName . " for signing out! See you next time!"; if ($Type == 2) echo "The entered Student ID# is invalid. Please try again!"; if ($Type == 3) echo "An unexpected error has occured. Please try again!"; if ($Type == 4) echo "You have already signed out today!" . $Auto; if ($Type == 5) echo "You didn't sign in today."; A: The UPDATE sql statement will return true, even if it doesn't find any matches (it still runs correctly, it just updates 0 rows). Change this: if ($Type == 1) {if ($mysqli->query("UPDATE " . $Date . " SET Time_Out='" . $Time . "' WHERE Last_Name='" . $LName . "'")) {} else {$Type = 5;} } To this: if ($Type == 1) { if ($mysqli->query("SELECT * FROM " . $Date . " WHERE Last_Name='" . $LName . "'")->num_rows > 0) $mysqli->query("UPDATE " . $Date . " SET Time_Out='" . $Time . "' WHERE Last_Name='" . $LName . "'"); else $Type = 5; } You run the select query to first determine if the record exists (if num_rows property of the result is > 0) and based on that either update the record or set your return value to 5.
[ "es.stackoverflow", "0000028563.txt" ]
Q: Buscar datos API Twitter Estoy consultando datos a Twitter de la siguiente manera: <?php $consumerKey = ''; $consumerSecret = ''; $oAuthToken = ''; $oAuthSecret = ''; require_once('twitteroauth.php'); $tweet = new TwitterOAuth($consumerKey, $consumerSecret, $oAuthToken, $oAuthSecret); $result = $tweet->get('search/tweets', array('q' => '#HASHTAG_BUSCADA', 'count' => 1, 'result_type' => 'recent')); $out=""; $t = json_decode($result, true); foreach ($t['statuses'] as $user) { echo $res = $out."".$user['text']."<br/>"; } ?> Con ello obtengo el "text" del último tweet publicado con la "#HASHTAG_BUSCADA" pero además me gustaría obtener el "screen_name". Si hago echo $result puedo ver que ese dato está allí, pero no sé cómo mostrarlo? Ejemplo: echo $result: { "statuses": [ { "created_at": "Tue Oct 18 20:18:59 +0000 2016", "id": 7.8847448056577e+17, "id_str": "788474480565768192", "text": "Les comparto un peque\u00f1o flash de lo que fue nuestro show en el #Antelfest - #Elsuperhobby\nNo paramos! https:\/\/t.co\/pnN6sdO2RG", "truncated": false, "entities": { "hashtags": [ { "text": "Antelfest", "indices": [ 63, 73 ] }, { "text": "Elsuperhobby", "indices": [ 76, 89 ] } ], "symbols": [ ], "user_mentions": [ ], "urls": [ { "url": "https:\/\/t.co\/pnN6sdO2RG", "expanded_url": "http:\/\/fb.me\/5jfcTPaOu", "display_url": "fb.me\/5jfcTPaOu", "indices": [ 102, 125 ] } ] }, "metadata": { "iso_language_code": "es", "result_type": "recent" }, "source": "<a href=\"http:\/\/www.facebook.com\/twitter\" rel=\"nofollow\">Facebook<\/a>", "in_reply_to_status_id": null, "in_reply_to_status_id_str": null, "in_reply_to_user_id": null, "in_reply_to_user_id_str": null, "in_reply_to_screen_name": null, "user": { "id": 288743808, "id_str": "288743808", "name": "Martin Palomeque", "screen_name": "MartinPalomeque", "location": "Uruguay", "description": "M\u00fasico en El Super Hobby", "url": "http:\/\/t.co\/MqRJDhC4UU", "entities": { "url": { "urls": [ { "url": "http:\/\/t.co\/MqRJDhC4UU", "expanded_url": "http:\/\/www.myspace.com\/martinpalomeque", "display_url": "myspace.com\/martinpalomeque", "indices": [ 0, 22 ] } ] }, "description": { "urls": [ ] } }, "protected": false, "followers_count": 219, "friends_count": 110, "listed_count": 0, "created_at": "Wed Apr 27 11:47:32 +0000 2011", "favourites_count": 32, "utc_offset": -7200, "time_zone": "Greenland", "geo_enabled": false, "verified": false, "statuses_count": 1562, "lang": "es", "contributors_enabled": false, "is_translator": false, "is_translation_enabled": false, "profile_background_color": "C0DEED", "profile_background_image_url": "http:\/\/pbs.twimg.com\/profile_background_images\/240474891\/fondo_martin_palomeque.jpg", "profile_background_image_url_https": "https:\/\/pbs.twimg.com\/profile_background_images\/240474891\/fondo_martin_palomeque.jpg", "profile_background_tile": false, "profile_image_url": "http:\/\/pbs.twimg.com\/profile_images\/619274158694866945\/Pt0bn5Fc_normal.jpg", "profile_image_url_https": "https:\/\/pbs.twimg.com\/profile_images\/619274158694866945\/Pt0bn5Fc_normal.jpg", "profile_banner_url": "https:\/\/pbs.twimg.com\/profile_banners\/288743808\/1436481438", "profile_link_color": "0084B4", "profile_sidebar_border_color": "C0DEED", "profile_sidebar_fill_color": "DDEEF6", "profile_text_color": "333333", "profile_use_background_image": true, "has_extended_profile": false, "default_profile": false, "default_profile_image": false, "following": false, "follow_request_sent": false, "notifications": false, "translator_type": "none" }, "geo": null, "coordinates": null, "place": null, "contributors": null, "is_quote_status": false, "retweet_count": 0, "favorite_count": 0, "favorited": false, "retweeted": false, "possibly_sensitive": false, "lang": "es" } ], "search_metadata": { "completed_in": 0.018, "max_id": 7.8847448056577e+17, "max_id_str": "788474480565768192", "next_results": "?max_id=788474480565768191&q=%23antelfest&count=1&include_entities=1&result_type=recent", "query": "%23antelfest", "refresh_url": "?since_id=788474480565768192&q=%23antelfest&result_type=recent&include_entities=1", "count": 1, "since_id": 0, "since_id_str": "0" } } echo $res: Les comparto un pequeño flash de lo que fue nuestro show en el #Antelfest - #Elsuperhobby No paramos! https://t.co/pnN6sdO2RG Pero no consigo extrar el "screen_name"que sería el siguiente: MartinPalomeque A: Te dejo el ejemplo funcionando en: Ver Demo $res = ''; foreach ($t['statuses'] as $user) { $res .= $user['text']."\n\n"; $res .= $user['user']['screen_name']; } echo $res
[ "stackoverflow", "0011783907.txt" ]
Q: Is uwsgi protocol faster than http protocol? I am experimenting with various setups for deploying django apps. My first choice was using a simple apache server with mod_wsgi, which I had implemented before for private use. Since the current deployment is for public use, I am looking at various options. Based on the information available online, it seems it is good to have nginx for serving static content as well as a reverse proxy for a dynamic content server. Now given my previous knowledge of Apache I was considering using the same for dynamic content. But then I came across Gunicorn and later uWSGI. Currently I am implementing uWSGI. I see that it allows multiple protocols including http. What are the advantages of using one protocol over the other. I understand that given my requirement of scaling the app over multiple servers, means that I cannot use Unix sockets, which seem to be recommended in some tutorials. So the other choices are TCP socket with uwsgi or with http. Do they have much theoretical difference. I am not aware of the details of uwsgi protocol and would like to know, if using it over http protocol would make things faster? A: Ultimately your bottlenecks are not going to be in the particular routing mechanisms for requests unless you really muck up the configuration. So arguably a waste of time to be focused too much on basing decisions on things at that level. Go watch my talk from PyCon for some context on where bottlenecks are really going to be. http://lanyrd.com/2012/pycon/spcdg/
[ "superuser", "0001423055.txt" ]
Q: Graphviz (neato) segfault when processing tree with 50,000 vertices I have a 5MB .gv file with the edges for a 50,000 node tree. I've run neato on it (with a few output formats). The .gv file was generated by SageMath (built-in Graph.show method was not terminating). All I get is the following: neato(2258,0x108a0d5c0) malloc: *** set a breakpoint in malloc_error_break to debug out of memory fish: 'neato 11.gv -Tsvg > 11.svg' terminated by signal SIGSEGV (Address boundary error) Is this size graph too big for graphviz to handle? I imagine layout for a dense graph of this size would be very messy/slow, even infeasible, but I assumed a tree would be easy to layout. I can think of some very straightforward layout algorithms off the top of my head; I'd just prefer to use a command line tool I have installed. Also if anyone thinks another SE site would be a better fit, please add a comment, thanks! edit: I just found out about sfdp. I will try that and post an answer if problem's solved. A: It appears that switching to sfdp solved this problem. Output is generated in less than a minute (though not readable with default settings; will have to fiddle with that).
[ "magento.stackexchange", "0000196216.txt" ]
Q: Magento 2.2 error: Unable to unserialize value After upgrade to the version 2.2 my modules which has serialized values does not work any more. Here is some info from the Magento 2.2 release notes: Significant enhancements in platform security and developer experience. Security improvements include the removal of unserialize calls and protection of this functionality to increase resilence against dangerous code execution attacks. We have also continued to review and improve our protection against Cross-Site Scripting (XSS) attacks. ... In general, we’ve removed serialize/unserialize from most the code to improve protection against remote code execution attacks. We’ve enhanced protection of code where use of object serialization or unserialization was unavoidable. Additionally, we’ve increased our use of output escaping to protect against cross-site scripting (XSS) attacks. Its seems ok, but how I can correctly convert a data when a customer updates a module to the new version? In my case update to the version 2.2 does brokes the site with the error: Unable to unserialize value. I've added the correct serializer (Magento\Framework\Serialize\Serializer\Serialize) to the my resource models, but seems it is not correct solution. In the Magento\Framework\Flag class I seen interesting solution, but seems it's not good enough: /** * Retrieve flag data * * @return mixed */ public function getFlagData() { if ($this->hasFlagData()) { $flagData = $this->getData('flag_data'); try { $data = $this->json->unserialize($flagData); } catch (\InvalidArgumentException $exception) { $data = $this->serialize->unserialize($flagData); } return $data; } } where: $this->json instance of Magento\Framework\Serialize\Serializer\Json $this->serialize instance of Magento\Framework\Serialize\Serializer\Serialize So, the question is: what is the correct solution for this case? Should I write the UpgradeData script that does unserialize the old values and serializes them back using Json (re-save all models)? PS: I've read this posts Notice: unserialize(); Error at offset in Magento 2.2 Magento 2.2: Unable to unserialize value? Magento 2 Unable to unserialize value but there is no answer for my question. A: The problem is in /vendor/magento/framework/Serialize/Serializer/Json.php there is a function unserialize($string) which gives you a syntax error if the string is already serialized. There is a workaround - you can check if string is serialized and then use serialize($string). Change unserialize to: public function unserialize($string) { /* Workaround: serialize first if is serialized */ if($this->is_serialized($string)) { $string = $this->serialize($string); } $result = json_decode($string, true); if (json_last_error() !== JSON_ERROR_NONE) { throw new \InvalidArgumentException('Unable to unserialize value.'); } return $result; } and add function to check if string is serialized: function is_serialized($value, &$result = null) { // Bit of a give away this one if (!is_string($value)) { return false; } // Serialized false, return true. unserialize() returns false on an // invalid string or it could return false if the string is serialized // false, eliminate that possibility. if ($value === 'b:0;') { $result = false; return true; } $length = strlen($value); $end = ''; switch ($value[0]) { case 's': if ($value[$length - 2] !== '"') { return false; } case 'b': case 'i': case 'd': // This looks odd but it is quicker than isset()ing $end .= ';'; case 'a': case 'O': $end .= '}'; if ($value[1] !== ':') { return false; } switch ($value[2]) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: break; default: return false; } case 'N': $end .= ';'; if ($value[$length - 1] !== $end[0]) { return false; } break; default: return false; } if (($result = @unserialize($value)) === false) { $result = null; return false; } return true; } After save fe. category without problem, You can restore class to default and there wont be such problem in future. A: So, solution is write a UpdateData script in the own module which change the default serialized values to the JSON (like Magento does it in the CatalogRules module): app/code/MageWorx/ShippingRules/Setup/UpgradeData.php class UpgradeData implements UpgradeDataInterface { /** * @var \Magento\Framework\App\ProductMetadata */ protected $productMetadata; /** * @var MetadataPool */ private $metadataPool; /** * @var \Magento\Framework\DB\AggregatedFieldDataConverter */ private $aggregatedFieldConverter; /** * UpgradeData constructor. * * @param MetadataPool $metadataPool * @param ObjectManagerInterface $objectManager */ public function __construct( MetadataPool $metadataPool, ObjectManagerInterface $objectManager, \Magento\Framework\App\ProductMetadata $productMetadata ) { $this->productMetadata = $productMetadata; $this->metadataPool = $metadataPool; if ($this->isUsedJsonSerializedValues()) { $this->aggregatedFieldConverter = $objectManager->get('Magento\Framework\DB\AggregatedFieldDataConverter'); } } /** * @return bool */ public function isUsedJsonSerializedValues() { $version = $this->productMetadata->getVersion(); if (version_compare($version, '2.2.0', '>=') && class_exists('\Magento\Framework\DB\AggregatedFieldDataConverter') ) { return true; } return false; } Here we use the ObjectManager class because there is no such class \Magento\Framework\DB\AggregatedFieldDataConverter in the magento versions < 2.2. Then initialize the update method: /** * {@inheritdoc} */ public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context) { $setup->startSetup(); // 2.0.2 - module version compatible with magento 2.2 if (version_compare($context->getVersion(), '2.0.2', '<') && $this->aggregatedFieldConverter) { // Convert each entity values $this->convertRuleSerializedDataToJson($setup); $this->convertZoneSerializedDataToJson($setup); } $setup->endSetup(); } and method for conversion: /** * Convert Zone metadata from serialized to JSON format: * * @param ModuleDataSetupInterface $setup * * @return void */ protected function convertZoneSerializedDataToJson(ModuleDataSetupInterface $setup) { $metadata = $this->metadataPool->getMetadata(ZoneInterface::class); $this->aggregatedFieldConverter->convert( [ new FieldToConvert( SerializedToJson::class, $setup->getTable(Zone::ZONE_TABLE_NAME), $metadata->getLinkField(), 'conditions_serialized' ), ], $setup->getConnection() ); } where: ZoneInterface - entity interface, usually located at the Module/Vendor/Api/Data/ Zone::ZONE_TABLE_NAME - corresponding table name, like 'mageworx_shippingrules_zone' string conditions_serialized - name of the field having a serialized data, which should be converted to JSON To make it work it is necessary to have few important things: Your interface should have corresponding model in the etc/di.xml: <preference for="MageWorx\ShippingRules\Api\Data\RuleInterface" type="MageWorx\ShippingRules\Model\Rule" /> Corresponding entity repository should be defined in the RepositoryFactory in the etc/di.xml (and this repository should exist): <type name="Magento\Framework\Model\Entity\RepositoryFactory"> <arguments> <argument name="entities" xsi:type="array"> <item name="MageWorx\ShippingRules\Api\Data\RuleInterface" xsi:type="string">MageWorx\ShippingRules\Api\RuleRepositoryInterface</item> <item name="MageWorx\ShippingRules\Api\Data\ZoneInterface" xsi:type="string">MageWorx\ShippingRules\Api\ZoneRepositoryInterface</item> </argument> </arguments> </type> Your entity shoul be defined in the MetadataPool (in etc/di.xml): <type name="Magento\Framework\EntityManager\MetadataPool"> <arguments> <argument name="metadata" xsi:type="array"> <item name="MageWorx\ShippingRules\Api\Data\RuleInterface" xsi:type="array"> <item name="entityTableName" xsi:type="string">mageworx_shippingrules</item> <item name="identifierField" xsi:type="string">rule_id</item> </item> <item name="MageWorx\ShippingRules\Api\Data\ZoneInterface" xsi:type="array"> <item name="entityTableName" xsi:type="string">mageworx_shippingrules_zone</item> <item name="identifierField" xsi:type="string">entity_id</item> </item> </argument> </arguments> </type> In corresponding resource model default serializer (class) should not be defined or should be instance of Magento\Framework\Serialize\Serializer\Json (as default). It's stored in the $this->serializer attribute of the resource model. If something goes wrong during the load process of your model I'll recomend you to start debugging from resource model, especially from the magento/framework/Model/ResourceModel/AbstractResource.php class from method protected function _unserializeField(DataObject $object, $field, $defaultValue = null) where: $object - should be instance of your model $field - serialized field, like conditions_serialized The following example is taken from the MageWorx Shipping Suite extension.
[ "writers.stackexchange", "0000032534.txt" ]
Q: In first person narrative, is it acceptable to end rhetorical questions with a period? In first person narrative, would it be acceptable to use a period in place of a question mark when the narrator is asking a rhetorical question? example: My car broke down again. Why does this always seem to happen when I'm broke and between jobs(? or .) I feel, as the narrator, it is more of a statement and I am trying to display an emotion other than inquiry. A: A rhetorical question is still a question, isn't it? I would use a question mark for a question and a period for a statement. "Why does this always happen to me?" "Rats, this always happens when I'm broke and between jobs."
[ "scicomp.stackexchange", "0000026774.txt" ]
Q: Computing accurate fluxes with FEM I have solved Poisson equation on a 3d domain with neumann and dirichlet boundary condition. I get the potential, take the gradient for each element and integrate on a surface of an element, I do this for all elements on a surface enclosing an electrode I am interested in knowing the current through. This does not give very accurate results, upto 50% error. And commercial FEM software gets very accurate fluxes. Does anyone know how they do it or know a better way to compute flux? I am unable to find any references on this A: If $\nabla u$ is of more interest than $u$ itself, it is reasonable to set $\mathbb v := -\sigma \, \nabla u$ and convert your Poisson problem $$ -\nabla \cdot (\sigma \, \nabla u) = f \quad \text{in }\Omega, \\ u = g_E \quad \text{on }\partial\Omega_E, \\ \sigma \, \nabla u \cdot \hat{\mathbb n} = g_N \quad \text{on }\partial\Omega_N $$ to a mixed one: $$ \frac{1}{\sigma} \, \mathbb v + \nabla u = 0 \quad \text{in }\Omega, \\ \nabla \cdot \mathbb v = f \quad \text{in }\Omega, \\ u = g_E \quad \text{on }\partial\Omega_E, \\ \mathbb v \cdot \hat{\mathbb n} = -g_N \quad \text{on }\partial\Omega_N. $$ (Note that for the mixed problem essential BCs are natural and natural BCs are essential.) Here you build an approximation for $\mathbb v$ directly since it is one of the unknowns. Hence you do not lose accuracy due to numerical differentiation. This mixed Poisson formulation is pretty well discussed in literature. A: If averaging the element fluxes, as suggested by @Bill Greene, does not produce accurate enough fluxes, there are ways to improve the accuracy of the fluxes by post-processing. A standard and quite straightforward method, which is mentioned as an exercise in the book by Hughes T.J.R., "The Finite Element Method", is as follows: If your problem is: \begin{align*} & \nabla^2 u = f \quad \text{in} \quad \Omega \\ & \frac{\partial u}{\partial n} = T \quad \text{on} \quad \Gamma_T && \text {Neumann data} \\ & \frac{\partial u}{\partial n} = T^* \quad \text{on} \quad \Gamma_g && \text {sought flux on the Dirichlet boundary} \\ & u = g \quad \text{on} \quad \Gamma_g && \text {Dirichlet data} \end{align*} Then you find the unknown fluxes by solving the corresponding weak problem: Find $T^*\in L_2(\Gamma_g)$ such that for all $w\in H^{\frac{1}{2}}(\Gamma_g)$ there holds: \begin{equation*} \int_{\Gamma_g} wT^* d\Gamma = \int_\Omega w_{,i}u_{,i} d\Omega - \int_{\Omega} wf d\Omega - \int_{\Gamma_T} wT d\Gamma, \end{equation*} where the comma followed by index $i$ denotes differentiation with respect to the coordinates (the summation convention is implied). Note that the Dirichlet data are not used here. You proceed to discretize this additional weak problem as you did for the main problem.
[ "stackoverflow", "0053654713.txt" ]
Q: Google Compute Engine CPU Quotas How do I find out about the current Google Compute Engine CPU quotas for my project at a particular data center? A: To find out the quota for CPUs please follow these instructions: Go to the Quota Increase page in the Google Cloud Platform Console. Expand the Quota type dropdown menu and select All quotas. Expand the Metric dropdown menu. Click on None to hide all quotas and then type CPUs in the search box to search for CPUs quota. Select CPUs from the results list. You should be able to see all Google Compute Engine CPU quotas for all region
[ "stackoverflow", "0058015856.txt" ]
Q: org.apache.hadoop.hive.ql.io.orc.OrcStruct cannot be cast to org.apache.hadoop.io.BinaryComparable at org.apache.hadoop.hive.ql.exec.MapOperator.process(MapOperator.java:563) at org.apache.hadoop.hive.ql.exec.tez.MapRecordSource.processRow(MapRecordSource.java:83) ... 17 more Caused by: java.lang.ClassCastException: org.apache.hadoop.hive.ql.io.orc.OrcStruct cannot be cast to org.apache.hadoop.io.BinaryComparable at org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe.doDeserialize(LazySimpleSerDe.java:166) at org.apache.hadoop.hive.serde2.AbstractEncodingAwareSerDe.deserialize(AbstractEncodingAwareSerDe.java:71) at org.apache.hadoop.hive.ql.exec.MapOperator$MapOpCtx.readRow(MapOperator.java:149) at org.apache.hadoop.hive.ql.exec.MapOperator$MapOpCtx.access$200(MapOperator.java:113) at org.apache.hadoop.hive.ql.exec.MapOperator.process(MapOperator.java:554) ... 18 more 2019-09-19 11:50:29,860 [INFO] [TezChild] |task.TezTaskRunner|: Encounted an error while executing task: attempt_1568591126479_21189_1_01_000000_2 java.lang.RuntimeException: java.lang.RuntimeException: org.apache.hadoop.hive.ql.metadata.HiveException: Hive Runtime Error while processing writable {140725, 222117, 11A2, YYYYYYNN , F, R, SeLect Advntg RX OB, N, MATERNITY , I, 0.00, 04, N, N, Y, Y, Y, N, 003, A, B, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , P, N, S, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , 00, 0P7001, N, SB2, SeLectBL ADvntg RX OB , MATERNITY , 20100101, Y, N, N, , , N, 99, N, 00, Y, 12, N, 0.00, 501, , , , , , , , , , , , , , , , , , , , , , , , , , , 020, , , , , , , , , , , , , 01, 02, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , Y, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , Y, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , 20130715, , , , , 001, , , 0.00, N, N, 99, , 00, , 20100101, , I, 900, 900, 900, DOC.00000000.PRIM, 00, 000, 000, , 000, 000, 000, 0101, 0104, 0204, , , , , , , , , , , , 20100101, 11U2, , 00000000, 00000000, DOC.00000000.PRIM, , , , } at org.apache.hadoop.hive.ql.exec.tez.TezProcessor.initializeAndRunProcessor(TezProcessor.java:173) at org.apache.hadoop.hive.ql.exec.tez.TezProcessor.run(TezProcessor.java:139) at org.apache.tez.runtime.LogicalIOProcessorRuntimeTask.run(LogicalIOProcessorRuntimeTask.java:347) at org.apache.tez.runtime.task.TezTaskRunner$TaskRunnerCallable$1.run(TezTaskRunner.java:194) at org.apache.tez.runtime.task.TezTaskRunner$TaskRunnerCallable$1.run(TezTaskRunner.java:185) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:422) at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1866) at org.apache.tez.runtime.task.TezTaskRunner$TaskRunnerCallable.callInternal(TezTaskRunner.java:185) at org.apache.tez.runtime.task.TezTaskRunner$TaskRunnerCallable.callInternal(TezTaskRunner.java:181) at org.apache.tez.common.CallableWithNdc.call(CallableWithNdc.java:36) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:748) Caused by: java.lang.RuntimeException: org.apache.hadoop.hive.ql.metadata.HiveException: Hive Runtime Error while processing writable {140725, 222117, 11A2, YYYYYYNN , F, R, SeLect Advntg RX OB, N, MATERNITY , I, 0.00, 04, N, N, Y, Y, Y, N, 003, A, B, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , P, N, S, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , 00, 0P7001, N, SB2, SeLectBL ADvntg RX OB , MATERNITY , 20100101, Y, N, N, , , N, 99, N, 00, Y, 12, N, 0.00, 501, , , , , , , , , , , , , , , , , , , , , , , , , , , 020, , , , , , , , , , , , , 01, 02, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , Y, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , Y, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , 20130715, , , , , 001, , , 0.00, N, N, 99, , 00, , 20100101, , I, 900, 900, 900, DOC.00000000.PRIM, 00, 000, 000, , 000, 000, 000, 0101, 0104, 0204, , , , , , , , , , , , 20100101, 11U2, , 00000000, 00000000, DOC.00000000.PRIM, , , , } at org.apache.hadoop.hive.ql.exec.tez.MapRecordSource.processRow(MapRecordSource.java:91) at org.apache.hadoop.hive.ql.exec.tez.MapRecordSource.pushRecord(MapRecordSource.java:68) at org.apache.hadoop.hive.ql.exec.tez.MapRecordProcessor.run(MapRecordProcessor.java:325) at org.apache.hadoop.hive.ql.exec.tez.TezProcessor.initializeAndRunProcessor(TezProcessor.java:150) ... 14 more Caused by: org.apache.hadoop.hive.ql.metadata.HiveException: Hive Runtime Error while processing writable {140725, 222117, 11A2, YYYYYYNN , F, R, SeLect Advntg RX OB, N, MATERNITY , I, 0.00, 04, N, N, Y, Y, Y, N, 003, A, B, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , P, N, S, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , 00, 0P7001, N, SB2, SeLectBL ADvntg RX OB , MATERNITY , 20100101, Y, N, N, , , N, 99, N, 00, Y, 12, N, 0.00, 501, , , , , , , , , , , , , , , , , , , , , , , , , , , 020, , , , , , , , , , , , , 01, 02, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , Y, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , Y, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , 20130715, , , , , 001, , , 0.00, N, N, 99, , 00, , 20100101, , I, 900, 900, 900, DOC.00000000.PRIM, 00, 000, 000, , 000, 000, 000, 0101, 0104, 0204, , , , , , , , , , , , 20100101, 11U2, , 00000000, 00000000, DOC.00000000.PRIM, , , , } at org.apache.hadoop.hive.ql.exec.MapOperator.process(MapOperator.java:563) at org.apache.hadoop.hive.ql.exec.tez.MapRecordSource.processRow(MapRecordSource.java:83) ... 17 more Caused by: java.lang.ClassCastException: org.apache.hadoop.hive.ql.io.orc.OrcStruct cannot be cast to org.apache.hadoop.io.BinaryComparable at org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe.doDeserialize(LazySimpleSerDe.java:166) at org.apache.hadoop.hive.serde2.AbstractEncodingAwareSerDe.deserialize(AbstractEncodingAwareSerDe.java:71) at org.apache.hadoop.hive.ql.exec.MapOperator$MapOpCtx.readRow(MapOperator.java:149) at org.apache.hadoop.hive.ql.exec.MapOperator$MapOpCtx.access$200(MapOperator.java:113) at org.apache.hadoop.hive.ql.exec.MapOperator.process(MapOperator.java:554) ... 18 more 2019-09-19 11:50:29,872 [INFO] [TezChild] |runtime.LogicalIOProcessorRuntimeTask|: Final Counters for attempt_1568591126479_21189_1_01_000000_2: Counters: 33 [[File System Counters HDFS_BYTES_READ=38594, HDFS_READ_OPS=2, HDFS_OP_OPEN=2][org.apache.tez.common.counters.TaskCounter SPILLED_RECORDS=0, GC_TIME_MILLIS=116, CPU_MILLISECONDS=6310, PHYSICAL_MEMORY_BYTES=3571974144, VIRTUAL_MEMORY_BYTES=10842828800, COMMITTED_HEAP_BYTES=3571974144, INPUT_RECORDS_PROCESSED=1, INPUT_SPLIT_LENGTH_BYTES=44890, OUTPUT_RECORDS=0, OUTPUT_BYTES=0, OUTPUT_BYTES_WITH_OVERHEAD=0, OUTPUT_BYTES_PHYSICAL=0, ADDITIONAL_SPILLS_BYTES_WRITTEN=0, ADDITIONAL_SPILLS_BYTES_READ=0, ADDITIONAL_SPILL_COUNT=0, SHUFFLE_CHUNK_COUNT=0][HIVE DESERIALIZE_ERRORS=1, RECORDS_IN_Map_1=0, RECORDS_OUT_INTERMEDIATE_Map_1=0][TaskCounter_Map_1_INPUT_fmr_disk_file INPUT_RECORDS_PROCESSED=1, INPUT_SPLIT_LENGTH_BYTES=44890][TaskCounter_Map_1_OUTPUT_Reducer_2 ADDITIONAL_SPILLS_BYTES_READ=0, ADDITIONAL_SPILLS_BYTES_WRITTEN=0, ADDITIONAL_SPILL_COUNT=0, OUTPUT_BYTES=0, OUTPUT_BYTES_PHYSICAL=0, OUTPUT_BYTES_WITH_OVERHEAD=0, OUTPUT_RECORDS=0, SHUFFLE_CHUNK_COUNT=0, SPILLED_RECORDS=0]] 2019-09-19 11:50:29,872 [INFO] [TezChild] |runtime.LogicalIOProcessorRuntimeTask|: Joining on EventRouter 2019-09-19 11:50:29,872 [INFO] [TezChild] |runtime.LogicalIOProcessorRuntimeTask|: Closed processor for vertex=Map 1, index=1 2019-09-19 11:50:29,873 [INFO] [TezChild] |runtime.LogicalIOProcessorRuntimeTask|: Closed input for vertex=Map 1, sourceVertex=fmr_disk_file 2019-09-19 11:50:29,873 [INFO] [TezChild] |impl.PipelinedSorter|: Reducer 2: Starting flush of map output 2019-09-19 11:50:29,873 [INFO] [TezChild] |impl.PipelinedSorter|: Reducer 2: done sorting span=0, length=0, time=0 A: This is the hive table exception, when we create a table in the hive during migration we simply copy the ddl of the table from the source to target. When we copy the ddl structure from source we need to remove "STORED AS INPUTFORMAT" and "OUTPUTFORMAT" which will appear as below. STORED AS INPUTFORMAT org.apache.hadoop.hive.ql.io.orc.OrcInputFormat OUTPUTFORMAT org.apache.hadoop.hive.ql.io.orc.OrcOutputFormat By removing above lines, we can replace it with below STORED AS ORC; For me issue has resolved for the same.
[ "stackoverflow", "0041540038.txt" ]
Q: Error updating a select box by ajax I'm trying to update a selectbox that depends on another selectbox. Depending on the first one, it will search all those records that are related. Should work, this I am doing at the device login but I am getting the following error: ActionController::RoutingError (uninitialized constant Usuarios::SessionsControllerController): activesupport (4.2.6) lib/active_support/inflector/methods.rb:263:in `const_get' activesupport (4.2.6) lib/active_support/inflector/methods.rb:263:in `block in constantize' activesupport (4.2.6) lib/active_support/inflector/methods.rb:259:in `each' activesupport (4.2.6) lib/active_support/inflector/methods.rb:259:in `inject' activesupport (4.2.6) lib/active_support/inflector/methods.rb:259:in `constantize' actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:70:in `controller_reference' actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:60:in `controller' actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:39:in `serve' actionpack (4.2.6) lib/action_dispatch/journey/router.rb:43:in `block in serve' actionpack (4.2.6) lib/action_dispatch/journey/router.rb:30:in `each' actionpack (4.2.6) lib/action_dispatch/journey/router.rb:30:in `serve' actionpack (4.2.6) lib/action_dispatch/routing/route_set.rb:817:in `call' rack-pjax (1.0.0) lib/rack/pjax.rb:12:in `call' actionpack (4.2.6) lib/action_dispatch/middleware/flash.rb:260:in `call' warden (1.2.6) lib/warden/manager.rb:35:in `block in call' warden (1.2.6) lib/warden/manager.rb:34:in `catch' warden (1.2.6) lib/warden/manager.rb:34:in `call' rack (1.6.4) lib/rack/etag.rb:24:in `call' rack (1.6.4) lib/rack/conditionalget.rb:25:in `call' rack (1.6.4) lib/rack/head.rb:13:in `call' remotipart (1.3.1) lib/remotipart/middleware.rb:32:in `call' actionpack (4.2.6) lib/action_dispatch/middleware/params_parser.rb:27:in `call' actionpack (4.2.6) lib/action_dispatch/middleware/flash.rb:260:in `call' rack (1.6.4) lib/rack/session/abstract/id.rb:225:in `context' rack (1.6.4) lib/rack/session/abstract/id.rb:220:in `call' actionpack (4.2.6) lib/action_dispatch/middleware/cookies.rb:560:in `call' activerecord (4.2.6) lib/active_record/query_cache.rb:36:in `call' activerecord (4.2.6) lib/active_record/connection_adapters/abstract/connection_pool.rb:653:in `call' activerecord (4.2.6) lib/active_record/migration.rb:377:in `call' actionpack (4.2.6) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call' activesupport (4.2.6) lib/active_support/callbacks.rb:88:in `__run_callbacks__' activesupport (4.2.6) lib/active_support/callbacks.rb:778:in `_run_call_callbacks' activesupport (4.2.6) lib/active_support/callbacks.rb:81:in `run_callbacks' actionpack (4.2.6) lib/action_dispatch/middleware/callbacks.rb:27:in `call' actionpack (4.2.6) lib/action_dispatch/middleware/reloader.rb:73:in `call' actionpack (4.2.6) lib/action_dispatch/middleware/remote_ip.rb:78:in `call' actionpack (4.2.6) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call' web-console (2.3.0) lib/web_console/middleware.rb:28:in `block in call' web-console (2.3.0) lib/web_console/middleware.rb:18:in `catch' web-console (2.3.0) lib/web_console/middleware.rb:18:in `call' actionpack (4.2.6) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call' railties (4.2.6) lib/rails/rack/logger.rb:38:in `call_app' railties (4.2.6) lib/rails/rack/logger.rb:20:in `block in call' activesupport (4.2.6) lib/active_support/tagged_logging.rb:68:in `block in tagged' activesupport (4.2.6) lib/active_support/tagged_logging.rb:26:in `tagged' activesupport (4.2.6) lib/active_support/tagged_logging.rb:68:in `tagged' railties (4.2.6) lib/rails/rack/logger.rb:20:in `call' actionpack (4.2.6) lib/action_dispatch/middleware/request_id.rb:21:in `call' rack (1.6.4) lib/rack/methodoverride.rb:22:in `call' rack (1.6.4) lib/rack/runtime.rb:18:in `call' activesupport (4.2.6) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call' rack (1.6.4) lib/rack/lock.rb:17:in `call' actionpack (4.2.6) lib/action_dispatch/middleware/static.rb:120:in `call' rack (1.6.4) lib/rack/sendfile.rb:113:in `call' railties (4.2.6) lib/rails/engine.rb:518:in `call' railties (4.2.6) lib/rails/application.rb:165:in `call' rack (1.6.4) lib/rack/content_length.rb:15:in `call' thin (1.7.0) lib/thin/connection.rb:86:in `block in pre_process' thin (1.7.0) lib/thin/connection.rb:84:in `catch' thin (1.7.0) lib/thin/connection.rb:84:in `pre_process' thin (1.7.0) lib/thin/connection.rb:53:in `process' thin (1.7.0) lib/thin/connection.rb:39:in `receive_data' eventmachine (1.2.0.1) lib/eventmachine.rb:194:in `run_machine' eventmachine (1.2.0.1) lib/eventmachine.rb:194:in `run' thin (1.7.0) lib/thin/backends/base.rb:73:in `start' thin (1.7.0) lib/thin/server.rb:162:in `start' rack (1.6.4) lib/rack/handler/thin.rb:19:in `run' rack (1.6.4) lib/rack/server.rb:286:in `start' railties (4.2.6) lib/rails/commands/server.rb:80:in `start' railties (4.2.6) lib/rails/commands/commands_tasks.rb:80:in `block in server' railties (4.2.6) lib/rails/commands/commands_tasks.rb:75:in `tap' railties (4.2.6) lib/rails/commands/commands_tasks.rb:75:in `server' railties (4.2.6) lib/rails/commands/commands_tasks.rb:39:in `run_command!' railties (4.2.6) lib/rails/commands.rb:17:in `<top (required)>' bin/rails:9:in `require' bin/rails:9:in `<top (required)>' spring (2.0.0) lib/spring/client/rails.rb:28:in `load' spring (2.0.0) lib/spring/client/rails.rb:28:in `call' spring (2.0.0) lib/spring/client/command.rb:7:in `call' spring (2.0.0) lib/spring/client.rb:30:in `run' spring (2.0.0) bin/spring:49:in `<top (required)>' spring (2.0.0) lib/spring/binstub.rb:31:in `load' spring (2.0.0) lib/spring/binstub.rb:31:in `<top (required)>' /home/luis/.rbenv/versions/2.3.1/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:68:in `require' /home/luis/.rbenv/versions/2.3.1/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:68:in `require' bin/spring:13:in `<top (required)>' bin/rails:3:in `load' bin/rails:3:in `<main>' Rendered /home/luis/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb (1.5ms) Rendered /home/luis/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/routing_error.text.erb (9.7ms) this is my new.html.erb (view->devise->sessions) <%= form_for(resource, as: resource_name, url: session_path(resource_name), html: {class: "form-horizontal"}) do |f| %> <h1>Login Form</h1> <div class="forml"> <div class="form-group"> <div > <%= f.text_field :login, autofocus: true, :class => "form-control", :placeholder =>"Username or Email", :required => "" %> </div> </div> <div class="form-group"> <div > <%= f.password_field :password, autofocus: true, :class => "form-control", :placeholder =>"Password", :required => "" %> </div> <%= select_tag :empresa, options_for_select(@empresas.map{|e|[e.Empresa, e.id]}), :'data-remote' => 'true', :'data-url' => url_for(:controller => 'sessions_controller', :action => 'busqueda_sucursales', format: 'js') %> <div id="sucursales"><%= render 'sucursales' %></div> </div> </div> <div class="form-group"> <% if devise_mapping.rememberable? -%> <div class="checkbox-inline col-md-5"> <%= f.check_box :remember_me %> <%= f.label :remember_me %> </div> <% end -%> </div> <div> <%= f.submit "Log in", :class => "btn btn-default submit col-md-10"%> <div class="form-group"> <%= render "devise/shared/links" %> </div> </div> <div class="clearfix"></div> <div class="separator"> </div> <% end %> this is my partial _sucursales.html.erb(view->devise->sessions) <div class="form-group"> <%= label_tag :sucursal, "Selecciona sucursal:" %> <div class=""> <%= select_tag :sucursal, options_for_select(@sucursales.map{|e|[e.Sucursal, e.IdEmpresa]}), class: "form-control js-example-basic-single" %> </div> </div> this is my busqueda_sucursales.js.erb (view->devise->sessions) $("#sucursales").html("<%= escape_javascript(render("sucursales"))%>") this is my sessions_controller.rb (controllers->usuarios) class Usuarios::SessionsController < Devise::SessionsController # before_action :configure_sign_in_params, only: [:create] # GET /resource/sign_in # def new # super # end # POST /resource/sign_in # def create # super # end # DELETE /resource/sign_out # def destroy # super # end # protected # If you have extra params to permit, append them to the sanitizer. # def configure_sign_in_params # devise_parameter_sanitizer.permit(:sign_in, keys: [:attribute]) # end def busqueda_sucursales #Actualiza las sucursales concorde a las empresas en el acceso @sucursales = Empresa.where("empresamadre_id = ?", params[:empresa]) respond_to do |format| format.js end end def new @empresas = Empresamadre.all @sucursales = Empresa.where("empresamadre_id = ?", @empresas.first.id) super end def create super end def update super end private def sign_up_params allow = [:email, :usuario, :password, :password_confirmation, :nombre, :idempresa] params.require(resource_name).permit(allow) end end this is my routes.rb devise_for :usuarios, controllers: { registrations: "usuarios/registrations", sessions: "usuarios/sessions", passwords: "usuarios/passwords"} resources :usuarios do get 'usuarios_check', :on => :collection get 'usuarios_check2', :on => :collection end get 'usuarios/sessions_controller/busqueda_sucursales', as: 'busqueda_sucursales' A: Reading the first line of your error, it seemed off to see the word Controller repeated: ActionController::RoutingError (uninitialized constant Usuarios::SessionsControllerController): This line: <%= select_tag :empresa, options_for_select(@empresas.map{|e|[e.Empresa, e.id]}), :'data-remote' => 'true', :'data-url' => url_for(:controller => 'sessions_controller', :action => 'busqueda_sucursales', format: 'js') %> replace :controller => 'sessions_controller' with :controller => 'sessions' See the examples here: http://apidock.com/rails/ActionView/RoutingUrlFor/url_for
[ "stackoverflow", "0027088021.txt" ]
Q: stripe token is not passing I have an application built in Laravel 4 and uses this package I am following this tutorial This is the error I am getting http://postimg.org/image/c4qwjysgp/ My issue is $token is not correctly passing or the $token is empty. I have already done a var_dump($token); die(); and get nothing but a white screen so not data is passing. Here is the view @extends('layouts.main') @section('content') <h1>Your Order</h1> <h2>{{ $download->name }}</h2> <p>&pound;{{ ($download->price/100) }}</p> <form action="" method="POST" id="payment-form" role="form"> <input type="hidden" name="did" value="{{ $download->id }}" /> <div class="payment-errors alert alert-danger" style="display:none;"></div> <div class="form-group"> <label> <span>Card Number</span> <input type="text" size="20" data-stripe="number" class="form-control input-lg" /> </label> </div> <div class="form-group"> <label> <span>CVC</span> <input type="text" size="4" data-stripe="cvc" class="form-control input-lg" /> </label> </div> <div class="form-group"> <label> <span>Expires</span> </label> <div class="row"> <div class="col-lg-1 col-md-1 col-sm-2 col-xs-3"> <input type="text" size="2" data-stripe="exp-month" class="input-lg" placeholder="MM" /> </div> <div class="col-lg-1 col-md-1 col-sm-2 col-xs-3"> <input type="text" size="4" data-stripe="exp-year" class="input-lg" placeholder="YYYY" /> </div> </div> </div> <div class="form-group"> <button type="submit" class="btn btn-primary btn-lg">Submit Payment</button> </div> </form> @stop Here is the route Route::post('/buy/{id}', function($id) { Stripe::setApiKey(Config::get('laravel-stripe::stripe.api_key')); $download = Download::find($id); //stripeToken is form name, injected into form by js $token = Input::get('stripeToken'); //var_dump($token); // Charge the card try { $charge = Stripe_Charge::create(array( "amount" => $download->price, "currency" => "gbp", "card" => $token, "description" => 'Order: ' . $download->name) ); // If we get this far, we've charged the user successfully Session::put('purchased_download_id', $download->id); return Redirect::to('confirmed'); } catch(Stripe_CardError $e) { // Payment failed return Redirect::to('buy/'.$id)->with('message', 'Your payment has failed.'); } }); Here is the js $(function () { console.log('setting up pay form'); $('#payment-form').submit(function(e) { var $form = $(this); $form.find('.payment-errors').hide(); $form.find('button').prop('disabled', true); Stripe.createToken($form, stripeResponseHandler); return false; }); }); function stripeResponseHandler(status, response) { var $form = $('#payment-form'); if (response.error) { $form.find('.payment-errors').text(response.error.message).show(); $form.find('button').prop('disabled', false); } else { var token = response.id; $form.append($('<input type="hidden" name="stripeToken" />').val(token)); $form.get(0).submit(); } } Here is the stripe.php in package <?php return array( 'api_key' => 'sk_test_Izn8gXUKMzGxfMAbdylSTUGO', 'publishable_key' => 'pk_test_t84KN2uCFxZGCXXZAjAvplKG' ); A: I figured out the problem. In the source for the external javascript file, the "/" was missing at the beginning of the relative path. That is why the javascript file for the homepage was rendering fine but the /buy page was not rendering the javascript file.
[ "judaism.stackexchange", "0000027479.txt" ]
Q: Why do we say we don't dip food on other days? In the four questions, we ask "on all other nights, we don't dip, even once, but on this night, we dip twice" How can we ask this if we dip challah in salt on Shabbat (and other days)? A: The Lubavitcher Rebbe (Sichos Kodesh 5741 vol 3. pg. 408) explains that the meaning of "טיבול" (dipping) here is in a liquid that necessitates washing hands prior such as the Karpas in salt-water, or the Marror in Charoses (that contains wine). However, dipping bread in dry salt is not considered "טיבול". [In that talk, the Rebbe made reference to a Torah journal that had been just been printed (Yeshivas Tomchei Temimim Ocean Parkway Gilyon 5 Haaroh 16), which quoted him as explaining that on a regular Friday night one does not have to dip the Challah into salt, but could rather sprinkle the salt onto the Challah. He commented that this answer is not necessary (as above), but since it was published in his name, he probably had said it "l'richvcha demilsa"].
[ "stackoverflow", "0058485833.txt" ]
Q: Best Practice for window functions in PostgreSQL I have a table with record_id and record_created_time columns (postgresql). I want to calculate duration by minute between timeline of each records. Can I do it with window functions (using partition by)? record_id | record_time | value(minute) ------------|------------------------|-------- 1 | 2019-10-01 01:00:00+02 | 0 1 | 2019-10-01 01:03:00+02 | 3 2 | 2019-10-01 02:00:00+02 | 0 2 | 2019-10-01 02:05:00+02 | 5 2 | 2019-10-01 02:07:00+02 | 2 A: Yes, this can be done with the window function lag(): select record_id, record_time, record_time - lag(record_time) over (partition by record_id order by record_time) as diff_to_previous from the_table order by record_id, record_time; Note that this will return an interval, if you want the value in minutes, you need to convert that value: extract(epoch from record_time - lag(record_time) over (partition by record_id order by record_time)) / 60 as minutes
[ "stackoverflow", "0040306221.txt" ]
Q: Rails javascript buttons causing post I've created a form where a user can move items from the left side to the right side using two buttons. After the user has finished adding their items they can name & save the group. At least that's how it's supposed to work. Instead, as soon as I add one item, and click on the 'move right' button the POST action fires. Why are my javascript driven buttons firing the POST action instead of the submit_tag? Here's what the form looks like view/settings/global.html.erb: The form code in the view: <%= form_tag '/create_host_group', id: "host_group_form", class: "form-horizontal" do %> <%= label_tag "Group Name", nil, required: true, class: "control-label col-md-2 col-sm-2 col-xs-12" %> <%= text_field_tag 'host_group_name', nil, class: "form-control" %> <%= label_tag "Available Hosts", nil, class: "control-label col-md-2 col-sm-2 col-xs-12" %> <select id="hosts_available" class="form-control" size="30" multiple> <% @network_hosts.each do |n| %> <option value="<%= n.id %>"><%= n.ip_address %></option> <% end %> </select> <button id="btnRight" class="btn btn-success"><i class="fa fa-2x fa-forward"></i></button> <br/> <button id="btnLeft" class="btn btn-danger"><i class="fa fa-2x fa-backward"></i></button> <select id="hosts_assigned" class="form-control" size="30" multiple></select> <%= submit_tag "Add Group", class: "btn btn-success" %> <% end %> <script> $("#btnLeft").click(function(){ var selectedItem = $("#hosts_assigned option:selected"); $("#hosts_available").append(selectedItem); }); $("#btnRight").click(function(){ var selectedItem = $("#hosts_available option:selected"); $("#hosts_assigned").append(selectedItem); }); </script> In my controller for loading the view settings_controller.rb: class SettingsController < ApplicationController before_action :get_company_and_locations def global get_network_hosts end end The POST action is calling network_host_groups_controller#create, which I'm just trying to debug right now: class NetworkHostGroupsController < ApplicationController def create group_name = params[:host_group_name] assigned_hosts = params[:hosts_assigned] puts "#{group_name}: #{assigned_hosts}" end end And my routes are: match '/global_settings', to: 'settings#global', via: 'get' match '/create_host_group', to: 'network_host_groups#create', via: 'post' A: Button elements default to submit on click. Add a type="button" attribute to indicate to the browser that clicking the button shouldn't submit the form! <button type="button" id="btnRight" class="btn btn-success">
[ "diy.stackexchange", "0000059308.txt" ]
Q: Is this wall load bearing based on the attached blueprints? I would like to remove a wall in my walk-out basement but I don't know how to interpret this architectural blueprint. Based on this blueprint, is the wall bearing load or not? I have highlighted the wall in question in the pictures below. Click for larger view Click for larger view A: EDIT: On second look, the drawing actually tells us. There's a note box to the right: TYP BEARING WALL 2x4 stud 16" O.C. on Continuous footing. The dashed line around the wall indicates the footing. ORIGINAL: If I'm reading the drawing correctly, IT DEFINITELY IS. For the sake of this discussion, north is the top of the drawing. There appears to be a beam running E-W from the post to the East wall. There are no notes on the west wall talking about a beam pocket. This leads me to believe that the dark line following the same path as the beam is simply a dimension line, not a continuation of the beam. So the beam does not extend westward towards the area you want to deal with. This makes the total span in the area you're looking at 36 feet. Far too long for 2 x 12's, which means the wall you want to remove is definitely supporting the joists. Even if the beam does continue, I would take great care. 20 feet is about the max for a joist span. This job calls for a professional engineer to assess the situation. The solution is probably to dig a footer where the doorway is now, and put up a steel post and raise another short steel or paralam beam where the wall is. This involves building temporary stud walls on either side of the existing wall to support the load while you're working. You'll need to find a contractor who has done this type of work before.
[ "photo.stackexchange", "0000089006.txt" ]
Q: Nikon D5500 proximity sensor failure? I've been struggling with this for some time, & I feel the issue has been getting worse. The rear screen of my D5500 works perfectly - when I press the menu button, or the 'view' button for the last picture taken, or put it in Live View. There is nothing wrong at all with the screen, per se. Other than that, it only works if I switch off "Info display auto off" in the settings menu - which is irritating, as the 'screen off when eye in position' is rather useful. Pressing the Info button does nothing, half squeezing the shutter release does nothing. The display in the viewfinder does what it ought, but the rear screen does not want to be my friend. I'm aware there's a proximity sensor, but wasn't sure a) where it was or b) what could interfere with it. I had considered, amongst other things... My tripod mount, or macro rail was being 'seen'. Nope. My remote release cable. Nope. The fact I have extension tubes attached. Nope. My hotshot flash. Nope. I was starting to wonder whether it was actually 'broken' & needed a trip back to the factory; or whether there was some kind of 'global software reboot' I could do - the big switch it off & back on again... A: Forgive this self-question/answer, but I thought it may help anyone else with a similar issue, which had eluded me for months. I do, of course, now feel remarkably stupid for not having figured it out earlier, however, think the blushes worth it. The proximity sensor is here original unhighlighted image http://www.imaging-resource.com/PRODS/nikon-d5500/nikon-d5500TECH.HTM The smallest piece of grit, dirt, finger smear or generic gunk on it or near it, on an otherwise spotless camera body, will play merry hell with the actual proximity of your face & the recognition of that fact. So, the fix was simply to clean the sensor & the area around it.
[ "stackoverflow", "0055124818.txt" ]
Q: How to handle a key of a parent array? How to handle a key (index) of a parent array? I'm getting numeric keys, but I need an index as a key. Example. <?php $arrayFirst = [ "index" => [ 'a' => '1', ], [ 'a' => '2', ] ]; $arraySecond = [ "index" => [ 'b' => '1', ], [ 'b' => '2', ] ]; var_dump(array_map(function(...$items){ return array_merge(...$items); }, $arrayFirst, $arraySecond)); A: If keys of two arrays are complete the same, then you can try using func array_combine(): var_dump( array_combine( array_keys($arrayFirst), array_map( function(...$items) { return array_merge(...$items); }, $arrayFirst, $arraySecond ) ) ); Example
[ "stackoverflow", "0029625254.txt" ]
Q: Web API Controller Unit Testing I have an N-tier project that am trying to test the API controller but the flow is a little bit more complex which makes me ask for some opinion from you guys... Please any suggestion will be appreciated so much... I'm getting an error Object reference not Set to An Instance Of An Object This is my test class and method that get all fake symptoms [TestClass] public class SymptomsControllerTest { private Mock<IAdministrationManagementService> _administrationManagementServiceMock; SymptomsController objController; IList<SymptomObject> listSymptoms; [TestInitialize] public void Initialize() { _administrationManagementServiceMock = new Mock<IAdministrationManagementService>(); objController = new SymptomsController(_administrationManagementServiceMock.Object); listSymptoms = new List<SymptomObject>() { new SymptomObject() { Name = "Head1" }, new SymptomObject() { Name = "Head2" }, new SymptomObject() { Name = "Head3" } }; } [TestMethod] public void Symptom_Get_All() { //Arrange _administrationManagementServiceMock.Setup(x => x.GetSymptoms()).ReturnsAsync(listSymptoms); //Act var result = objController.Get() as List<SymptomObject>; //Assert Assert.AreEqual(result.Count, 3); Assert.AreEqual("Head1", result[0].Name); Assert.AreEqual("Head2", result[1].Name); Assert.AreEqual("Head3", result[2].Name); } } the service am trying to communicate to looks likes this public Task<IList<SymptomObject>> GetSymptoms() { return Task.Run(() => { try { using (var _uow = new HomasUoW()) { var entities = _uow.Symptoms.GetAll().Where(x => x.isDelete == false); if (entities.Count() > 0) { IList<SymptomObject> list = new List<SymptomObject>(); foreach (var entity in entities) { var obj = AutoMapper.Mapper.DynamicMap<Symptom, SymptomObject>(entity); obj.Name = entity.Name; list.Add(obj); } return list; } else { throw new InvalidOperationException(Resources.NonExistingObjectRetrievalError); } } } catch (Exception) { throw; } }); } and the API Controller looks like this public IHttpActionResult Get() { try { var symptoms = _Service.GetSymptoms(); if (symptoms != null) { return Ok(symptoms); } return NotFound(); } catch (Exception ex) { return InternalServerError(ex); } } Please look at it carefully and check if am missing any thing that is not allowing the test to pass. A: Based on your comment: the null exception is coming from this line of code Assert.AreEqual(result.Count, 3); Clearly the result object is null. Look at how you get that object: var result = objController.Get() as List<SymptomObject>; Even if Get() returns something, the behavior of the as keyword is such that when you try to interpret an object as the wrong type, the result will be null. You're trying to interpret that object as List<SymptomObject>. But what does Get() return? public IHttpActionResult Get() You can't cast IHttpActionResult to List<SymptomObject>. You have two options: Your WebAPI controller should return a List<SymptomObject> (which I would say is probably the better approach, but there are more considerations to be made outside the scope of the code shown), or; Your test should validate the IHttpActionResult being returned.
[ "stackoverflow", "0016345013.txt" ]
Q: SO_KEEPALIVE: Detecting connection lost or terminated I have multiple threads who have a socket open with a client application each. Each of those threads receive an instruction from a main thread to send commands to the client (commands could be run test, stop test, terminate session, exit....). Those threads are generic, they just have a socket per client and just send a command when the main thread asks it to. The client could exit or crash, or network could be bad. I have been trying to see how to figure out that my TCP session has ended per client. Two solutions that I have found that seem appropriate here. 1) Implement my own heartbeat system 2) Use keepAlive using setsockopt. I have tried 2) as it sounds faster to implement, but I am not sure of one thing: Will SO_KEEPALIVE generate a SIGPIPE when connection is interrupted please? I saw that it should be the case but never received a SIGPIPE. This is how my code looks: void setKeepAlive(int sockfd) { int optval; optval = 1; setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &optval, sizeof(optval)); optval = 1; setsockopt(sockfd, SOL_TCP, TCP_KEEPIDLE, &optval, sizeof(optval)); optval = 1; setsockopt(sockfd, SOL_TCP, TCP_KEEPCNT, &optval, sizeof(optval)); optval = 1; setsockopt(sockfd, SOL_TCP, TCP_KEEPINTVL, &optval, sizeof(optval)); } And my code that accepts connection is as follows: for (mNumberConnectedClients = 0; mNumberConnectedClients < maxConnections; ++mNumberConnectedClients) { clientSocket = accept(sockfd, (struct sockaddr *) &client_addr, &clientLength); // set KeepAlive on socket setKeepAlive(clientSocket); pthread_create(&mThread_pool[mNumberConnectedClients], NULL, controlClient, (void*) &clientSocket); } signal(SIGPIPE, test); .... And the test function: void test(int n) { printf("Socket broken: %d\n", n); } test() never gets triggered. Is it my understanding that is wrong please? I am not sure if SIGPIPE gets generated or not. Thanks a lot. A: If a keep-alive fails, the connection will simply be invalidated by the OS, and any subsequent read/write operations on that socket will fail with an appropriate error code. You need to make sure your reading/writing code is handling errors so it can close the socket, if it is not already doing so.
[ "stackoverflow", "0001501567.txt" ]
Q: Updating Linking Tables I've currently adding a bit of functionality that manages holiday lettings on top of a CMS that runs on PHP and MySQL. The CMS stores the property details on a couple of tables, and I'm adding a third table (letting_times) that will contain information about when people are staying at the property. Basic functionality would allow the user to add new times when a guest is staying, edit the times that the guest is staying and remove the booking if the guest no longer wants to stay at the property. Right now the best way that I can think of updating the times that the property is occupied is to delete all the times contained in the letting_times database and reinsert them again. The only other way that I can think to do this would be to include the table's primary key and do an update if that is present and has a value, otherwise do an insert, but this would not delete rows of data if they are removed. Is there a better way of doing this? A: Here's my recommendation for the LETTING_TIMES table: PROPERTY_ID, pk & fk EFFECTIVE_DATE, pk, DATE, not null EXPIRY_DATE, DATE, not null Setting the pk to be a composite key (PROPERTY_ID and EFFECTIVE_DATE) allows you to have more than one record for a given property while stopping them from being on the same day. There isn't an easy way to stop [sub?]lets from overlapping, but this would alleviate having to delete all times contained for a property & re-adding.
[ "stackoverflow", "0055802071.txt" ]
Q: Filtering data to only keep up to 10 duplicates in two variables, with missing data We have survey data for a survey that respondents can take multiple times, and we want to retain only the first 10 entries per respondent. The respondent must provide either an email address or a phone number, which we want to use to check for duplicates. Using R, I ordered the data by response date, and used the following code to add counts for the email addresses and phone numbers: surveydata <- surveydata %>% group_by(email) %>% mutate(email_count = row_number()) surveydata <- surveydata %>% group_by(phone) %>% mutate(phone_count = row_number()) I thought that I could just filter out the entries where email_count or phone_count was over 10. However this process also counted all of the NAs together, so if I filtered out all of the entries with counts over 10, I'd be deleting a lot of entries that we actually want to keep. I tried the following if statement to try to reset the email_count and phone_count if the email or phone entries were blank, but it didn't work: # This doesn't work if (is.na(surveydata$email)) { surveydata$email_count = 0 } Even though the code ran without error, none of the entries without emails had email_count set to 0. I used the following code to create new data tables that list the emails and phone numbers that occur more than 10 times: dup_emails <- data.frame(table(surveydata$email)) dup_phones <- data.frame(table(surveydata$phone)) dup_emails <- dup_emails[dup_emails$Freq > 10,] dup_phones <- dup_phones[dup_phones$Freq > 10,] I would like to create a For loop to check each row in surveydata where, if the email address or phone number match one of the email addresses or phone numbers in dup_emails or dup_phones, and the email_count or phone_count is over 10, then set a new variable "remove" to 1. After that, I could then filter out any data where "remove" = 1. I wrote the following code, but it's not working. All of the values for "remove" remain 0: # This doesn't work surveydata$remove <- 0 for (i in length(unique(dup_emails$Var1))) { if(surveydata$email == dup_emails[i,1] && thdsweeps$email_count > 10) { surveydata$remove <- 1 } } Any help or suggestions would be greatly appreciated! A: I figured out a solution. I created a new TRUE/FALSE variable for whether or not the email or phone variables were NAs. surveydata$email_remove <- is.na(surveydata$email) surveydata$phone_remove <- is.na(surveydata$phone) And then filtered out all rows where the email or phone counts were above 10 and the "remove" variables were FALSE. surveydata_clean <- surveydata[!(surveydata$email_count > 10 & surveydata$email_remove == FALSE),] surveydata_clean <- surveydata_clean[!(surveydata_clean$phone_count > 10 & surveydata_clean$phone_remove == FALSE),]
[ "stackoverflow", "0000989363.txt" ]
Q: Django Relational database lookups I cant figure out how to do relationships. I have a products model and a stores model. A product has a foreign key to the stores. So i would like to get the product name, and the store name in the same lookup. Since the products model is: class Products(models.Model): PrName = models.CharField(max_length=255) PrCompany = models.ForeignKey(Companies) And the company model is: class Companies(models.Model): ComName = models.CharField(max_length=255) How do i make django return ComName (from the companies model) when i do: Prs = Products.objects.filter(PrName__icontains=ss) A: Assuming you get results: Prs[0].PrCompany.ComName # Company name of the first result If you want all the company names in a list: company_names = [product.PrCompany.ComName for product in Prs]
[ "magento.stackexchange", "0000296723.txt" ]
Q: Magento 2: Setting div position on category page <div class="alocolumns clearfix"> <div class="column main"></div> <div class="sidebar sidebar-main"></div> </div> I need this way <div class="alocolumns clearfix"> <div class="sidebar sidebar-main"></div> <div class="column main"></div> </div>**strong text** I checked 2columns-left.xml,but here it shown only sidebar <?xml version="1.0"?> <layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_layout.xsd"> <update handle="1column"/> <referenceContainer name="columns"> <container name="div.sidebar.main" htmlTag="div" htmlClass="sidebar sidebar-main" after="main"> <container name="sidebar.main" as="sidebar_main" label="Sidebar Main"/> </container> <container name="div.sidebar.additional" htmlTag="div" htmlClass="sidebar sidebar-additional" after="div.sidebar.main"> <container name="sidebar.additional" as="sidebar_additional" label="Sidebar Additional"/> </container> </referenceContainer> </layout> How to change the position of the div ? A: You can add this line in your catalog_category_view.xml layout file app/design/frontend/Vendor/Theme/Magento_Catalog/layout/catalog_category_view.xml <move element="div.sidebar.main" destination="columns" before="-" /> Like <?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <move element="div.sidebar.main" destination="columns" before="-" /> </body> </page> After adding this line please run below command once php bin/magento cache:clean layout php bin/magento cache:flush layout Hope this will help you!
[ "stackoverflow", "0007736956.txt" ]
Q: Query to find columns that end with percent symbol % What T-SQL query I should use to find out all rows that have column1 ending with %? I am using SQL SERVER 2000. Sample data in column1: column1 ------- 100px 100% <- THIS ROW 200px 200% <- THIS ROW 300px 300% <- THIS ROW A: SELECT * FROM table WHERE column1 LIKE '%[%]' A: DECLARE @TMP TABLE(COL VARCHAR(MAX)) INSERT INTO @TMP VALUES ('100%') INSERT INTO @TMP VALUES ('100px') SELECT * FROM @TMP WHERE COL LIKE '%[%]' Please check out question Escape a string in SQL Server so that it is safe to use in LIKE expression for more examples of escaping special characters. The official documentation is in the MSDN article for the LIKE operator (SQL Server 2000).
[ "stackoverflow", "0012965573.txt" ]
Q: Force paperclip to rename files when custom interpolation change I use Paperclip to manage uploaded images for a certain Model in Rails 3. This model belongs_to another model. I want my image path to reflect this relationship, so I created a custom interpolation for this. The problem is that, I also want to be able to edit the name of the belongs_to objects, and I would like Paperclip to rename the files accordingly. Here is a simple example: class Make < ActiveRecord:Base attr_accessible :name has_many :models end class Model < ActiveRecord:Base attr_accessible :img, :make, :name belongs_to :make has_attached_file :img, :style => { :thumb => "100x100" }, :path => "/cars/:make_name/:name/:style/:hash.png", :hash_secret => "blabla" Paperclip.interpolates :make_name do |attachment, style| attachment.instance.make.name end Paperclip.interpolates :name do |attachment, style| attachment.instance.name end end So let's say I create a make Chevrolet and a Model Camaro, my image path will be /cars/chevrolet/camaro/thumb/my_hash.png If I decide to change the Chevrolet entry name to Chevy, Rails try to locate the image at /cars/chevy/camaro/thumb/my_hash.png, but as the image was not renamed, it's not found. How do I force Paperclip to update all the images paths when an entry is renamed? Thanks! A: A more robust file path could use the make id instead of make name. I.e., /cars/:make_id/:name/:style/:hash.png would continue to work when the make name is changed.
[ "stackoverflow", "0049419745.txt" ]
Q: How to create a new column with unique values My Table TB_PRUEBAS has a column called "CltsVcdos" with several repeated customer's Id's. Now, I want to add a new column that shows me a 1 when the Id is unique, and 0 when the Id is repeated. Part of the Query That's what I want Thank you! A: Case When ((ROW_NUMBER() OVER( PARTITION BY CltsVcdos ORDER BY CltsVcdos ASC) ) =1) then 1 else 0 end You can Use above condition to get the UNIQUEVALUES. Following example explains it further CREATE TABLE [dbo].[TB_PRUEBAS]( [CltsVcdos] [int] NULL ) ON [PRIMARY] INSERT [dbo].[TB_PRUEBAS] ([CltsVcdos]) VALUES (101) INSERT [dbo].[TB_PRUEBAS] ([CltsVcdos]) VALUES (101) INSERT [dbo].[TB_PRUEBAS] ([CltsVcdos]) VALUES (101) INSERT [dbo].[TB_PRUEBAS] ([CltsVcdos]) VALUES (102) INSERT [dbo].[TB_PRUEBAS] ([CltsVcdos]) VALUES (102) INSERT [dbo].[TB_PRUEBAS] ([CltsVcdos]) VALUES (104) SELECT ROW_NUMBER() OVER(ORDER BY CltsVcdos ASC) AS Row#, [CltsVcdos], (ROW_NUMBER() OVER( PARTITION BY CltsVcdos ORDER BY CltsVcdos ASC) ) As RepeatedRowNumber , Case When ((ROW_NUMBER() OVER( PARTITION BY CltsVcdos ORDER BY CltsVcdos ASC) ) =1) then 1 else 0 end As UNIQUEVALUES FROM [dbo].[TB_PRUEBAS] P
[ "chemistry.stackexchange", "0000015973.txt" ]
Q: Are phenylboranes susceptible to ipso or meta substitution? Are phenylboranes susceptible to ipso or meta electrophilic aromatic substitution, i.e. what's the regioselectivity? A: A SciFinder search turns up very little on this type of transformation. Qui and coworkers run halogenations of phenyl boronate esters using N-halosuccinimide using gold(III) catalysis. The regioselectivity was essentially 1:1:1 for ortho:meta:para. When the reaction was carried out with other substituents as well, the other substituent's directing group preference dominated the regioselectivity. Gold(III)-Catalyzed Halogenation of Aromatic Boronates with N-Halosuccinimides There is one other reaction in SciFinder that is relevant, however I don't have access to the full text (and it's in Russian, so I wouldn't be able to read it anyway). The substrate is a benzene ring substituted with a borane cluster. The reported regioselectivity is 80:20 for meta:para. Electrophilic substitution in the benzene ring of 9-phenyl-o- and -m-carborane. Zakharkin, L. I. et al Zhurnal Organicheskoi Khimii, 23(8), 1691-5; 1987.
[ "stackoverflow", "0013003493.txt" ]
Q: Double variable if statement not working I'm making a double variable if statement and it keeps returning an error. I don't know what's wrong: variable = float(0) for index in range(10): variable = variable + float(2) if x <= float(variable/3) and > float(variable-2.0/3): # do something else: pass or something like that. This is the basic structure. Why does it keep highlighting the > in red whenever I try to run it? A: Python supports regular inequalities as well, so you could just write this: if variable - 2.0 / 3 < x <= variable / 3: # ...
[ "stackoverflow", "0020538638.txt" ]
Q: How to pick a value in data.table? My data is of the following form structure(list(atp = c(1, 0, 1, 0, 0, 1), len = c(2, NA, 3, NA, NA, 1), Day_1 = c(8, 7, 8, 9, 6, 6), Day_2 = c(94, 94, 102, 97, 102, 100), Day_3 = c(104, 162, 133, 142, 96, 122)), .Names = c("atp", "len", "Day_1", "Day_2", "Day_3"), row.names = c(NA, -6L), class = "data.frame") I want to attain the following output structure(list(atp = c(1, 0, 1, 0, 0, 1), len = c(2, NA, 3, NA, NA, 1), Day_1 = c(8, 7, 8, 9, 6, 6), Day_2 = c(94, 94, 102, 97, 102, 100), Day_3 = c(104, 162, 133, 142, 96, 122), output = c(94, NA, 133, NA, NA, 6)), .Names = c("atp", "len", "Day_1", "Day_2", "Day_3", "output"), row.names = c(NA, -6L), class = "data.frame") which is basically depending on column 2 values it picks the value from column 3, 4 or 5. I have achieved it through the following code result<-cbind(y, output=apply(y, 1, function(r) r[r["len"]+2])) But this process is very time taking. Is there any way to speed up the process? How can I use data.tables for this? A: One possible approach: result <- cbind(y, output = unlist(y[3:5])[nrow(y) * (y$len -1) + seq.int(nrow(y))]) Another one (this should be faster): result <- cbind(y, output = y[3:5][cbind(seq.int(nrow(y)), y$len)]) Both approaches result in: # atp len Day_1 Day_2 Day_3 output # 1 1 2 8 94 104 94 # 2 0 NA 7 94 162 NA # 3 1 3 8 102 133 133 # 4 0 NA 9 97 142 NA # 5 0 NA 6 102 96 NA # 6 1 1 6 100 122 6
[ "stackoverflow", "0038155105.txt" ]
Q: Negative Margin-Top Not Working in Chrome I have a transparent nav using Bootstrap with an image that has a margin-top: -100px CSS value so it shows under the navbar. It renders properly in IE: But for some reason the image isn't recognizing the negative margin-top in Chrome: My HTML is slightly complicated, but needs to be that way (for a variety of reasons): <div class="hero-image-row"> <div class="hero-image-outer text-center"> <div class="hero-image-inner text-center"> <%= image_tag 'Background 1.jpg', class: "hero-image",alt: "Delicious-looking hot dogs on a manly grill. Just like God intended." %> </div> <!-- hero-image-inner --> </div> <!-- hero-image-inner --> </div> <!-- row --> And my CSS is as follows: /* NAVIGATION */ #custom-bootstrap-menu.navbar { margin-bottom: 0px !important; } #custom-bootstrap-menu.navbar-default .navbar-brand { color: black; } #custom-bootstrap-menu.navbar-default { font-size: 18px; font-family: $font-typewriter; background-color: $transparent-white !important; border: none; border-radius: 0px; } #custom-bootstrap-menu.navbar-default .navbar-nav>li>a { color: black; } #custom-bootstrap-menu.navbar-default .navbar-nav>li>a:hover, #custom-bootstrap-menu.navbar-default .navbar-nav>li>a:focus { color: black; background-color: $transparent-black !important; } #custom-bootstrap-menu.navbar-default .navbar-toggle { border-color: black; } #custom-bootstrap-menu.navbar-default .navbar-toggle:hover, #custom-bootstrap-menu.navbar-default .navbar-toggle:focus { background-color: $transparent-black; } #custom-bootstrap-menu.navbar-default .navbar-toggle:hover .icon-bar, #custom-bootstrap-menu.navbar-default .navbar-toggle:focus .icon-bar { background-color: $transparent-black; } #custom-bootstrap-menu.navbar-default .navbar-toggle { border-color: black !important; } #custom-bootstrap-menu.navbar-default .navbar-toggle .icon-bar { background: black !important; } /* HEROS */ .hero-image-row { margin-top: -50px !important; overflow-x: hidden !important; width: 100% !important; } .hero-image-outer { width: 300%; height: 400px; overflow-y: hidden !important; } .hero-image-inner { width: 66%; overflow-x: hidden !important; } .hero-image { height: 400px; margin-left: -50%; z-index: 0 !important; } @media screen and (min-width: 700px) { .hero-image-outer { width: 100%; } .hero-image-inner { width: 100%; height: 400px; } .hero-image { width: 100%; height: auto; margin-left: 0%; } } .overlap-hero-image { margin-top: -300px; height: 300px; } .height-auto { height: auto !important; } Can anyone help me diagnose why Chrome is acting up here? I have used similar code on other sites and have never had an issue. I have tried it with and without the SCSS variables for transparency, so I know that's not the issue. It really is something with the margin. ADDED NAVBAR CODE: <div id="custom-bootstrap-menu" class="navbar navbar-default " role="navigation"> <div class="container-fluid"> <div class="navbar-header"><a class="navbar-brand" href="/">The Manly Art of BBQ</a> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-menubuilder"><span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button> </div> <div class="collapse navbar-collapse navbar-menubuilder"> <ul class="nav navbar-nav navbar-right"> <li><a href="/products">Man Rules</a></li> <li><a href="/about-us">BBQ</a></li> <li><a href="/contact">My Mancard</a></li> </ul> </div> <!-- collapse --> </div> <!-- container-fluid --> </div> <!-- custom-bootstrap-menu --> A: I ended up fixing it using this for the top navbar to remove it from the flow: #custom-bootstrap-menu { position: absolute; width: 100%; }
[ "scifi.stackexchange", "0000149103.txt" ]
Q: What is Chirrut Imwe`s staff made out of? We see Chirrut Imwe beat many Stormtroopers unconcious with his staff and several times pieces of armour visibly chip and shatter when struck. Do we know exactly what Chirrut Imwe's staff is made out of? It looks like it's wood with a possible steel grip or handle, but Chirrut hits troopers with both the steel and wooden ends so I don't think it's the grip that makes it especially powerful. A: Wood She found the speaker at last, seated on the ground a few steps down the line of stalls. He was dressed simply, in a dark shirt and charcoal robe in the local style, and his smooth skin fought gamely against the years that infected his words. His eyes were milky and unfocused, and at his side lay a sturdy wooden staff in the dust. Are there trees left on Jedha? Jyn wondered. Rogue One: A Star Wars Story Whether it’s made of something sturdier than our puny Earth wood is uncertain, but certainly quite possible. There are woods in Star Wars that are quite hard, such as that of the brylark tree. A: From the film's Visual Guide CHIRRUT'S STAFF Chirrut carries a flame-hardened uneti-wood staff to help guide his path as he walks through the streets of Jedha. The top is capped with a metal lamp that contains a kyber sliver. Designed as a symbolic source of inner illumination, it also allows Chirrut to better gauge where the end of the staff is, as he can hear both the battery and crystal harmonic. Star Wars: Rogue One: The Ultimate Visual Guide