text
stringlengths
64
89.7k
meta
dict
Q: Javascript. Restrict the user to input the same number characters as in the textbox I will flash a scrambled word and then the user will type in what the scrambled word is. So far I have this code. This is for shuffle and display. document.getElementById("shuffle").value = shuffle(document.getElementById("word").value); var shuffledword = document.getElementById("shuffle").value; var z = shuffledword.split("").join('&nbsp;&nbsp;&nbsp;&nbsp;'); var x=document.getElementById("demo"); x.innerHTML=z; var str=document.getElementById("demo").innerHTML; var n=str.replace(charcode,"..."); document.getElementById("demo").innerHTML=n; What I want is to restrict the user to input the same number letters as in the shuffled word. Example: the word is "DOOMED"; I want to make it so that the user cannot click the letter D and O three times, but only once or twice. Same for the other letters, depending on the number letters in the shuffled word. It this possible? A: // Set an object with each letters of the (shuffled) word and their count var letters = {}; for (var i=0 ; i<word.length ; i++) { var c = word.charAt(i); if ( ! letters[c]) letters[c] = 1; else letters[c]++; } ... function process_user_char(K) { // When user enter letter K if ( ! letters[K]) { alert("You cannot enter " + K); return false; } else { letters[K]-- ; return true; } } .... // To check wether user entered all letters, returns Yes or No function check_if_user_entered_all_letters() { for (var o in letters) { if (letters[o]) return "No"; } return "Yes"; } edit Added return true / false in process_user_char to integrate into onkeypressed. Here is the jsfiddle.
{ "pile_set_name": "StackExchange" }
Q: Why I can not pass a variable between controller functions in codeigniter I have this in a codeigniter controller: <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Test extends CI_Controller { public $idioma; public function index() { parent::__construct(); // get the browser language. $this->idioma = strtolower(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2)); $data["idioma"] = $this->idioma; $this->load->view('inicio', $data); } public function hello(){ $data["idioma"] = $this->idioma; $this->load->hello('inicio', $data); } } Inicio view: <a href="test/hello">INICIO <?php echo $idioma ?></a> hello view: Hello <?php echo $idioma ?> The inicio view works great, but when the hello view is loaded there's nothing displayed. Any idea why this is not working? A: If you wish to set a class property automatically you would do it in the constructor, not in index(). index() does not run before other methods if they are called directly. In your case I assume you're calling hello via the url as test/hello class Test extends CI_Controller { public $idioma; public function __construct(){ parent::__construct(); // get the browser language. $this->idioma = strtolower(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2)); } public function index() { $data["idioma"] = $this->idioma; $this->load->view('inicio', $data); } public function hello(){ $data["idioma"] = $this->idioma; $this->load->hello('inicio', $data); } }
{ "pile_set_name": "StackExchange" }
Q: Is it bad practice to keep increasing rotational degrees (over 360) I am experimenting with a creative javascript framework P5.js and often times I'm using degrees to rotate a sphere. However, I do this by continuously increasing a variable and basing the rotation off of that variable. Is it a bad practice to infinitely increase a variable? Should I reset the rotation to 0 when it hits 360? Example: this.deg = 0; this.show = function(){ rotateY(radians(this.deg)); sphere(this.x, this.y, this.r); this.deg++; // Continuously increasing the deg :( } A: Well, it depends. If you talking about wether it affects any performance of p5.js then No, as it most probably already do something like this.deg%=360 on degree anyways. However you should be careful with very large integers in JavaScript, as you might lose precision for very large integers or might overflow the size. Besides that, you should really keep the things under 360 so to avoid any confusion during debugging. Any Easy way of doing this is using modulus operator in your code, like so this.deg = 0; this.show = function(){ rotateY(radians(this.deg)); sphere(this.x, this.y, this.r); this.deg++; this.deg%=360; // keep it under 360 deg , always } Read More about Safe Limit for Integers in JavaScript : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER and this stackoverflow question : What is JavaScript's highest integer value that a Number can go to without losing precision?
{ "pile_set_name": "StackExchange" }
Q: Why is $mg$ positive and $N$ negative in this problem? In this problem: A car of mass $430\ \mathrm{kg}$ travels around a flat, circular race track of radius $178\ \mathrm{m}$. The coefficient of static friction between the wheels and the track is $0.266$. The same car now travels on a straight track and goes over a hill with radius $178\ \mathrm{m}$ at the top. What is the maximum speed that the car can go over the hill without leaving the road? Correct answer: $41.766\ \mathrm{m/s}$. Explanation: $$\frac{mv^2}{r} = mg - N$$ where $N$ is the normal force acting on the car from the ground. The car will fly off the ground just when $N = 0$ so the maximum speed allowed will be $$\begin{align}v_{\text{max}} &= \sqrt{gr} \\ &= \sqrt{(9.8\ \mathrm{m/s^2})(178\ \mathrm{m})} \\ &= 41.766\ \mathrm{m/s}.\end{align}$$ The car is not driving upside down! So why is the force of gravity positive and the normal force considered negative in this problem? A: The centripetal acceleration always points toward the center of the circle. In this case, the center of the circle is below the car, so the centripetal acceleration points downward. Now, you'll notice that, in the given solution, the centripetal acceleration term is positive. That means the writer has chosen a coordinate system where positive is downward, and negative is upward. Any force that acts downward (like gravity) will be represented by a positive term ($+mg$), and any force that acts upward (like the normal force) will be represented by a negative term ($-N$). Alternatively, you could make the opposite choice: pick positive to be up, and negative to be down. In that case, the centripetal acceleration, since it points downward, would be represented by a negative term, $-\frac{mv^2}{r}$. Same for gravity ($-mg$). And the normal force, pointing upward, would be represented by a positive term, $+N$.
{ "pile_set_name": "StackExchange" }
Q: Primefaces p:panelGrid cosider a comment as an component I'm using the component p: panelGrid, and within it put various components of my form. I was surprised when, in order to facilitate understanding of the code, I put a comment, and he regarded it as a component and ordered form based on the comment. Can anyone explain to me why this happens? A: Try setting javax.faces.FACELETS_SKIP_COMMENTS to true in web.xml. <context-param> <param-name>javax.faces.FACELETS_SKIP_COMMENTS</param-name> <param-value>true</param-value> </context-param>
{ "pile_set_name": "StackExchange" }
Q: How to remove spacific values from url string I have this URL string: http://jackson/search/page/3/?features=Sea%20View&submit=search Now I want to remove this part from ul: page/3/ when page is reload. I am not good with jQuery and regex so I will appreciate if you help me. Note: Page number can be anything form 1 to 100. Thanks. A: Have your tried using String.replace() var url = "http://jackson/search/page/3/?features=Sea%20View&submit=search"; url = url.replace(/page\/\d+\//, '');
{ "pile_set_name": "StackExchange" }
Q: How does one open the HUD from the command line. Alt is used to open the HUD in 12.04. I'd like to use alt to execute a second action as well as open the HUD by having alt execute an executable script. So Alt = script, that does HUD and other stuff. I know how to do all of this except call the HUD from the command line. A: The HUD service is available as a service on DBus, so if you'd just like to poll it for information you can do that with a gdbus command, like this. gdbus call --session --dest com.canonical.hud --object-path /com/canonical/hud --method com.canonical.hud.StartQuery "my query" 5 If you're trying to get Unity to show the HUD prompt you can do that with the XTest extension using xdotool like this: xdotool key alt If you're interested in playing with HUD it's probably best to use the hud-gtk tool which is in the indicator-appmenu-tools package. A: You can query the hud from the command line using hud-cli, but it doesn't actually raise the Unity side of hud and it doesn't let you activate the results. It's really only useful for testing hud searches. I don't think there is a way to do what you are describing at this time.
{ "pile_set_name": "StackExchange" }
Q: How to remove native mac title bar on a Java Swing app I have a quick question that I don't think I've seen before on stack exchange. This might be due in part to me not knowing what to ask, but regardless I thought I'd post a question with the wording I'd use for any other beginners. My question is related to the UI design of a Java Swing application. I am using the NetBeans GUI designer to quickly lay out my idea, but as I am doing it on a mac, I'm not a big fan of the native "close, minimize, expand" buttons. I would like to achieve something similar to the discord style which looks like this. It doesn't have to be exactly the same but I'm just trying to get an idea for what I would do. I'm mainly just looking for pointers into where I would go about finding the information to do this as I would like to actually gain some knowledge from this. (As opposed to having you just fix my code) Any help is greatly appreciated and I look forward to your responses; thanks. A: you can remove the title bar using undecorated property in your JFrame properties. Just go to properties and check the undecorated as checked. Then you have use your custom designed title bar with "close","maximize" and "minimize" buttons or what you like and you have to code for mouse pointer to drag the Frame to any location in screen.
{ "pile_set_name": "StackExchange" }
Q: jboss 7 deploy 2 jars : one sharing other I have 2 maven projects ProjectA and ProjectB. pom.xml in ProjectA has dependency of ProjectB and uses classes from there. After mvn install i copy both .jar files into standalone/deployments in jboss7 and run ./standalone.sh. The exception is ClassNotFoundException and deploying fail. pom.xml of ProjectA ` <modelVersion>4.0.0</modelVersion> <groupId>com.duracel</groupId> <artifactId>projectA</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>com.duracel</groupId> <artifactId>projectB</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <dependency> <groupId>javax.ejb</groupId> <artifactId>ejb-api</artifactId> <version>3.0</version> </dependency> </dependencies> ` pom.xml of ProjectB ` <modelVersion>4.0.0</modelVersion> <groupId>com.duracel</groupId> <artifactId>projectB</artifactId> <version>0.0.1-SNAPSHOT</version> ` both surronded by <project> tags ofcorz A: Every artifact deployed in JBoss has his own classloader. From your question it is not clear what you want to do or what is inside the jar files. In general cases web applications are deployed as war or as ear file. Both can contain different jar files and share one classloader. If project b contain only some until classes than you can optionally install it as a module. For more information about modules have a look here jboss modules
{ "pile_set_name": "StackExchange" }
Q: Angular 2: Inserting capture element dynamically when creating components (dynamically) My goal is to create a child component and insert into the parent component template. There are examples to do this. However, I create parent component template (DOM Elements) dynamically in the parent component while most of the examples shown statically create the template with the capture element. Here's the code app.component import {Component, ViewChild, ViewContainerRef, ComponentFactoryResolver} from '@angular/core'; import {NewChildComponent} from "./newChild.component"; @Component({ selector: 'app-main', templateUrl: 'app.component.html' }) export class AppComponent { @ViewChild('captureElement', {read: ViewContainerRef}) captureElement: ViewContainerRef; constructor (private componentFactoryResolver: ComponentFactoryResolver) { var childComponent = this.componentFactoryResolver.resolveComponentFactory(NewChildComponent); var myArea = document.getElementById('myArea'); var myRow = document.createElement("div"); myArea.appendChild(myRow); //I want to add the capture element #myCapture as a child of myRow //Add something like this <div #captureElement></div> programmatically through JS/TS // How can I do this? // I then create the component this.parent.createComponent(NewChildComponent); } app.component.html <div id="myArea"> <!-- Static way of doing it --> <!--<div #captureElement></div>--> </div> Instead of statically defining in #captureElement where the child component would be inserted, I would like to create it dynamically in the parent component and make it a child component. Here are a list of questions I referred before I asked this question Angular2: Insert a dynamic component as child of a container in the DOM How to place a dynamic component in a container Angular 2 dynamic tabs with user-click chosen components Tried a couple of things Tried to create a div element with a #captureElement as an attribute programmatically but that doesn't work. Tried to create a random element programmatically and use ViewContainerRef to find it. That doesn't work either. A: We can't create a ViewContainerRef, as a ViewContainerRef only exists within a view. In 2.3.0, attachView was introduced which allows you to be able to attach change detection to the ApplicationRef. You can create some class that will encapsulate your logic like: export class HtmlContainer { private attached: boolean = false; private disposeFn: () => void; constructor( private hostElement: Element, private appRef: ApplicationRef, private componentFactoryResolver: ComponentFactoryResolver, private injector: Injector) { } attach(component: Type<any>) : ComponentRef<any> { if(this.attached) { throw new Error('component has already been attached') } this.attached = true; const childComponentFactory = this.componentFactoryResolver.resolveComponentFactory(component); let componentRef = childComponentFactory.create(this.injector); this.appRef.attachView(componentRef.hostView); this.disposeFn = () => { this.appRef.detachView(componentRef.hostView); componentRef.destroy(); }; this.hostElement.appendChild((componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0]); return componentRef; } dispose() { if(this.attached) { this.disposeFn(); } } } this class is just helper that 1) resolves your dynamic component this.componentFactoryResolver.resolveComponentFactory(component); 2) then compiles component by calling compFactory.create 3) after that registers its changeDetector (componentRef.hostView extends ChangeDetectorRef) by calling mentioned above appRef.attachView (otherwise change detection won't work for your component) 4) and finally appends the rootNode of your component to the host element this.hostElement.appendChild((componentRef.hostView as EmbeddedViewRef<any>).rootNodes[0]); You can use it as follows: @Component({ selector: 'my-app', template: `<div id="myArea"></div> `, entryComponents: [NewChildComponent] }) export class AppComponent { containers: HtmlContainer[] = []; constructor( private appRef: ApplicationRef, private componentFactoryResolver: ComponentFactoryResolver, private injector: Injector) { } ngOnInit() { var myArea = document.getElementById('myArea'); var myRow = document.createElement("div"); myArea.appendChild(myRow); this.addComponentToRow(NewChildComponent, myRow, 'test1'); this.addComponentToRow(NewChildComponent, myRow, 'test2'); } addComponentToRow(component: Type<any>, row: HTMLElement, param: string) { let container = new HtmlContainer(row, this.appRef, this.componentFactoryResolver, this.injector); let componentRef = container.attach(component); componentRef.instance.param1 = param; this.containers.push(container); } ngOnDestroy() { this.containers.forEach(container => container.dispose()); } } Plunker Example See also Angular2 - Component into dynamicaly created element Angular2 Dynamic Component Injection in Root https://github.com/angular/material2/blob/2.0.0-beta.1/src/lib/core/portal/dom-portal-host.ts#L30-L86 (you can find here fallback for angular < 2.3.0)
{ "pile_set_name": "StackExchange" }
Q: any possible method concatenate date and time as an integer Is there any possibility to get get and time as an integer in php. in php am getting the date of the server as $todayDate and time as $currentTime $todayDate = date("Y-m-d"); // get current date value $currentTime = date("h:i:s"); // get current time value if current date is 2017-05-26 an time is 15:20 i require the integer value as 201705261520 if there is any method please suggest. A: you don't need any new method simply you can do something like this $todaydate=date("Ymdhis");
{ "pile_set_name": "StackExchange" }
Q: Escaping special characters in ruby This is a common question, but just can't seem to find the answer without resorting to unreliable regular expressions. Basically if there is a \302\240 or similar combination in a string I want to replace it with the real character. I am using PLruby for this, hence the warn. obj = {"a"=>"some string with special chars"} warn obj.inspect NOTICE: {"Outputs"=>["a\302\240b"]} <- chars are escaped warn "\302\240" NOTICE: <-- there is a non breaking space here, like I want warn "#{json.inspect}" NOTICE: {"Outputs"=>["a\302\240"b]} <- chars are escaped So these can be decoded when I use a string literal, but with the "#{x}" format the \xxx placeholders are never decoded into characters. How would I assign the same string as the middle command yields? Ruby Version: 1.8.5 A: You mentioned that you're using PL/ruby. That suggests that your strings are actually bytea values (the PostgreSQL version of a BLOB) using the old "escape" format. The escape format encodes non-ASCII values in octal with a leading \ so a bit of gsub and Array#pack should sort you out: bytes = s.gsub(/\\([0-8]{3})/) { [ $1.to_i(8) ].pack('C') } That will expand the escape values in s to raw bytes and leave them in bytes. You're still dealing with binary data though so just trying to display it on a console won't necessarily do anything useful. If you know that you're dealing with comprehensible strings then you'll have to figure out what encoding they're in and use String methods to sort out the encoding.
{ "pile_set_name": "StackExchange" }
Q: How do I change the background color of a selected react-bootstrap ToggleButton? I'm using react-bootstrap and am trying to change the background color of a selected <ToggleButton> to blue. e.g.: <ButtonToolbar> <ToggleButtonGroup type="radio" name="options" value={...} onChange={...}> <ToggleButton ... /> <ToggleButton ... /> <ToggleButton ... /> </ToggleButtonGroup> </ButtonToolbar> So instead of the dark grey you see below for M/W/F I'd like blue. I've tried a billion CSS tricks and just can't get it to take. Thanks! A: You can do this is CSS by adding the following class and style rule. !important is needed to override the react-bootstrap library's style. .Btn-Blue-BG.active { background-color: blue !important; } and <ToggleButton className="Btn-Blue-BG" ...> See demonstration below: https://codesandbox.io/s/6nwkwnn29z
{ "pile_set_name": "StackExchange" }
Q: Proper way to use a config file? I just started using a PHP framework, Kohana (V2.3.4) and I am trying to set up a config file for each of my controllers. I never used a framework before, so obviously Kohana is new to me. I was wondering how I should set up my controllers to read my config file. For example, I have an article controller and a config file for that controller. I have 3 ways of loading config settings // config/article.php $config = array( 'display_limit' => 25, // limit of articles to list 'comment_display_limit' => 20, // limit of comments to list for each article // other things ); Should I A) Load everything into an array of settings // set a config array class article_controller extends controller{ public $config = array(); function __construct(){ $this->config = Kohana::config('article'); } } B) Load and set each setting as its own property // set each config as a property class article_controller extends controller{ public $display_limit; public $comment_display_limit; function __construct(){ $config = Kohana::config('article'); foreach ($config as $key => $value){ $this->$key = $value; } } } C) Load each setting only when needed // load config settings only when needed class article_controller extends controller{ function __construct(){} // list all articles function show_all(){ $display_limit = Kohana::config('article.display_limit'); } // list article, with all comments function show($id = 0){ $comment_display)limit = Kohana::config('article.comment_display_limit'); } } Note: Kohana::config() returns an array of items. Thanks A: If you are reading a group of configuration items for a controller, store them in class member ($this->config), if you are reading a single configuration item; read it individually.
{ "pile_set_name": "StackExchange" }
Q: Generate Bootstrap tooltip on-the-fly I have a page with a text and some words in the text can change dynamically. These words have an element and should have a tooltip. When the user hovers the word (or I guess on a touch device clicks it), a tooltip should be generated using generateSpecialMarkupElement($(element).text()). Once the HTML has been rendered to the DOM another JavaScript function has to be called replaceMarkupHTML(). I don't have control over these functions unfortunately. Now I'm wondering if there is a simple way in bootstrap get this done. For instance a before event to run the first function and an after event to call the second one. Here is a simple example text and simplified versions of the functions: http://jsfiddle.net/8aqz5auk/1/ So is there a bootstrap-way of hooking/intercepting this kind of thing? Or is there maybe another simple way it could be done? Edit: I just had an idea. When bootstrap shows a tooltip, it seems to inject an element into the DOM. The interesting part is the container with the class 'tooltip-inner'. So I tried to listen on the body for new elements matching '.tooltip-inner' to be injected and whenever that happens I try to manipulate it: $('body').on('DOMNodeInserted', '.tooltip-inner', function () { var el = $(this) el.html("") // empty the tooltip element el.append(generateSpecialMarkupElement(el.text())) // insert the generated markup element replaceMarkupHTML() // replace the markup element with normal html }); Unfortunately it doesn't work. It just throws a a million errors and the site freezes when I try it. Edit 2: Thanks to Chris Barr, I got a little bit closer: http://jsfiddle.net/8aqz5auk/2/ But the tooltip doesn't always show up and the position of the tooltip seems to be kind of wrong (shows up on top of the word, rather then next to/above/below/...). A: You might want to look into the tooltip events listed in the docs: https://getbootstrap.com/docs/3.3/javascript/#tooltips-events $('.elements-with-tooltips').on('show.bs.tooltip', function () { // do something… }) You can run a function: before being shown, after being shown, before hiding, after hiding, and when the element is inserted into the DOM.
{ "pile_set_name": "StackExchange" }
Q: Cant resolve setLevel on HttpLoggingInterceptor Retrofit2.0 I am using Retrofit and I want to log my response and other things, I am using this https://futurestud.io/tutorials/retrofit-2-log-requests-and-responses type but I am facing Cant resolve setLevel error HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(Level.BODY); // i am getting error on this OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); httpClient.addInterceptor(logging); //this is also getting error I am using this compile 'com.squareup.okhttp3:logging-interceptor:3.3.1' and Retrofit compile 'com.squareup.retrofit2:converter-gson:2.1.0' dependency. A: Write your interceptor code inside the getClient() method like public class RestClient { public getClient() { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); } } A: Add this dependency to your app's gradle: compile 'com.squareup.okhttp3:logging-interceptor:3.2.0' And use it like below: Build your OkHttpClient like below: final OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder(); HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); okHttpClientBuilder.addInterceptor(interceptor); okHttpClientBuilder.connectTimeout(RestConstants.DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS) return okHttpClientBuilder.build(); And set it to your Retrofit as Client. I recommend you to check if your app is Debuggable and than set your log interceptor. So in production you'll not log api results. A: If you're using okhttp3, make sure you import the okhttp3(instead of okhttp) logging: change implementation 'com.squareup.okhttp:logging-interceptor:3.14.1' to implementation 'com.squareup.okhttp3:logging-interceptor:3.14.1'
{ "pile_set_name": "StackExchange" }
Q: changing font format for each sheet I am kind of stuck with changing a font size for each sheet. I also want to change the font into bold when a value in the "E" column is below 18. Dim ws As Worksheet ' Loop through all of the worksheets in the active workbook. For Each ws In ActiveWorkbook.Worksheets ' format font of currently looped worksheet object feferenced by WS With ws.Cells.Font .Name = "Calibri" .Size = 9 .Strikethrough = False .Superscript = False .Subscript = False .OutlineFont = False .Shadow = False .Underline = xlUnderlineStyleNone .TintAndShade = 0 .ThemeFont = xlThemeFontNone cr = ws.Cells(.Rows.Count, "A").End(xlUp).Row If Cells(cr, 5).Value < 18 Then Selection.Font.Bold = True End If End With Next ws Any tips for me to fix the problem. I am getting an error 438 on this line: cr = .Cells(.Rows.Count, "A").End(xlUp).Row I also tried cr = ws.Cells(.Rows.Count, "A").End(xlUp).Row Both codes are not working...Help A: What error have you got? I think the code above would change the font size just fine. BUT the code changing font for cells with value under 18 to bold doesn't work. You want to change each cell to bold, if the rule applied, right? Try "conditional formating" (will apply each time cell value changed and < 18) or modify your code like this (will apply each time you run the macro): ... Dim i as integer cr = ws.Cells(.Rows.Count, "A").End(xlUp).Row For i = 1 to cr 'loop through all value in column e If .cells(i,5).value <18 then .cells(i,5).font.bold = true Next i ....
{ "pile_set_name": "StackExchange" }
Q: Using one pthread_mutex_t and multiples pthread_cond_t with pthread_cond_wait() According to Open Group Base Specifications Issue 7, IEEE Std 1003.1-2008, a single condition variable (pthread_cond_t) shouldn't be used along different mutexes (pthread_mutex_t) in pthread_cond_wait() while at least one thread is waiting on this condition variable: eg. pthread_cond_wait(&cond1, &mutex1) can't be used in parallel with pthread_cond_wait(&cond1, &mutex2): this behavor is unspecified. But it is not specified if using a single mutex with multiple condition variables is allowed, eg: pthread_cond_wait(&cond1, &mutex1) in parallel with pthread_cond_wait(&cond2, &mutex1). I think such construction should be avoided to allow safe (two way) dynamic binding [...] formed between that mutex and condition variable Could someone comment on this issue ? A: It's perfectly fine to use the same mutex for multiple condition variables, just not the reverse. One way to think about this is: Part of the contract of pthread_cond_wait is that when the calling thread awakens from its wait, it will own the locked mutex, which makes sense only if there's just one mutex associated with the condition variable. To see why you might want to do this, imagine a design where you have a number of global counters protected by a single mutex (user count, # of open files, etc.). You could then quite reasonably have multiple condition variables you might want to wait on, all associated with that single mutex: pthread_cond_wait(&usercount_lessthan_limit_cond, &global_mutex); ... pthread_cond_wait(&openfilecount_lessthan_limit_cond, &global_mutex); ...etc...
{ "pile_set_name": "StackExchange" }
Q: How to get value from RadioButtonList using jQuery? I need to find out what is the selected value of RadioButtonList: <div class="editor-field radio-button-list"> <%= Html.RadioButtonListForEnum("Type", Model.Type)%> </div> I tried to use: $("#Type").find(":checked").val() but all I get is "undefined"... Any ideas? A: I'm not sure the id of Type is coming out how you think it is. Or maybe Type is a duplicate Id. In any event, I think this is what you want $(".editor-field.radio-button-list").find(":checked").val() A: It's working for server side control: $("#<%=ControlID.ClientID%>").find(":checked").val();
{ "pile_set_name": "StackExchange" }
Q: How can I make a low poly triangular pendentive? I accidentally made this once, but I forgot how I did it. It's 3D, and it's the same dimension of a regular cube. I know how to make the arches, but I don't know how to fill it once the arches are in place. Edit: I'd like an ability to see it as smooth while low-poly, if it's possible. I guess a triangular pendentive is a better way to explain it :) Any help appreciated! A: You can use circle meshes to create the exact shape in your example image, if I understand correctly. I created circles on three faces of a standard cube, removed doubles, deleted excess vertices, filled the faces, and fixed normals: A: Add circle, set vertices to 3. Convert it to 2D bezier curve and scale handles. After that add sphere, scale rotate as you want. Set top view and do Knife Project with your curve object. Invert selection in face mode and delete faces.
{ "pile_set_name": "StackExchange" }
Q: Calculate distance longitude latitude of multiple in dataframe R I'm not sure if this is the right place to ask my question (I'm new to R and this site). My question is the following: how can I calculate the distance between longitude and latitude points? I searched at this site for an answer to my problem, but the answers only considered 2 points (while I have a data set containing more than 207000 rows). I have a dataframe called 'adsb_relevant_columns_correct_timedifference' containing the following columns: Callsign, Altitude, Speed, Direction, Date_Time, Latitude, Longitude. Callsign Altitude Speed Direction Date_Time Latitude Longitude A118 18000 110 340 2017-11-06 22:28:09 70.6086 58.2959 A118 18500 120 339 2017-11-06 22:29:09 72.1508 58.7894 B222 18500 150 350 2017-11-08 07:28:09 71.1689 59.1234 D123 19000 150 110 2018-05-29 15:13:27 69.4523 68.1235 I would like to calculate the distance (in meters) between each measurement (each row is a new measurement)and add this as a new column called 'Distance'. This first distance calculation should come on the second row because for later purposes. Therefore, the first row of column 'Distance' can be zero or NA, that does not matter. So, I would like to know to distance between the first measurement (Lat 70.6086 and Long 58.2959) and the second measurement (Lat 72.1508 and 58.7894). Then the distance between the second and the third measurement. Then between the third and the fourth, and so on for more than 207000 measurements. The expected output should be like this: Callsign Altitude Speed Direction Date_Time Latitude Longitude Distance A118 18000 110 340 2017-11-06 22:28:09 70.6086 58.2959 NA A118 18500 120 339 2017-11-06 22:29:09 72.1508 58.7894 172000 B222 18500 150 350 2017-11-08 07:28:09 71.1689 59.1234 110000 D123 19000 150 110 2018-05-29 15:13:27 69.4523 68.1235 387000 I found the distm function in R, for which I can do it manually for only two measurements instead of the complete dataset. distm(p1, p2, fun = distHaversine) I tried the following code adsb_relevant_columns_correct_timedifference <- mutate(adsb_relevant_columns_correct_timedifference, Distance = distm(c(adsb_relevant_columns_correct_timedifference$Longitude, adsb_relevant_columns_correct_timedifference$Latitude), c(lag(adsb_relevant_columns_correct_timedifference$Longitude, adsb_relevant_columns_correct_timedifference$Latitude)), fun = distCosine)) However, I got the following error Error in mutate_impl(.data, dots) : Evaluation error: Wrong length for a vector, should be 2. I'm sorry for my long explanation, but I hope that my question is clear. Can someone please tell me how to calculate the distance between the several measurements and add this as a new column to my dataframe? A: Instead of distm you can use the distHaversine-function. Further in your mutate call you should not repeat the dataframe and use the $ operator, mutate already nows where to look for the columns. The error occurs because you need to use cbind instead of c, as c creates one long vector, simply stacking the columns together, whereas cbind creates a dataframe with two columns (what you want to have in this case). library(geosphere) library(dplyr) mutate(mydata, Distance = distHaversine(cbind(Longitude, Latitude), cbind(lag(Longitude), lag(Latitude)))) # Callsign Altitude Speed Direction Date_Time Latitude Longitude Distance # 1 A118 18000 110 340 2017-11-06T22:28:09 70.6086 58.2959 NA # 2 A118 18500 120 339 2017-11-06T22:29:09 72.1508 58.7894 172569.2 # 3 B222 18500 150 350 2017-11-08T07:28:09 71.1689 59.1234 109928.5 # 4 D123 19000 150 110 2018-05-29T15:13:27 69.4523 68.1235 387356.2 With distCosine it is a little bit more tricky, as it doesn't return NA if one of the input latitudes or longitudes is missing. Thus I modified the function a little bit and this solves the problem: modified_distCosine <- function(Longitude1, Latitude1, Longitude2, Latitude2) { if (any(is.na(c(Longitude1, Latitude1, Longitude2, Latitude2)))) { NA } else { distCosine(c(Longitude1, Latitude1), c(Longitude2, Latitude2)) } } mutate(mydata, Distance = mapply(modified_distCosine, Longitude, Latitude, lag(Longitude), lag(Latitude))) # Callsign Altitude Speed Direction Date_Time Latitude Longitude Distance # 1 A118 18000 110 340 2017-11-06T22:28:09 70.6086 58.2959 NA # 2 A118 18500 120 339 2017-11-06T22:29:09 72.1508 58.7894 172569.2 # 3 B222 18500 150 350 2017-11-08T07:28:09 71.1689 59.1234 109928.5 # 4 D123 19000 150 110 2018-05-29T15:13:27 69.4523 68.1235 387356.2 Here I use mapply to apply the modified function with the arguments Longitude, Latitude, lag(Longitude), lag(Latitude). I'm quite sure there has to be a more elegant way, but at least this works. Data mydata <- structure(list(Callsign = c("A118", "A118", "B222", "D123"), Altitude = c(18000L, 18500L, 18500L, 19000L), Speed = c(110L, 120L, 150L, 150L), Direction = c(340L, 339L, 350L, 110L), Date_Time = c("2017-11-06T22:28:09", "2017-11-06T22:29:09", "2017-11-08T07:28:09", "2018-05-29T15:13:27"), Latitude = c(70.6086, 72.1508, 71.1689, 69.4523), Longitude = c(58.2959, 58.7894, 59.1234, 68.1235)), .Names = c("Callsign", "Altitude", "Speed", "Direction", "Date_Time", "Latitude", "Longitude"), class = "data.frame", row.names = c(NA, -4L))
{ "pile_set_name": "StackExchange" }
Q: Line breaks between variables in PHP I have a variable like this in foreach $variable=$variable1." ".$variable2; Output is apple fruit tomato fruit pineapple fruit How I want is apple fruit tomato fruit pineapple fruit How can I achieve it? A: "\t" is not a viable option but @Magnus Eriksson gave good answer: echo "\t".$var1."\t".$var2.PHP_EOL: apple fruit tomato fruit pineapple fruit echo ' '.str_pad($var1,20," ").$var2.PHP_EOL: apple fruit tomato fruit pineapple fruit
{ "pile_set_name": "StackExchange" }
Q: Check the convergence of $ \sum_{n=1}^{\infty} \ln(x)^n$ I`m trying to check the domain of $R$ for $$ \sum_{n=1}^{\infty} \ln(x)^n$$ so what I did is to take $a_n$ and he is $1$ so $\rightarrow -1<x<1$ $$ -1<\ln(x)<1 \longrightarrow \frac{1}{e} < x < e$$ now lets check the left and right sides for $e$ its Diverging and my problem is with $\frac{1}{e}$ how I check him? $$ \lim\limits_{n\to 0} \left(\ln\left(\frac{1}{e}\right)\right)^n$$ how I can write it? and what its give to me? Thanks! A: You may try to work with geometric series: $$|\log x|<1\iff \frac1e<x<e\;\implies\;\sum_{n=1}^\infty\log^nx\;\;\text{converges}$$ $$|\log x|\ge 1\iff 0<x<\frac1e\;\;or\;\;x>e\;\implies\;\sum_{n=1}^\infty\log^nx\;\;\text{diverges}$$ The above is assuming you meant $\,\log(x)^n=(\log x)^n\;$ , as hinted in the last part of your question.
{ "pile_set_name": "StackExchange" }
Q: WooCommerce - Deleting the upper price on the product page with variations I would need to delete the price above the variations, under the product title, but ONLY in the product page, not on the main store page. I was not able to accomplish this. Is this possible with custom code? Many thanks. A: Use css to hide price from product details page. .type-product p.price { display: none; }
{ "pile_set_name": "StackExchange" }
Q: 4 Column Footer Not Stacking for Mobile So basically I've got this 4 column footer and it's perfect, but rather than stacking for mobile, it just gets smashed. I just want each category to stack once it swaps to mobile view, or just shrink responsively across all sizes. I've tried setting widths but no luck. Any help or tips would be appreciated! footer .clear { clear: both; float: none; } footer { background: #222; overflow: hidden; border-top: solid 1px #000; padding: 58px 0 0; font-family: arial, helvetica, sans-serif; line-height: 1.5em; } footer p, footer ul, footer a, footer .btn { font-family: arial, helvetica, sans-serif; line-height: 1.5em; text-transform: none; } footer li { font-size: .875em; line-height: 1.5em; } footer .btn { background: #4497c4; background-image: -webkit-linear-gradient(top, #4497c4, #2d6a8e); background-image: -moz-linear-gradient(top, #4497c4, #2d6a8e); background-image: -ms-linear-gradient(top, #4497c4, #2d6a8e); background-image: -o-linear-gradient(top, #4497c4, #2d6a8e); background-image: linear-gradient(to bottom, #4497c4, #2d6a8e); -webkit-border-radius: 5; -moz-border-radius: 5; border-radius: 5px; -webkit-box-shadow: 0px 1px 2px #ffffff; -moz-box-shadow: 0px 1px 2px #ffffff; box-shadow: 0px 1px 2px #ffffff; color: #ffffff!important; font-size: 15px; padding: 5px 15px 6px 15px; border: solid #25658a 1px; text-decoration: none; -moz-box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2) inset; -webkit-box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2) inset; box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2) inset; } footer .content { max-width: 1000px; margin: 0 auto; padding: 0 20px; } @media screen and (max-width: 768px) { footer .content { padding: 0 10px; } } footer .last { margin-right: 0px !important; } @media only screen and (max-width: 485px) { footer .last { clear: both; } } #emailsignup { float: left; width: 330px; } #emailsignup .footer-logo { display: block; width: 155px; height: 41px; background: url("https://www.proxibid.com/images/footer-logo-proxibid.png") top left no-repeat; text-indent: -9999px; margin-bottom: 30px; } #emailsignup a, #helpfullinks a, #social a, #poweredby a { color: rgba(255, 255, 255, 0.7); text-decoration: none; } #emailsignup p { font-size: 13px; color: #FFF; margin: 0px 0px 16px; } #helpfullinks { float: right; } @media only screen and (max-width: 825px) { #helpfullinks { float: none; clear: both; } } #helpfullinks div { float: left; margin-right: 45px; width: 20%; } #helpfullinks div a { display: inline; margin-top: -6px; margin-bottom: 8px; } #helpfullinks p.category { color: #FFF; font-size: 21px; margin: 0 0 14px; } #helpfullinks p.category a { color: #FFF; } #helpfullinks ul { list-style-type: none; padding: 0px; margin: 14px 0 0 0; } #helpfullinks li { padding: 0px; margin: 0 0 6px; font-size: 15px; } #poweredby { max-width: 100%; margin: 115px auto 0; overflow: hidden; text-align: center; } @media screen and (max-width: 768px) { #poweredby { margin: 26px auto 0; } } #poweredby p { font-size: 13px; color: rgba(255, 255, 255, 0.7); margin: 0 0 10px; text-align: center; } #poweredby ul { display: inline-block; margin: 0px auto; list-style-type: none; padding: 0px; } #poweredby li { margin: 0 40px 0 0; float: left; } @media only screen and (max-width: 495px) { #poweredby li { margin: 0 0 10px 0; float: none; clear: both; } } #poweredby .footer-divvy { display: block; width: 77px; height: 24px; background: url("https://www.proxibid.com/images/footer-logo-divvy.png") top left no-repeat; text-indent: -9999px; } #poweredby .footer-finest { display: block; width: 77px; height: 24px; background: url("https://www.proxibid.com/images/footer-logo-thefinest.png") top left no-repeat; text-indent: -9999px; } #poweredby .footer-apn { display: block; width: 77px; height: 24px; background: url("https://www.proxibid.com/images/footer-logo-apn.png") top left no-repeat; text-indent: -9999px; } #social { margin: 60px auto; overflow: hidden; text-align: center; } @media screen and (max-width: 768px) { #social { margin: 26px auto; } } #social ul { margin: 0px auto; list-style-type: none; padding: 0px; } #social ul.social, #social ul.contact { display: inline-block; } #social li { margin: 0 17px 0 0; float: left; color: rgba(255, 255, 255, 0.7); } @media only screen and (max-width: 495px) { #social li { margin: 0 0 10px 0; float: none; clear: both; } } #social li a { color: rgba(255, 255, 255, 0.7); } iframe { overflow: hidden; } #footerSealiFrame { border: medium none; height: 175px; margin: 0 auto; width: 100%; display: block; overflow: hidden; } @media only screen and (max-width: 600px) { #footerSealiFrame { height: 285px; } #footerSeals>img, #footerSeals>embed, #footerSeals>object, #footerSeals>a { display: inline-block !important; margin: 0 6px 10px !important; vertical-align: middle !important; } } <footer> <div class="content"> <div id="helpfullinks"> <div> <p class="category">About</p> <ul> <li><a href="#">Our Mission</a></li> <li><a href="#">AdaptaPASS</a></li> <li><a href="#">Affiliates</a></li> <li><a href="#">Campus Representatives</a></li> <li><a href="#">Privacy Policy</a></li> </ul> </div> <div> <p class="category">Products</p> <ul> <li><a href="#">All-Access Course Bundles</a></li> <li><a href="#">CRAM Courses</a></li> <li><a href="#">Audio Lectures</a></li> <li><a href="#">TestBank Software</a></li> <li><a href="#">Digital Flashcards</a></li> <li><a href="#">Exam Stress Relief</a></li> </ul> </div> <div> <p class="category">Resources</p> <ul> <li><a href="#">Free Assessment</a></li> <li><a href="#">Start a Free Trial</a></li> <li><a href="#">Blog</a></li> <li><a href="#">Requirements by State</a></li> </ul> </div> <div class="last"> <p class="category">Support</p> <ul> <li><a href="#">(800) 824 2811</a></li> <li><a href="#">Use the chat feature below to reach one of our support specialists</a></li> <li><a href="#">Contact Us</a></li> <li><a href="#">Login to AdaptaPASS</a></li> <li><a href="#">Login to myYaeger Student Portal</a></li> </ul> </div> <div class="clear"></div> </div> <div class="clear"></div> <div id="poweredby"> <ul> <li class="last"><img src="include/images/footerlogo.png"></li> </ul> </div> <div class="clear"></div> <div id="social"> <ul class="social"> <li><a target="_blank" href="#">Facebook</a></li> <li><a target="_blank" href="#">Twitter</a></li> <li><a target="_blank" href="#">YouTube</a></li> <li class="last"><a target="_blank" href="#">LinkedIn</a></li> </ul> <div class="clear"></div> <ul class="contact"> <li class="last">&copy;2017 Yaegar CPA Review, All Rights Reserved</li> </ul> </div> </div> </footer> A: Essentially, what you need to do is kill the floats and reset the width at the appropriate viewport widths, for example: #helpfullinks div { /* for the sake of demonstration */ float: none; width: 100%; } footer .clear { clear: both; float: none; } footer { background: #222; overflow: hidden; border-top: solid 1px #000; padding: 58px 0 0; font-family: arial, helvetica, sans-serif; line-height: 1.5em; } footer p, footer ul, footer a, footer .btn { font-family: arial, helvetica, sans-serif; line-height: 1.5em; text-transform: none; } footer li { font-size: .875em; line-height: 1.5em; } footer .btn { background: #4497c4; background-image: -webkit-linear-gradient(top, #4497c4, #2d6a8e); background-image: -moz-linear-gradient(top, #4497c4, #2d6a8e); background-image: -ms-linear-gradient(top, #4497c4, #2d6a8e); background-image: -o-linear-gradient(top, #4497c4, #2d6a8e); background-image: linear-gradient(to bottom, #4497c4, #2d6a8e); -webkit-border-radius: 5; -moz-border-radius: 5; border-radius: 5px; -webkit-box-shadow: 0px 1px 2px #ffffff; -moz-box-shadow: 0px 1px 2px #ffffff; box-shadow: 0px 1px 2px #ffffff; color: #ffffff!important; font-size: 15px; padding: 5px 15px 6px 15px; border: solid #25658a 1px; text-decoration: none; -moz-box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2) inset; -webkit-box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2) inset; box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2) inset; } footer .content { max-width: 1000px; margin: 0 auto; padding: 0 20px; } @media screen and (max-width: 768px) { footer .content { padding: 0 10px; } } footer .last { margin-right: 0px !important; } @media only screen and (max-width: 485px) { footer .last { clear: both; } } #emailsignup { float: left; width: 330px; } #emailsignup .footer-logo { display: block; width: 155px; height: 41px; background: url("https://www.proxibid.com/images/footer-logo-proxibid.png") top left no-repeat; text-indent: -9999px; margin-bottom: 30px; } #emailsignup a, #helpfullinks a, #social a, #poweredby a { color: rgba(255, 255, 255, 0.7); text-decoration: none; } #emailsignup p { font-size: 13px; color: #FFF; margin: 0px 0px 16px; } #helpfullinks { float: right; } @media only screen and (max-width: 825px) { #helpfullinks { float: none; clear: both; } } #helpfullinks div { float: left; margin-right: 45px; width: 20%; } #helpfullinks div a { display: inline; margin-top: -6px; margin-bottom: 8px; } #helpfullinks p.category { color: #FFF; font-size: 21px; margin: 0 0 14px; } #helpfullinks p.category a { color: #FFF; } #helpfullinks ul { list-style-type: none; padding: 0px; margin: 14px 0 0 0; } #helpfullinks li { padding: 0px; margin: 0 0 6px; font-size: 15px; } #poweredby { max-width: 100%; margin: 115px auto 0; overflow: hidden; text-align: center; } @media screen and (max-width: 768px) { #poweredby { margin: 26px auto 0; } } #poweredby p { font-size: 13px; color: rgba(255, 255, 255, 0.7); margin: 0 0 10px; text-align: center; } #poweredby ul { display: inline-block; margin: 0px auto; list-style-type: none; padding: 0px; } #poweredby li { margin: 0 40px 0 0; float: left; } @media only screen and (max-width: 495px) { #poweredby li { margin: 0 0 10px 0; float: none; clear: both; } } #poweredby .footer-divvy { display: block; width: 77px; height: 24px; background: url("https://www.proxibid.com/images/footer-logo-divvy.png") top left no-repeat; text-indent: -9999px; } #poweredby .footer-finest { display: block; width: 77px; height: 24px; background: url("https://www.proxibid.com/images/footer-logo-thefinest.png") top left no-repeat; text-indent: -9999px; } #poweredby .footer-apn { display: block; width: 77px; height: 24px; background: url("https://www.proxibid.com/images/footer-logo-apn.png") top left no-repeat; text-indent: -9999px; } #social { margin: 60px auto; overflow: hidden; text-align: center; } @media screen and (max-width: 768px) { #social { margin: 26px auto; } } #social ul { margin: 0px auto; list-style-type: none; padding: 0px; } #social ul.social, #social ul.contact { display: inline-block; } #social li { margin: 0 17px 0 0; float: left; color: rgba(255, 255, 255, 0.7); } @media only screen and (max-width: 495px) { #social li { margin: 0 0 10px 0; float: none; clear: both; } } #social li a { color: rgba(255, 255, 255, 0.7); } iframe { overflow: hidden; } #footerSealiFrame { border: medium none; height: 175px; margin: 0 auto; width: 100%; display: block; overflow: hidden; } @media only screen and (max-width: 600px) { #footerSealiFrame { height: 285px; } #footerSeals>img, #footerSeals>embed, #footerSeals>object, #footerSeals>a { display: inline-block !important; margin: 0 6px 10px !important; vertical-align: middle !important; } } /* Additional */ @media (max-width: 600px) { #helpfullinks div { float: none; width: 100%; border-bottom: 1px solid #5a5a5a; margin-bottom: 10px; padding-bottom: 10px; } } <footer> <div class="content"> <div id="helpfullinks"> <div> <p class="category">About</p> <ul> <li><a href="#">Our Mission</a></li> <li><a href="#">AdaptaPASS</a></li> <li><a href="#">Affiliates</a></li> <li><a href="#">Campus Representatives</a></li> <li><a href="#">Privacy Policy</a></li> </ul> </div> <div> <p class="category">Products</p> <ul> <li><a href="#">All-Access Course Bundles</a></li> <li><a href="#">CRAM Courses</a></li> <li><a href="#">Audio Lectures</a></li> <li><a href="#">TestBank Software</a></li> <li><a href="#">Digital Flashcards</a></li> <li><a href="#">Exam Stress Relief</a></li> </ul> </div> <div> <p class="category">Resources</p> <ul> <li><a href="#">Free Assessment</a></li> <li><a href="#">Start a Free Trial</a></li> <li><a href="#">Blog</a></li> <li><a href="#">Requirements by State</a></li> </ul> </div> <div class="last"> <p class="category">Support</p> <ul> <li><a href="#">(800) 824 2811</a></li> <li><a href="#">Use the chat feature below to reach one of our support specialists</a></li> <li><a href="#">Contact Us</a></li> <li><a href="#">Login to AdaptaPASS</a></li> <li><a href="#">Login to myYaeger Student Portal</a></li> </ul> </div> <div class="clear"></div> </div> <div class="clear"></div> <div id="poweredby"> <ul> <li class="last"><img src="include/images/footerlogo.png"></li> </ul> </div> <div class="clear"></div> <div id="social"> <ul class="social"> <li><a target="_blank" href="#">Facebook</a></li> <li><a target="_blank" href="#">Twitter</a></li> <li><a target="_blank" href="#">YouTube</a></li> <li class="last"><a target="_blank" href="#">LinkedIn</a></li> </ul> <div class="clear"></div> <ul class="contact"> <li class="last">&copy;2017 Yaegar CPA Review, All Rights Reserved</li> </ul> </div> </div> </footer> Bonus Because it's Friday and I'm feeling particularly generous, here's a flex-box method: #helpfullinks { display: flex; flex-direction: column; flex-flow: wrap; } footer .clear { clear: both; float: none; } footer { background: #222; overflow: hidden; border-top: solid 1px #000; padding: 58px 0 0; font-family: arial, helvetica, sans-serif; line-height: 1.5em; } footer p, footer ul, footer a, footer .btn { font-family: arial, helvetica, sans-serif; line-height: 1.5em; text-transform: none; } footer li { font-size: .875em; line-height: 1.5em; } footer .btn { background: #4497c4; background-image: -webkit-linear-gradient(top, #4497c4, #2d6a8e); background-image: -moz-linear-gradient(top, #4497c4, #2d6a8e); background-image: -ms-linear-gradient(top, #4497c4, #2d6a8e); background-image: -o-linear-gradient(top, #4497c4, #2d6a8e); background-image: linear-gradient(to bottom, #4497c4, #2d6a8e); -webkit-border-radius: 5; -moz-border-radius: 5; border-radius: 5px; -webkit-box-shadow: 0px 1px 2px #ffffff; -moz-box-shadow: 0px 1px 2px #ffffff; box-shadow: 0px 1px 2px #ffffff; color: #ffffff!important; font-size: 15px; padding: 5px 15px 6px 15px; border: solid #25658a 1px; text-decoration: none; -moz-box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2) inset; -webkit-box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2) inset; box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2) inset; } footer .content { max-width: 1000px; margin: 0 auto; padding: 0 20px; } @media screen and (max-width: 768px) { footer .content { padding: 0 10px; } } footer .last { margin-right: 0px !important; } @media only screen and (max-width: 485px) { footer .last { clear: both; } } #emailsignup { float: left; width: 330px; } #emailsignup .footer-logo { display: block; width: 155px; height: 41px; background: url("https://www.proxibid.com/images/footer-logo-proxibid.png") top left no-repeat; text-indent: -9999px; margin-bottom: 30px; } #emailsignup a, #helpfullinks a, #social a, #poweredby a { color: rgba(255, 255, 255, 0.7); text-decoration: none; } #emailsignup p { font-size: 13px; color: #FFF; margin: 0px 0px 16px; } #helpfullinks { float: right; } @media only screen and (max-width: 825px) { #helpfullinks { float: none; clear: both; } } #helpfullinks div { float: left; margin-right: 45px; width: 20%; } #helpfullinks div a { display: inline; margin-top: -6px; margin-bottom: 8px; } #helpfullinks p.category { color: #FFF; font-size: 21px; margin: 0 0 14px; } #helpfullinks p.category a { color: #FFF; } #helpfullinks ul { list-style-type: none; padding: 0px; margin: 14px 0 0 0; } #helpfullinks li { padding: 0px; margin: 0 0 6px; font-size: 15px; } #poweredby { max-width: 100%; margin: 115px auto 0; overflow: hidden; text-align: center; } @media screen and (max-width: 768px) { #poweredby { margin: 26px auto 0; } } #poweredby p { font-size: 13px; color: rgba(255, 255, 255, 0.7); margin: 0 0 10px; text-align: center; } #poweredby ul { display: inline-block; margin: 0px auto; list-style-type: none; padding: 0px; } #poweredby li { margin: 0 40px 0 0; float: left; } @media only screen and (max-width: 495px) { #poweredby li { margin: 0 0 10px 0; float: none; clear: both; } } #poweredby .footer-divvy { display: block; width: 77px; height: 24px; background: url("https://www.proxibid.com/images/footer-logo-divvy.png") top left no-repeat; text-indent: -9999px; } #poweredby .footer-finest { display: block; width: 77px; height: 24px; background: url("https://www.proxibid.com/images/footer-logo-thefinest.png") top left no-repeat; text-indent: -9999px; } #poweredby .footer-apn { display: block; width: 77px; height: 24px; background: url("https://www.proxibid.com/images/footer-logo-apn.png") top left no-repeat; text-indent: -9999px; } #social { margin: 60px auto; overflow: hidden; text-align: center; } @media screen and (max-width: 768px) { #social { margin: 26px auto; } } #social ul { margin: 0px auto; list-style-type: none; padding: 0px; } #social ul.social, #social ul.contact { display: inline-block; } #social li { margin: 0 17px 0 0; float: left; color: rgba(255, 255, 255, 0.7); } @media only screen and (max-width: 495px) { #social li { margin: 0 0 10px 0; float: none; clear: both; } } #social li a { color: rgba(255, 255, 255, 0.7); } iframe { overflow: hidden; } #footerSealiFrame { border: medium none; height: 175px; margin: 0 auto; width: 100%; display: block; overflow: hidden; } @media only screen and (max-width: 600px) { #footerSealiFrame { height: 285px; } #footerSeals>img, #footerSeals>embed, #footerSeals>object, #footerSeals>a { display: inline-block !important; margin: 0 6px 10px !important; vertical-align: middle !important; } } /* Bonus (let's get Flexy) */ @media (max-width: 600px) { #helpfullinks { display: flex; flex-direction: column; flex-flow: wrap; } #helpfullinks div { width: 100%; margin-right: auto; margin-left: auto; border-bottom: 1px solid #5a5a5a; margin-bottom: 10px; padding-bottom: 10px; } } <footer> <div class="content"> <div id="helpfullinks"> <div> <p class="category">About</p> <ul> <li><a href="#">Our Mission</a></li> <li><a href="#">AdaptaPASS</a></li> <li><a href="#">Affiliates</a></li> <li><a href="#">Campus Representatives</a></li> <li><a href="#">Privacy Policy</a></li> </ul> </div> <div> <p class="category">Products</p> <ul> <li><a href="#">All-Access Course Bundles</a></li> <li><a href="#">CRAM Courses</a></li> <li><a href="#">Audio Lectures</a></li> <li><a href="#">TestBank Software</a></li> <li><a href="#">Digital Flashcards</a></li> <li><a href="#">Exam Stress Relief</a></li> </ul> </div> <div> <p class="category">Resources</p> <ul> <li><a href="#">Free Assessment</a></li> <li><a href="#">Start a Free Trial</a></li> <li><a href="#">Blog</a></li> <li><a href="#">Requirements by State</a></li> </ul> </div> <div class="last"> <p class="category">Support</p> <ul> <li><a href="#">(800) 824 2811</a></li> <li><a href="#">Use the chat feature below to reach one of our support specialists</a></li> <li><a href="#">Contact Us</a></li> <li><a href="#">Login to AdaptaPASS</a></li> <li><a href="#">Login to myYaeger Student Portal</a></li> </ul> </div> <div class="clear"></div> </div> <div class="clear"></div> <div id="poweredby"> <ul> <li class="last"><img src="include/images/footerlogo.png"></li> </ul> </div> <div class="clear"></div> <div id="social"> <ul class="social"> <li><a target="_blank" href="#">Facebook</a></li> <li><a target="_blank" href="#">Twitter</a></li> <li><a target="_blank" href="#">YouTube</a></li> <li class="last"><a target="_blank" href="#">LinkedIn</a></li> </ul> <div class="clear"></div> <ul class="contact"> <li class="last">&copy;2017 Yaegar CPA Review, All Rights Reserved</li> </ul> </div> </div> </footer>
{ "pile_set_name": "StackExchange" }
Q: AngularJS google Chart : ChartRangeFilter I am using AngularJS Google Chart to display a line chart. I was reading about ChartRangeFilter and need to use it in my graph. Is it possible to integrate the range filter from within AngularJs Google Chart? or it doesn't have this feature supported yet? I couldn't find any tutorial/documentations about this topic, so any help is appreciated! A: Apparently, it's not supported yet: there's a feature request and a few discussion about it. Furthermore, it appears that it has an attempt to support it, but it still needs revision, and probably some work. I think it would be a great opportunity for anyone interested on it to test and contribute.
{ "pile_set_name": "StackExchange" }
Q: Execute code in django as a timed event I have a message board application that needs to collect and display messages without any user input or action. I am currently doing this by refreshing the page using the html meta refresh tag. I realize that this is not a great solution. This is the relevant section that I want to run frequently without refreshing the page. {% if grams_list %} #if there exists any messages for the user {% for g in grams_list %} #for each message <h2 class="gram-display">{{ g.message }}</h2> #display the message {% endfor %} {% else %} #otherwise display this nice picture <h2 id="nograms" class="gram-display">No grams right now.</h2> <img id="bird" src="/static/cardinal_from_pixabay.jpg"> {% endif %} Is this the sort of thing that could be accomplished with JavaScript? I know that it is possible to have javascript trigger a Javascript function every so often, but is this possible to trigger this event? Alternately, does Django have some built-in function that does this? Could it be handled by signals (I looked at signals but didn't really understand them, though they looked like they had potential to be useful). A: Django signals can not do this. Look at jQuery.load() (http://api.jquery.com/load/) for what is probably the simplest method to do this that is similar to what you're doing now (you'll have to put the template as a separate url/view).
{ "pile_set_name": "StackExchange" }
Q: Display base64 images in a html email on Ios I generate a html string who contains base64 images. When the MFMailComposeViewController open, I see the images in the generated email. When I send it and open it, the images are not displayed, there are just empty square. My code - (IBAction)actionShareByEmail:(id)sender { if([MFMailComposeViewController canSendMail]) { MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init]; picker.mailComposeDelegate = self; NSString* subject = @"Environments list with qrcode"; [picker setSubject:subject]; [picker setMessageBody:[manager getHtmlWithEnvironments:nil] isHTML:YES]; [self presentViewController:picker animated:YES completion:nil]; } } -(NSString*)getHtmlWithEnvironments:(NSArray*)envDictionnaries{ NSMutableString* html = [[NSMutableString alloc]init]; [html appendString: @"<html><body>"]; for (NSDictionary *d in self.arEnvironments) { UIImage* qrcode = [QRCodeGenerator qrImageForString:[d objectForKey:@"env_name"] imageSize:200.0];//Works fine NSData *imageData = UIImagePNGRepresentation(qrcode); NSString *encodedString = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]; [html appendString: [NSString stringWithFormat:@"<H3>%@</h3><img src=\"data:image/png;base64,%@\" width=\"200\" height=\"200\" alt=\"test\" /></br></br>",[d objectForKey:KEY_ENV_NAME],encodedString]]; } [html appendString: @"</html><body>"]; return html; } How can I do to display images correctly ? A: It looks like support for inline images is low - mainly due to security issues. The link to Campaign Monitor in the second question below gives more information. More Information: Send a base64 image in HTML email Base64 HTML embedded images not showing when mailed
{ "pile_set_name": "StackExchange" }
Q: What is the difference between == True and != None? def get_next_target(page): start_link = page.find('<a href="') if start_link == -1: return None, 0 end_link = page.find('">', start_link) url = page[start_link + 9 : end_link] return url, end_link def print_all_links(page): url = True while url != None: url, endpos = get_next_target(page) if url: print url #True page = page[endpos : ] else: break page = '<div id="top_bin"><div id="top_content" class="width960"><div class="udacity float-left"><a href="http://udacity.com"><a href="http://udacity.com"><a href="http://udacity.com"><a href="http://udacity.com">' print print_all_links(page) My question here is when I print out the result it will print four URLs and that what is expected, but when I set the while to while url == True: it will print out one URL only, so what is the reason? Isn't != None equals to ==True A: Note that it isn't considered very good design in the first place to return this kind of sentinel. get_next_target should return a target, and nothing else (ignoring, for now, the state needed to find the next target). If there is an error, raise an exception. In this case, the lack of another target isn't really an error, but as we'll see, it does signal the end of the iteration. There is already an exception for that: StopIteration. def get_next_target(page): start_link = page.find('<a href="') if start_link == -1: raise StopIteration end_link = page.find('">', start_link) url = page[start_link + 9 : end_link] return url, end_link def print_all_links(page): while True: try: url, endpos = get_next_target(page) print url page = page[endpos:] except StopIteration: break We can write a better iterator for returning links from a given page, though, that doesn't expose the state needed to parse the page. def get_targets(page): while True: start_link = page.find('<a href="') if start_link == -1: break end_link = page.find('">', start_link) yield page[start_link + 9:end_link] def print_all_links(page): for url in get_targets(page): print url
{ "pile_set_name": "StackExchange" }
Q: Magento 2 phtml get store view being viewed In Magento 2 I have a phtml file I am trying to get what store view is currently being seen by the website visitor. However it does not seem to work. I dont want to have to create a whole module or plugin . if (Mage::app()->getStore()->getId() > '1') { echo "you are 1"; } elseif (Mage::app()->getStore()->getId() > '2') { echo "you are 2"; } else { echo "you are not 1 or 2"; } A: You can fetch the current store id and the store name in phtml file (using ObjectManager) like below : $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface'); $storeID = $storeManager->getStore()->getStoreId(); $storeName = $storeManager->getStore()->getName(); you can use this $storeID according to your condition : if ($storeID > '1') { // your logic } However, this is not a proper approach. A much cleaner way would be to use a block or a helper A: you can inject the Magento\Store\Model\StoreManagerInterf‌​ace in your constructor to get the store view in block and send to phtml. protected $_storeManagerInterface; public function __construct( \Magento\Store\Model\StoreManagerInterf‌​ace $storeManagerInterface ) { $this->_storeManagerInterface = $storeManagerInterface; } Then in your code you can do: $currentStore = $this->_storeManagerInterface->getStore(); $currentStoreId = $currentStore->getId(); based on store id you can write a condition.
{ "pile_set_name": "StackExchange" }
Q: why mod (%) calculation result of zero will not consider as falsy in javascript condition evaluation if (!5%5) { console.log('its a 5%!'); } if (5%5 === 0) { console.log('its a 5%! but eval differently'); } https://codepen.io/adamchenwei/pen/ZXNraK?editors=0010 Something like above you will only see 2nd statement to evaluate to be true. Why is that? Isn't first statement ! help revert the value into true already. What did I missed? A: !5 is 0. 0 % 5 is falsy. Therefore, your if doesn't trigger. A: The expression !5%5 is interpreted as if it were parenthesized (!5)%5. In other words, the ! operator binds very tightly, so !5 is evaluated before the % operator. Consider an expression like -x+y. Clearly, that means (-x)+y, and not -(x+y), because of traditional arithmetic operator precedence rules. The ! operator is in that respect similar to unary -. The expression !5 is 0, and 0%5 is 0, so !5%5 is not "truthy".
{ "pile_set_name": "StackExchange" }
Q: Python input always returns a string I ran this code through Visual Studio Code: counter = 0 while True: max_count = input('enter an int: ') if max_count.isdigit(): break print('sorry, try again') max_count = int(max_count) while counter < max_count: print(counter) counter = counter + 1 And was very surprised to see this response: python "/home/malikarumi/Documents/PYTHON/Blaikie Python/flatnested.py" malikarumi@Tetuoan2:~$ python "/home/malikarumi/Documents/PYTHON/Blaikie Python/flatnested.py" enter an int: 5 Traceback (most recent call last): File "/home/malikarumi/Documents/PYTHON/Blaikie Python/flatnested.py", line 7, in <module> if max_count.isdigit(): AttributeError: 'int' object has no attribute 'isdigit' Because input() is always supposed to return a string: https://docs.python.org/3.5/library/functions.html#input I put in a quoted string: malikarumi@Tetuoan2:~$ python "/home/malikarumi/Documents/PYTHON/Blaikie Python/flatnested.py" enter an int: '5' 0 1 2 3 4 and now it works as expected. Then I ran it on my standard issue Ubuntu terminal: malikarumi@Tetuoan2:~/Documents/PYTHON/Blaikie Python$ python3 flatnested.py enter an int: 5 0 1 2 3 4 And it worked as expected, note no quotes around the 5. What's going on here? Has Visual Studio Code 'rewritten' the rules of Python? A: Short Answer It appears that when you run the code through Visual Studio Code, Python 2.7 is being used to run the code. If you wish to continue using Python 2.7, use the raw_input instead of the input function. Explanation Take a look at the Python 2.7 documentation for the input function. It's different from the input function used in Python 3.x. In Python 2.7, the input function uses the eval function to process the input the program receives as though the input were a line of Python code. python "/home/malikarumi/Documents/PYTHON/Blaikie Python/flatnested.py" malikarumi@Tetuoan2:~$ python "/home/malikarumi/Documents/PYTHON/Blaikie Python/flatnested.py" enter an int: 5 Traceback (most recent call last): File "/home/malikarumi/Documents/PYTHON/Blaikie Python/flatnested.py", line 7, in <module> if max_count.isdigit(): AttributeError: 'int' object has no attribute 'isdigit' What's happening in the case above, with Python 2.7, is: eval("5").isdigit() # 5.isdigit() The above Python statement is invalid, because it results in trying to call an .isdigit() method on an integer. But, integers in Python do not have that method. malikarumi@Tetuoan2:~$ python "/home/malikarumi/Documents/PYTHON/Blaikie Python/flatnested.py" enter an int: '5' 0 1 2 3 4 In the case above, with Python 2.7, what's happening is: eval("'5'").isdigit() # '5'.isdigit() The statement above is valid because it results in a string calling a .isdigit() method, which does exist for strings. I hope this answers your question and gives you a clearer understanding of the differences between the input functions in Python 2.7 and Python 3.x.
{ "pile_set_name": "StackExchange" }
Q: Get Directions API call ? react-native In many iOS apps I can see a button saying getDirections, which will upon click open an Apple/Google maps with latitude and longitude passed as destination. I have my TouchableHighlight button with lat and lng ready. What API endpoint do I need to call in onPress callback to open Apple maps with my coordinates as route destination? A: To link to another application, such as Maps, use LinkingIOS: https://facebook.github.io/react-native/docs/linkingios.html // Replace lat and long with your own decimal latitude and longitude values var url = 'http://maps.apple.com/?ll=<lat>,<long>'; LinkingIOS.openURL(url); For maps the URL scheme is just the same as from a standard Obj-C app: https://developer.apple.com/library/ios/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html A: To link to another application, and open itinerary as Maps, use this function: export function openDirections(latitude, longitude) { Platform.select({ ios: () => { Linking.openURL('http://maps.apple.com/maps?daddr=' + latitude + ',' + longitude); }, android: () => { Linking.openURL('http://maps.google.com/maps?daddr=' + latitude + ',' + longitude); } })(); }
{ "pile_set_name": "StackExchange" }
Q: ASP.net c# magical array issue I'm encountering an interesting issue with the following code. productObject is a custom object that contains a number of product-related variables including a 'VendorLocationId'. Given these items in a listbox: "Town A" value:1 "Town B" value:2 Also given: both items are selected within the listbox. 1 productObjectArray[] productObjectArray = new productObjectArray[lstLocation.Items.Count]; 2 int counter = 0; 3 foreach (ListItem li in lstLocation.Items) 4 { 5 if (li.Selected == true) 6 { 7 productObject.VendorLocationId = li.Value; 8 productObjectArray[counter] = productObject; 9 } 10 counter++; 11 } After executing, the above code gives this result: productObjectArray[0].VendorLocationId = 2 productObjectArray[1].VendorLocationId = 2 I find this perplexing. If I step through the code, productObjectArray[0].VendorLocationId = 1 and counter = 1 until line 7. Then productObjectArray[0].VendorLocationId magically equals 2 and counter = 1. A: It seems that your "productObject" is declared outside of this code block, and you're therefore referencing both elements in your array to the same object. Therefore, when you change "productObject" the final time in the loop, it affects all of the items in the array, because they are all pointing to the same exact object. What you need to do is have each element in the array point to a new instance of your object.
{ "pile_set_name": "StackExchange" }
Q: Передать массив в функцию только в том случае, если он существует Нужно сравнить несколько массивов на совпадение значений. $result = array_intersect($var_1,$var_2,$var_3,$var_4,$var_5,$var_6,$var_7); Если массив есть,то мы его передаём, если нет, то сравниваем остальные и так для каждого. Если нет $var_2, но есть остальные, то сравниваем так $result = array_intersect($var_1,$var_3,$var_4,$var_5,$var_6,$var_7);, если нет $var_5,$var_6, но есть остальные, то сравниваем так $result = array_intersect($var_1,$var_2,$var_3,$var_4,$var_7); И так далее. A: call_user_func_array() – вызывает функцию с массивом параметров. array_filter() фильтрует массив. План такой: из массива массивов оставляем только непустые элементы, и передаем их в array_intersect(): $result = call_user_func_array( 'array_intersect', array_filter( array( $var_1,$var_2,$var_3,$var_4,$var_5,$var_6,$var_7 ), function($a){ return isset($a) && is_array($a) && !!count($a);} ) ); Рабочий пример
{ "pile_set_name": "StackExchange" }
Q: Prove that a Möbius transformation $T$ sends the imaginary line to the circle $\{z: |z|=2\}$, Problem Let $T:\overline{\mathbb C} \to \overline{\mathbb C}$ be a Möbius transformation such that $T(1+2i)=1$, $T(-1+2i)=4$ and $|T(0)|=2$. Show that $|T(bi)|=2$ for all $b \in \mathbb R$. The exercise asks me to show that the imaginary line is mapped to the circle centered at $0$ of radius $2$. I've tried to solve it in the most basic way, which is to express $T(z)=\dfrac{az+b}{cz+d}$,, solve for $a,b,c,d$ from the information given and try to get to $|T(bi)|=(T(bi)\overline{T(bi)})^{\frac{1}{2}}=2$. I am still struggling with the operations but I wanted to know: Is there a simpler way or an alternative solution to this one? I would appreciate if someone could suggest another solution using properties of Möbius transformations, or cross-ratio, symmetric points or whatever it is useful in the theory of Möbius transformations to solve the problem. A: Möbius transformations map straight lines and circles to straight lines and circles. Also, Möbius transformations preserve symmetry in the sense that if $z,w$ are two points symmetric with respect to a circle or straight line $C$, then $Tz$ and $Tw$ are symmetric with respect to $T(C)$. The points $1+2i$ and $-1+2i$ are symmetric with respect to the imaginary axis. So the points $1$ and $4$ are symmetric with respect to $C = T(i\mathbb{R})$. And $C$ contains at least one point with modulus $2$. There is only one straight line in the plane with respect to which $1$ and $4$ are symmetric, the line $\operatorname{Re} z = \frac{5}{2}$. That line contains no point with modulus $2$. So $C$ must be a circle. The midpoint of that circle must lie on the straight line through $1$ and $4$, so on the real axis, and it cannot lie between $1$ and $4$. A circle with respect to which $1$ and $4$ are symmetric and whose midpoint is real $> 4$ lies entirely to the right of the line $\operatorname{Re} z = \frac{5}{2}$, so contains no point with modulus $2$. Thus the midpoint $a$ must lie to the left of $1$. Of two such circles $C_{a,r} = \{z : \lvert z-a\rvert^2 = r^2\}$ with $a < 1$ such that $1$ and $4$ are symmetric with respect to $C_{a,r}$, one is entirely contained in the interior of the other. The two points $1$ and $4$ are symmetric with respect to $C_{0,2}$. Therefore $C = C_{0,2}$ is the only such circle containing any point with modulus $2$.
{ "pile_set_name": "StackExchange" }
Q: Android: Updating Fragments (that might not yet be created) from activity Is there any way to do this? I'm working on an application that uses multiple tabs to manage bluetooth connections, messages and other stuff. I need my activity to inform each of these tabs (fragments) of certain events such as connection status, messages delivered. I used an approach where i keep a reference to each of my fragments in the adapter. The problem is that fragments are not instantiated until o switch to the tab that uses it. Is it possible to instantiate all four fragments so that i can update their view even though it has not been shown yet? Thanks a lot, and sorry for my english A: If you use a ViewPager (you mentioned "tabs") just call setOffscreenPageLimit() in onCreate() of your App (after initializing ViewPager). Set the limit to the number of your fragments. With this all of your fragments will be instantiate.
{ "pile_set_name": "StackExchange" }
Q: git root branches... how do they work? I was reading up on http://pages.github.com/ and one thing caught my eye: If you create a new root branch named gh-pages in your repository, any content pushed there will be published to [url] I searched everywhere for information about root branches, but there don't seem to be many resources on this. Does anybody know how to best explain what root branches are? My current understanding is that if there are two root branches, they essentially represent two 'repositories' within one repository. Is this accurate? A: The steps given in the link you mentioned tell you how to create one: $ cd /path/to/fancypants $ git symbolic-ref HEAD refs/heads/gh-pages $ rm .git/index $ git clean -fdx A root branch is basically a "branch" that is started as an orphan and has no previous history. While every repo starts with a master and the branches are branched off from that, a root branch will not be branched off from master ( of course there are repos with no master, renamed master etc, but master is the common case) and have its own history. Conceptually, yes, it is like two repos in a repo. In the above steps, the gh-pages is created as a root branch. Also see my answer here: How do I create a commit without a parent in Git?
{ "pile_set_name": "StackExchange" }
Q: What is the HTTP header :host, :method, :path, :scheme, :version used for? I have seen that Twitter and Facebook is using :host, :method, :path, :scheme, :version in their HTTP requests. I just wonder what they are used for? My first guess is that they use custom headers to prevent CSRF attacks. But you only need one header to prevent CSRF attacks not 5. A: This might be SPDY or experimental HTTP/2.0. See http://greenbytes.de/tech/webdav/draft-ietf-httpbis-http2-09.html#HttpRequest
{ "pile_set_name": "StackExchange" }
Q: Calling methods from class and from instance I do not understand why those scripts act differently: class A: x=3 y=5 __z=8 def __init__(self): print "Hi, I am an instance object of A class!" print "I have two components: x i y" print "Component x =", self.x print "Component y =", self.y print 'Component z=', self.__z, 'but z is private' def fun1(self): return self.x+self.y class B(A): pass i=B() print i.x, i.y, i.fun1() If I delete i=B() line and change last line to print B().x, B().y, B().fun1(), strings in __init__ are printed three times, as the class A is created everytime I call its methods. Why same thing doesn't happen when I create "i" instance? A: You created only one instance of B: i=B() So __init__ is called only once. In your other example, you created a new instance of B three times.
{ "pile_set_name": "StackExchange" }
Q: Getting values from Get and Set methods using separate classes I am new to Java: I have the following program that connects to different databases using an Enum to call the different database connection. I need to put the credentials, username and password in a class by itself but I am not sure because they are both initialized using get and set and the only way I can get this to work is called them both in the same method. First I have this class which initializes the connection strings and data elements. class DatabaseUtility { private String USERNAME; private String PASSWORD; private String HSQLDB; private String MYSQL; public DatabaseUtility() { USERNAME = null; PASSWORD = null; HSQLDB = null; MYSQL = null; } public String getUsername() { return USERNAME; } public void setUsername(String username) { USERNAME = username; } public String getPassword() { return PASSWORD; } public void setPassword(String password) { PASSWORD = password; } public String getHsdbConn() { return HSQLDB; } public void setHsdb(String hsdbConnection) { HSQLDB = hsdbConnection; } public String getMySqlConn() { return MYSQL; } public void setMySqlConn(String mySqlConnection) { MYSQL = mySqlConnection; } } Next I have an enum use to call both db types: public enum DBType { HSQLDB, MYSQL } Next I have a method which uses a switch statement to assign the different db connection based on the user preference in the main method. *This is the focus of my post, I have to call both the get and set methods in here, I would rather not set the credentials in the same method but not sure how to separate the two. import java.sql.*; class DatabaseConnectivity { DatabaseUtility dbUtil = new DatabaseUtility(); public Connection getConnection(DBType dbType) throws SQLException { dbUtil.setHsdb("jdbc:hsqldb:data/explorecalifornia"); dbUtil.setMySqlConn("jdbc:mysql://jsa/explorecalifornia"); dbUtil.setUsername("dbuser"); dbUtil.setPassword("dbpassword"); switch (dbType) { case MYSQL: return DriverManager.getConnection(dbUtil.getMySqlConn(), dbUtil.getUsername(), dbUtil.getPassword()); case HSQLDB: return DriverManager.getConnection(dbUtil.getHsdbConn(), dbUtil.getUsername(), dbUtil.getPassword()); default: return null; } } } Finally, here is the main class, notice the DBType enum called in the try catch block. import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class MultiDatabaseConnectionMain { public static void main(String[] args) throws SQLException { DatabaseConnectivity databaseConnectivity = new DatabaseConnectivity(); Connection connection = null; Statement statement = null; ResultSet resultset = null; try { connection = databaseConnectivity.getConnection(DBType.MYSQL); System.out.println("Connected"); System.out.println(); statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); resultset = statement.executeQuery("SELECT * FROM states"); resultset.last(); System.out.println("Number of rows: " + resultset.getRow()); } catch (SQLException e) { System.err.println(e); } finally { if (resultset != null) { resultset.close(); } if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } } } A: I am not 100% sure, but I think what you are asking is that you have to call dbUtil.set* and dbUtil.get* in the same method. What I would suggest is that you create enum with db properties so whatever dbType passed to the argument you can just call getters on them. You can define your enum as below. public enum DBType { //ser properties you want for db. url, username are just dummy values HSQLDB("url", "username", "password"), MYSQL("url", "username", "password"); private String url; private String username; private String password; private DBType(String url, String username, String password){ this.url = url; //set other properties } public String getUrl(){ return this.url; } //getter for all the other values } and in DatabaseConnectivity's getConnection method will be public Connection getConnection(DBType dbType) throws SQLException { return DriverManager.getConnection(dbType.getUrl(), dbType.getUsername(), dbType.getPasword()); }
{ "pile_set_name": "StackExchange" }
Q: Trying to get lazy evaluation to work for infinite stream I'm trying to implement an infinite stream with a filter operation. I want to make it not crash with a stack overflow error by using lazy evaluation for the tail. abstract class MyStream[+A] { def head: A def tail: MyStream[A] def #::[B >: A](element: B): MyStream[B] // prepend operator def filter(predicate: A => Boolean): MyStream[A] } class FiniteStream[+A](val head: A, val tail: MyStream[A]) extends MyStream[A] { override def #::[B >: A](element: B): MyStream[B] = new FiniteStream[B](element, this) override def filter(predicate: A => Boolean): MyStream[A] = { lazy val filteredTail = tail.filter(predicate) if (predicate(head)) filteredTail else filteredTail } } class InfiniteStream[+A](override val head: A, generator: A => A) extends MyStream[A] { override def tail: MyStream[A] = { lazy val tail = new InfiniteStream[A](generator(head), generator) tail } override def #::[B >: A](element: B): MyStream[B] = new FiniteStream[B](element, this) override def filter(predicate: A => Boolean): MyStream[A] = { lazy val filteredTail = tail.filter(predicate) if (predicate(head)) head #:: filteredTail else filteredTail } } object MyStream { def from[A](start: A)(generator: A => A): MyStream[A] = new InfiniteStream[A](start, generator) } val stream: MyStream[Int] = MyStream.from(1)((n: Int) => n + 1) val filtered = stream.filter(_ % 2 == 0) But this program does indeed crash with a stack overflow error. It seems like my lazy evaluation strategy does not work. The tail is still being evaluated. Why? A: The problem is caused by InfiniteStream.filter, it creates the tail filter as a lazy value but then accesses it immediately which forces the value to be evaluated. This causes the whole stream to be evaluated as recursive calls blowing up the stack. A lazy val delays the execution of the expression used to construct a variable until it is accessed. So you need to delay access to tail.filter(predicate) until the user of the stream accesses the tail. The easiest and more functional way to achieve this would be to implement filter with a view. That is filter returns a new stream that only filters the tail on demand. EG class FilterStream[+A] private (predicate: predicate: A => Boolean, stream: MyStream) extends MyStream[A] { override def head: A = stream.head override def tail: MyStream[A] = FilterStream.dropWhile(!predicate(_), stream) } object FilterStream { def apply[A](predicate: predicate: A => Boolean, stream: MyStream[A]): MyStream[A] = { new FilterStream(predicate, dropWhile(!predicate(_), stream)) } @tailrec def dropWhile[A](predicate: predicate: A => Boolean, stream: MyStream[A]): MyStream[A] = { if (stream.isEmpty || predicate(stream.head)) stream else dropWhile(predicate, stream.tail) } } Finally you should consider implementing an empty stream with its own type and object for many reasons but also so that you can terminate an infinite stream if your generator decides it wants to. object Nil extends MyStream[Nothing] { override def head: A = throw NoSuchElement override def tail: MyStream[A] = throw NoSuchElement } Head and tail are always unsafe methods, another improvement would be to use case classes to expose the shape of your stream, then users would pattern match on the stream. This would protect your users from having to use unsafe methods like head and tail.
{ "pile_set_name": "StackExchange" }
Q: why the formatting rect I get from WM_GETRECT is (2,2,98,34)? hWndEdit = CreateWindow(TEXT("edit"), NULL, WS_CHILD | WS_VISIBLE | ES_LEFT | ES_MULTILINE | ES_AUTOVSCROLL | WS_BORDER, pt.x, pt.y, 100, 50, hWnd, (HMENU)ID_EDIT, hInst, NULL); RECT* rect_temp; rect_temp = new RECT(); SendMessage(hWndEdit, EM_GETRECT, 0, (LPARAM)rect_temp); PS:the problem is what I get is always (2,2,34,98). A: from MSDN for EM_GETRECT: Gets the formatting rectangle of an edit control. The formatting rectangle is the limiting rectangle into which the control draws the text. The limiting rectangle is independent of the size of the edit-control window. You can send this message to either an edit control or a rich edit control. the part: The limiting rectangle is independent of the size of the edit-control window. CreateWindow creates whole control not what inside it, to modify inside formatting of EDIT use EM_SETRECT .
{ "pile_set_name": "StackExchange" }
Q: Should I put reference on my resume? (Not a typical situation) I worked in a small company. There were two boss (One is 'X', the other one is 'Y') who were in charge of my duties, but I did not have a good relationship with 'X'. I left the company and start to look for job. I use broadcast letters to approach companies that may need my experience and background. Since I put the name of my last company on my resume, people may call the company. If a potential employer looks for who was in charge my work duties, I guess the receptionist would re-direct the call to 'X'. Therefore I want to know should I put 'Y' contact information directly on my resume in case a potential employer wants to talk to someone in my previous company? Thanks A: Don't put references on your resume. It looks either suspicious or naive. Neither of which is good. They generally won't call unless they have interviewed you and then they ask you to give them the references. Usually the HR forms you ask them to fill out will have a space for your supervisor's name, since you worked for both, you can choose which one to put in there. Otherwise, don't ever lie about who your supervisor was. That is too easy to check. Often they will talk to the HR person instead of your boss and if you lie and say you worked for Y when the paperwork in HR says you worked for X , then you will be caught in your lie. However let this be a lesson to you and learn not to have people at work that you don't want contacted. If you have a boss you didn't get along with, it is as much your fault as his and you need to learn how to get along with people you dislike. If you know they will be contacting your former boss and there was a problem with him, it is better to be up front about it. Tell them who else inteh company can vouch for you, explain that you had a conflict and then explain how you plabn to avoid such conflicts in the future. But really, in your next job, it should be a priority to get along with your boss no matter what you think of him or her.
{ "pile_set_name": "StackExchange" }
Q: Asking for password when adding new folder in /Users/.../Sites/? My Mac's hard drive was recently replaced, and I copied my folders over from my old drive to the new one. One problem, however, is my sites folder. Originally, I had them located in /library/webserver/sites/, but now they're just in /Users/.../sites. If I try to create a new folder within any of the subfolders, it will prompt me for my admin password. The same happens in Coda when I'm trying to add a new folder, but there it just denies me. Basically, how can I fix the permissions on these files so that I no longer need to enter my admin password? The files are the same, if I try to save one of them, I also need to enter the password. Update: TextWrangler is giving me the error -5000. Update 2: So is Terminal: ERROR: Unexpected Error. (-5000) A: Easy fix. Open Terminal.app and type the following command: sudo chmod -R -N /Users/*/Sites sudo chmod -R 744 /Users/*/Sites (edit: Added -R to recursively change permissions) (edit: Kudos to ughoavgfhwless for pointing out the -N flag to reset the ACLs) You will be asked for your password. Enter it (keep in mind it won't show up in terminal). Now, assuming there isn't a more serious issue with your OS X installation, this will correct the permissions on all of the users sites folders. (If you installed OS X on a case-sensitive HFS partition, you need to make sure the case of the command matches the case of the directories. If you don't know about this, it's safe to assume you can ignore this and proceed with the above listed command.) Good luck and happy chmoding!
{ "pile_set_name": "StackExchange" }
Q: Add Queue to OpenJMS at the moment I am playing around a little bit with openJMS. I already got the examples working, but in that cases I have to add / edit the queues and topics in the admin-page. Is it possible - and how - to add queues dynamically while openJMS is running? What I want to do is, creating and destroying objects at runtime that can describe to the JMS and have their own point-to-point queue. A: Found the answer by my self, it's rather good described on the official usersguide - why didn't I find it first? http://openjms.sourceforge.net/usersguide/admin.html
{ "pile_set_name": "StackExchange" }
Q: How to handle camel-quickfix CannotSendException? I am using QuickFix/J 1.6.4 in a camel-quickfix component. Sometimes, I get the CannotSendException and it is not clear, what the exception cause is. I looked at the code, but there it seems that this exception is thrown, when the message could not be send - regardless of the reason. So how do I have to handle this exception? Do I have to implement a retry mechanism, or does the engine handle this for me? If the engine does, how can I verify, that the message is sent afterwards? Exception Stacktrace (I replaced the FIX message with *** because I cannot publish it): org.apache.camel.component.quickfixj.CannotSendException: Cannot send FIX message: *** at org.apache.camel.component.quickfixj.QuickfixjProducer.sendMessage(QuickfixjProducer.java:75) at org.apache.camel.component.quickfixj.QuickfixjProducer.process(QuickfixjProducer.java:47) at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61) at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:145) at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77) at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:468) at org.apache.camel.spring.spi.TransactionErrorHandler.processByErrorHandler(TransactionErrorHandler.java:220) at org.apache.camel.spring.spi.TransactionErrorHandler.process(TransactionErrorHandler.java:101) at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:171) at org.apache.camel.processor.Pipeline.process(Pipeline.java:121) at org.apache.camel.processor.Pipeline.process(Pipeline.java:83) at org.apache.camel.processor.ChoiceProcessor.process(ChoiceProcessor.java:117) at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77) at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:468) at org.apache.camel.spring.spi.TransactionErrorHandler.processByErrorHandler(TransactionErrorHandler.java:220) at org.apache.camel.spring.spi.TransactionErrorHandler$1.doInTransactionWithoutResult(TransactionErrorHandler.java:183) at org.springframework.transaction.support.TransactionCallbackWithoutResult.doInTransaction(TransactionCallbackWithoutResult.java:33) at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:131) at org.apache.camel.spring.spi.TransactionErrorHandler.doInTransactionTemplate(TransactionErrorHandler.java:176) at org.apache.camel.spring.spi.TransactionErrorHandler.processInTransaction(TransactionErrorHandler.java:136) at org.apache.camel.spring.spi.TransactionErrorHandler.process(TransactionErrorHandler.java:105) at org.apache.camel.spring.spi.TransactionErrorHandler.process(TransactionErrorHandler.java:114) at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:196) at org.apache.camel.processor.Pipeline.process(Pipeline.java:121) at org.apache.camel.processor.Pipeline.process(Pipeline.java:83) at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:196) at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:109) at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:91) at org.apache.camel.component.jms.EndpointMessageListener.onMessage(EndpointMessageListener.java:112) at org.springframework.jms.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:555) at org.springframework.jms.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:515) at org.springframework.jms.listener.AbstractMessageListenerContainer.doExecuteListener(AbstractMessageListenerContainer.java:485) at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.doReceiveAndExecute(AbstractPollingMessageListenerContainer.java:325) at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.receiveAndExecute(AbstractPollingMessageListenerContainer.java:243) at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.invokeListener(DefaultMessageListenerContainer.java:1103) at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.executeOngoingLoop(DefaultMessageListenerContainer.java:1095) at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:992) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1164) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:634) at java.lang.Thread.run(Thread.java:809) A: I have found the nabble on this topic and in camel-quickfix versions before Camel 2.10.0 it was probably not possible to ensure that a FIX message was sent. This has been changed with the CAMEL-5247 patch and the CannotSendException has been added. So it is now possible to configure the sending of FIX messages as a synchronous write with SocketSynchronousWrites, even if it is not recommended for performance reasons. Write messages synchronously. This is not generally recommended as it may result in performance degradation. The MINA communication layer is asynchronous by design, but this option will override that behavior if needed. So now you can also get info about failed sending of FIX messages, even if you do not use SocketSynchronousWrites. The error handling must then be implemented in the application.
{ "pile_set_name": "StackExchange" }
Q: Iterating through a two dimensional array in Ruby and substituting a string for every instance win_array = [ ["TL", "TM", "TR"], ["ML", "MM", "MR"], ["BL", "BM", "BR"], ["TL", "ML", "BL"], ["TM", "MM", "BM"] , ["TR", "MR", "BR"], ["TL", "MM", "BR"], ["TR", "MM", "BL"] ] win_array[0].map! {|x| x == "TR" ? "1" : x } #works for [0] array win_array[0..7].map! {|x| x == "TR" ? "1" : x } #doesn't work win_array.each.map! {|x| x == "TR" ? "1" : x } #doesn't work win_array.each {|x| x.map! == "TR" ? "1" : x } #doesn't work I am trying to permanently change every instance of "TR" in this 2D array to either an integer or a string. I have tried to use the .map! methods outlined above with little luck. Any help would be greatly appreciated. A: I passed the block you used to change win_array[0] (in the first attempt) to a double-nested map! call, so it sweeps over each element. win_array.map! { |a| a.map! { |x| x == "TR" ? "1" : x } }
{ "pile_set_name": "StackExchange" }
Q: I can not identify the missing argument I am trying to write a code to show the list of privileges for the object User1. class User: def __init__(self, f_name, l_name, age): self.f_name = f_name self.l_name = l_name self.age = age def describe(self): print(f"The user {self.f_name} {self.l_name} has {self.age} years old person.") def greet(self): print(f"Hi {self.f_name}, you are the Administer right now!") class Privileges: def __init__(self, privileges): self.privileges = ['add post', 'del post', 'ban users'] def show_privileges(self): print(f"These are the Admin list of privileges: {self.privileges}.") class Admin(User): def __init__(self, f_name, l_name, age): super().__init__(f_name, l_name, age) self.privileges = Privileges() user1 = Admin('Porco', 'Rosso', 42) user1.privileges.show_privileges() This is the output but I can not find this missing argument: Traceback (most recent call last): File "C:\Users\Administrator\Desktop\python_work\teste34.py", line 25, in <module> user1 = Admin('Porco', 'Rosso', 42) File "C:\Users\Administrator\Desktop\python_work\teste34.py", line 23, in __init__ self.privileges = Privileges() TypeError: __init__() missing 1 required positional argument: 'privileges' [Finished in 0.433s] I would like to complement with a code I did before where there were no need to pass the argument: class User: def __init__(self, f_name, l_name, age): self.f_name = f_name self.l_name = l_name self.age = age def describe(self): print(f"The user {self.f_name} {self.l_name} has {self.age} years old person.") def greet(self): print(f"Hi {self.f_name}, you are now the Admin!") class Admin(User): def __init__(self, f_name, l_name, age): super().__init__(f_name, l_name, age) self.privileges = ['add post', 'del post', 'ban users'] def show_privileges(self): print(f"These are SysOp list of privileges: {self.privileges}.") user1 = Admin('Porco', 'Rosso', 42) user1.describe() user1.greet() user1.show_privileges() A: self.privileges = Privileges() doesn't pass any arguments. class Privileges: def __init__(self, privileges): demands an argument named privileges. It never uses it though, so perhaps you just need to remove it, making it: class Privileges: def __init__(self): If it's supposed to have a default value, you want something like: class Privileges: def init(self, privileges=('add post', 'del post', 'ban users')): self.privileges = list(privileges) Note that you shallow copy whatever you were passed to avoid the problems with mutable default arguments and similar issues if a user passes their own list (where you don't want your modifications to affect them, or vice-versa).
{ "pile_set_name": "StackExchange" }
Q: Is it possible to make conditional includes and conditional function calls? Is following possible: 1) Somewhere I define something like: private static enum MODE { ANDROID, HOLO_EVERYWHERE } public static final MODE = MODE.ANDROID; 2) use this definitions and make some CUSTOM code, like following (or similar, or just somehow else, this code is just an example to demonstrate what I want... something like #ifdef in C...): if (MODE == MODE.ANDROID) include android.app.Activity as ACTIVITY; else include com.WazaBe.HoloEverywhere.sherlock.SActivity as ACTIIVTIY; public ExtendedActivity extends ACTIVITY { public ExtendedActivity() { if (MODE == MODE.ANDROID) this.callFunction1(); else this.callFunction2(); } } EDIT My goal is following: I don't want to wrap the two classes because I want my library to work without the other library (like the HoloEverywhere library) installed... I don't want a user of my library either change my code or include the HoloLibrary... I want him to be able to set up which base class to use and that's it... A: Yes it's possible to act like that, but not outside of the Class-Members. But it's not possible to cast an extended class 1. Outside of it, 2. the Classmembers have to be registred before running the Programm and that's not possible in this way. public ExtendedActivity extends ACTIVITY { public ExtendedActivity() { if (MODE == MODE.ANDROID) { include android.app.Activity; this.callFunction1(); } else { include com.WazaBe.HoloEverywhere.sherlock.SActivity; this.callFunction2(); } } } Otherwise you could use Reflections for exactly this Problem. See also: http://docs.oracle.com/javase/tutorial/reflect/
{ "pile_set_name": "StackExchange" }
Q: Assign result of `log10(2)` to a constant I want to assign the result of log10(2) to a constant. I did const float f = log10(2); And it tells that Initializer element is not a constant expression. I also defined a new function const float Log10(float f) { return (const float)log10(f); } But the compiler is complaining(why wouldn't it? I'm also using log10 function) that Type qualifiers are ignored on function's return type. Does that mean there are no functions which can return a constant? Then how can I do what I want to? EDIT: As some people have doubts, I included the math.h header file and linked it with -lm, but I'm using the -pedantic option in gcc, and it does not accept it. A: Assuming that f is declared at global level. Unlike C++, C does not permit runtime expressions to be used when initializing global variables. All expressions must be computable at compile time. Therefore const float f = log10(2); is not a valid C, while const float f = 0.30102999566; is valid. From C Reference: When initializing an object of static or thread-local storage duration, every expression in the initializer must be a constant expression or string literal. A: This will work #include <stdio.h> #include <math.h> int main() { const float f = log10(2); printf("%f\n", f); } But this will not work #include <stdio.h> #include <math.h> const float f = log10(2); int main() { printf("%f\n", f); } because you cannot initialise a global variable from a function return value. Note too that the compiler warns about mixing float with double. Never use float unless there are very good reasons why you cannot use double.
{ "pile_set_name": "StackExchange" }
Q: Prove that: $\overbrace{222...222}$(repeated $1980$ times), divisible by $1982$ Prove that: $\overbrace{222...222}$(repeated $1980$ times), divisible by $1982$ A: $991$ is prime. Then, Fermat's theorem says that $$10^{990}\equiv 1\pmod{991}$$ That is, the number with $990$ nines is a multiple of $991$. This was the hard part. Can you continue?
{ "pile_set_name": "StackExchange" }
Q: Triads not showing up to fight? (Java Set missing an item) I have code from two companies asoft and bsoft. I cannot change either. This is a simplified version of my situation which I'm pretty sure has enough information to the find what's causing the problem. bsoft provides IGang, which represents a gang that can battle other gangs. package bsoft; public interface IGang { /** @return negative, 0, or positive, respectively * if this gang is weaker than, equal to, or stronger * than the other */ public int compareTo(IGang g); public int getStrength(); public String getName(); public void attack(IGang g); public void weaken(int amount); } asoft provides GangWar, which allows IGangs to battle: package asoft; import java.util.*; import bsoft.*; /** An `IGang` ordered by identity (name) */ public interface ComparableGang extends IGang, Comparable<IGang> {} package asoft; import java.util.*; public class GangWar { public final Set<ComparableGang> gangs = new TreeSet<ComparableGang>(); public void add(ComparableGang g) {gangs.add(g);} public void doBattle() { while (gangs.size() > 1) { Iterator<ComparableGang> i = gangs.iterator(); ComparableGang g1 = i.next(); ComparableGang g2 = i.next(); System.out.println(g1.getName() + " attacks " + g2.getName()); g1.attack(g2); if (g2.getStrength() == 0) { System.out.println(g1.getName() + " smokes " + g2.getName()); gangs.remove(g2); } if (g1.getStrength() == 0) { System.out.println(g2.getName() + " repels " + g1.getName()); gangs.remove(g1); } } for (ComparableGang g : gangs) { System.out.println(g.getName() + " now controls the turf!"); } } } It requires the additional constraint that the Gangs you supply to it are Comparable, presumably so it can sort by name or avoid duplicates. Each gang (in an arbitrary order, Set order used here for simplicity) attacks another gang, until only one gang is left (or no gangs, if the last two have a tie). I've written a simple implementation of ComparableGang to test it out: import asoft.*; import bsoft.*; import java.util.*; class Gang implements ComparableGang { final String name; int strength; public Gang(String name, int strength) { this.name = name; this.strength = strength; } public String getName() {return name;} public int getStrength() {return strength;} public int compareTo(IGang g) { return strength - g.getStrength(); } public void weaken(int amount) { if (strength < amount) strength = 0; else strength -= amount; } public void attack(IGang g) { int tmp = strength; weaken(g.getStrength()); g.weaken(tmp); } public boolean equals(Object o) { if (!(o instanceof IGang)) return false; return name.equals(((IGang)o).getName()); } } class Main { public static void main(String[] args) { GangWar gw = new GangWar(); gw.add(new Gang("ballas", 2)); gw.add(new Gang("grove street", 9)); gw.add(new Gang("los santos", 8)); gw.add(new Gang("triads", 9)); gw.doBattle(); } } Testing it out... $ java Main ballas attacks los santos los santos repels ballas los santos attacks grove street grove street repels los santos grove street now controls the turf! The problem is, triads do not show up to the fight. In fact, printing gangs.size() right at the start of doBattle() returns 3 instead of 4. Why? How to fix it? A: The problem is, triads do not show up to the fight. In fact, printing gangs.size() right at the start of doBattle() returns 3 instead of 4. Why? Both triads and grove street have a strength of 9. Therefore they're equal in terms of Gang.compareTo (implementing Comparable). Therefore only one is permitted in a TreeSet. If you don't want to remove items which are duplicates in terms of their sort order, don't use a TreeSet... EDIT: The ComparableGang interface description indicates what's expected: /** An `IGang` ordered by identity (name) */ public interface ComparableGang extends IGang, Comparable<IGang> {} Your compareTo method does not order "by identity (name)" - it orders by strength. To be honest, it's a pretty stupid interface in the first place, as it would have been perfectly easy for asoft to create a class of public class GangNameComparator : Comparator<IGang>, and then supply that as the comparator to the tree set if they wanted to order by name. However, as they're suggesting that you should implement the comparison, you need to do so as the interface describes: public int compareTo(IGang g) { return name.compareTo(g.getName()); } However... as you note in comments (and as noted in Rob's answer), this then contradicts the convention-bustingly-named IGang description: public interface IGang { /** @return negative, 0, or positive, respectively * if this gang is weaker than, equal to, or stronger * than the other */ public int compareTo(IGang g); } It's impossible to implement ComparableGang to satisfy both its own documentation and the IGang documentation. This is basically broken by design, on asoft's part. Any code should be able to use an IGang implementation, knowing only about IGang, and relying on the implementation following the IGang contract. However, asoft broke that assumption by requiring different behaviour in an interface extending IGang. It would have been reasonable for them to add more requirements in ComparableGang, so long as they didn't violate the existing requirements of IGang. Note that this is an important difference between C# and Java. In C#, two functions in two different interfaces with the same signature can be combined into one interface that inherits both of them and the two methods remain distinct and accessible. In Java, the two methods, since they are completely abstract and have the same signature, are considered to be the same method and a class implementing the combined interfaces has only one such method. So in Java ComparableGang is invalid because it cannot have an implementation of compareTo() that satisfies the contract of ComparableGang and the contract of IGang. A: TL;DR: Use B) Below From the javadoc for Comparable (and same for Comparator too!): The natural ordering for a class C is said to be consistent with equals if and only if e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2) for every e1 and e2 of class C. Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false. In your case (simplified), equals is defined as equality of name compareTo is defined as comparison of strength This fails the above condition: when the two strengths are equal, but the two names are different when the two names are equal, but the two strengths are different (probably a condition avoided by your application logic) Answer How to correct? A) If your requirements allow you to have the set sorted by name (consistent with comment in asoft code): // will only return 0 if the strengths are equal AND the names are equal public int compareTo(ComparableGang g) { return name.compareTo(g.getName()); } B) If your requirements force you to have the set sorted by strength (and then name) (consistent with comment in bsoft code). // will return 0 if & only if the strengths are equal AND the names are equal public int compareTo(ComparableGang g) { int result = strength - g.getStrength(); if (result == 0) result = name.compareTo(g.getName()); return result; } // will return true if & only if the strengths are equal AND the names are equal public boolean equals(Object o) { if (!(o instanceof ComparableGang)) return false; ComparableGang gang2 = (ComparableGang)o; return name.equals(gang2.getName()) && strength == gang2.getStrength(); } // For this case, if it's illegal to have two gangs of same name but different // strength (it should be illegal!), then app logic must enforce this - the Set // no longer will. Comment 1: Whilst it's an issue for you to modify asoft's GangWar class, it would be better if you could place above two methods of B) into: class ComparableGangComparator implements Comparator<ComparableGang> { } and then modify how GangWar constructs the Set: public final Set<ComparableGang> gangs = new TreeSet<ComparableGang>( new ComparableGangComparator()); That way, you can leave the two methods of A) within class Gang - leaving the class with it's "true" equals & compareTo from an object identity POV. Comment 2: Contradicting comments on asoft's & bsoft's compareTo methods From a theoretical POV: If asoft's comment is not a typo, then not only has asoft extended bsoft's interface, but they've changed the required behaviour of one of the methods. This is not actually a contradiction at all - it's an override: asoft's comment "wins". From a practical POV: You need your fingers crossed asoft did this on purpose & the comment is correct. If it's a typo from asoft, then bsoft's comment is better & bsoft "wins". You could send a query to asoft or check their doc/examples to confirm.
{ "pile_set_name": "StackExchange" }
Q: Textview buffer insert warning This is probably a noobish question to ask, but hopefully someone has an answer. I'm just trying to append text to the end of a textview ('log' in this case), and the following code DOES work; log.Buffer.Insert (log.Buffer.EndIter, "\n TCPserver>>Simple Constructor"); but I'm getting a warning I would LOVE To get rid of, because I'm doing this in a lot of different places; Warning CS0618: 'Gtk.TextBuffer.Insert(Gtk.TextIter, string)' is obsolete: 'Replaced by 'ref TextIter iter' overload' (CS0618) (bubbles) A: All you have to do is create a local variable to the TextIter and then pass the Insert function a reference to that. Here's a snippet of code that should work, I do something very similar in one of my projects: var tb = log.Buffer; var ti = tb.GetIterAtLine (tb.LineCount); tb.Insert (ref ti, "TCPserver>>Simple Constructor\n"); I also tried this code with the newline at the beginning of the string, but that didn't work for me. Edit: var ti = log.Buffer.EndIter; log.Buffer.Insert (ref ti, "\n TCPserver>>Simple Constructor"); Is a bit cleaner and placing the newline at the beginning of the string also works.
{ "pile_set_name": "StackExchange" }
Q: Let $K \subset \mathbb{R^1}$ consist of $0$ and the numbers $\frac{1}{n}$ for $n = 1,2,3,...$. Prove that $K$ is compact. Let $K \subset \mathbb{R^1}$ consist of $0$ and the number $\frac{1}{n}$ for $n = 1,2,3,...$. Prove that $K$ is compact. My (Attempted) Proof $K = \left\{0, \left\{\frac{1}{n}\right\}_{n=1}^{\infty}\right\}$. Put $E =\left\{E_n\right\} = \left\{(n-1, n+1)\right\}_{n \in \mathbb{Z}}$. Note that the $(n-1, n+1)$ represents an interval in $\mathbb{R^1}$, and not a 2-tuple/ordered-pair. It is clear that $E \subset \mathbb{R^1}$, and since $E$ is a collection of open sets, $E$ is also open. Now $K \subset E$, and thus $E$ is an open cover of $K$. If we take $E_0 \in \left\{E_n\right\}$, we can see that $K \subset E_0$, and since $\{E_0\}$ is a finite collection and a subset of $E$, $K$ must be compact. $\square$ Is my proof logically sound and rigorously correct? Furthermore is my proof an example of what is generally called a constructive proof? A: Sorry, this is wrong. It's not enough to find a finite open cover of $K$. (Every set, whether compact or not, has a finite open cover.). This is a very common mistake when people first learn about compactness. Instead, you must show that if you are given an open cover of $K$, say $C$, then you can find a finite subset of $C$ that is also a cover of $K$. Your proof should begin "Let $C$ be an open cover of $K$." (That is, $C$ is a family of open sets whose union contains $K$). Then show how, no matter what is in $C$, you can find a finite subset of $C$ that is also a cover of $K$ Hint: There must be some element of $C$ that includes 0. (Why?). Call this element $g$. Then $g$ must be an open set. (Why?) What else must $g$ cover?
{ "pile_set_name": "StackExchange" }
Q: Unity3D - Gear VR Input doesn't work between scenes I'm creating a project using the Gear VR, where you can rotate an object and display information based on the swipe and tap controls on the side of the headset. Everything works great, I can rotate and select stuff when I use the touchpad on the side of the Gear VR, but when I change scenes and return to the main menu, and then go back into the scene I was just on, the functionality stops working. I am using this script I've made: using UnityEngine; using UnityEngine.SceneManagement; using System.Collections; using System; public class GearVRTouchpad : MonoBehaviour { public GameObject heart; public float speed; Rigidbody heartRb; void Start () { OVRTouchpad.Create(); OVRTouchpad.TouchHandler += Touchpad; heartRb = heart.GetComponent<Rigidbody>(); } void Update() { if (Input.GetKeyDown(KeyCode.W)) { SceneManager.LoadScene("Main Menu"); } } void Touchpad(object sender, EventArgs e) { var touches = (OVRTouchpad.TouchArgs)e; switch (touches.TouchType) { case OVRTouchpad.TouchEvent.SingleTap: // Do some stuff break; case OVRTouchpad.TouchEvent.Up: // Do some stuff break; //etc for other directions } } } I've noticed that when I start my game, an OVRTouchpadHelper is created. I don't know if that has anything to do with my problem. The error I am getting is: MissingReferenceException: The object of type 'GearVRTouchpad' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object. BUT I have not referenced this script anywhere else. When I check my scene in play mode, the script is still there with the variable assignments still present. Any help would be great! A: OVRTouchpad.TouchHandler is a static EventHandler (so it will persist through the lifetime of the game). Your script is subscribing to it when it's created but isn't unsubscribing when it's destroyed. When you reload the scene the old subscription is still in the event but the old GearVRTouchpad instance is gone. This will result in the MissingReferenceException next time the TouchHandler event fires. Add this to your class: void OnDestroy() { OVRTouchpad.TouchHandler -= Touchpad; } Now, whenever a GameObject with the GearVRTouchpad behaviour is destroyed, the static event in OVRTouchpad will no longer have a reference to it.
{ "pile_set_name": "StackExchange" }
Q: Ruby give class variable include I am playing with modules and classes to get something done. When I fire up MyClass without any kind of inheritance I used class MyClass::A4.generate, where A4 overrides the format function. A4 looks like this: class A4 < MyClass def somefunction format = { :width => 200, :height => 100 } end end But now I would want to create multiple classes (generating different kind of files) onto a couple of formats. My first attempt was a class MyClass < AnotherClass but this is more some kind of trying Javacode in Ruby, well that's what a lot of people on internet say. Now the second attempt is a bit more Ruby like: module AnotherModule def somefunction format = { :width => 50 } end end class MyClass include AnotherModule def initialize end ...... end Is something like this possible? class A4 < AnotherModule def somefunction format = { :width => 200, :height => 100 } end end MyClass::A4.new.generate If so, how? A: I didn't like your naming so from now on, let me call Afile what you called MyClass and PrintSettings what you called AnotherModule. Presuming you have PrintSettings, A4 and Afile defined like this module PrintSettings # stuff end module A4 end class Afile include PrintSettings end And now, you want to dynamically include A4 (it's important A4 is a module and not a class), you could do the following somewhere inside Afile extend format # example: class Afile include PrintSettings def format=(new_format) extend new_format end end # and then using like: file = Afile.new file.format = A4 So, to sum up, when you want to mix-in a module at the time you define the class, you use include, and when you have an object, and want that object to extend some module, you use extend.
{ "pile_set_name": "StackExchange" }
Q: How to modify width of the button which placed under DataGridSelectAllButton in WPF DataGrid? I need to modify Width of DataGridSelectAllButton so i change that using code below: <ControlTemplate x:Key="DataGridControlTemplate" TargetType="{x:Type DataGrid}"> <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True"> <ScrollViewer x:Name="DG_ScrollViewer" Focusable="false"> <ScrollViewer.Template> <ControlTemplate TargetType="{x:Type ScrollViewer}"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Button Style="{DynamicResource {ComponentResourceKey ResourceId=DataGridSelectAllButtonStyle, TypeInTargetAssembly={x:Type DataGrid}}}" Visibility="{Binding HeadersVisibility, ConverterParameter={x:Static DataGridHeadersVisibility.All}, Converter={x:Static DataGrid.HeadersVisibilityConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" **Width="20"**> </Button> <DataGridColumnHeadersPresenter x:Name="PART_ColumnHeadersPresenter" Grid.Column="1" Visibility="{Binding HeadersVisibility, ConverterParameter={x:Static DataGridHeadersVisibility.Column}, Converter={x:Static DataGrid.HeadersVisibilityConverter}, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/> <ScrollContentPresenter x:Name="PART_ScrollContentPresenter" CanContentScroll="{TemplateBinding CanContentScroll}" Grid.ColumnSpan="2" Grid.Row="1" d:IsLocked="True"/> <ScrollBar x:Name="PART_VerticalScrollBar" Grid.Column="2" Maximum="{TemplateBinding ScrollableHeight}" Orientation="Vertical" Grid.Row="1" Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}" Value="{Binding VerticalOffset, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}" ViewportSize="{TemplateBinding ViewportHeight}" d:IsLocked="True"/> <Grid Grid.Column="1" Grid.Row="2" d:IsLocked="True"> <Grid.ColumnDefinitions> <ColumnDefinition Width="{Binding NonFrozenColumnsViewportHorizontalOffset, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <ScrollBar x:Name="PART_HorizontalScrollBar" Grid.Column="1" Maximum="{TemplateBinding ScrollableWidth}" Orientation="Horizontal" Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}" Value="{Binding HorizontalOffset, Mode=OneWay, RelativeSource={RelativeSource TemplatedParent}}" ViewportSize="{TemplateBinding ViewportWidth}" d:IsLocked="True"/> </Grid> </Grid> </ControlTemplate> </ScrollViewer.Template> <ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/> </ScrollViewer> </Border> </ControlTemplate> Problem is that when i change the Width of the DataGridSelectAllButton,i must change width of the Buttom,which placed under DataGridSelectAllButton on each row too,but i don't know how?Any Idea? A: <Style TargetType="{x:Type DataGridRowHeader}" x:Key="DataGridRowHeaderStyle"> <Setter Property="Width" Value="20"/></Style>
{ "pile_set_name": "StackExchange" }
Q: PHP encoding problem : symbols showing interrogation mark Symbols like "é" show interrogation marks in my php site. My MySQL database uses utf8mb4_general_ci everywhere The HTML is UTF-8 : meta charset is set to UTF-8 The response header is : Content-Type: text/html; charset=UTF-8 My SQL requests (in the PHP) that feature an "é" symbole result in a broken answer, but the same requests via phpMyAdmin (directly on the server) are working. Also, for some reason, one "é" symbol works on my site, all the rest of them are interrogation marks (and they're all in a datatable generated by the same php code) Would the problem perhaps be with the apache server ? A: Try running the following query before you fetch the data. SET NAMES 'utf8mb4'
{ "pile_set_name": "StackExchange" }
Q: Using firebase cloud functions to listen for changes in the background My DB schema is as follows: "Works" : { "-LLiIlsIS1XJonGRa8j6" : { "acceptedDate" : { }, "answers" : { }, "category" : "matematyka", "createDate" : { }, "creatorID" : "KjxVHwUirhUwHRbBDhMCRoHliMQ2", "finishDate" : { }, "firebaseKey" : "-LLiIlsIS1XJonGRa8j6", "level" : "Liceum", "number" : 1, "pointAmount" : 8, "pointBoost" : 0, "rated" : 1, "reported" : false, "solverID" : "XKUNXPozOsMM3sgQXY2F5iVMAkZ2", "state" : "Completed", "taskAmount" : 1, "workText" : "Czy pierwiastek z liczby parzystej zawsze jest liczba parzysta?" }, "-LLiKGP3Zq1uX3ugRzSF" : { "acceptedDate" : { }, "answers" : { } }, "available" : false, "boostAmount" : 0, "category" : "matematyka", "createDate" : { }, "creatorID" : "KjxVHwUirhUwHRbBDhMCRoHliMQ2", "finishDate" : { }, "firebaseKey" : "-LLiKGP3Zq1uX3ugRzSF", "level" : "Liceum", "number" : 2, "pointAmount" : 8, "pointBoost" : 0, "rated" : 1, "reported" : false, "solverID" : "XKUNXPozOsMM3sgQXY2F5iVMAkZ2", "state" : "Completed", "taskAmount" : 1, "workText" : "Czy pierwiastek z liczby ujemnej zawsze jest liczba ujemna?" } So I want the cloud function to fire up each time a new object is pushed to "Works". So far I have this code: export const onWorkAddition = functions.database.ref('Works').onCreate(snap => { console.log('new work created'); console.log(snap.val()); }); Unfortunately this code doesn't log anything. What am I missing? I am new to cloud functions so if I'm missing something important let me know. A: I needed to do it like this export const onWorkAddition = functions.database.ref('/Works/{workId}').onCreate((snapshot, context) => { console.log(context.params.workId); });
{ "pile_set_name": "StackExchange" }
Q: Force Carbonating and Serving Kegs Simulanteously I'm trying to come up with the most cost effective way to have kegs both force carbonating at 20+ PSI and (other) kegs being served at 10-12 PSI. Obviously, I could buy an entirely separate regulator and CO2 tank, but that can be quite expensive. So far my only other idea has been to attach a manifold to a regulator on a CO2 tank and attach a second regulator to the outlet of that manifold. I'd then attach a second manifold to the second regulator. The first regulator would be run at force carbonation pressures while the second would be run at serving pressures. This all seems a bit Rube Goldberg-esque but I'm curious if anyone's either tried this with success or has a more practical idea. A: You definitely don't need a second tank. What you need is something like this. If you have an existing dual-gauge regulator you can just remove the cylinder stem and use a nipple to couple a single-gauge regulator on there. Or if you have a single-gauge regulator you'd just remove the cap nut from where the second (high-pressure) gauge would be and do the same kind of thing. What you have to look out for is the thread directions on these different fittings. Some have all right-threaded parts. Some have a mix of right-and-left threads. Some have all left-threads. Make double sure you're getting the right threads, and also note the threads before taking anything apart, as you may be tightening something you thought you were loosening. You'll want to make sure your attaching regulators via the port labeled 'HI' or 'HIGH' on the back so your second regulator is getting full pressure from the tank, not stepped down pressure from the first regulator. And don't forget to use a couple wraps of teflon tape when making threaded unions. This will give you two (or I guess as many as you wanted) regulators drawing from one tank with fully independent pressure control, easy peasy.
{ "pile_set_name": "StackExchange" }
Q: WCF caching like it was with WebServices Does anybody know if WCF support kind of caching like it was with Web Services or should i implement it manually? A: I believe you need to set the [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)] attribute on your WCF implementation class, as in [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)] public class MyService: IMyService { public void SomeMethod() { HttpContext.Current.Cache["someKey"] = "someValue"; } } See http://msdn.microsoft.com/en-us/library/system.servicemodel.activation.aspnetcompatibilityrequirementsmode.aspx for more details.
{ "pile_set_name": "StackExchange" }
Q: Asp.net thread question In my ASP.NET MVC application I have a number of threads that wait for a certain length of time and wake up to do some clean tasks over and over. I have not deployed this application to a production server yet but on my dev machine they seem to work as expected. For these threads to work the same on IIS7 do I need to look out for anything? Will IIS7 keep my threads alive indefinitely? are there implications to worry about? Also I want to queue, lets say 50 objects that were created through various requests and process them all in one go. I'd like to maintain them inside a list and then process the list which means that the list object has to be kept alive indefinitely. I'd like to avoid serializing my objects into the DB in order to maintain this queue. What is the correct way of achieving this? A: Will IIS7 keep my threads alive indefinitely? No, if the application pool recycles (if there's a long inactivity or some memory threshold is hit) those threads will be stopped as the application will be unloaded from memory. If those objects are so much precise I wouldn't recommend you keeping them in memory but rather serialize them to some persistent storage so that they could be processed later in case of failure.
{ "pile_set_name": "StackExchange" }
Q: 型の不一致 kotlin.IntArray public interface AsyncCallback { public fun preExecute() public fun postExecute(result: JSONObject) public fun progressUpdate(progress: Int) public fun cancel() } 〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜 fun onProgressUpdate(vararg _progress: Int) { super.onProgressUpdate(*_progress) mAsyncCallback!!.progressUpdate(_progress[0]) } *_progress の部分でエラーが出ています Type mismatch Required: kotlin.Array<(out) kotlin.Int!>! Found: kotlin.IntArray Javaの場合Integerですが、Kotlinだとエラーになります。 protected void onProgressUpdate(Integer... _progress) ~~~~~~~~~~~~~~ ↓値の渡し先 @SuppressWarnings({"UnusedDeclaration"}) protected void onProgressUpdate(Progress... values) { } 直し方がわかりません。 A: 勝手な推測ですがおそらくandroid.os.AsyncTaskのonProgressUpdateメソッドをオーバライドしたいんですね。 であればoverride fun onProgressUpdate(vararg p: Int?)というシグネチャにすれば解決するはずです。 下記コードはvalidです(Kotlinのバージョンは1.0.0-beta-1103)。 class Foo: AsyncTask<A, Int, C>() { override fun onProgressUpdate(vararg p: Int?) { super.onProgressUpdate(*p) } } 質問内容とは関係ないアドバイスですが、質問内容をもう少し具体的かつシンプルにすると回答が集まりやすいと思いますよ。例えば使用しているKotlinバージョンなど。 あとはまずKotlinのドキュメントを一通り読んでみてはいかがでしょうか?
{ "pile_set_name": "StackExchange" }
Q: TabBar / "More View Controller" - Possible to have icons in colors other than black? Is it possible to have the icons in a TabBar and / or the "More navigation controller" be in colors other than grey and black? I tried changing the color of the icon I set for the view controller using UITabBarItem's - (id)initWithTitle:(NSString *)title image:(UIImage *)image tag:(NSInteger)tag method. My client thinks the interface is too dark and want's to brighten it up with some colorful icons... Thanks! A: Coming a bit late to this but my approach to change the More controller icons was to (and not sure if Apple will approve it) do the following: id moreNavController = [tabs.moreNavigationController.viewControllers objectAtIndex:0]; if ([moreNavController respondsToSelector(@selector(view)]) { UITableView *t = (UITableView*)[moreNavController view]; [t setDataSource:self]; } Then I just implement the UITableViewDatasourceProtocol methods -(NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section{ id o =[tabs.moreNavigationController.viewControllers objectAtIndex:0]; return [o tableView:tableView numberOfRowsInSection:section]; //let the existing data source actually return the number of rows } and -(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath { /* configure cell as normal with what ever image in the imageView property*/ cell.imageView.image = <someimageobj> } A: Nope :( The buttons on a tabbar or toolbar are drawn with the alpha channel so they don't have color although the .png has. So, you can subclass the TabBar or ToolBar and implement your own buttons drawing the entire bar.
{ "pile_set_name": "StackExchange" }
Q: Which method called when UITableView scroll down and bounce? i parse some data from XML. I want my table to show first 10 rows, then when user scroll to bottom and table bounce, then it update (load new data from xml) and then show new rows. For example firstly user get 10 rows, then other 10, then rest 10. I want to know which method is called when tableview bounce to bottom, and some advice how to implement it, thank you. A: UITableView is a subclass of UIScrollView, and UITableViewDelegate conforms to UIScrollViewDelegate. So the delegate you attach to the table view will get events such as scrollViewDidScroll:, and you can call methods such as contentOffset on the table view to find the scroll position. - (void)scrollViewDidScroll:(UIScrollView *)aScrollView { CGPoint offset = aScrollView.contentOffset; CGRect bounds = aScrollView.bounds; CGSize size = aScrollView.contentSize; UIEdgeInsets inset = aScrollView.contentInset; float y = offset.y + bounds.size.height - inset.bottom; float h = size.height; // NSLog(@"offset: %f", offset.y); // NSLog(@"content.height: %f", size.height); // NSLog(@"bounds.height: %f", bounds.size.height); // NSLog(@"inset.top: %f", inset.top); // NSLog(@"inset.bottom: %f", inset.bottom); // NSLog(@"pos: %f of %f", y, h); float reload_distance = 10; if(y > h + reload_distance) { NSLog(@"load more rows"); } } by neoneye
{ "pile_set_name": "StackExchange" }
Q: Compose method in recompose Library I was looking at the compose function in recompose library by @acdlite to compose boundary conditions for Higher Order Components and this is what it looks the compose function looks like const compose = (...funcs) => funcs.reduce((a, b) => (...args) => a(b(...args)), arg => arg); However, I tried Eric-Elliott's one liner approach to compose, from https://medium.com/javascript-scene/reduce-composing-software-fe22f0c39a1d, specifically, this piece of code. const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x); I tried using both these variants, in my react component like so, const ListWithConditionalRendering = compose( withLoadingIndicator, withDataNull, withListEmpty )(Users); and they both seem to work fine. I am unable to understand if there is any difference in the way the above functions work, if so, what are they. A: There's a few differences for very niche scenarios that might be helpful to be aware of. The first one precomposes a function, which means it calls reduce() when it is composed rather than when it will be called. In contrast, the second approach returns a scoped function that calls reduceRight() when it is called, rather than when it was composed. The first method accepts multiple arguments to the last function in the array, while the second method only accepts one argument: const compose1 = (...funcs) => funcs.reduce((a, b) => (...args) => a(b(...args)), arg => arg); const compose2 = (...fns) => x => fns.reduceRight((v, f) => f(v), x); const f = s => (...args) => (console.log('function', s, 'length', args.length), args); compose1(f(1), f(2), f(3))(1, 2, 3); compose2(f(4), f(5), f(6))(1, 2, 3); The first method may result in a stack overflow if the array of functions is very large because it is pre-composed, whereas the second method is (relatively)† stack safe: const compose1 = (...funcs) => funcs.reduce((a, b) => (...args) => a(b(...args)), arg => arg); const compose2 = (...fns) => x => fns.reduceRight((v, f) => f(v), x); const f = v => v; try { compose1.apply(null, Array.from({ length: 1e5 }, () => f))(); console.log('1 is safe'); } catch (e) { console.log('1 failed'); } try { compose2.apply(null, Array.from({ length: 1e5 }, () => f))(); console.log('2 is safe'); } catch (e) { console.log('2 failed'); } † The second method will still result in a stack overflow if ...fns is too large because arguments are also allocated on the stack. A: If you are interested in what structure the reduce-composition actually builds, you can visualize it as follows: /* original: const compose = (...funcs) => funcs.reduce((a, b) => (...args) => a(b(...args)), arg => arg); */ const compose = (...funcs) => funcs.reduce((a, b) => `((...args) => ${a}(${b}(...args)))`, $_("id")); const $_ = name => `${name}`; const id = x => x; const inc = x => x + 1; const sqr = x => x * x; const neg = x => -x; const computation = compose($_("inc"), $_("sqr"), $_("neg")); console.log(computation); /* yields: ((...args) => ((...args) => ((...args) => id(inc(...args))) (sqr(...args))) (neg(...args))) */ console.log(eval(computation) (2)); // 5 (= id(inc(sqr(neg(2)))) So what is going on here? I replaced the inner function (...args) => a(b(...args)) with a Template-String and arg => arg with the $_ helper function. Then I wrapped the Template-String in parenthesis, so that the resulting String represents an IIFE. Last but not least I pass $_ helper functions with proper names to compose. $_ is a bit odd but it is really helpful to visualize unapplied/partially applied functions. You can see from the computational structure that the reduce-composition builds a nested structure of anonymous functions and rest/spread operations are scattered throughout the code. Visualizing and interpreting partially applied functions is hard. We can simplify it by omitting the inner anonymous function: const compose = (...funcs) => funcs.reduce($xy("reducer"), $_("id")); const $_ = name => `${name}`; const $xy = name => (x, y) => `${name}(${x}, ${y})`; const id = x => x; const inc = x => x + 1; const sqr = x => x * x; const neg = x => -x; console.log( compose($_("inc"), $_("sqr"), $_("neg")) // reducer(reducer(reducer(id, inc), sqr), neg) ); We can further simplify by actually running the composition: const compose = (...funcs) => funcs.reduce((a, b) => (...args) => a(b(...args)), $x("id")); const $x = name => x => `${name}(${x})`; console.log( compose($x("inc"), $x("sqr"), $x("neg")) (2) // id(inc(sqr(neg(2)))) ); I believe that the visualization of complex computations like this is a powerful technique to comprehend them correctly and to gain a better understanding of nested/recursive computational structures.
{ "pile_set_name": "StackExchange" }
Q: Convergence and Divergence of Improper Integral $\int_{0}^{\infty}x^m ( \ln x)^n dx$ Is this integral $\int_{0}^{\infty}x^m (lnx)^n dx$ divergent or convergent? Why? I understand that if we plot the integrand at any values of m,n (except zero), we can clearly see that the limit does not exist, however how can I prove this mathematically, if possible? A: For $m = n = 1$ we have $$\int_0^{\infty}x \ln x \text{ d} x = \left[{x^2\over 4}(2 \ln x -1)\right]_0^{\infty} = \lim_{x\to \infty}{x^2\over 4}(2 \ln x -1) \to \infty$$ Since we disproved convergence for a particular case, the integral cannot converge for the general case either.
{ "pile_set_name": "StackExchange" }
Q: R referring to elements of a vector in a list of vectors If I have a list with e.g. coordinates in it, how can I refer to the elements of each element of the list individually? coord=list(c(104,1.5),c(144.97,-37.78),c(121.5,25.03)) What I'd like to do is something like for(i in coord){ print(i[1]) print(i[2])} The above example doesn't work (In practice of course I'll use them to plot something). The following one does work but I'm trying to see if there is a more elegant 'R' way to do it. coord=c(c(104,1.5),c(144.97,-37.78),c(121.5,25.03)) for(i in seq(1,length(coord),2)){ print(coord[i]) print(coord[i+1]) } A: I don't quite get what exactly do you want... aren't you trying to do this? > coord[[1]][1] [1] 104
{ "pile_set_name": "StackExchange" }
Q: How can I extract a javascript value in scrapy I am using scrapy to crawl youtube videos and I need the language of title/description of the video.When I use browser view source on this video I can inside a script tag there is a variable 'METADATA_LANGUAGE': 'no'. Can I extract this value in scrapy and its extensions or I should download and parse html with libraries like beautifulsoup / htmlparser. A: Based on this you can select the text of script with xpath/css and then use regex to search the variable name. Assum the first script contains the METADATA_LANGUAGE: items = response.xpath('//script/text()')[0].re(".*METADATA_LANGUAGE.*")
{ "pile_set_name": "StackExchange" }
Q: Are anime budget and worldwide gross data publicly available? On Wikipedia there are two lists about box office bombs and highest-grossing films. On nearly every movie page on Wikipedia, there are two values: budget and box office, showing how much a film costs and how much it yields. Is there something like this for anime, considering home videos, worldwide licenses and/or merchandising? A: I doubt that the budgets are available for every series. Studios rarely have any incentive to release these numbers, and it could make fans angry if they think the studio isn't giving their favorite series a big enough budget. I was able to find some information. A single episode of anime generally costs around 10 million yen (see here or here, roughly $115,000 USD), though the exact number varies depending on production quality, voice actors, licensing fees, and other factors. The best I've been able to find is this, which really only has a few anime series from 2005 and earlier, and also includes a lot of western animation. As a note, sales figues, unlike production figures, are widely reported. This forum thread has a lot of data related to that. This gives a sort of upper bound on the production costs, but it's not usually very accurate. For instance, the first season of Fate/Zero sold 52,133 bluray boxes at 39,900 yen each (roughly $496 USD), so the total revenue is about 2 billion yen, which for a 13 episode show corresponds to 160 million yen per episode. That's certainly way more than they actually spent.
{ "pile_set_name": "StackExchange" }
Q: How to present an invisible interacting button above the UIImageView In my app I want to pick some image from the gallery or the camera via ImagePicker (this part works fine though) and present it in UIImageView. So in IB I created a view, button, and a method (which selected an image): @property (retain, nonatomic) IBOutlet UiImageView *sourceImageView; @property (retain, nonatomic) IBOutlet UiButton *selectImageButton; -(IBAction)selectImage; On the first run of the app I need to present a button instead of a View, so I put it above the view in IB and make the view hidden. But after the user picks up the image, it needs to be presented in the view instead of the button, and if user wants to select another image, he sould pressed on the displayed image and pick another. So, I think, I need to set the button invisible somehow, but it should be above the view and react to touches. I'm trying an obvious decision: -(void)viewDidAppear{ _selectedImageButton.hidden=YES; _sourceImageView.hidden=NO; and it's untouchable. I tried also to set the _selectImageButton.alpha to minimum values, it works, until it's equal to 0. But in that case a bit of a button is still visible above the view, and I can't accept it. I feel that there should be some easy way to do this, because the problem seems to be common. A: from H2CO3's comment: If you create a button of style UIButtonTypeCustom, then it will be invisible by default (due the lack of sensible default graphics properties) just have the button be transparent that way and there is no need to hide anything
{ "pile_set_name": "StackExchange" }
Q: MySQL InnoDB table shows a negative number of rows in phpMyAdmin I just converted a MyISAM table to InnoDB with around 1.4 million rows. When I converted it to InnoDB, it now shows -1.4 million rows. The table still works as expected, but why does it shows negative in the rows column? A: If you look closely, you'll notice it's not a negative sign, it's a tilde, which means "approximately". InnoDB tables do not store the exact count of rows in the table, so you are being shown approximately how many rows are in the table. If you use the COUNT(*) function you can retrieve the exact number of rows.
{ "pile_set_name": "StackExchange" }
Q: Javascript/HTML - Problema al hacer un buscador abierto Estoy intentando hacer un buscador en javascript que recibe las variables de una base de datos desde PHP y MYSQLI y necesito realizar una busqueda de todos los resultados similares a la palabra introducida de tal forma que me inserte en mi html los resultados similares. En resumen, en Javascript tengo un array de variables y cuando el usuario llama la funcion para buscar (desde el html), necesito que el Javascript agregue el resultado mas cercano a la palabra introducida y los resultados mas similares(estos resultados similares pueden tener menos caracteres que el original e incluso mas caracteres que el similar) Por Ejemplo: -La palabra que el usuario introduce es "Escritor" -La lista de resultados que tengo incluye: ["Escritor","Escrito","Escritura","Escrupuloso","Estudio"] -Deberia mostrar como resultado "Escritor" y como resultado similares "Escrito", "Escritura" A: Yo lo tengo asi en alguna pagina. Esto esta dentro de un for. if(array[x].toUpperCase().indexOf(PALABRA_BUSCADA.toUpperCase()) != -1){ alert(array[x]); } espero te ayude
{ "pile_set_name": "StackExchange" }
Q: Question about the asymptotic growth rate of two functions If we have arbitrary constants $x > 1$ and $y > 0$, how can I go about proving that $x^n$ is not $O(n^y)$? I think this may be achievable using recurrences but I am not sure about the methodology behind that, so any help is appreciated. A: We can compute the limit of the ratio of the two functions by applying L'Hopital's rule $\lceil y \rceil$ times: $$\lim_{n\to\infty} \frac{x^n}{n^y} = \lim_{n\to\infty}\frac{x^n\log^y x}{y!}= \infty$$ This is clear as $y$ is a defined constant and thus the bottom half of the fraction is inconsequential as $n\to\infty$. Now, for $x^n$ to be $O(n^y)$ we require $\exists c$ such that $x^n \le c \cdot n^y \implies \frac{x^n}{n^y} \le c$ beyond some $n_0$. As $n \to \infty$ we have calculated the ratio which leads to a contradiction as no $c$ can exist which is $\ge \infty$ beyond $n_0$. As such, $x^n$ is not $O(n^y)$.
{ "pile_set_name": "StackExchange" }
Q: Interpreting perturbation theory in general relativity In quantum mechanics we start with a Hamiltonian $H_0$ for which we know the exact eigenstates and energy eigenvalues. We perturb it by a known term $H$, and then attempt to compute (approximately) the new eigenstates and eigenvalues. In general relativity, my understanding is we start with a metric $g_{\mu \nu}$, and perturb it by a known $h_{\mu \nu}.$ But in my lecture notes (http://arxiv.org/pdf/0804.2595.pdf), the lecturer shows how to compute $h_{\mu \nu}$. I thought we perturbed a system by a known quantity; can someone clarify the regular procedure of perturbation theory in general relativity, and what typical 'goals' are? The only alternative I see is that we perturb a known solution $g_{\mu \nu}$ by an unknown perturbation $h_{\mu \nu}$, state how we would like the stress-energy $T_{\mu \nu}$ to change, and then try and compute $h_{\mu \nu}$ such that it does. Could this be the correct interpretation? A: Yes, your second guess is more or less correct. In GR, perturbing the metric is the usual way of doing perturbation theory. One writes for the true metric $g_{\mu\nu}$ an expansion of the form $$ g_{\mu\nu} = g^{(0)}_{\mu\nu}+h_{{\mu\nu}}+O(h^2), $$ where $g^{(0)}_{\mu\nu}$ is known and usually called background metric. One then substitutes this into the Einstein equations and find equations for $h_{\mu\nu}$. Solving those then gives you the first order correction to the background metric.
{ "pile_set_name": "StackExchange" }
Q: Coding challenge on career cup, finding the smallest sum partition Question: Given an integer array. Find out the equal sum partition with the smallest sum. For example: a = [1, 3, 2, 2, 1, 3]. There are three equal sum partitions: [(1, 3), (2, 2), (1, 3)], [(1, 3, 2), (2, 1, 3)] and [(1, 3, 2, 2, 1, 3)]. First one has the smallest equal sum, so return 4 Notice you cannot reorder the input array. Thoughts: Initially I want to keep summing every two pair, every three pair,...,etc until the only subarray left would be the array itself. Then I would be able to isolate the minimum with that approach. Although, I feel like this is a decent strategy I am lost on how to achieve implementing this. Does anyone have any suggestions? A: #include <vector> #include <iostream> #include <algorithm> #include <numeric> using namespace std; template <class T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { for (auto& val : v) { os << val << " "; } os << std::endl; return os; } template <class T> std::ostream& operator<<(std::ostream& os, const std::vector<std::vector<T>>& v) { for (auto& v2 : v) { os << "| "; for (auto& v3 : v2) { os << v3 << " "; } } os << "|" << std::endl; return os; } int main() { std::vector<int> v = {1, 3, 2, 2, 1, 3}; //std::cout << v; std::vector<int> partitionsums; partitionsums.push_back(std::accumulate(v.begin(), v.end(), 0)); // for each number we can get that divides the v.size() for (size_t i = 2; i < v.size(); ++i) { if (v.size() % i == 0) { const size_t cnt = i; const size_t len = v.size() / i; //std::cout << len << " " << i << "\n"; // we create `cnt` number of vectors each of `len` size std::vector<std::vector<int>> vs; for (size_t j = 0; j < cnt; ++j) { std::vector<int> tmp; for (size_t k = 0; k < len; ++k) { const size_t idx = j * len + k; tmp.push_back(v[idx]); } vs.push_back(tmp); } //std::cout << vs; // for each vector we need to calculate the sum std::vector<int> sums; for (auto& v2 : vs) { sums.push_back(std::accumulate(v2.begin(), v2.end(), 0)); } // if all sums are the same, add the sum value to the set if (std::unique(sums.begin(), sums.end()) == sums.begin() + 1) { partitionsums.push_back(sums.front()); } } } // get the smallest sum of the partitions std::sort(partitionsums.begin(), partitionsums.end()); const int smallest_sum = partitionsums.front(); std::cout << "The smallest sum of partitions of vector: " << v << "\tis: " << smallest_sum << std::endl; return 0; } Live version available at onlinegdb. Use dynamic programming and split the problem into sub-problems: Create a "partition" of the input array of defined size Calculate the sum of all partitioned arrays Check if the sum is unique Find the smallest of unique sums.
{ "pile_set_name": "StackExchange" }
Q: android launch zxing scanner only after entering fragment I have an app that uses SherlockFragment and hamburger menu by jeremyfeinstein "SlidingMenu" also my app uses zxing barcode scanner when I enter a fragment , in the fragment I have a button that launches the barcode scanner, but what I need is that when the fragment enters, to launch the scanner, then when the scanner view gets dismissed, dont do anything, the problem is that now i have my scan(); inside onCreateView so when the scanner gets dismissed it fires again, here some code, in PhoneMenuList.java ,,, the fragment gets called: private void switchFragment(Fragment fragment, int index) { if (getActivity() == null) return; /* // doesnt work if (newContent instanceof PhoneValidateView) { ((PhoneValidateView) newContent).scan(); } */ MainActivityPhone change = (MainActivityPhone) getActivity(); change.switchContent(newContent); } then on PhoneValidateView.java public class PhoneValidateView extends SherlockFragment{ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ scan(); } ... } so how to show the "scan()" only when fragment loaded by table? not every time fragment appears? thanks! A: Add a state to your fragment and only call scan() when it is in inital state. private boolean mScannerLaunched = false; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ // ... mScannerLaunched = savedInstanceState != null && savedInstanceState.getBoolean("mScannerLaunched", false); if (!mScannerLaunched) { scan(); mScannerLaunched = true; } } public void onSaveInstanceState(Bundle state) { super.onSaveInstanceState(state); state.putBoolean("mScannerLaunched", mScannerLaunched); }
{ "pile_set_name": "StackExchange" }
Q: wpf toolkit, datagrid, comboboxcolumn In a datagrid I have two DataGridComboBoxColumns. The items of one of these columns should depend on what is selected in the other column. The underlying collection used to model this is a dictionary<string,List<string>>. How should i go about implementing this? I can't seem to hook up to any relevant events on the columns, and I cant find any databinding scenarios that support this.. A: Instead of using a DataGridComboBoxColumn for the second column, I went with a DataGridTemplateColumn with an embedded Combobox. For the itemsource i defined a converter: string -> List<string>. The converter translates the value of the selecteditem of the other DataGridComboBox (which is bound to Navn) into List<string>, this is just a dictionary lookup. Like so: <my:DataGridTemplateColumn> <my:DataGridTemplateColumn.CellTemplate> <DataTemplate> <ComboBox SelectedItem="{Binding Værdi}" ItemsSource="{Binding Navn, Converter={StaticResource dimensionToValues}}" > </ComboBox> </DataTemplate> </my:DataGridTemplateColumn.CellTemplate> </my:DataGridTemplateColumn>
{ "pile_set_name": "StackExchange" }
Q: Isn't recv() in C socket programming blocking? In Receiver, I have recvfd=accept(sockfd,&other_side,&len); while(1) { recv(recvfd,buf,MAX_BYTES-1,0); buf[MAX_BYTES]='\0'; printf("\n Number %d contents :%s\n",counter,buf); counter++; } In Sender , I have send(sockfd,mesg,(size_t)length,0); send(sockfd,mesg,(size_t)length,0); send(sockfd,mesg,(size_t)length,0); MAX_BYTES is 1024 and length of mesg is 15. Currently, It calls recv only one time. I want recv function to be called three times for each corresponding send. How do I achieve it? A: To send discrete messages over a byte stream protocol, you have to encode messages into some kind of framing language. The network can chop up the protocol into arbitrarily sized packets, and so the receives do not correlate with your messages in any way. The receiver has to implement a state machine which recognizes frames. A simple framing protocol is to have some length field (say two octets: 16 bits, for a maximum frame length of 65535 bytes). The length field is followed by exactly that many bytes. You must not even assume that the length field itself is received all at once. You might ask for two bytes, but recv could return just one. This won't happen for the very first message received from the socket, because network (or local IPC pipe, for that matter) segments are never just one byte long. But somewhere in the middle of the stream, it is possible that the fist byte of the 16 bit length field could land on the last position of one network frame. An easy way to deal with this is to use a buffered I/O library instead of raw operating system file handles. In a POSIX environment, you can take an open socket handle, and use the fdopen function to associate it with a FILE * stream. Then you can use functions like getc and fread to simplify the input handling (somewhat). If in-band framing is not acceptable, then you have to use a protocol which supports framing, namely datagram type sockets. The main disadvantage of this is that the principal datagram-based protocol used over IP is UDP, and UDP is unreliable. This brings in a lot of complexity in your application to deal with out of order and missing frames. The size of the frames is also restricted by the maximum IP datagram size which is about 64 kilobytes, including all the protocol headers. Large UDP datagrams get fragmented, which, if there is unreliability in the network, adds up to greater unreliability: if any IP fragment is lost, the entire packet is lost. All of it must be retransmitted; there is no way to just get a repetition of the fragment that was lost. The TCP protocol performs "path MTU discovery" to adjust its segment size so that IP fragmentation is avoided, and TCP has selective retransmission to recover missing segments.
{ "pile_set_name": "StackExchange" }
Q: Jquery Array Contains I have an array that all the name of all selected check boxes. How can I check if that array contains specific value other than given string. var selected_options = $('input[checked=checked]').map( function() { return $(this).attr('name'); }).get(); How can I check if the array selected_options has other elements other than lets say 'CancelTerms'? A: I don't think there is the need to create an array for that. Just filter out element not having a certain name value using attribute equals selector with :not() pseudo-class selector ( or not() method ) and get its length. if($('input[checked=checked]:not([name="CancelTerms"])') .length > 0){ // code } If you would like to do it with the array then use Array#some method. if(selected_options.some(function(v){ return v != "CancelTerms"; })){ // code } or Array#filter method can be used. if(selected_options.filter(function(v){ return v!= "CancelTerms"; }).legth){ // code }
{ "pile_set_name": "StackExchange" }
Q: Edit MenuBar with Css in JavaFx Thanks for reading. I have trying to edit a menu-bar with css but the menu item don't changed. I realized the parts of menu-bar are: Menubar, menu, menu-items but the last one don't work rightly. Help .menu-bar{ -fx-background-color: peru; -fx-border-color: #f0cd90; -fx-border-width: 2 } .menu-bar .label { -fx-font-size: 25 pt; -fx-font-family: "Segoe UI Light"; -fx-text-fill: #dedede; } .menu:hover { -fx-background-color: #bc784e; } .menu-item .label{ -fx-font-size: 25 pt; -fx-label-line-length: 8; -fx-background-color: #cc66ff; } I'm using Scene builder. A: Make: .menu .label{ -fx-text-fill: black;} Reference: https://forums.oracle.com/message/10402062
{ "pile_set_name": "StackExchange" }
Q: Imported GPX files into QGIS ver 2.0.1-fields missing? Just imported GPX file into QGIS.Opened attribute table. where are the following fields? Latitude,Longitude,,symbol,and time . Am I missing something??I used a Garmin Oregon 300 to collect the data. Verified that all the listed fields have info in them using other both Mac and Windows GPS programs. A: If you can see the points on your map, then, please, don't be worry about the first two fields! You only need to create an expression based label for your layer, like below, and then you'll be able to see the latitude & longitude: Now, about the last two fields: I don't know nothing about your data, but because you are sure the time and the symbol elements exist in your gpx file, try to repeat the import, after deleting the schemaLocation reference in your <gpx> element. If there is a reference to a companion file, like an xsl, with some import rules, it must be deleted also. Below is such an example: If, eventually, you can not see the time and symbol columns, can you upload the gpx file for a review? EDIT If you want to see the latitude and the longitude in your attribute table then: right click your layer name: complete as bellow and press OK: open up th new layer attribute table, toggle editing mode and press field calculator to create the latitude and longitude columns as new fields: Now, if you are not satisfied having the latitude and longitude as decimal degrees, thanks to this link you can have them as DMS, as in OziExplorer:
{ "pile_set_name": "StackExchange" }
Q: Is "Fade in" an idiom around authors? A couple of days ago, I saw a character on the show Californication type Fade in: and then continue to write a movie script (as you can see here). Yesterday, I heard someone say: If you would like to write a successful book, just type "Fade in" and start writing. Is Fade in an idiom around authors? Is it commonly used? A: I think "Fade in" is meant to refer to the effect used in TV and movies when the image goes from black (or sometimes white or another shade) to the opening scene of the movie/show. As such, you would see the words "Fade In" and "Fade Out" on TV/movie scripts. It sounds like the quote you included was using that same concept as bit of a humorous idiom for writing a novel... as though the first scene of the novel could "fade in"to view of the reader.
{ "pile_set_name": "StackExchange" }
Q: Proper 'cleartool mkview' for ClearCase Snapshot view creation Good afternoon, Seems like I am somewhat stuck in CC-land these days, but I have one (hopefully) final question regarding proper CC-handling: When using the CC View Creation Wizard, I can create a proper Snapshot view on my machine perfectly fine, however when trying to do the same with the mkview command, it fails... Using the the view creation wizard results into the (working) following view: cleartool> lsview battjo6r_view2 battjo6r_view2 \\Eh40yd4c\Views\battjo6r_view2.vws cleartool> lsview -long battjo6r_view2 Tag: battjo6r_view2 Global path: \\Eh40yd4c\Views\battjo6r_view2.vws Server host: Eh40yd4c Region: CT_WORK Active: NO View tag uuid:f34cf43f.b4d048df.845d.ed:21:a2:9c:45:ff View on host: Eh40yd4c View server access path: D:\Views\battjo6r_view2.vws View uuid: f34cf43f.b4d048df.845d.ed:21:a2:9c:45:ff View attributes: snapshot View owner: WW005\battjo6r However, when trying to create the view manually via mkview -snapshot -tag battjo6r_view2 -vws \\Eh40yd4c\Views\battjo6r_view2.vws -host Eh40yd4c -hpath D:\Views\battjo6r_view2.vws -gpath \\Eh40yd4c\Views\battjo6r_view2.vws battjo6r_view2 ... I get the following error: cleartool> mkview -snapshot -tag battjo6r_view2 -vws \\Eh40yd4c\Views\battjo6r_view2.vws -host Eh40yd4c -hpath D:\Views\battjo6r_view2.vws -gpath \\Eh40yd4c\Views\battjo6r_view2.vws battjo6r_view2 Created view. Host-local path: Eh40yd4c:D:\Views\battjo6r_view2.vws Global path: \\Eh40yd4c\Views\battjo6r_view2.vws cleartool: Error: Unable to find view by uuid:6f99f7ae.6a5d40e4.ba32.37:8e:e5:a4:ed:18, last known at "<viewhost>:<stg_path>". cleartool: Error: Unable to establish connection to snapshot view "6f99f7ae.6a5d40e4.ba32.37:8e:e5:a4:ed:18": ClearCase object not found cleartool: Warning: Unable to open snapshot view "D:\SnapShotViews\battjo6r_view2". cleartool: Error: Unable to create snapshot view "battjo6r_view2". Removing the view ... Any idea why this is happening? Am I missing something? A: This is usually due to the albd not running. Actually, it is running, but ClearCase tries to contact the wrong host. Here: Host-local path: Eh40yd4c:D:\Views\battjo6r_view2.vws is highly suspicious. Try: mkview -snapshot -tag battjo6r_view2 -vws \\Eh40yd4c\Views\battjo6r_view2.vws -host Eh40yd4c -hpath \\Eh40yd4c\Views\battjo6r_view2.vws -gpath \\Eh40yd4c\Views\battjo6r_view2.vws battjo6r_view2 That is: hpath = gpath. or, if the first command fails, also (it is simpler and may work) mkview -snapshot -tag battjo6r_view2 -vws \\Eh40yd4c\Views\battjo6r_view2.vws battjo6r_view2 Hopefully, ClearCase could determine for itself the host, hpath and gpath.
{ "pile_set_name": "StackExchange" }
Q: Subliminal does not work in Ubuntu 18.04 Subliminal gives this error in Ubuntu 18.04 Traceback (most recent call last): File "/usr/bin/subliminal", line 9, in <module> load_entry_point('subliminal==1.1.1', 'console_scripts', 'subliminal')() File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 480, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 2693, in load_entry_point return ep.load() File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 2324, in load return self.resolve() File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 2330, in resolve module = __import__(self.module_name, fromlist=['__name__'], level=0) File "/usr/lib/python3/dist-packages/subliminal/__init__.py", line 10, in <module> from .api import (ProviderPool, check_video, provider_manager, download_best_subtitles, download_subtitles, File "/usr/lib/python3/dist-packages/subliminal/api.py", line 13, in <module> from .subtitle import compute_score, get_subtitle_path File "/usr/lib/python3/dist-packages/subliminal/subtitle.py", line 7, in <module> from guessit.matchtree import MatchTree File "/usr/lib/python3/dist-packages/guessit/__init__.py", line 99, in <module> from guessit.plugins import transformers File "/usr/lib/python3/dist-packages/guessit/plugins/transformers.py", line 222, in <module> reload() File "/usr/lib/python3/dist-packages/guessit/plugins/transformers.py", line 220, in reload reload_options(all_transformers()) File "/usr/lib/python3/dist-packages/guessit/plugins/transformers.py", line 179, in all_transformers return _extensions.objects() File "/usr/lib/python3/dist-packages/guessit/plugins/transformers.py", line 111, in objects return self.map(self._get_obj) File "/usr/lib/python3/dist-packages/stevedore/extension.py", line 261, in map raise NoMatches('No %s extensions found' % self.namespace) stevedore.exception.NoMatches: No guessit.transformer extensions found Output of apt-cache policy subliminal Installed: 1.1.1-2 Candidate: 1.1.1-2 Version table: *** 1.1.1-2 500 500 http://in.archive.ubuntu.com/ubuntu bionic/universe amd64 Packages 500 http://in.archive.ubuntu.com/ubuntu bionic/universe i386 Packages 100 /var/lib/dpkg/status A: Answer that works not only for Ubuntu 18.04, Bionic but also any release with pip installed The problem appears to be an incompatibility between the latest python stevedore package and guessit, as reported in the Debian Bug Report Logs The solution would be to install an appropriate version of stevedore from the PyPi Repository, in order to do that Uninstall the existing packages that you've obtained from apt by using sudo apt-get purge -y python3-stevedore Install the PyPi version of subliminal with the appropriate version of stevedore by using sudo pip3 install subliminal stevedore==1.19.1 Now running subliminal from the terminal will let it run as usual: A: argparse is now part of Python2 and Python3, but subliminal depends on python3-stevedore and this package contains the entry argparse in requires.txt. You can check this with: Vivid cat /usr/lib/python3/dist-packages/stevedore-1.3.0.egg-info/requires.txt Wily cat /usr/lib/python3/dist-packages/stevedore-1.5.0.egg-info/requires.txt The solution is a dirty hack, remove the line: Vivid sudo sed -i.bak '/argparse/d' /usr/lib/python3/dist-packages/stevedore-1.3.0.egg-info/requires.txt Wily sudo sed -i.bak '/argparse/d' /usr/lib/python3/dist-packages/stevedore-1.5.0.egg-info/requires.txt For Bionic (18.04) the above works but take into account the stevedore version is higher. It can be checked with: ls -l /usr/lib/python3/dist-packages/ and then search for the stevedore-* folder. In my case: sudo sed -i.bak '/argparse/d' /usr/lib/python3/dist-packages/stevedore-1.28.0.egg-info/requires.txt
{ "pile_set_name": "StackExchange" }
Q: Angular Form Reset on Successful Submission Hoping for someone familiar with Angular to please take a quick look at my syntax. form.component.html: (click)="onSubmit(ruleForm)" rule.component.ts: onSubmit(form: NgForm) { this.dataRulesService.createRuleRequest(this.rule, form, this.newRule); } newRule(form: NgForm) { this.rule = { //model is reset }; form ? form.reset() : null; } rule.service.ts: public createRuleRequest(rule: Rule, form: NgForm, newRule: (form: NgForm) => any) { //logic this._postCreateRuleRequest(rule, form, newRule); } private _postCreateRuleRequest(rule: Rule, form: NgForm, newRule: (form: NgForm) => any) { this.http.post(`${environment.API_URL}rules/create`, rule).subscribe((response: any) => { //success logic }); newRule(form); }, () => { //failure logic }); }); } I'm trying to reset the form and the rule model on successful submission only (but keep form state on failure). Fairly new to Angular. I tried to pass the NgForm object itself down and pass the newRule function down to the service. This is working for a "Clear Form" button I have on the page - but in much simpler way. When passing newRule down to rule.service, I get an error: vendor.bundle.js:54437 ERROR TypeError: Cannot set property 'rule' of undefined at webpackJsonp../src/app/components/data-rules/data- rules.component.ts.DataRulesComponent.newRule I assume this is a reference to this.rule in the newRule function, which works fine when called from within the rule.component but can't find "this.rule" when called from the service. I should include that rule is being declared publicly: rule.component.ts: public rule: Rule; Any guidance on this syntax would be appreciated. Update: Add data-rules.component per request import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { DataRulesService } from './data-rules.service'; import { Rule } from './rule'; import { NgForm } from '@angular/forms'; @Component({ selector: 'app-data-rules', templateUrl: './data-rules.component.html', styleUrls: ['./data-rules.component.scss'] }) export class DataRulesComponent implements OnInit { public rule: Rule; constructor(private http: HttpClient, private dataRulesService: DataRulesService) { } ngOnInit() { this.newRule(null); } onSubmit(form: NgForm) { this.dataRulesService.createRuleRequest(this.rule, form, this.newRule); } newRule(form: NgForm) { this.rule = { ruleName: '', sqlQuery: '', description: '', frequency: '', emailAddressList: '', documentation: '' }; form ? form.reset() : null; } } A: Issue The issue is with keyword this used in following snippet. newRule(form: NgForm) { this.rule = { ruleName: '', sqlQuery: '', description: '', frequency: '', emailAddressList: '', documentation: '' } You are defining the function newRule in DataRulesComponent and invoking this function in DataRulesService due to which context (this) is changed. When you invoke newRule function in DataRulesService, this will refer to DataRulesService not DataRulesComponent where you don't have rule variable. That why you are getting undefined error. Fix The main objective of this newRule function is to reset the value of rule and form object. So lets implement the same in different way by creating new function reset in Rule class. Step 1 class Rule{ public reset(rule) { rule.ruleName = ''; rule.sqlQuery =''; rule.description = ''; rule.frequency = ''; rule.emailAddressList = ''; rule.documentation = ''; } } Step 2 Since you are already passing the rule no need to additional parameter newRule Change this.dataRulesService.createRuleRequest(this.rule, form, this.newRule); to this.dataRulesService.createRuleRequest(this.rule, form); Step 3 The last would be in createRuleRequest function of DataRulesService. Just remove the last parameter createRuleRequest(rule, form){ ... rule.reset(rule); //it will reset rule. form.reset(); // reset the form .. //Above code will replace the function newRule(); } Note : I had written the code in stackoverflow editor directly so there could be typo and syntactical error. Please correct yourself.
{ "pile_set_name": "StackExchange" }
Q: Is there any way to implement compareTo method which would compare any supplied argument? The compiler says " cannot find symbol: method compareTo(java.lang.Object) ". Could you please advice where is the mistake here? Here is the part of the code: public class OBTComparable<ObjectType> implements Comparable<OBTComparable> { public OTBComparable leftNode = null; public OBTComparable mainNode = null; public OBTComparable rightNode = null; public ObjectType object = null; public OBTComparable(ObjectType requiredObject) { object = requiredObject; } @Override public int compareTo(OBTComparable other) { if(object.compareTo(other.object) == 0) return 0; else if (object.compareTo(other.object) > 0) return 1; else return -1; } } A: You need to scope ObjectType to Comparable too, because OBTComparable is delegating compareTo() to ObjectType: If you change <ObjectType> to <ObjectType extends Comparable<ObjectType>>, it will compile: public class OBTComparable<ObjectType extends Comparable<ObjectType>> implements Comparable<OBTComparable> A: I think this is the proper code you are looking for (I replaced ObjectType with T for clarity): class OBTComparable<T extends Comparable<? super T>> implements Comparable<OBTComparable<T>> { public OBTComparable<T> leftNode = null; public OBTComparable<T> mainNode = null; public OBTComparable<T> rightNode = null; public T object = null; public OBTComparable(T requiredObject) { object = requiredObject; } @Override public int compareTo(OBTComparable<T> other) { if (object.compareTo(other.object) == 0) { return 0; } else if (object.compareTo(other.object) > 0) { return 1; } else return -1; } } What did I change here: OBTComparable uses a type parameter, so you should show it when you implement Comparable. Therefore you have implements Comparable<OBTComparable<T>> instead of simply implements Comparable<OBTComparable>. You compare two objects in the compareTo method, but are they comparable? To make sure this requirement is fulfilled, you should write OBTComparable<T extends Comparable<T>> instead of just OBTComparable<T>. Then you will know that you can call compareTo.
{ "pile_set_name": "StackExchange" }
Q: Include boolean params with g:include are passed as Strings to the included view I don't know if the following change is an issue or it is intended. <g:include view="line.gsp" params="['label':'test', 'progress':false]"/> Then the expression in line.gsp aways evaluates to true, because the type of the 'progress' param is String, not Boolean. class is: ${params.progress.getClass()} <g:if test="${params.progress}"> this should not be displayed </g:if> Note that the same is applicable for other types, not just Boolean. I am using grails 3.3.8 This didn't happen in grails 2.5.2. I didn't find anything about this online so that's why I am asking here. Thanks. Edit: As suggested by Daniel, I've tried with grails 3.3.2 also. I just created an app with grails create-app and modified the existing index.gsp to include line.gsp, as shown in the code above. Here is a screenshot: A: I realize you have already found a workaround to this, but it was bothering me that your code was not working the same way mine was, so I decided to investigate a bit further in case anyone else runs into this issue. As other people here have mentioned, params.anything will typically return a String value. This is because params are typically encoded as URI parameters (like ?progress=false) and not autoboxed into any other type. (This is perfectly reasonable; there would be no good way for Grails to know what type they should be.) However, it is possible (and occasionally reasonable) to render your view or template from a controller like render view: whatever, model: [your: model, params: params] where you specifically include params in the model. (Perhaps you have a lot of parameters that you do not need to individually recreate in the model.) In this case, the params map will exist as both URI parameters (?progress=false) and page-scoped model entry (params: [progress: Boolean.FALSE]). Page scope takes priority over URI parameters, and so your types will be preserved. In my testing, I added your code to an existing page where I was already passing params into the model, and so type was preserved for a newly added parameter as well. (Note that once params are in page scope, they're there for included templates or views as well.) Consequently, I saw progress type of Boolean, while in a basic example it would be type String. TL/DR: either assume params are strings, or explicitly include params in your page-scoped model when rendering.
{ "pile_set_name": "StackExchange" }
Q: Global Texture Container For my first large-ish endevor in Open-GL I'm making a simulator of sorts. I've got much of the basic functionality working, but recently ran into a problem. As I've since realized, I originally designed the program so that each object in the simulator had its own class which stored its position, texture, draw code, etc. This became a problem, however, when I began creating lots of objects of the same type, as I quickly realized that I wrote the classes to reload a new instance of the texture data for each instance of an object. To fix this I considered making a simple texture database class of sorts which would contain a pointer to a single instance of each objects texture data that each instance of the object would copy upon its creation. The problem here is that lots of different classes in the simulator create objects and I am hesitant to simply store the texture database class at the top of the program hierarchy and pass it down to every function that creates an object, as I feel that this will get very complex very fast. Instead I feel it would be better to have a global container class that would keep track of the texture pointers, but I'm not sure how I could store the pointers without instantiating an instance of the container which would require passing it all over the place. I'm hoping that there is a more elegant and simple solution that I'm overlooking, otherwise I'll try the way I've described. Alternatively, if it seems some restructuring of the simulator would be best, that isn't out of the question, but I'd appreciate any advice. A: Edit: Removed singleton solution in favor of simpler static std::map using existing buildTex function. Note it is not thread safe as implemented. GLuint buildTex(string strFileName) { static map<string, GLuint> s_Textures; if (s_Textures.find(strFileName) == s_Textures.end()) { GLuint hTexture; // TODO: load hTexture from file s_Textures[strFileName] = hTexture; } return s_Textures[strFileName]; } // Tree.cpp void Tree::Draw() { GLuint hTex = buildTex("Tree.tex"); ... }
{ "pile_set_name": "StackExchange" }
Q: Single Linked List not working (C++) The following code builds correctly but causes the program to crash when I run it. Can someone please tell me whats wrong with it. I suspect that there is something wrong with the DeleteNode function. #include <iostream> #include <cstdlib> using namespace std; class list { private: typedef struct node { int data; node* next; }* nodePtr; //this means that 'nodePtr' will mean a pointer to the struct node nodePtr head; nodePtr current; nodePtr temp; public: list() { //constuctor head = NULL; current = NULL; temp = NULL; }; void AddNode(int addData) //to add a particular data value { nodePtr n= new node; n->next = NULL; n->data = addData; if (head != NULL) { //if a list is already set up current = head; while (current->next != NULL) { //to get to the last node in the list current = current->next; } current->next = n; } else { // if list is not created head = n; //new node is front of the list } } void DeleteNode(int delData) //to delete a particular data value { nodePtr delPtr = NULL; temp = head; current = head; while (current != NULL && current->data!=delData) { //pass through whole list && find value temp = current; current = current->next; } if (current = NULL) { //data value not found in list cout << delData << " was not in the list." << endl; delete delPtr; //to free up memory space } else { delPtr = current; current = current->next; temp->next = current; //to reconnect list if (delPtr == head) { head = head->next; temp = head; } delete delPtr; cout << "The value " << delData << "was deleted." << endl; } } void PrintList() //to print all the data values { current = head; while (current != NULL) { //to go through the data valued of the list cout << current->data << endl; current = current->next; } } }; int main() { list Shahzad; Shahzad.AddNode(2); Shahzad.AddNode(78); Shahzad.AddNode(28); Shahzad.AddNode(2398); Shahzad.DeleteNode(78); Shahzad.PrintList(); return 0; } A: Your first problem is with the following line: if (current = NULL) You're actually assigning null to current at this point. This should actually be: if (current == NULL)
{ "pile_set_name": "StackExchange" }
Q: Sorting a Dictionary and writing it to a CSV file I have a dictionary with a tuple as a key and list as values myDict = { (1, 9078752378): [('Smith', 'Bob'), 'Head guard'], (2, 9097615707): [('Burdell', 'George'), 'Lifeguard'], (3, 9048501430): [('Smith', 'Amanda'), 'Lifeguard'], (4, 9026450912): [('Brown', 'John'), 'Lifeguard'], (5, 9027603006): [('Flowers', 'Claudia'), 'Lifeguard'], (6, 9055520890): [('Smith', 'Brown'), 'Head guard'], (7, 9008197785): [('Rice', 'Sarah'), 'Lifeguard'], (8, 9063479070): [('Dodd', 'Alex'), 'New Lifeguard'], (9, 9072301498): [('Sparrow', 'Jack'), 'New Lifeguard'], (10, 9084389677): [('Windsor', 'Harry'), 'New Lifeguard'] } I am COMPLETELY stuck on how to write this dictionary to a csv file in order written in this format 1 9078752378 Smith Bob Head guard ..and so on to 9 PLEASE HELP!!! A: Assuming your format is consistent, this should do the trick: with open('youfile.csv', 'w') as f: for k,v in sorted(myDict.iteritems()): f.write('{} {} {} {} {}\n'.format(k[0], k[1], v[0][0], v[0][1], v[1])) I should warn you about a potential gotcha in your output format though, if you need to parse this back again you want to quote values, or use a different separator, e.g.: 1 9078752378 Smith Bob "Head guard" A: with open("CSV", 'w') as f: f.write('\n'.join([",".join(map(str,[a,b,c,d,e])) for (a, b), ((c, d), e) in sorted(myDict.items())])) Explanation - sorted(myDict.items()) will sort the the dictionary based on keys. for (a, b), ((c, d), e) in sorted(myDict.items()) will unpack your values. ",".join(map(str,[a,b,c,d,e])) will join the unpacked values by comma. [",".join(map(str,[a,b,c,d,e])) for (a, b), ((c, d), e) in sorted(myDict.items())] is the list comprehension of the above comma-joined values. '\n'.join([",".join(map(str,[a,b,c,d,e])) for (a, b), ((c, d), e) in sorted(myDict.items())] will join the above list with newlines.
{ "pile_set_name": "StackExchange" }
Q: What is the max level in Kingdoms of Amalur? What is the level cap in Kingdoms of Amalur? And, perhaps more importantly, how many ability points will you have when you reach it? Is it always 3 per level? Can you get ability points in ways other than leveling up? A: The maximum level you can gain is 40. This gives you 120 maximum ability points as you get 3 pre-picked ones in the beginning (as pointed out by RavenDreamer) and 3 with each level up. This can be confirmed by a hands-on preview that appeared on NZGamer Feb. 1st. Also by this image from the in-game manual: A: While Marcelo's answer does an excellent job of pointing out the maximum level, the lesser half of my question, about the maximum number of ability points, has hereunto remained unanswered. Strictly speaking, there are many more ways to gain bonus skills than there are to gain bonus abilities (skill books, trainers, etc.). However, there are two ways to acquire more than the 120 ability points you get from level up. The first is from epic gems. The Gem of Enlightenment gives up to 15 ability points, and one of the tree specific gems can potentially give up to 25. The second, is from Purple and Gold armor pieces. Though I don't know what all pieces give the bonus (that is beyond the scope of the question), there are some items, such as the Mercenary's Boots, below, that also give +1 to all abilities in at tree, which means another potential +25. On the other hand, 120 ability points is already a lot, and you may not wind up interested in half the skills you might be able to unlock (some are even exclusive; chakram and sceptre mastery, for instance). But if you're dead set on maximizing your number of abilities, this'd be the way to do it. A: Level 40 is the max. With the assistance of trainers you can have practically all skills (i.e. lockpicking, etc,...) maxed out. I currently am only missing 5 more points to max out all of them and I have not finished the game. In addition, you can't contribute to tier 6 abilities if you do a hybrid UNLESS you only add a very small amount in one class while the majority of ability points are applied to another. When you visit a fateweaver you WILL NOT be able to reset the skills acquired through trainers or from character selection. This means if you create a character with +1 skill in lockpicking and a trainer gives you +1 in alchemy you will not get those points back when visiting a fateweaver. They will stay attached to those skills. There is a utility gem or epic gem (it escapes me right now exactly which) that will add +1 to all abilities in the first 4 tiers for all classes. You can smithy a chest armor to include that gem. There are also accessories that help a great deal. You will also aquire perm changes to each class (might, finess, sorcery) throughout the game. You can be 3 or 4 or even 5 over the default max when it comes to an ability.
{ "pile_set_name": "StackExchange" }
Q: Typical Unicode Error: Sublime vs. Atom I have a very very simple code (getting some content from Twitter) import tweepy from textblob import TextBlob consumer_key = '7ezxdMbfSOFH9Q1IGZ774ojfd' consumer_secret = 'JMG9HCeRpd2gPa30UxGyNCb9yRmOF4kr9MRIEv1trnJOzJEk8P' access_token = '1735574195-d6R48bgxJv5YlhWHstr0eO3pg2usvZSh7fLd75D' access_token_secret = '6VlIvRsDPgVksTM0u8SZQdEudETpjzGimkpxCdtJ0S7Dg' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) public_tweets = api.search('Trump') for tweet in public_tweets: print(tweet.text) analysis = TextBlob(tweet.text) print(analysis.sentiment) I have installed Python 3. When I run the program through Sublime and Terminal (in my Mac) it works fine. On the other hand when I run it on Atom I get the very usual error: Traceback (most recent call last): File "/Users/Marion/test2.py", line 30, in <module> print(tweet.text) UnicodeEncodeError: 'ascii' codec can't encode character '\u2026' in position 139: ordinal not in range(128) where line 30 is the print(tweet.text). I have looked at similar question but I have not managed to solve the problem (since I am a rookie in programming and Python). Since I have Python 3 should the program not work also on Atom too since it works on Sublime? And, of course, how can I resolve it? A: on terminal run these three lines to set encoding 'utf-8': echo "export LC_ALL=en_US.UTF-8" >> ~/.bash_profile echo "export LANG=en_US.UTF-8" >> ~/.bash_profile source ~/.bash_profile quit from atom then open it again. or on your code print(tweet.text.encode('utf-8'))
{ "pile_set_name": "StackExchange" }
Q: Issue with Null I designed below Null class for generic programming, and I can do something like if T A=Null(), everything works fine except for std::string, where the compiler is unable to find the proper operator == and give me a lot of errors. The issue is why other types works out all right? Something I did wrong? struct Null { operator std::string() const { return std::string{}; } operator int() const { return 0; } }; int main() { std::string s = "hello"; Null n; std::cout << (0 == n) << std::endl; // works std::cout << (n == 0) << std::endl; // works std::cout << (s == n) << std::endl; // error: no match for operator== } A: The == in use here is actually: template< class CharT, class traits, class Alloc > bool operator==( const basic_string<CharT,Traits,Alloc>& lhs, const basic_string<CharT,Traits,Alloc>& rhs ); User-defined conversion sequences aren't considered for template type deduction, so it cannot deduce the CharT parameter here (or the others). To fix this you might have to define your own non-template operator==.
{ "pile_set_name": "StackExchange" }
Q: Angular 6 add input on enter key I have component called text-editor.component and this is my html template: <div class="container"> <div id="testo" class="offset-1 text-center" > <input type="text" class="col-8 text-center"> </div> </div> I want to add a new input text when I press the enter key. This is what I'm trying to achieve: <div id="testo" class="offset-1 text-center" > <input type="text" class="col-8 text-center"> <!-- second input --> <input type="text" class="col-8 text-center"> </div> </div> when the user presses enter after inputting text into the input, a new input should spawn. I am using Angular's template driven forms. A: You can approach this using Reactive Forms FormArray. You would attach an (keyup) or (keyup.enter) handler to the <input />. Within the handler for this keyup event, we push a new FormControl to a FormArray. This example uses FormBuilder to generate a FormGroup that contains a FormArray with a key of things. We use the push method of FormArray to add a new FormControl/AbstractControl within the handler for keyup. Component: import { Component } from '@angular/core'; import { FormBuilder, FormGroup, FormArray } from '@angular/forms'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { name = 'Angular'; myForm: FormGroup; constructor(private fb: FormBuilder) { this.createForm(); } onEnter() { this.addThing(); } get things() { return this.myForm.get('things') as FormArray; } private createForm() { this.myForm = this.fb.group({ things: this.fb.array([ // create an initial item this.fb.control('') ]) }); } private addThing() { this.things.push(this.fb.control('')); } } Template: <form [formGroup]="myForm"> <div formArrayName="things"> <div *ngFor="let thing of things.controls; let i=index"> <label [for]="'input' + i">Thing {{i}}:</label> <input type="text" [formControlName]="i" [name]="'input' + i" [id]="'input' + i" (keyup.enter)="" /> </div> </div> </form> At a very basic level you can loop through each in the form array using the controls property of the respective FormArray element and the value using the value property: <ul> <li *ngFor="let thing of things.controls">{{thing.value}}</li> </ul> Here is a StackBlitz demonstrating the functionality. A: Controller Declare an array 'inputs' and initialises it with a value of 1. inputs = [1]; Create a function addInput(). addInput() { this.inputs.push(1); } HTML <div id="testo" class="offset-1 text-center" *ngFor="let more of inputs"> <input type="text" class="col-8 text-center" (keyup.enter)="addInput()"> </div> In your template you'll be calling the addInput() function every time you hit enter (keyup.enter). The function pushes a new value into the array, whose length increases by 1 and that in turn creates a new input field.
{ "pile_set_name": "StackExchange" }
Q: How to create rectangle form point x and y I want to calculate area rectangle form point x and y class Point{ let x: Int let y: Int init(x: Int,y: Int){ self.x = x self.y = y } } class Rectangle{ func area() -> Int{ //I have no idea } } A: class Point { let x: Int let y: Int init(x: Int, y: Int) { self.x = x self.y = y } } class Rectangle { let nw: Point let se: Point init(nw: Point, se: Point) { self.nw = nw self.se = se } func area() -> Int { return (se.y - nw.y) * (se.x - nw.x) } func containsPoint(_ p: Point) -> Bool { let isContainHorizontal = (nw.x <= p.x) && (p.x <= se.x ) let isContainVertical = (nw.y <= p.y) && (p.y <= se.y) return isContainHorizontal && isContainVertical } func combine(_ rect: Rectangle) -> Rectangle { return Rectangle(nw: Point(x: max(nw.x, rect.nw.x), y: max(nw.y, rect.nw.y)), se: Point(x: min(se.x, rect.se.x), y: min(se.y, rect.se.y))) } } output 2. 6 3. false, true 4. 1
{ "pile_set_name": "StackExchange" }
Q: Username full text search in Meteor.users I am trying to search the meteor.users collection by username. I have followed all the steps detailed here, but I can't seem to make it work meteor.users. Here is the code I have for that: On Server Startup: Meteor.startup(function(){ Meteor.users._ensureIndex({ "username":"text", }); }); In my publish function: Meteor.publish("Meteor.users.userSearch",function(searchVal){ if(!searchVal){ return Meteor.users.find({}); } return Meteor.users.find({$text:{$search:searchVal}}); }); On the client: Template.foo.helpers({ users(){ var searchValue = Session.get('searchVal'); Meteor.subscribe('Meteor.users.userSearch',searchValue); return Meteor.users.find({}); } }); Can someone please help me figure out what is wrong with the above? When there is no searchValue, it works correctly and all the users are returned. As soon as there is any search value, no users are returned at all. I have also tried directly in the mongodb console db.users.find({$text:{$search:"some_test"}}) and again there is no collection object returned. A: You do not need to do full text search if you just want to search value of only one field (username in this case). Using normal find command with Regex value as search value is better in this case: Meteor.users.find({ username: new RegExp('user1', 'gi'), });
{ "pile_set_name": "StackExchange" }
Q: Woocommerce Order API Line Item ID changes on update I’m retrieving Woocommerce orders via the "order updated" webhook and storing specific data in a separate database. We are also using a personalisations plugin which allows customers to add custom messages to products. This creates 2 separate line items, which would otherwise be the same product variation in the backend. On my separate database, when creating or updating a row, I need to use order_id, variation_id as well as the id entry (from line_items => id) to check whether a record must be created or updated. This ensure that 2 identical product variations with separate custom messages aren't overwritten by each other. On order create the following JSON response is sent. {"id":10656,"parent_id":0,"number":"10656","order_key":"wc_order_5a9815fa1add6","created_via":"checkout","version":"3.1.2","status":"pending","currency":"ZAR","date_created":"2018-03-01T17:02:18","date_created_gmt":"2018-03-01T15:02:18","date_modified":"2018-03-01T17:02:18","date_modified_gmt":"2018-03-01T15:02:18","discount_total":"0.00","discount_tax":"0.00","shipping_total":"0.00","shipping_tax":"0.00","cart_tax":"60.79","total":"495.00","total_tax":"60.79","prices_include_tax":true,"customer_id":5148,"customer_ip_address":"197.89.123.74","customer_user_agent":"mozilla\/5.0 (linux; android 6.0.1; samsung sm-g900h build\/mmb29k) applewebkit\/537.36 (khtml, like gecko) samsungbrowser\/6.4 chrome\/56.0.2924.87 mobile safari\/537.36","customer_note":"","billing":{"first_name":"Tasneem","last_name":"Modack","company":"","address_1":"","address_2":"","city":"","state":"","postcode":"","country":"ZA","email":"[email protected]","phone":"0828736647"},"shipping":{"first_name":"Tasneem","last_name":"Modack","company":"","address_1":"","address_2":"","city":"","state":"","postcode":"","country":"ZA"},"payment_method":"payfast","payment_method_title":"Pay With Your Card or Instant EFT.","transaction_id":"","date_paid":null,"date_paid_gmt":null,"date_completed":null,"date_completed_gmt":null,"cart_hash":"666062e6d9100aa43860fb71caef1466","meta_data":[{"id":506232,"key":"_store_location","value":"loop-street-cbd"},{"id":506233,"key":"_collection_date","value":"3 March, 2018"},{"id":506234,"key":"_collection_time","value":"10:00 AM"},{"id":506235,"key":"mailchimp_woocommerce_is_subscribed","value":"1"},{"id":506259,"key":"_billing_vat_number","value":""}],"line_items":[{"id":28607,"name":"Rainbow - Yes (add R50.00)","product_id":415,"variation_id":2590,"quantity":1,"tax_class":"","subtotal":"434.21","subtotal_tax":"60.79","total":"434.21","total_tax":"60.79","taxes":[{"id":1,"total":"60.79","subtotal":"60.79"}],"meta_data":[{"id":194971,"key":"transform-into-a-pinata","value":"Yes (add R50.00)"}],"sku":"N005-P","price":434.21,"_product_group":"rainbow-cakes"}],"tax_lines":[{"id":28609,"rate_code":"ZA-VAT-1","rate_id":1,"label":"VAT","compound":false,"tax_total":"60.79","shipping_tax_total":"0.00","meta_data":[]}],"shipping_lines":[{"id":28608,"method_title":"Local pickup","method_id":"local_pickup:10","total":"0.00","total_tax":"0.00","taxes":[],"meta_data":[{"id":194976,"key":"Items","value":"Rainbow - Yes (add R50.00) × 1"}]}],"fee_lines":[],"coupon_lines":[],"refunds":[]} The line_item => id, when the order is created is 28607 On order update the following JSON response is sent. {"id":10656,"parent_id":0,"number":"10656","order_key":"wc_order_5a9815fa1add6","created_via":"checkout","version":"3.1.2","status":"pending","currency":"ZAR","date_created":"2018-03-01T17:02:18","date_created_gmt":"2018-03-01T15:02:18","date_modified":"2018-03-01T17:02:18","date_modified_gmt":"2018-03-01T15:02:18","discount_total":"0.00","discount_tax":"0.00","shipping_total":"0.00","shipping_tax":"0.00","cart_tax":"60.79","total":"495.00","total_tax":"60.79","prices_include_tax":true,"customer_id":5148,"customer_ip_address":"197.89.123.74","customer_user_agent":"mozilla\/5.0 (linux; android 6.0.1; samsung sm-g900h build\/mmb29k) applewebkit\/537.36 (khtml, like gecko) samsungbrowser\/6.4 chrome\/56.0.2924.87 mobile safari\/537.36","customer_note":"","billing":{"first_name":"Tasneem","last_name":"Modack","company":"","address_1":"","address_2":"","city":"","state":"","postcode":"","country":"ZA","email":"[email protected]","phone":"0828736647"},"shipping":{"first_name":"Tasneem","last_name":"Modack","company":"","address_1":"","address_2":"","city":"","state":"","postcode":"","country":"ZA"},"payment_method":"payfast","payment_method_title":"Pay With Your Card or Instant EFT.","transaction_id":"","date_paid":null,"date_paid_gmt":null,"date_completed":null,"date_completed_gmt":null,"cart_hash":"666062e6d9100aa43860fb71caef1466","meta_data":[{"id":506232,"key":"_store_location","value":"loop-street-cbd"},{"id":506233,"key":"_collection_date","value":"3 March, 2018"},{"id":506234,"key":"_collection_time","value":"1:00 PM"},{"id":506235,"key":"mailchimp_woocommerce_is_subscribed","value":"1"},{"id":506256,"key":"_billing_vat_number","value":""}],"line_items":[{"id":28604,"name":"Rainbow - Yes (add R50.00)","product_id":415,"variation_id":2590,"quantity":1,"tax_class":"","subtotal":"434.21","subtotal_tax":"60.79","total":"434.21","total_tax":"60.79","taxes":[{"id":1,"total":"60.79","subtotal":"60.79"}],"meta_data":[{"id":194951,"key":"transform-into-a-pinata","value":"Yes (add R50.00)"}],"sku":"N005-P","price":434.21,"_product_group":"rainbow-cakes"}],"tax_lines":[{"id":28606,"rate_code":"ZA-VAT-1","rate_id":1,"label":"VAT","compound":false,"tax_total":"60.79","shipping_tax_total":"0.00","meta_data":[]}],"shipping_lines":[{"id":28605,"method_title":"Local pickup","method_id":"local_pickup:10","total":"0.00","total_tax":"0.00","taxes":[],"meta_data":[{"id":194956,"key":"Items","value":"Rainbow - Yes (add R50.00) × 1"}]}],"fee_lines":[],"coupon_lines":[],"refunds":[]} The line_item => id, when the order is updated is 28604 This will create an additional line item in the order on my system when in fact it is the same line item. Is there a reason why this happens, and is there a possible workaround? NOTE Dropping the rows and re-adding is not an options as the database on my system contains separate columns that are not related to Woocommerce. UPDATE According to the JSON response, specifically the "date_created", it appears that the "order created" webhook fires twice but on "order updated" it only fires once. A: This is definitely an issue with the personalization plugins you mentioned, because woocommerce on its own does not create a new line item on update as evident from the code below https://github.com/woocommerce/woocommerce/blob/master/includes/api/legacy/v2/class-wc-api-orders.php#L867 protected function set_line_item( $order, $item, $action ) { $creating = ( 'create' === $action ); // if ( $creating ) { $line_item = new WC_Order_Item_Product(); } else { $line_item = new WC_Order_Item_Product( $item['id'] ); } I would strongly recommend you to disable the customisation plugin and try.
{ "pile_set_name": "StackExchange" }
Q: Prevent Duplicate Records in SQL Server I have 3 tables in my Database, one for student and other for the courses and the third one to store what every student select from courses. I want to prevent the student from selecting the same course more than once. what condition should I provide in Insert statement in the third table? Thanks A: Your StudentCourse table should have a unique constraint on the (StudentId, CourseId) table. As an alternative, you can create the Primary Key on your StudentCourse table as a composite key on (StudentId, CourseId).
{ "pile_set_name": "StackExchange" }