INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
как пользоваться Enum, преобразовывая param[i] (<-тут int) в string (слово, которое соответствует данному param)? Есть класс с перечислением: public class ObjectManagerScript : MonoBehaviour { public enum param1 {blala, Hi, Hello, Hmm}; public enum param2{again, Ask, Queastion}; } И другой класс, где я хочу выводить слова вместо цифр: public class ObjectChooser : MonoBehaviour { // тут пропущен код, который присваивает param1 и param2 числа // в итоге каждому param1 и param2 соответствует одно из чисел своего enum for (int i = 0; i < maxObjects; i++){ Debug.Log(param1[i]);// это неправильно, просто я даже не знаю, как примерно это может выглядеть // т.е тут имею ввиду, что, например, param1 = 2 (значит, Hello), и это i-элемент из maxObjects } Вот как-то так. Попробовал поискать, но даже не знаю, как сформулировать вопрос
Это можно реализовать используя класс Enum.aspx). Количество констант в **enum** можно найти так: Enum.GetNames(typeof(param1)).Length; или Enum.GetValues(typeof(param1)).Length; Получить имя крнстанты так: Enum.GetName(typeof(param1),индекс_константы) * * * В твоем случае: for (int i = 0; i < maxObjects; i++) Debug.Log(Enum.GetName(typeof(param1),i); Или так: foreach(string s in Enum.GetNames(typeof(param1))) Debug.Log(s); * * * < < <
stackexchange-ru_stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "c#, unity3d, enum" }
How do I keep dirty state in EditText under the MVP pattern? I use the MVP pattern. In my Activity onResume() I call the Presenter which calls the Model, data is loaded and my Presenter call my Activity (View) and updates my EditText fields. Now if I change my EditText and call another Activity, come back to the original Activity my data is reloaded (due to onResume()) and my dirty data is gone. How do I handle this scenario best under the MVP pattern?
Your Activity are doing this process to initialize: onCreate -> onStart -> onResume -> Running If you open another activity: Running -> onPause And when you close the other activity: onPause -> onResume -> Running As you can see, when the other activity is closed, you will go to onResume another time. If you need to initialize your EditTexts, I think that is better to do at onCreate. In this way, you don't lose your data.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "android, mvp" }
Who is the artist behind the US box art for the first Mega Man? I've tried looking around but I have failed miserably to find it myself. **Who is the artist behind the box art for the US release of the firstMega Man?** ![Bad Box megaman]( Box art taken from Megaman wikia.
While we do not have the name, we do know who the person was and why it turned out like it did. Here's from an interview with the American MM team: _Quote:_ > The president of Capcom US said to his marketing guy: "We need a cover done tomorrow". He went out and got a friend of his to do it in like 6 hours. Source (timestamp 05:33):
stackexchange-gaming
{ "answer_score": 4, "question_score": 18, "tags": "mega man" }
How can I integrate pictures/images in review queues? I can't figure out how I can integrate pictures when I read first posts in the review queue. I hope I didn't oversee something obvious.
New users aren't able to post images (to prevent spam or abusive material) and their posts often end up containing * links to an image: some text here (source code: `some text here`) * bare links to an image page like this: < The first case is easy to solve: just put a `!` in front of the opening square bracket: `!some text here`. It's a little bit more work to make it clickable, probably the easiest way to do that is to use the image uploader (see below). For the second case, I usually visit the website, right click on the image and choose something like 'Copy image location' (exact text depends on your browser): ![enter image description here]( You can either use that link to manually construct the necessary source code yourself (a la the previous example), or better: use the image uploader and use the 'paste an image or link' option: ![enter image description here](
stackexchange-meta_askubuntu
{ "answer_score": 5, "question_score": 3, "tags": "support, image" }
Android Studio 3.1 : updating gradle file cause android studio to freeze Today I updated Android studio from 3.0.1 to 3.1. I encountered a weird issue with Gradle. Each time I tried to edit a .gradle file, Android Studio freezes. With some research, I saw that each time you edit a .gradle file, Android Studio send a request to search "< I'm behind a proxy at my work, everything is configured, everything worked properly before that update. Is anyone encountered the same issue with this version or a older one?
jcenter is having issues so when you get your project to build correctly the once enable offline-mode so AS don't have to connect to jcenter every gradle refresh. see this question for more info.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 6, "tags": "android, maven, android studio, gradle, android studio 3.1" }
Bash: [ -f ] && echo 1 # What is the file that checked correctly? What file is checked as existed and regular one when I do not add any file name in expression: `[ -f ] && echo 1`? $ [ -f ] && echo "1" 1
No file is checked. `[` interprets its arguments based on the _number_ of arguments it receives (ignoring `]`). In this case, with only _one_ argument, `-f` is not a unary operator; it is simply a non-empty string. That means it is equivalent to `[ -n -f ]`, which succeeds because the argument to the unary operator `-n` is indeed not empty.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "bash, conditional statements" }
Scala - how to call a method which expects a Map I have a scala method: def commitSync(offsets: Map[TopicPartition, OffsetAndMetadata]) = { consumer.commitSync(offsets.asJava) } TopicPartition is a class with 2 parameters (`String` and `Int`): `TopicPartition(java.lang.String topic, int partition)`. Making it in scala like this: `val tp = new TopicPartition("sometopicname", 99)` OffsetAndMetadata is public kafka class with type 'long' in it: `OffsetAndMetadata​(long offset)` How to call now a method `commitSync` with these 2 parameters? Thanks.
Lets say you declare two case classes case class TopicPartition(str:String,intVal:Int) case class OffsetAndMetadata(longVal:Long) Now you create a map with these values val offsets = Map(TopicPartition("sometopicname", 99) -> OffsetAndMetadata(999999)) You can now call your function commitSync as commitSync(offsets) I hope this answers your question.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "scala, hashmap" }
How to Set Checkbox Checked if Value Is Yes (Django) I have a form which I am prefilling through a GET request. I am setting the value of a checkbox to either `Yes` or `No`. I would like to set the checkbox to `checked` if the value is `Yes`. script <script> if ($('#cisco').val() == 'Yes') { $('#cisco').prop('checked', true); } </script> form.html <div class="field"> <div class="control"> <label class="checkbox"> <input type="checkbox" name="cisco" id="cisco" value="{{ request.GET.cisco }}">Cisco: </label> </div> </div>
Do an if else statement in the HTML. You don't need the javascript. <div class="field"> <div class="control"> <label class="checkbox"> {% if request.GET.cisco == "Yes" %} <input type="checkbox" name="cisco" id="cisco" checked> Cisco: {% else %} <input type="checkbox" name="cisco" id="cisco"> Cisco: {% endif %} </label> </div> </div>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, jquery, html, django" }
How to solve this mathematical operation as fast as possible? I am trying to overcome a test to get in a website. They ask me to do mathematical operations like this > "$840 \times 883 + 991 - 109$" and many more like this (every time) in few seconds. I cannot do that even though I am using a calculator and copy/paste. Is there any trick to solve it? I mean mentally in order to be approved? Many Thanks.
I sent them a mail asking about this, the reply was : > Hi Jaideep, > > Thanks for trying the test. > > There are many ways to tackle this challenge. As the role we are looking to fill is for a Java developer we would expect the candidate to write a program to connect to the page, read the question and submit the answer. It's impossible to do it by hand... the timeout is very small. > > Many thanks I hope you've got your answer now.
stackexchange-math
{ "answer_score": 0, "question_score": 1, "tags": "education" }
Is the Optional Parameter in C# 4 Backwards Compatible? I am curious to know that whether optional parameter introduced in C#4 is backward compatible or not? Let me clarify my question with a simple example. Suppose I write the following code in C#4 on .Net2 in VS2010: public void Foo(int val1, int val2, int val3 = 5){ .... } Now I compiled the code, make a dll and reference it to a C#2 / C#3 project on .Net2. In the code editor (other than VS2010, say VS2008) what I'll see in intellisense? 1. Two overloaded methods like: public void Foo(int val1, int val2) public void Foo(int val1, int val2, int val3) 2. Something else like: public void Foo(int val1, int val2, int val3) public void Foo(int val1, int val2, int val3 = 5) //VS2008 is not supposed to show this How I am supposed to call the C#4 method in C#2 project?
It'll just be one method - the C# compiler doesn't create overloads. It will be just as if you're calling a method created in VB.NET with optional parameters - they've been in .NET right from the start. It's just that the C# 2 compiler won't know how to deal with them, so you'll have to specify all the arguments yourself. Basically optional parameters only change how methods are called. If there's a method like this: public void Foo(int x = 10, int y = 20) and you call it like this: Foo(15); the C# 4 compiler will change the _calling_ side to: Foo(15, 20); The C# 2 compiler can't do that, so you'd have to specify both arguments.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 9, "tags": "c#, .net, visual studio 2008, visual studio 2010, optional parameters" }
Polygons of countries including territorial waters Where can I get polygons (multipolygons) of all countries of the world including the territorial waters of the countries? OpenStreetmap displays these areas but I can't find an extract of this subset of the OSM data. * is there a subset of OSM data available, just containing the territories (incl. water territories) of a country as multipolygons ? * or, can I find this set of polygons somewhere else?
The country boundaries including the territorial waters are available in the OSM data set. I found a site where these country shapes can be downloaded: <
stackexchange-gis
{ "answer_score": 3, "question_score": 1, "tags": "polygon, data, administrative boundaries" }
AttributeError: 'NoneType' object has no attribute 'text'? I'm fairly new to python and only have a couple hours of experience. I've been creating a script that scrapes the Air Quality readings for my country directly. I am trying to run this command within my script: psi = soup.find("div", {"class": "panel-stats-value-content"}).text Though when I run it, it responds with: AttributeError: 'NoneType' object has no attribute 'text' How can I fix this? So that `.text` will work?
This error is raised because `BeautifulSoup.find()` is unable to find any `div` elements with the class of `panel-stats-value-content` in the document, so returns `NoneType`. When you try and call a method on a `NoneType`, it will raise the above error, but with the method whatever you called on it. To fix this you need to make sure that the `div` element's class is correct.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "python, beautifulsoup" }
Bad URL in swift 2 When I want to load a url it goes always into the `catch` block. How can i solve this? I think it's something with the escaped url. If i set url in the `if` block it goes immediately to the `else` block. let urls : String = Baseurl+"lat="+latitude+"&lon="+longitude+"&APPID={"+apiKey+"}" let escapedurl = urls.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()) let url: NSURL = NSURL(string: escapedurl!)! if let url = NSURL(string: escapedurl!) { do { let contents = try NSString(contentsOfURL: url, usedEncoding: nil) print(contents) } catch { // contents could not be loaded print("bad") } } else { // the URL was bad! print("bads") }
URLHostAllowedCharacterSet() returns the character set for characters allowed in a host URL subcomponent. For example, in the URL < the host component is www.example.com. Try to change let escapedurl = urls.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()) into let escapedurl = urls.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet())
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "swift, swift2, nsurl" }
Will name change affect Brazilian visa (or passport in general)? I recently got married. My wife, who will be changing her last name soon, has a Brazilian visa in her American passport from when she went in 2011 and I am under the impression that the visa is good for the duration of the passport (which doesn't expire until like 2019 or so). I'm wondering if she changes her name, will that cause her to have to get a new passport and lose the visa? We are considering going to the World Cup next year, partially because she already has the visa anyway, so I want to make sure we don't screw up anything and lose it just because of a stupid name change.
Yes, she will need a new visa. From the Brazilian Consulate General in San Francisco: > _ **25\. I got married and changed my name on my new passport, but my visa, which has not expired, is still on my old one. Do I need a new visa or can I just travel bringing along the two passports?** The name on the visa has to match with the one on the valid passport. In this case, it is advisable that you apply for a new visa in order to avoid problems with the Brazilian immigration authorities.
stackexchange-travel
{ "answer_score": 5, "question_score": 4, "tags": "visas, passports, brazil" }
ffmpeg using drawtext and select together I'm trying to extract every 30th frame from a video and add text to it, and output as a jpg. Here's the code I'm using: ffmpeg -i test.mp4 -vf "select=not(mod(n\,30)), drawtext=fontfile='C\:\\Windows\\Fonts\\arial.ttf:text='test':fontcolor=white:fontsize=45:x=(main_w/2-text_w/2):y=1800:" -vsync vfr -q:v 2 img_%03d.jpg The first frame selected outputs as img_batch3d.jpg, then this is the error message I get: [image2 @ 00000146e59d0500] Could not get frame filename number 2 from pattern 'img_batch3d.jpg' (either set update or use a pattern like %03d within the filename pattern) av_interleaved_write_frame(): Invalid argument Please help.
You have to escape the `%` in a Windows batch file, so change `img_%03d.jpg` to `img_%%03d.jpg`. See Batch files - Escape Characters.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "batch file, ffmpeg" }
What does it say about a multivariate polynomial to be zero on a linear subspace? If I univariate polynomial $f(x)$ that vanishes at a point $x_0$, we conclude that $x - x_0$ divides $f(x)$, and in particular that $f$ is reducible if $\deg f > 1$. Can anything of significance be said if a multivariate polynomial $g : \mathbb{R}^d \to \mathbb{R}$ vanishes along an entire linear subspace $V < \mathbb{R}^d$? The case $\dim V = 1$ can occur quite easily: if $g$ is homogenous, any zero of $g$ produces such a $V$. Thus, I am particularly interested in $\dim V = 2$ or higher, or if there is a taxonomy of different ways the $\dim V = 1$ case can occur. This question is related to an earlier question on the Schwartz-Zippel lemma linked below. The motivation for both is that I have an algorithm that chooses a random linear subspace and succeeds whenever a particular multivariate polynomial doesn't vanish entirely on that subspace. Analogue of the Schwartz–Zippel lemma for subspaces
If $V$ has codimension $1$ and is cut out by a single linear equation $\sum_{i=1}^d a_i x_i = 0$, then you can conclude that $\sum a_i x_i$ divides $f$. The proof is fairly short: by applying a suitable change of coordinates you can assume WLOG that the linear equation is $x_1 = 0$, and then it's clear. In higher codimension you can't conclude much. For example, when $d = 2$ and $V$ has codimension $2$ then $V$ is a point, and vanishing on a point doesn't tell you too much in this case.
stackexchange-math
{ "answer_score": 2, "question_score": 2, "tags": "algebraic geometry, polynomials" }
Calculating $\int_{e^2}^{e^3} \frac{1}{x \ln(x)\ln(\ln(x))} dx$ We want to calculate $$\int_{e^2}^{e^3} \frac{1}{x \ln(x)\ln(\ln(x))} dx = \int_2^3 \frac{1}{e^t \cdot t \cdot \ln(t)} \cdot e^t dt = \int_2^3 \frac{1}{t \ln(t)} dt = \int_2^3 \frac{\frac{1}{t}}{\ln(t)} \\\ = \ln(\ln(3)) - \ln(\ln(2))$$ How does one get to the second part? Why can we change the upper bounds to $2$ and $3$ correspondingly? $$ \int_2^3 \frac{1}{e^t \cdot t \cdot \ln(t)} \cdot e^t dt $$ What is this method called? Is it just a variant of integration by substitution? Are there other examples of this? Thanks in advance!
This is due to rote substitution. Substitute $\color{red}{t=\ln(x)}$ and $\color{blue}{dt=\frac{dx}x}$. The limits change to $x=e^2\implies t=\ln(e^2)=2$ and $x=e^3\implies t=\ln(e^3)=3$. $$\int_{x=e^2}^{e^3} \frac{\color{blue}{dx}}{\color{blue}{x}\color{red}{\ln(x)}\ln(\color{red}{\ln(x)})} = \int_{t=2}^3 \frac{\color{blue}{dt}}{\color{red}t \ln(\color{red}t)}$$ Or equivalently, let $\color{red}{x=e^t}$ and $\color{blue}{dx=e^t\,dt}$. $$\int_{x=e^2}^{e^3} \frac{\color{blue}{dx}}{\color{red}{x}\ln(\color{red}{x})\ln(\ln(\color{red}{x}))} = \int_{t=2}^3 \frac{\color{blue}{e^t\,dt}}{\color{red}{e^t} \ln(\color{red}{e^t})\ln(\ln(\color{red}{e^t}))} = \int_{t=2}^3 \frac{dt}{t \ln(t)}$$ since $\ln(e^t)=t\ln(e)=t$.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "calculus, integration" }
Javascript object automatically sorts // mechanics MECHANICS_ISOLATION : 1, MECHANICS_NA : 2, MECHANICS_COMPOUND : 3, // mechanics Exercise.mechanics = {}; Exercise.mechanics[Exercise.MECHANICS_COMPOUND] = 'Compound'; Exercise.mechanics[Exercise.MECHANICS_ISOLATION] = 'Isolation'; Exercise.mechanics[Exercise.MECHANICS_NA] = 'N/A'; When I loop through `Exercise.mechanics`, the keys come out sorted. How can I get the unsorted keys to loop through? Thanks!
Keys in a hashmap is not reliable. Give you keys an order. For example, put your keys into an array and iterate the keys. var keys = [MECHANICS_ISOLATION, MECHANICS_NA, MECHANICS_COMPOUND]; for (var i = 0; i < keys.length; i++) { console.log(Exercise.mechanics[keys[i]]); }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, sorting, object" }
Input value must contain number higher than 5 In my contactform I want to display a inputfield, that may only contain a number, higher than 5. How can I achieve that? My current code is: <li> <div class="field"> <label for="gewensteaantal" class="required"><em>*</em><?php echo Mage::helper('contacts')->__('Requested qty') ?></label> <div class="input-box"> <input name="gewensteaantal" id="gewensteaantal" title="<?php echo Mage::helper('contacts')->__('Requested qty') ?>" value="" class="input-text required-entry" type="text" /> </div> </div> </li>
You can use custom validation class 'validate-value-greater-than-5' and add following script in form javascript. Validation.add('validate-value-greater-than-5', 'Please enter a value greater than 5.', function(v) { return Validation.get('IsEmpty').test(v) || (v > 5); });
stackexchange-magento
{ "answer_score": 2, "question_score": 1, "tags": "form validation, contact us, contact form, input" }
How to create invisible widget in Drupal I need to create an auto-generated value for every user on my site. No one should be able to edit this field so it should not appear on the user edit form. Is there a better way to achive this than simply removing its edit field with hook_form_alter?
Install the Field Permissions module: > The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity. And the Computed Field module: > Computed Field is a very powerful CCK field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. You can then create a field for your value, hide it from the registration/profile form, and use Computed Field to set its value to whatever you need it to be automatically.
stackexchange-drupal
{ "answer_score": 1, "question_score": 1, "tags": "7, entities" }
Fixed size string type container I need a fixed size string type for certain requirements. For now I've been doing a simple `char[20]` array of characters to meet this requirement. However, it is lacking certain stl container-friendly properties that I require now and then. For eg a simple `empty()`, `clear()` methods are required quite frequently and also the `length`/`size` property or `getSize()` method that might return this property or the ability to not manage '/0'. Not the actual size, but the size of string that fills the container. Now I know I can reimplement all this and I might in the future when I get some time, but for now is there another way to achieve this?
I am assuming that you want to hold the small string in-place, avoiding allocation on heap and indirection when accessing it. In that case, have a look at `small_vector` from Boost. typedef boost::container::small_vector<char> small_string; This would work as the string you want. UPDATE: It seems that many implementations of standard C++ library use the small string optimization (SSO) for `std::string`. It means that as long as your string is small enough (for example 22 characters on 64 bit architecture) it will be stored in-place. I strongly suggest you to use standard `std::string` then.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c++, string, c++11, stl, containers" }
difference between two dates is not working in php I am using the below code to calculate years, months, and days between 2 dates $date1=date_create("2015-01-01"); $date2=date_create("2015-12-31"); $diff=date_diff($date1,$date2); echo $diff->format("%y years"); echo $diff->format("%m month"); echo $diff->format("%d days"); This is the result 0 years 11 months 29 days. But this should b 1 year. Can anyone please guide how I can get the required result?
You are creating two dates within the same year. A full year has not elapsed. It is TO the end date, not THROUGH the end date. You need to set your end date to be January 1, 2016 as it is not including the full day of December 31, 2015; it's just evaluating to 2015-12-31 00:00:00.000000. // add a day to the end date to ensure the final date is included in the comparison date_add($date2,date_interval_create_from_date_string("1 day"));
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "php, datediff, date difference" }
Final Fantasy Crystal Chronicles Dolphin+VBA-M multiple controllers problem I've followed all the instructions on this wiki page. It works, except that inactive windows do not receive input from their respective controllers. Only the active VBA window receives input making multiplayer impossible. I've read three threads on the VBM forums about this issue with no answers. Actually, everyone claims to have figured it out and didn't say how they fixed it. How can I get all controllers to receive input?
After a great deal of google searching a kind soul (Skid) on the dolphin forums pointed me to the solution. It's a driver issue. The newer Xbox One drivers break background input functionality and it's been that way for quite some time it seems. Here is his post: "This might help if you are using xbox one controllers and windows 10: < Steps from the post: 1. Go to the Microsoft Catalog and download the first driver if you're on x64 2. Unpack it with 7zip or winrar 3. Open up Device Manager 4. Expand "Human Interface Devices" and find your device 5. Double-click it, go to the "Driver" tab and click on "Update Driver" 6. Click on "Browse your computer" 7. Click on "Let me pick from a list of device drivers..." 8. Click on "XINPUT compatible HID device", then on "Have Disk" 9. Browse to the unpacked directory from step 2 and install it The OP doesn't specify, but the file you want to point to is xinputhid.inf.
stackexchange-gaming
{ "answer_score": 1, "question_score": 3, "tags": "controllers, emulation, dolphin emulator" }
Ubuntu Server 11.10 from USB? I tried 'burning' the .iso onto a USB like I normally would with Ubuntu Desktop or Server 12.04, but it gives me an error during installation and tells me that it can't get files from CD or something. So, is a USB installation of Server 11.10 not possible? P.S. I need to install 11.10 because 12.04 is giving me a LOT of problems trying to convert to a static IP.
I have personally installed various Ubuntu server versions from USB. I use the Ubuntu Startup Disc Creator (installed by default in Ubuntu desktop editions). I do remember something like this happening to me with another distro, and I think it had to do with the way I made the USB stick. This < thread suggests that unetbootin could be the source of the issue in at least one instance, which also confirms my experience. If you haven't already, I'd try the Ubuntu Startup Disc Creator. I have assumed you have an Ubuntu desktop install, my apologies if not. Goodluck!
stackexchange-askubuntu
{ "answer_score": 1, "question_score": 2, "tags": "server" }
SQL select statement - return highest number value of a field I have the following SQL select statement SELECT first_name, year FROM users WHERE username='$username' This can return many results because a user record can exist per year e.g. one for 2012, 2011 etc. Therefore I want to only fetch the details of the user from the latest year that the user record exists for. Any ideas how i can do this? Thanks
You can find the max year for a user, and then nest that so that you only select the one record with that year. SELECT first_name, year FROM users U1 WHERE username='$username' and year = (select max(year) FROM users U2 WHERE U1.username=U2.username)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql, postgresql, select" }
How to control the screen slide by code in the android? I'm trying to writing an app that can help me to control my screen. For example,I can press a button,and my android phone can help me to slide from left to right by itself. Please refer to the picture as below. ![enter image description here]( I saw some of the Transfer beads Game Cheat MAYBE use this method to control the screen slide automatically, but actually I don't know how it does. For another example, refer form the following video. In this video,he made the phone slide the screen by itself. What I want to do is as same as his work. =) < Thank you all in advance!
As it figured out the OP needs a drag/drop on the same screen for his problem and not swiping between activities or fragments: The keyword is "android drag and drop": <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, android" }
Get field value using LINQ query I need to get the value of the fee in this linq query and pass it to another controller. I tried this var fee = from f in db.Certificates where f.ID == traveler.CertificateID && f.Fee>0 select f.Fee; int q = fee.Count(); string famount = fee.ToString(); if (q > 0) { TempData["famount"] = famount; } But it passes the sql statement. something simple but i am trying to save some time.
Your fee is IQueryable and you have to use `FirstOrDefault()` to get value var fee = from f in db.Certificates where f.ID == traveler.CertificateID && f.Fee>0 select f.Fee; string famount = fee.FirstOrDefault().ToString();
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "c#, asp.net mvc, linq" }
Why did my fuse not blow? I purchased a few fuses to get familiar with their workings, and I was surprised to see that the 100mA fast-blowing fuses I bought happily conducted up to 215mA (6V power supply, 10\$\Omega\$ resistor), where the filament just started glowing. I could reproduce this with a second fuse. Am I gravely misunderstanding something here, or is this an issue with the fuses? They are Bel Fuse Inc. 5SF 100-R parts.
Even fast fuses don't respond immediately after the rated current is reached. Most fuses require a significant over current to fire almost instantly. This is an obvious requirement since its all about heat, and minor heating (a raise ambient temperature) shouldn't affect the fuse too much (or at least not cause it to "blow"). Judging from the data-sheet, your 100mA fuse should blow after about 80 seconds @215mA @25°C. !enter image description here How long did you wait?
stackexchange-electronics
{ "answer_score": 39, "question_score": 28, "tags": "fuses" }
SQL: All rows of two tables merged together I am trying to combine two different tables in a select statement where all the rows in the first table are matched with all the rows in the second table. For example: Table1 Table1_ID | FKey_Table2_ID 1 9 2 null Table2 Table2_ID | Table2_Value 9 Yes 10 No 11 Maybe Results needed: Table1_ID | FKey_Table2_ID | Table2_ID | Table2_Value 1 9 9 Yes 1 null 10 No 1 null 11 Maybe 2 null 9 Yes 2 null 10 No 2 null 11 Maybe Please note that the first row in Table1 has a key already assigned from Table2.
This is called a cross join and can be accomplished like this: SELECT Table1_ID, FKey_Table2_ID, Table2_ID, Table2_Value FROM Table1 CROSS JOIN Table2 Or more simply SELECT Table1_ID, FKey_Table2_ID, Table2_ID, Table2_Value FROM Table1, Table2
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql, sql server" }
Assembly.CreateInstance and security I'm toying around with the idea of using C#'s ability to compile code on-demand as the basis of a scripting language. I was wondering, how can I sandbox the scripts that I am executing so that they cannot access the file system, network, etc. Basically, I want restricted permissions on the script being run. Steps that I take: CompilerResults r = CSharpCodeProvider.CompileAssemblyFromSource(source); Assembly a = r.CompiledAssembly; IScript s = a.CreateInstance(...); s.EntryPoint(...);
The recommended approach for this is to execute the suspect code in a sandboxed appdomain. Several reasons are given at < and an even more important one is that most of the other potential approaches are deprecated as of .NET 4.0.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 6, "tags": "c#, security, scripting" }
How to refer a local image file from UIWebView's HTML on iPhone? I would like to use `<img src="` **`temp.jpg`**`" />` in my UIWebView's HTML. How can I refer to a local file named **`temp.jpg`** to save precious loading time? Of course the obvious choice would be `<img src="` **`.\temp.jpg`**`" />` but I have no idea where my root is...
NSURL *url=[[NSBundle mainBundle] bundleURL]; [webView loadHTMLString:string baseURL:url]; This let's the root be the app's main bundle.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "ios, uiwebview" }
RDD transformation map, Python is it possible to convert all elements in the map method of Spark to the float (double), excepted the first one without to do the iteration with the for-loop? Something like this in pseudocode: input = sc.textFile('file.csv').map(lambda line: line.split(',')) #create a rdd<list> test = input.map(lambda line: line[0] else float(line)) #convert all elements of the list to float excepted the first one
It is possible although it arguably not a good practice. RDD is a homogeneous collection of objects. If you expect some kind of header it would be better to drop it than drag it all the way through. Nevertheless you can try something like this: from itertools import islice # Dummy data with open("/tmp/foo", "w") as fw: fw.writelines(["foo", "1.0", "2.0", "3.0"]) def process_part(i, iter): if i == 0: # We could use enumerate as well for x in islice(iter, 1): yield x for x in iter: yield float(x) (sc.textFile("foo.txt") .mapPartitionsWithIndex(process_part) .collect()) ## ['"foo"', 1.0, 2.0, 3.0, 4.0] If you expect empty partitions you count elements first: rdd.mapPartitionsWithIndex(lambda i, iter: [(i, sum(1 for _ in iter))]).collect() and replace 0 with an index of the first non-empty partition.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "python, list, apache spark, pyspark, rdd" }
Regex to exclude file pattern I have the following regex which I want to ignore sass partials: At the moment it looks like this: match /app\/stylesheets\/(?:.+\/)?[^_].+\.s[ca]ss/ do sass end Example file paths I want to parse are: /app/stylesheets/nonpartial.scss /app/stylesheets/folder/anothernonpartial.scss And examples of the partials I want to ignore are /app/stylesheets/_partial.scss #this is ignored /app/stylesheets/partials/_anotherpartial.scss #this gets a match The partials are not getting picked up by the regex, can anyone suggest a better one?
/app\/stylesheets(\/(\w+?))*\/(?!_)(\w+?)\.s[ca]ss/ This RegEx will match a file in /app/stylesheets in an arbitrary number of subdiretories whereas the filename must not begin with an underscore. This RegEx uses Look-Arounds.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "ruby, regex" }
Probability all Bernoulli random variables take value $1$ with limited independence Let $S_1,\dots, S_n$ be Bernoulli random variables which are $4$-wise independent. We have that for each $i$, $P(S_i = 1) = p$ for some fixed probability $0 < p < 1$. What can we say about $P(\forall i\; S_i= 1)$ in terms of upper ~~and lower~~ bounds? ~~Clearly $P(\forall i\; S_i= 1) \geq p^n$ but what is the largest it can be?~~
This has been treated in the literature: < also see < In particular, the upper bound goes to 0, but only polynomialy in $n$.
stackexchange-mathoverflow_net_7z
{ "answer_score": 7, "question_score": 4, "tags": "pr.probability" }
Building multiprocessor motherboard I would like to build a multi processor motherboard using ARM processors (e.g. the ARM Cortex A8 or A9 or others as well), for low-power computing. Is this possible ? I mean interconnecting the processors ... or the maximum I can do is putting e.g. 5 processors, RAM modules, EEPROM, etc (separated for each processor) and let one processor only coardinate the timing between them ? I would do this only for the fun now, but I cant exlude the possibility of running this on an actual machine (server maybe). I want to install GNU/Linux over it (maybe Debian GNU/Linux). Right now I'm a student in electronics and electrical engineering in bachelor 3rd year ... would like to do this in the summer holidays since we have a printed circuit board lab in our school which we can use almost for free.
Inter-processor communication is possible and as you indicate some kind of bus arbiter would be needed for shared memory. I don't want to steal your joy, but what you are describing is a _huge_ project. Unless your school lab is really advanced it is also likely that the PCB technology needed for this build (multi-layer, narrow isolation and maybe microvias) is missing. If you want to experiment with parallel computing maybe a dual-core microcontroller (processors + peripherals in one package) would be a good start. You can find some LQFP packages that are easy to solder. An even better way could be to study an existing design such as the Pandaboard (
stackexchange-electronics
{ "answer_score": 3, "question_score": 1, "tags": "board, processor" }
Good Pokemon for the Zero Isle South dungeon? The Zero Isle dungeons in the Pokemon Mystery Dungeon series (Explorers of Time, Darkness, and Sky specifically) are much more similar to a typical roguelike, adding restrictions that make the dungeon difficult to complete (and forcing you to rely on luck a _little more_ ). In particular, Zero Isle South makes you enter with no money, no items, and (for the dungeon) resets your Pokemon's level to 1. However, there are definitely some Pokemon that are better than others for attempting to complete the dungeon. For example, Mew is a great Pokemon because it can learn all TMs you pick up. **What other Pokemon are good for completing Zero Isle South?**
After doing some of my own research, I found that people seem to suggest these three: **Smoochum** (it seems almost everybody attempts the dungeon using Smoochum) * Has the ability **Forewarn** , allowing you to occasionally **evade moves** (even no-miss moves) * Learns **Sweet Kiss** at level 8, which is a 100 accuracy confusion causing attack * Learns **Powder Snow** at level 11, giving it a **room-clearing** move **Aerodactyl** * Has the **elemental fangs** (Ice, Fire, Thunder) at level 1, giving it a diverse moveset * Has **Supersonic** at level 1, allowing it to **confuse** enemies **Spritomb** * **Amazing stats** at level 1 * Has **Confuse Ray** at level 1, allowing it to **confuse** enemies * Has **Shadow Sneak** at level 1 (giving it a **ranged** attack)
stackexchange-gaming
{ "answer_score": 2, "question_score": 8, "tags": "pokemon mystery dungeon explorers" }
Unwanted Char Appears Giving Url to Images I have images in this order : [image][image] When i give each of them an url, - char suprisingly appears between them.I don't understand why - appears. Here is the code : <div style='float:left; width:320px;'> <span> <a href=' <img style='width:75px; height:75px' src='$img_root/logo_bogaz.jpg' alt='logo bogazici university'> </span> <span> <a href=' <img style='width:70px; height:70px' src='$img_root/gyte.gif' alt='logo gyte'> </span> </div> And OUTPUT : !enter image description here
It is part of the underline from your anchor tag. You can remove the underline as per below. (Note this will remove it for all links) Add this to fix: <style> a { text-decoration:none; } </style> Ideally this should go in a separate CSS file. But add it to the top of your HTML for an easy test.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "html, url, hyperlink" }
Is viscosity simply "slowing down time"? The Pitch drop experiment has pitch, a fluid with extremely high viscosity, flowing through a funnel. In 85 years, only 9 drops have fallen. Photographs of the drops, however, show an appearance just like drops of fluids with much lower viscosity like jelly or syrup. Indeed, the pitch drops look like regular drops "frozen in time". My question, then, is this: All else being equal, **is the flow of a high-viscosity fluid the same as that of a low-viscosity fluid, just slower?** That is, if a camera had been filming the pitch drop experiment for its entire duration and the footage was played back at a few hundred thousand times its recording speed, would it still be possible to distinguish pitch from honey?
Not necessarily, it depends on how different the viscosities are. @MonkeysUncle got it right. If the Reynolds number is < 2,000 the flow is laminar; if it's > 4,000 the flow is turbulent. Since the Reynolds number depends on viscosity, if the viscosity of the two fluids is different enough that it changes the flow from laminar to turbulent, then you wouldn't get matching flows simply by speeding up the video of the slow one. Water and lubricating oil have different enough viscosities, as one example.
stackexchange-physics
{ "answer_score": 7, "question_score": 4, "tags": "fluid dynamics, viscosity" }
Регулярное выражение для выбора данных между кавычками Сломал свой мозг. Пишу регулярное выражение, которое выберет мне данные из строки между кавычками, но проблема в том, что последний параметр выбирает все данные до последней кавычки, а мне нужно до первой встреченной. Сделал следующее регулярное выражение: "Min=(`"(?<minvalue>.*)`").*(max=`"(?<maxvalue>.*)`")" Символ ` экранирует кавычку. Пробовал добавлять [^`"] но не помогло :-( Подскажите решение плиз
Если между кавычками символов не очень много, используйте `«.*?»` вместо `«.*»`
stackexchange-ru_stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "c#, регулярные выражения, powershell" }
Finding the matrix for a matrix exponential I'm trying to find the matrix $A$ for which $$e^{tA}=\begin{pmatrix} \frac{1}{2}(e^t+e^{-t}) & 0 & \frac{1}{2}(e^t-e^{-t}) \\\ 0 & e^t & 0 \\\ \frac{1}{2}(e^t-e^{-t}) & 0 & \frac{1}{2}(e^t+e^{-t}) \end{pmatrix}$$ I know that $e^{tA}=\Psi(t)\cdot[\Psi(0)]^{-1}$, so $e^{tA}\cdot\Psi(0)=\Psi(t)$. Where $\Psi(t)=(\eta^{(1)}e^{\lambda_1x},\eta^{(2)}e^{\lambda_2x},\eta^{(3)}e^{\lambda_3x})$, with $\lambda_i$ the $i$-th eigenvalue with corresponding eigenvector $\eta^{(i)}$. However, this didn't really get me anywhere. Does anyone know how to do this?
As you know $$e^{tA} = I + tA + (t^2/2)A^2 + ....$$ Thus if you differentiate $$e^{tA}=\begin{pmatrix} \frac{1}{2}(e^t+e^{-t}) & 0 & \frac{1}{2}(e^t-e^{-t}) \\\ 0 & e^t & 0 \\\ \frac{1}{2}(e^t-e^{-t}) & 0 & \frac{1}{2}(e^t+e^{-t}) \end{pmatrix}$$ and evaluate the result at $t=0$, you will get your matrix $A$ I found $$A= \begin{pmatrix} 0&0&1\\\0&1&0\\\1&0&0\end{pmatrix}$$ Notice that the matrix $A$ satisfies $$(e^{tA})' = Ae^{tA}$$ and $$ e^{tA} =I $$ at $t=0.$
stackexchange-math
{ "answer_score": 20, "question_score": 9, "tags": "matrices, ordinary differential equations, matrix exponential" }
React and TypeScript: incorrectly extends base class 'Component' I'm trying to create a class with TypeScript that extends `React.Component`, but I'm having this error: Class 'Provider' incorrectly extends base class 'Component<{}, {}>'. Types of property 'render' are incompatible. Type '(props: any) => any' is not assignable to type '() => false | Element'. Here's the code: import * as React from "react"; export default class Provider extends React.Component { props; getChildContext() { const { children, ...context } = this.props; return context; } render(props) { const { children } = props; return children[0]; } }
The error message is telling you that `render()` doesn't expect an argument. I suspect you are supposed to be using `this.props`? Also your definition of an attribute `props` of type `any` is going to hide the type of `props` attribute in the base class so the compiler won't be able to work out the type of `children[0]`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "reactjs, typescript" }
Remarkable-rails framework requirements I have those : 1. rspec (2.11.0) 2. rvm (1.11.3.5) 3. rspec-rails (2.12.0) 4. remarkable (4.0.0.alpha4, 3.1.13) 5. remarkable_activemodel (4.0.0.alpha4) 6. remarkable_activerecord (4.0.0.alpha4, 3.1.13) 7. rails (3.2.3) My remarkable gem for rspec should work or not with those gems ?
Looking at the `Runtime Dependencies` for `remarkable_rails` gem `3.1.13` version, I would venture that it should work. According to that page, the dependencies are: remarkable ~> 3.1.13 remarkable_activerecord ~> 3.1.13 rspec >= 1.2.0 rspec-rails >= 1.2.0
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "ruby on rails 3, rspec" }
Arithmetic operation between command arguments and latex parameters I'm defining a new command that places two images one next to the other and I want to add an horizontal space between the two images which corresponds to one third of the space that remains blank. The command definition reads: \newcommand{\twofig}[4]{% \begin{center}\includegraphics[width=#2\columnwidth]{#1.png}% \hspace{(1-#2-#4)/3 \columnwidth }% \includegraphics[width=#4\columnwidth]{#3.png}% \end{center} } I'm missing what I should use in order to get this operation solved. I've tried with `\dimexpr` but I always got errors. Is it not the right solution? When should I use `\dimexpr` and when `\numexpr`? The etex manual also was not so helpful for me.
as cfr says, no calculation is necessary, but if `#2\columnwidth` works then `#2` must be a factor but `\numexpr` needs an integer and `\dimexpr` needs a length so neither can calculate `(1-#2-#4)` \makebox[\textwidth]{% \hfill \includegraphics{...}% \hfill \includegraphics{...}% \hfill} should do what you want. In general you can do \makebox[\textwidth]{% \hspace{\stretch{1}% \includegraphics{...}% \hspace{\stretch{2}% \includegraphics{...}% \hspace{\stretch{3}% } which will stretch the glue in the ratio 1:2:3, the example above is of course equivalent to having each argument of `\stretch` be `1`.
stackexchange-tex
{ "answer_score": 5, "question_score": 7, "tags": "macros, calculations, lengths, arguments, arithmetic" }
Eliminar elemento de un string JS Tengo la siguiente cadena [{"idServicio":10},{"idServicio":11},{"idServicio":12}] y lo que quiero hacer es eliminar un elemento a partir del valor del idServicio, por ejemplo eliminando el id de valor 11, y quede algo asi: [{"idServicio":10},{"idServicio":12}] Podría ayudarme del método `substr` pero quería saber si existe un método o función al que le pase el valor del id y lo elimine en una sola linea de código, sin preocuparse por la ubicación del elemento y las comas. > Para mi es un JSON, pero la consola de JS me dice que es un string (podrá ser ambos?) por eso el titulo de la pregunta es asi. Si tengo errados los conceptos agradezco cualquier comentario, estoy dando mis primeros pasos. Muchas gracias
Puedes auxiliarte del método `filter()` el cual: **Edición** Necesitas hacer uso de `JSON.parse()` puesto que al inicio tienes una cadena de textoy con dicho método obtendremos un objeto de JavaScript que será susceptible de ser iterado por el método que estoy proponiendo en esta _respuesta_ Va a permitirte generar un nuevo vector con los elementos del vector original que cumplan una determinada condición. Por ejemplo en tu escenario, puedes: Filtrar por la clave `idServicio` cuando esta misma sea diferente a 11, de modo que la variable `datos` se convierta en el nuevo vector que tiene todos los elementos del anterior menos aquel de id 11 Quedando así: data = '[{"idServicio":10},{"idServicio":11},{"idServicio":12}]' data2 = JSON.parse(data) let datos = data2.filter((elemento) => elemento.idServicio !== 11) console.log(datos)
stackexchange-es_stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "javascript, json" }
Geometrization & JSJ decomposition with boundary Is there any paper where I can find a good explanation of the JSJ decomposition, the geometrization theorem and the relations between them when the manifold has nonempty (and non necessarily toroidal) boundary? Currently I am trying to read the original Jaco-Shalen paper and a Scott's survey paper, buy they do not look to be completely satisfactory...
The work of Jaco-Shalen and Johannson actually handles manifolds with boundary. The theorem they prove (in the language of Johannson's Book) is: An irreducible, boundary-irreducible 3-manifold with useful boundary pattern possesses a characteristic submanifold, unique up to isotopy. The complement of the characteristic submanifold is atoroidal and acylindrical, hence (by Thurston) possesses a unique hyperbolic metric with totallygeodesic boundary. The characteristic submanifold has the property that every admissibly embedded I-bundle or Seifert fibered space is isotopic into the characteristic submanifold. All the notions, including useful boundary pattern and admissible embedding, are explained in Springer Lecture Notes in Mathematics 761 (Johannson: Homotopy equivalences of 3-manifolds with Boundaries), the above-cited Theorem is Proposition 9.4 in that Book.
stackexchange-mathoverflow_net_7z
{ "answer_score": 9, "question_score": 4, "tags": "reference request, gt.geometric topology, hyperbolic geometry, 3 manifolds" }
Foreign key in mysql table- is the presence of target data necessary? I have 2 tables TableA(id_A, name_A, info_A) tableB(id_B, A_id, some_data) foreign key(A_id) references tableA(id_A) So when I insert a row in B, with value XXX as value in the second column id_A, is it necessary that the table_A should have a row with XXX as id? If not, then what constraint should i lay upon the tables so that table B references only a table_A row that is present?
Yes, if TableA.id_A is the primary key, and TableB.A_id has a foreign key constraint referencing that primary key, then the XXX value must exist in TableA.id_A before TableB.A_id can contain XXX. It also means you can't delete or change the XXX value in TableA.id_A while the value XXX exists in TableB.A_id. You would have to delete, change, or set NULL the value in TableB.A_id first. You could also declare the foreign key with CASCADE options so that changes in TableA are also applied to TableB atomically. But you can never have an "orphan" value in a dependent table. Note that if you use the MyISAM storage engine for either TableA or TableB, then your definition of a foreign key constraints is silently ignored, and the database doesn't enforce any referential integrity between the two tables. You must use the InnoDB storage engine for both tables to get support for foreign key constraints.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "mysql, foreign keys" }
JSON, XML or String concatenation I am doing a new application where I want to choose which protocol to use in it. I tried the String concatenation and the XML before, but never tried the JSON Object. Well Which one of those three is better in terms of performance? I am aware that XML is way much better than string concatenation. So what to use? XML or JSON? Or maybe a new technology that I am not aware of? Thanks in advance **I am aware that XML is way much better than string concatenation**. Well in this I mean that in String concatenation, I am adding different values and splitters to a string and then looping to find the spliters on the device. like in the example: String toSend = "test1////test2////test3////test4////test5"; Here the splitter is `"////"` and I am sending 5 values. Getting these 5 values will be much more slower than XML in case of thousands of values.
It depends. :) Well, actually I think a properly written code to split a string will be more fast than an XML/JSON parser, however XML/JSON parsers are reliable in terms of returning exactly the same data structure. For instance, how would you handle a case when your data itself includes splitters? If such case is impossible under your business logic, then you may just go with string joining/splitting. Otherwise it is better not to reinvent the wheel and just use XML/JSON (JSON is more lightweight).
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "java, xml, json, blackberry" }
SqlCeCommand nullable values My code: SqlCeConnection sql = new SqlCeConnection(@"Data Source=C:\DB.sdf"); sql.Open(); cmd = new SqlCeCommand("INSERT INTO xxx(aaa) VALUES(@aaa)", sql); String param = null; //doesn't work //String param = "blah" //works cmd.Parameters.AddWithValue("@aaa", param); cmd.ExecuteNonQuery(); //(1) sql.Close(); (1) throws an exception when `param` is null. Database allows value in collumn `aaa` to be null. How can I insert null into table xxx ? Exception: `Parameterized query 'INSERT INTO xxx(aaa) VALUES(@aaa)' expects a parameter value which was not supplied.`
Try using `DBNull.Value` instead: var param = DBNull.Value;
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "c#, visual studio 2010, sql server ce" }
Could last PID variable $! be wrong? If a script launches a process and immediately after collects the PID with `$!`, could it get the wrong PID if somewhere else on the system a process is started in the moment between the time the script launches the process and when the script collects the PID with `$!`?
The `$!` special variable holds the PID of the last child process launched that the current shell started. It is never modified by actions happening in some other processes elsewhere on the system. `$!` can only be wrong if you yourself launch a new child process before collecting the value, because it's overwritten each time. For example, here the PID of "processX" is lost and the PID of "processY" is printed: processX & processY & echo Child process PID: $!
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 4, "tags": "linux, bash, process, pid" }
How to add text in a txt file with bash scripting i have a question. I need to add a text line into a txt file. This is my file: * 000 * 001 test1 * 002 test2 * 003 test3 * 004 * 005 test4 * 006 test5 * 007 test6 I need with bash scripting to add text in line 000 and 004. How can i do? Thanks to all!
You can use the "sed" tool to acheive your goal. It is quite powerful for manipulating files. You can use a command like this: sed -i /your/file.txt -e "s/000/000'\n'YOUR_NEW_LINE/" sed -i /your/file.txt -e "s/004/004'\n'YOUR_NEW_LINE/" (If I understand correctly, you have "000" at the begining of the first line of your file, and "004" for the fifth one)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "bash" }
Sync/Save list data from root site to subsite Is it possible to save newly created item from list one from the root site to the same list in the other sub site. Currently we are implementing country specific site and we have the global site where the global news and announcement will be published then it will also be available to the country sites Global Site ----> News List News 1 /en-US ----> News List News 1 from root site News en-US /en-PH ---> News List News PH News 1 from root site Need your help and suggestion. Thanks!
SharePoint workflow cannot create items in the list in another site. As a workaround for SharePoint Online, deploy the **Remote Event Receiver** to monitor the events in the list. The code/operations in an event receiver can be triggered when an item is created/modified/deleted, then copy item to another list in another site. Demo: Create a remote event receiver in SharePoint Add-ins
stackexchange-sharepoint
{ "answer_score": 0, "question_score": 0, "tags": "sharepoint online, workflow, multilingual" }
Is there a way to swap objects in Photoshop? In Photoshop CS6 I have a lot of (smart) objects perfectly spaced out but in the wrong order. All the objects are the same size. Is there a way to swap the location of a object with another one? Would save me loads of time. Thanks in advance!
I was forever doing this with catalogues and the like! You could do this quick and dirty by keeping the right and left most smart objects where they are, these are going to keep the edge boundaries. Then re-jig the ones in the middle and then select the right and left ones mentioned earlier along with the rejig ones, Align to Top/Vertical Align, and then 'Distribute Horizontal Centers' If you needed to swap the Right and Left boundary images, do this first, just by moving the ones you do want, ontop and with 'Snap to' on they should just click into place.
stackexchange-graphicdesign
{ "answer_score": 0, "question_score": 1, "tags": "adobe photoshop, cs6, smartobject" }
Can't connect Edge Impulse project from Raspberry pi 3 ![!\[enter image description here]( I wanted to connect the edge impulse audio classifier model from raspberry pi 2 and OS I am using is Raspbian lite. I got an error, [SER] Using microphone hw:1,0 Failed to initialize Linux tool Error code was not 0: Probing devices... [0:15:05.824831212] [938] INFO Camera camera_manager.cpp:293 libcamera v0.0.0+3156-f4070274 Failed to start device monitor! Could anyone help me to understand what is actually error message trying to say?
If you don't need a camera, use: edge-impulse-linux --disable-camera
stackexchange-raspberrypi
{ "answer_score": 0, "question_score": 0, "tags": "raspberry pi os" }
Understanding For-in Loop Here I have variable that has an object whose one value is an array of objects eg. var test = { "key1": val1, "key2": [{"a":1, "b":[{},{}] }, {"a":1, "b":[{},{}] }] }; I am now unable to understand why following piece of code iterates two times. Shouldnt it just iterate once as only 1 array element is present? code snippet: for( index in test.key2)
This is where good indentation is key. var test = { "key1": val1, "key2": [ { "a":1, "b":[{},{}] }, { "a":1, "b":[{},{}] } ] }; Here you can clearly see that it in fact has 2 items.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": -6, "tags": "javascript" }
How to revoke given permission in Chrome and Firefox? One of the new APIs made available to developers is Geolocation API. As it's been defined in Specification, any browser should take the express permission of the user when revealing his/her geographic position to the surfed website. However, it's also been said that user can revoke that given permission at any time. I searched almost everywhere in Chrome and Firefox and I didn't find any place to revoke given permissions. Does anyone know how should I do that? (This is also the case in Contacts API)
chrome://settings/content has a section that allows you to revoke location permissions.
stackexchange-stackoverflow
{ "answer_score": 39, "question_score": 21, "tags": "firefox, google chrome, w3c" }
How to add multitouch support for ChromeEmbeddedFramework browser on windows 8? I 've develooped a basic custom browser with CEF (Chromium Embedded Framework) Python . This browser is meant to run into an interactive kiosk with windows 8. It has a multi-touch screen for all user interactions. If I run Google Chrome on the machine, the multi-touch gestures (scroll and virtual keyboard) are supported. Unfortunately my CEF browser doesn't have detect any multi-touch event. How can I fix it? ANy pointer is welcomed.
The problem was fixed by using CEF3 rather than CEF1
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "python, windows 8, multi touch, chromium embedded" }
If document class is equal to something then do not use package I am trying to create a file which includes common packages and macros I use. It is something like this. commonDefinitions.tex \interdisplaylinepenalty=2500 \usepackage{algorithmic} \usepackage{cite} \usepackage{appendix} ... other packages and macros But some packages clash with each other in combinations. For example when I try to use \documentclass[journal]{IEEEtran} \usepackage{appendix} It gives error since IEEEtran already created command appendix. I would like to get some solution to this problem something like below. if document class is not IEEEtran \usepackage{appendix} end if
A way is \makeatletter \@ifclassloaded{IEEEtran}{}{\usepackage{appendix}} \makeatother But I believe that documents written for submission should _not_ have any reference to conflicting packages (and so tricks like this one). How would you use the commands provided by `appendix` if the document class is `IEEEtran`?
stackexchange-tex
{ "answer_score": 19, "question_score": 19, "tags": "packages, conditionals, document classes" }
Core Data Design: better 1 model with 2 stores or 2 models and 2 stores? I'm facing a design problem using core data in an iOS app. I've got two stores, one will contain a sort of catalog, the other only user data. I've read all those questions: * CoreData with multiple stores: configuration woes * Why might I want 2 or more Core Data models? * Can multiple (two) persistent stores be used with one object model, while maintaining relations from one to the other? But what I still didn't get is if it is better two use one model on two persistent stores or two models merge them at runtime with two stores. What will be easier, eventually, to migrate?
The definite way to go here is have **one** data model with **two** stores, administered via two so-called **configurations**. In the model editor you can define which entities belong to which configuration. In code you specify the identifier string of each configuration when adding the persistent store. See the WWDC 2012 video on Core Data and iCloud that explains it really well.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "ios, macos, core data, persistence" }
Compare Guid with default or empty? What is the right way to check whether a Guid is empty? First method: Guid value; // ... if (value != Guid.Empty) or second method: if (value != default(Guid)) I think the second method is better, but I can't explain why.
Since `Guid.Empty == default(Guid)` it does not really matter, but I would prefer `Guid.Empty` for readability.
stackexchange-stackoverflow
{ "answer_score": 29, "question_score": 19, "tags": "c#, .net" }
error: request for member '..' in '..' which is of non-class type I have a class with two constructors, one that takes no arguments and one that takes one argument. Creating objects using the constructor that takes one argument works as expected. However, if I create objects using the constructor that takes no arguments, I get an error. For instance, if I compile this code (using g++ 4.0.1)... class Foo { public: Foo() {}; Foo(int a) {}; void bar() {}; }; int main() { // this works... Foo foo1(1); foo1.bar(); // this does not... Foo foo2(); foo2.bar(); return 0; } ... I get the following error: nonclass.cpp: In function ‘int main(int, const char**)’: nonclass.cpp:17: error: request for member ‘bar’ in ‘foo2’, which is of non-class type ‘Foo ()()’ Why is this, and how do I make it work?
Foo foo2(); change to Foo foo2; You get the error because compiler thinks of Foo foo2() as of function declaration with name 'foo2' and the return type 'Foo'. But in that case If we change to `Foo foo2` , the compiler might show the error `" call of overloaded ‘Foo()’ is ambiguous"`.
stackexchange-stackoverflow
{ "answer_score": 812, "question_score": 541, "tags": "c++" }
Ruby: trying to run set command I am working with Chef and ruby and I am trying to run the set command. setVarList = %x(set) If I just type set it works fine, but if I run this script I get the following error: /var/chef/cache/cookbooks/motd/recipes/default.rb:22: command not found: set What is wrong?
As Anew already mentioned: **set** is bash built in command, but ruby %x() shell is **sh**. %x(echo $0) The workaround is running bash explicitly, as proposed by CodeGnome in comment. %x(/bin/bash -c set)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "ruby, bash, shell" }
How to express a certain 60-minute period If the time was 15:34, how could I refer to the 60-minute period between 14:00 and 15:00? If I were to say _the last hour_ it would likely mean the period from 14:34 to 15:34. So how do I express time period from _x-1_ o'clock till _x_ o'clock, irrespective of how many minutes have passed _x_ o'clock. It's like the difference between 'every hour' and 'on the hour'.
There seems to be some consensus that any 60-minute period one refers to should be called an hour, but I don't agree... If I want to refer to the period between 14:00 and 15:00, I call that _between 2 and 3_ , whether I mean the whole period or some incident that occurred within that time frame: > I was sleeping between 2 and 3. > How many customers did we have between 2 and 3? The nice thing is that you can use the same expression for time periods other than 60 minutes as well.
stackexchange-english
{ "answer_score": 2, "question_score": 0, "tags": "word choice" }
Change colors in Emacs ido mode I've installed Emacs-starter-kit (< and I've customized the colour scheme. But in the minibuffer (in ido mode, which is default in Emacs-starter-kit) red colour looks different. screenshot How I can customize colours in the ido minibuffer and make it looks in the same way as in regular buffers? Thanks.
Here are the faces for ido and how I set them in my .emacs: (custom-set-faces '(ido-subdir ((t (:foreground "#66ff00")))) ;; Face used by ido for highlighting subdirs in the alternatives. '(ido-first-match ((t (:foreground "#ccff66")))) ;; Face used by ido for highlighting first match. '(ido-only-match ((t (:foreground "#ffcc33")))) ;; Face used by ido for highlighting only match. '(ido-indicator ((t (:foreground "#ffffff")))) ;; Face used by ido for highlighting its indicators (don't actually use this) '(ido-incomplete-regexp ((t (:foreground "#ffffff")))) ;; Ido face for indicating incomplete regexps. (don't use this either) I found them by doing `M-x` set-face-foreground `RET` and then typing "ido-" and using completion to get the available face names. It may be simpler to use `M-x` customize-face and then using completion like above to customize the faces using the simple interface.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 3, "tags": "emacs" }
How to effectively calculate $(1/\sqrt1 + \sqrt2) + (1/\sqrt2 + \sqrt3) +\cdots + (1/\sqrt{99} + \sqrt{100})$ I have this series: $$\frac{1}{\sqrt1 + \sqrt2} +\frac{1}{\sqrt2 + \sqrt3} +\frac{1}{\sqrt3 + \sqrt4} +\cdots+\frac{1}{\sqrt{99} + \sqrt{100}} $$ My question is, what approach would you use to calculate this problem effectively?
Hint :$\displaystyle \frac{1}{\sqrt{(n+1)}+\sqrt{n}}=\sqrt{n+1}-\sqrt{n}$(By multiplying the numerator and the denominator by multiplying $(\sqrt{n+1}-\sqrt{n})$ to both numerator and denominator.) So we have, $(1/(\sqrt1 + \sqrt2)) + (1/(\sqrt2 + \sqrt3)) + .. + (1/(\sqrt{99} + \sqrt{100}))=\displaystyle \sum_{n=1}^{99}\frac{1}{\sqrt{(n+1)}+\sqrt{n}}=\sum_{n=1}^{99}\sqrt{n+1}-\sqrt{n}=\sqrt{100}-\sqrt{1}=10-1=9$
stackexchange-math
{ "answer_score": 4, "question_score": 3, "tags": "summation" }
SQL query to join results from two tables but also include rows that do not have counterparts in the other table? Given two tables APPLE and ORANGE, NAME APPLES Alice 5 Bob 10 Trudy 1 NAME ORANGES Bob 50 Trudy 10 Dick 10 How can I write a JOIN to show the table: NAME APPLES ORANGES Alice 5 - Bob 10 50 Trudy 1 10 Dick - 10 I currently have SELECT a.NAME, APPLES, ORANGES FROM APPLE a JOIN ORANGE o ON o.NAME = a.NAME but that only returns the fields that have a value in both APPLE and ORANGE.
SELECT COALESCE(a.NAME, b.NAME) as NAME, APPLES, ORANGES FROM APPLE a FULL OUTER JOIN ORANGE o ON o.NAME = a.NAME
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 4, "tags": "sql, database, oracle" }
Multiple facebook user id for the same user I've a problem with facebook login. I've created an app in a facebook developer's account. Next I've used the facebook PHP SDK to make user login and: * In the PHP SDK response, return this fb id: 884035841685689 * At the following address: < if I search with this query "me?fields=id" return this fb id: 750153425073932 * At the following address: < if I paste the user's facebook link in the textbox it will return this fb id: 100002378440884 I don't understand why with the same user account, return three different facebook id.
User IDs are "App Scoped" nowadays. * The first one is the App Scoped ID of your own App. * The second one is the App Scoped ID of the "Graph API Explorer App". Select your own App and you will get the same ID as with the PHP SDK. * The last one is actually the "real" ID. You only get that one by scraping the user profile, which is not allowed on Facebook. More information about App Scoped IDs: <
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "php, facebook, facebook graph api" }
SSRS Percentage not coming proper I am using the Pie chart and Showing the Percentage based on Group count. Most of the Time I am getting write Answer some time the total is coming 99 percent. like below example I have Pie Chart its showing 35 ,32 and 32. I am not getting the (35+32+32) 99 i need out put like 36 32 32
Unfortunately, this is usually due to rounding the numbers in the chart display. Your data is something like **35.4** , **32.4** , **32.2** but when they get rounded it seems to only add up to 99. The way I usually handle this is to display one digit past the decimal point. Not a great fix but it did stop managers from asking why it didn't add up to 100%.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "reporting services, ssrs 2008, percentage, ssrs 2008 r2, ssrs 2012" }
How to solve "ValueError: y should be a 1d array, got an array of shape (73584, 15) instead." I am new to python and machine learning. I want to fit SVM to the training sets. from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test=train_test_split(x, y, test_size=0.3) clf=SVC(kernel='rbf') clf.fit(x_train,y_train) Then I got an error: `ValueError: y should be a 1d array, got an array of shape (73584, 15) instead.` x_train.shape, x_test.shape, y_train.shape, y_test.shape Output: ((73584, 37), (31536, 37), (73584, 15), (31536, 15)) So how should I fix this problem? Would appreciate a lot if any advices. * * * Shape of `y`: ![]( Examples of label `y` are: ![](
SVM output is, for each data point, one class. Therefore, with 73584 data points of 37 features, your target needs to be a vector of 73584 classifications, each of which is a class number. Did you one-hot encode your output? You should undo that.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, machine learning" }
ASP.NET auto submits form with only one textbox <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " <html xmlns=" <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <input type="text" /> </form> </body> </html> When I hit the enter key, when the input box has focus - the form submits. If I **add another input box it doesn't submit**. How can I avoid the auto submit when there's only one input box?
Look here for the answer SO post HTH
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "asp.net" }
Null pointer exception with static hashMap public class arraylst { static HashMap<String,List<String>>hm; public static void main(String[] args) { hm.put("2",Arrays.asList("a","b","c")); } } I don't understand why this causes `NullPointerException`. Can someone please help me out?
You need to set `hm`: hm = new HashMap<String, List<String>>(); before you use it.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "java, hashmap, nullpointerexception" }
how to get new link after String Replace can you help me I want the results of the code is new url with hyperlink ( new.url, not old.url ) old.url/example.html to => new.url/example.html i have javascript code like this, <p id="crot"></p> var currentURL=location.href; var str = currentURL; var res = str.replace("old.url", "new.url"); var result = res.link(""); document.getElementById("crot").innerHTML = result;
To create a link wrap it in an anchor tag: var currentURL = location.href; var currentURL = " // for testing var str = currentURL; var result = str.replace("old.url", "new.url"); var link = "<a href='"+result+"'>"+result+"</a>"; // add link document.getElementById("crot").innerHTML = link; <p id="crot"></p>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript" }
Can AutoHotKey control display states? Would like to know if AutoHotKey can control: 1. Display On/Screen On 2. Display Off/Screen to black Found this online which was suggested to be able to turn a screen on but it doesn't seem to work: `PostMessage, 0x0112, 0xF170, % -1,, A`. How can I figure out which parameters to post?
> I think it just needs some benign keyboard/mouse input to turn the screen on. No, that is possible using a command, please take a look: How can I wake-up a PC using a command? (i.e. equivalent to moving a mouse, etc) When you move a mouse or push a key, you trigger a hardware interrupt that will be sent to the operating system. And exactly this message can you simulate by sending a keystroke like SendKeys.
stackexchange-superuser
{ "answer_score": 1, "question_score": -1, "tags": "windows, windows 10, autohotkey" }
Validating a complex object in Flask def validateWord(classObject): if (hasattr('classObject', 'students') and 0 < len(classObject["students"])): studentObject = classObject["students"][0] else: return False if ("id" in classObject and "name" in classObject and "id" in studentObject and "fName" in studentObject and "lName" in studentObject): return True else: return False I have an object class and it has an object named students inside of it. There's a one-to-many relationship between the two object and I need to validate that complex object whenever the user make a POST request. The issue is that I have a complex object and the validation I wrote would only work if I only have 1 student per class. How do you write a validation function that checks every student instead of just checking the first? I am using Flask. Is there a better way to do this?
If you want to check `"id" in studentObject and "fName" in studentObject and "lName" in studentObject` for all students, you can use the `all()` function. For instance: def validateWord(classObject): if "students" in classObject: students = classObject["students"] return ( "id" in classObject and "name" in classObject and all("id" in student and "fName" in student and "lName" in student for student in students) ) else: return False Note: I think you need to write `hasattr(classObject, "students")` instead of `hasattr("classObject", "students")` or may be it is `"students" in classObject`.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, flask" }
C# Outlook 2013 Addin Accessing Explorer Is it possible to access Explorer to check for the existence of certain folders, and create folders if necessary from an outlook addin? If so what API/interface is used to do so from outlook. The MAPIFolder seems to be just for the outlook folders. Thanks in advance EDIT: To clarify, I'm talking about OS folder that are not part of outlook. The particular folders I'm speaking of are actually on a file server in the domain. Which is mapped to the users computer who would be using the addin. Will the fact the he is a domain user and already authenticated mean I wont run into any issue when trying to access the filesystem from the addin?
You need to use System.IO.* class for checking whether a folder exists or not. For example, the Exists.aspx) method of the Directory or File classes from the System.IO namespace determines whether the given path refers to an existing directory/file on disk: if(File.Exists(path)) { // This path is a file ProcessFile(path); } else if(Directory.Exists(path)) { // This path is a directory ProcessDirectory(path); } else { Console.WriteLine("{0} is not a valid file or directory.", path); }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, vsto, outlook addin, explorer" }
When I use php to get the value of a select list using the post method sometimes the value doesn't fully show up When I use the post method and php to process a simple form, I try to echo the select list option and it doesn't all show up for instance one of my options is video card $200 and when it echos on card $200 shows up on the page. Here is the select list: <select name="hardware"> <option>&nbsp;</option> <option>Monitor $100</option> <option>Mother Board $250</option> <option>Video Card $200</option> <option>Keyboard $300</option> </select> and here is the php code <?php $parts=$_POST['hardware']; $partsQuantity=$_POST['hquantity']; $software=$_POST['software']; $softwareQuantity=$_POST['squantity']; echo "".$parts." ".$partsQuantity."<br>".$software." ".$softwareQuantity."<br>"; ?> when I choose video card $200 and echo it only card $200 shows up
When the form is submitted, the value of $_POST['hardware'] will be the value of the option you selected in the hardware select, not a list of the values of all of the different options contained in the select. Also, your option tags are all missing the value attribute.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "php, post, echo" }
What should be datatype of mysql table column, for storing notes I am working on a web application which stores notes created by users. I am confused between whether to store notes as separate files on filesystem, or use database column for saving the text. If mysql is better solution then what datatype should I use(content can be simple text or html)?
If you need speed, you can use MySQL. You need to use either `BLOB` or if it is just text, use `TEXT` as the datatype. Use a good DB engine (MySQL, SQLite, etc). Then, for maximum performance, use memcached to cache content. ### Keep in mind a couple things: 1. MySQL has a query cache. If you are issuing the same queries repeatedly, you can gain a lot of performance without adding a caching layer. 2. MySQL is really fast anyway. Have you load-tested to demonstrate it is not fast enough? Another thing is, it is hard to search on flat files. If you use MySQL, not only it is faster, but also it is easier for you to search.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mysql, file io, blob" }
How to get last N records with activerecord? With `:limit` in query, I will get first N records. What is the easiest way to get last N records?
## Updated Answer (2020) You can get last N records simply by using last method: `Record.last(N)` Example: `User.last(5)` Returns 5 users in descending order by their id. ## Deprecated (Old Answer) An active record query like this I think would get you what you want ('Something' is the model name): Something.find(:all, :order => "id desc", :limit => 5).reverse **edit** : As noted in the comments, another way: result = Something.find(:all, :order => "id desc", :limit => 5) while !result.empty? puts result.pop end
stackexchange-stackoverflow
{ "answer_score": 178, "question_score": 191, "tags": "ruby on rails, ruby, activerecord" }
Most Efficient Way To Get Objects In A Rectagular Area - Unity2D _First of all, if you know a better way to do what I want to achieve please don't hesitate to suggest your own method._ What I want to do is the classic area selection in RTS games, which player drags his mouse to draw a rectangle and units inside rectangle become selected. At this point, I have two ideas: 1. A dedicated gameObject with a trigger BoxCollider2D. 2. Detecting overlaps with Physics2D.OverlapArea method. In the first method, the gameObject will get resized on the fly while the user drags and by using collision control the objects get selected. In the second method starting point and end point of the area is being recorded and script draws an OverlapArea using these two coordinates. Which one would be more effective in terms of performance? Thanks in advance.
I would definitely go with the second method. In this manner, you don't have to have anything firing in your physics engine, or have to deal with disabling/enabling colliders when you are not using them. The second method also has the added benefit of having Point1 and Point2 parameters, which coincide with your drag/draw selection interface. You are going to start dragging at Point1 and release at Point2. Using the second method for this mechanic is the way to go.
stackexchange-gamedev
{ "answer_score": 4, "question_score": 4, "tags": "2d, unity" }
Is Wolfram wrong about unique 3-colorability, or am I just confused? The illustration on Wolfram's page claims to present a uniquely colorable, triangle-free graph. However, this seems to be blatantly false: the graph has a symmetry with respect to a reflection through the horizontal axis, and we can use this symmetry to construct a new colouring not isomorphic to the original one. Am I missing something obvious here, or is the illustration simply wrong? If it's the latter, what is a simple example of a triangle-free, uniquely 3-colourable graph? !enter image description here
Yes, Wolfram is wrong in this case. I just checked the archives of the Journal of Combinatorial Theory (where the erratum to the paper in question is published) and the two top vertices are supposed to be connected by an edge. I cannot provide a link because it requires a login, and I was able to log in through my university's subscription to the journal. !Graph with added line
stackexchange-math
{ "answer_score": 45, "question_score": 34, "tags": "graph theory, coloring" }
jquery hover remains hovered when cursor is moved away via mouse-wheel scrolling I'm not sure if this is a limitation of the jquery function or a bug on my code, but i can see the same behavior happening on the example at < My implementation is that i have a pop up box that shows when the mouse is hovered over a product item, and the hidden when the mouse hovers out. The issue is when the mouse is hovered and the pop up box shows, if I scroll down/up the page with the mousewheel/trackpad, while the mouse cursor is not on the product item anymore due to the scrolling, the hover-out behavior is not detected, and the pop up box remains in sight, remaining in the middle of the screen since its position is determined during the hover event, relative to the product's position on the screen. Does this make sense ? Can anyone help ?
This is a somewhat intrusive solution, but it should work: // The normal hover handler $("#productElement").hover(function(){ $("#otherElement").show(); },function(){ $("#otherElement").hide(); }); // A global scroll handler that hides an specific // element whenever the user scrolls. $(document).scroll(function(){ $("#otherElement").hide(); }); In the above code, `#productElement` would be the label that the user hovers to, and `#otherElement` would be the dialog that pops up on hover. That is just the basics of how it would work; you would adapt it to your code.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "jquery, hover, mouseover" }
How to tag specific input files from different directories I am reading two set of directories (let's say dirA and dirt) as inputs to my MapReduce jobs and I need to tag them differently in some way so that during map phase I know which is from which. Any advice?
You could investigate using MultipleInputs and define a different mapper for each input path, or examine the input split (Context.getInputSplit() \- cast it to a FileSplit and get the path) and adjust the output accordingly.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "hadoop, mapreduce" }
Logging on gcloud node.js I'm experimenting with node.js and managed servers. So far so good. I just can't figure out how to log to the console on my development server. I'm talking about the console I see in the terminal after running gcloud preview app run . (not the browser console). console.log() doesn't appear to do anything at all.
Try using this command: gcloud preview app --verbosity debug run .
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "node.js, gcloud node" }
How can I call a function defined in an Angular component in a JavaScript file? In a `.ts` file, I have the following code export class SomeClass { . . . public someMethod() { ... } } I want to call this `someMethod` method in a `.js` file. I tried import { SomeClass } from '../../../../SomeClass'; . . . SomeClass.someMethod(); but got the following error: `someMethod is not a function` Do I have to make the method `static`? I prefer not because it calls other methods and I will have to make all of them `static`. Can I create an instance of this class in the `.js` file? Thanks!
there are two solutions either create instance of the class first then use public method like let class = new SomeClass(); class.someMethod(); or make it static Method then your code will compile successfully
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, angular, frontend" }
Do I need to consider the Client OS when testing websites? I have a general web question. **To be able to test my website on various browsers properly, do I need to consider the operating system too?** Is it enough to just test my site on FireFox 3, for example, or do I need to test it on FireFox 3 on Windows, Mac, and Linux? Is it possible for a given browser version to behave differently on different platforms?
I'd say yes, well platform at least. Some other differences between Mac OS X and Windows (don't forget Linux) * different gamma levels * font rendering * fonts installed by default * size of the chrome I realise testing on all OS's can be difficult, so make use of BrowserShots.org.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 4, "tags": "testing" }
noexcept for different operations with template type inside function I want to write a template function foo, that do some operations on type T, and inside this function values of type T can be: * copied * assigned * summed with operator+ So, I need to specify noexcept for this function with restrictions I've mentioned above. Here is my code, but it isn't work properly: template<class T> void foo() noexcept(noexcept(std::declval<T>() + std::declval<T>()) && std::is_copy_constructible<T>::value && std::is_assignable<T, T>::value) {} bool b1 = noexcept(foo<int>()); // false, but should return true bool b2 = noexcept(foo<std::string>()); // false What should I do, to make it work right?
`noexcept(foo<int>());` is false because `std::is_assignable<int, int>::value` is false, e.g. you cannot write `1 = 1`. What you might have wanted to do is to use `std::is_assignable<T&, T>` instead.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "c++, c++11, stl, noexcept" }
Does "Disk Operating System" imply that there was a "non-disk" Operating System? In the 1980's at primary school we saw MS-DOS and DR DOS competing before Windows 3.1 and subsequent releases took over that space. At home we had Apple II's which booted up to a BASIC prompt. On these we ran ProDOS and CP/M. 30 years later my kids hardly know what a disk is. That made me think "Why was it called a 'disk' operating system? Was it to contrast it with a 'ROM' based operating system? (You never really heard of a 'ROS'). My question is: **Does "Disk Operating System" imply that there was a "non-disk" Operating System?**
The term "Disk Operating System", or commonly "DOS", was used in the early days of personal computing to distinguish operating systems that also contained software for supporting disk devices, since not all of them did. The DOS software could access blocks stored on disk, that were organized into files, and there was "filesystem" software included for managing the collection of files on the disk. The term does not imply that the DOS software itself **had to be loaded from disk**. Several popular systems included the DOS software in ROM in the microcomputer, or even in the disk drive itself, as was the case with Commodore disk drives and CBM DOS. Other DOS software, like ProDOS and MS-DOS, did load from disk. So, yes, operating systems lacking software support for disk devices would be called simply "OS" and not "DOS".
stackexchange-retrocomputing
{ "answer_score": 104, "question_score": 102, "tags": "operating system, terminology" }
How to create an array from an Excel with several sheets in Python I have an Excel with 18 sheets, and each one has more or less 20 columns with exactly 100 data each one (2000 data approx). I would like to create an array with 18 items (1 per sheet), and each item with the 2000 data one after the other, I mean, to join a column ending element followed by the first of the next column. Thank you!
From parse-excel-github: * * * import xlrd book = xlrd.open_workbook("myfile.xls") print("The number of worksheets is {0}".format(book.nsheets)) print("Worksheet name(s): {0}".format(book.sheet_names())) sh = book.sheet_by_index(0) print("{0} {1} {2}".format(sh.name, sh.nrows, sh.ncols)) print("Cell D30 is {0}".format(sh.cell_value(rowx=29, colx=3))) for rx in range(sh.nrows): print(sh.row(rx))z * * * && related-thread: good luck!
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "python, excel" }
Get numbers from url as string in php using get method I have a URL structure as **example.com/tag/abcd** I have tag.php where I have used: $e=$_GET['t']; $e=str_replace("-", " ", $e); But whenever there is a number in place of abcd it produces 500 error. Moreover, if there is **abcd-12** then I am getting only 'abcd' through GET method. 500 Error is produced when URL is like **example.com/tag/123** Here is htaccess code RewriteRule ^tag/([a-zA-Z-]+) tag.php?t=$1 [NC,L]
I am not really sure of what you are trying to do but this should do the trick : $e=strval($_GET['t']); $e=str_replace("-", " ", $e); **Edit :** Okay, you added your rewrite rule, now the problem is clear : [a-zA-Z-] This matches only characters and -, not numbers. Try [a-zA-Z0-9-] I recommend you this site to visualize your regex : <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php" }
What's the preferred way of writing units per unit? Why do we write units such as meters _per_ second as $\mathrm{m\,s} ^{-1}$ instead of $\mathrm{m/s} $. Is the latter still a valid way of expressing units? Why are there two different ways of expressing the same unit of measurement?
It seems to come down to personal preference more than anything else. The exponent notation could be argued to be slightly clearer in a purely linear setting like browser text, since it eliminates any potential ambiguity over whether you're using the forward slash as a division sign or a separator.($\mathrm{m\,s} ^{-1}$ is more useful as units get more complex as it removes any ambiguity around the 'division') Both are still used because they are perfectly correct. According to the rule of indices (exponents), $\mathrm{m\,s} ^{-1}$ and $\mathrm{m/s} $ are the same mathematically.
stackexchange-physics
{ "answer_score": 4, "question_score": 0, "tags": "conventions, units, si units" }
How can I use Macros in Delphi? How can I use Macros in Delphi? This feature is available in `FPC` for quite some time now. Could it be done with pre or post build events? Example: {$define sum:=a:=a+b;}
You cannot use macros in Delphi. No such functionality exists. The closest built in functionality would be an `inline` function. * * * You could certainly write your own pre-processor that expands macros. However, you won't be able to make that integrate well with the IDE. At least, not in a way that I would consider acceptable. The problem is where to expand the macro to. You can hardly expand it to the original file, because you cannot realistically modify that. So you'd need to expand to a temporary file. And the compiler doesn't have any mechanism to build from a temporary files. I suppose you might expand to an include file. That may be the best option but it's going to be horrible to work with. For instance, consider the fun when debugging.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "delphi, delphi xe6" }
How to Format the DateTime of Scanned Files List? I scan a directory for png files and put their modified dates in a List. But how can I format the `DateTime`? I would like to keep `Date` and remove `Time`. * * * List<DateTime> MyFileDates = Directory.GetFiles("C:\\Images\\", "*.png") .Select(File.GetLastWriteTime) .ToList(); * * * I tried using `.ToString("dd/MM/yy")` but it gives error `No overload for method 'ToString' takes 1 arguments.` List<DateTime> MyFilesDates = Directory.GetFiles("C:\\Images\\", "*.png") .Select(File.GetLastWriteTime) .ToString("dd/MM/yy") .ToList();
There's two ways of achieving this. One is to convert `List<DateTime>` to `List<string>` with strings formatted to `dd/MM/yy` List<string> MyFilesDates = Directory.GetFiles("C:\\Images\\", "*.png") .Select(p => File.GetLastWriteTime(p) .ToString("dd/MM/yy")) .ToList(); Other way is to remove time component (set it to 00:00:00): List<DateTime> MyFilesDates = Directory.GetFiles("C:\\Images\\", "*.png") .Select(p => File.GetLastWriteTime(p)) .Select(p => new DateTime(p.Year, p.Month, p.Day)) .ToList();
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "c#" }
Finding the value of a for which the plane and a line are parallel I need to find the value of a for which the line r which is passing through the point Q=(0, 0, 0) and P=(a, 1, 2) is parallel to the plane with equation $$ \alpha: a(x+y)-z=0 $$ So, I know from where I could start but I get stuck. First, I find the parametric equation of r, knowing that it's passing through Q and P I get a directional vector: $$ OP = (a, 1, 2) $$ Using Q as a starting system, I find its equation $$ r: \begin{cases} x=at \\\y=t \\\z=2t \end{cases}$$ To see if the plane and the line are parallel, I'd do the cross poduct between two directional vectors and see if it's 0. However, I don't know how I should do it considering I have a real parameter in both the equation of the line and the plane.
The easiest way here is to determine $a$ such that the line directional vector and the plane normal vector are perpendicular. For this, their dot product needs to be zero, i.e. $$(a,1,2) \cdot (a,a,-1) = 0$$ (The coordinates of the plane normal vector are the coefficients next to $x$, $y$ and $z$ respectively in the implicit equation of the plane.)
stackexchange-math
{ "answer_score": 0, "question_score": 1, "tags": "linear algebra, 3d" }
Does Oracle Nosql Cloud Service have provision to set max read units consumption per second? Does Oracle Nosql Cloud Service have provision to set max read units consumption per second. For e.g. In 40K read units, I want to reserve 20K for 1st operation and rest 20K for 2nd operation. In order to make sure 20K is always reserved for 1st operation, I want to set max read units consumption per second for 2nd operation. Is this something possible to do?
The provision values are for the entire table, so if a table has 40K read units /second, it’s up to the application to apportion them per operation.The SDKs have rate limiting support that can help with this. For example, see < > Sets a default percentage of table limits to use. This may be useful for cases where a client should only use a portion of full table limits. This only applies if rate limiting is enabled using setRateLimitingEnabled(boolean). You could use this method in your case.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "oracle nosql" }
Proving combinator identity KMN=M Have a problem proving **K** MN=M 1. By the **K** combinator definition $ (\lambda x y.x) M N $ 2. Parenthesized $ ((\lambda x. (\lambda y.x)) M) N $ 3. By the principal axiom of lambda calculus $ (\lambda y.M) N $ 4. Second application of the principal axiom $ M[y:= N] $ ? This would give correct result if M is y-free. Apparently there is an error at one of the steps.
When you reduce $(\lambda x.\lambda y.x)M$, the result is $(\lambda y.x)[x:= M]$. This substitution is only defined if$y$ is not free in $M$. Otherwise the $\lambda y$ will need to be $\alpha$-renamed before you can proceed. Some texts define the substitution function to do this $\alpha$-renaming implicitly, others consider the result of the substitution to be undefined if the variable capture condition is not met.
stackexchange-math
{ "answer_score": 3, "question_score": 0, "tags": "lambda calculus" }
How do I get the knee to bend the other direction? ![enter image description here]( I've set the pole target as child bone to the IK bone attached to the yellow bone which solved some problems. The knee now constantly bends in the exact opposite direction. ![enter image description here]( ![enter image description here]( * * * ![enter image description here]( ![enter image description here]( It rotates the foot. It something with rotation. In a video, I heard something about redirecting all axes, but couldn't find where because the given shortcut didn't work.
**EDIT:** After inspecting the file you provided, the issue is that the leg bones actually bend backwards at the knee very slightly. In this case, Blender will never make the point point the direction you want. If you pull the knee joint forward a bit, or even just make the leg bones perfectly in line the IK will work as expected. In the IK constraint options, right by where you selected the pole target, there is a _Pole Angle_ option that will change the angle of the bend in relation to the target. Since yours is simply backwards, setting it to 180 degrees should do the trick.
stackexchange-blender
{ "answer_score": 3, "question_score": 0, "tags": "pose mode" }
Writting and reading a custom variable to a file in Ocaml I'm trying to write and then read a variable to a file. The variable is from a data type created by me. ( _If helps:_ > type sys = File of string * string list | Folder of string * sys list ;; ) How can I do this? I've been reading about the use of fprintf, but for what I get it'd had to be converted somehow into a String first, right?
If you are sure your type will not change, you can use `input_value` and `output_value` from Pervasives. let write_sys sys file = let oc = open_out file in output_value oc sys; close_out oc let read_sys file = let ic = open_in file in let sys : sys = input_value ic in close_in ic; sys `read_sys` will break whenever you will try to read value stored with an other version of `sys` (or if you change your version of OCaml between writing and reading). If you want safety, you can use automatic serializer such as sexplib (if you want to be able to read the file you are creating) or biniou for efficient conversion.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 6, "tags": "ocaml" }
Can you disable blessings like Daruk's Protection? Are you able to disable blessings like Daruk's Protection? I keep wasting it on weaker enemies while I'm on my way to the enemies that I want to actually use it on.
Yes, you can disable any of the blessings by: 1. Opening your "Key Items" menu 2. Select the blessing ("A" on Wii U) 3. Select "Disable" You can enable the blessing again in the same menu. ![Disabling Blessings](
stackexchange-gaming
{ "answer_score": 19, "question_score": 15, "tags": "zelda breath of the wild" }
Greatest common divisor of consecutive square free numbers I guess that every prime number occurs as the greatest common divisor of two consecutive square free numbers, which I don't expect a proof of. But I've done some experiments indicating that: > If $m, n$ are consecutive square free numbers then $\gcd(m, n)$ is not composite. Is that true and can it be proved?
Barring miscalculation we have $$\gcd(28331962460555993122305,28331962460555993122290)=15$$ And these two numbers are consecutive square free integers. Indeed we can obtain the relevant factorings via WA. This example was constructed out of the Chinese Remainder Theorem, using $$\text {ChineseRemainder}[(0,1,2,3,4,5,6,7,8,10,11,14),$$$$(15,4,7^2,9,11^2,25,13^2,17^2,19^2,23^2,29^2,31^2)]$$ in WA
stackexchange-math
{ "answer_score": 15, "question_score": 6, "tags": "number theory, elementary number theory, prime numbers, gcd and lcm, conjectures" }
SQL left / right JOIN issue I'm trying to run script below, but always getting NULL values for name field. SELECT u.name AS _user_name, s.name AS _school_name FROM fwg_files AS f LEFT JOIN users AS u ON u.id = f.user_id LEFT JOIN user_profiles AS up ON up.user_id = u.id LEFT JOIN school AS s ON s.id = up.profile_value The problem seems to me in JOIN ON school table, I tried to SELECT s.id and it returns NULL values also. When I change last line to RIGHT JOIN it starts to work, but I can see just the s.name value, the others are NULL Table fwg_files id | user_id 240 | 414 241 | 436 Table users id | name 414 | Name 1 436 | Name 2 Table user_profiles user_id | profile_value 414 | "6" 436 | "14" Table school id | name 6 | School 1 14 | School 2 Thank you
If the quotations on the `profile_value` column is a must then need to use a mix of `CONVERT` and `SUBSTRING_INDEX` to get rid of the quotations in order to be able to do the operation. Check the following code: SELECT users.name as User, s.name as School FROM fwg_files AS ff LEFT JOIN users ON users.id = ff.user_id LEFT JOIN user_profiles AS up ON up.user_id = users.id LEFT JOIN school AS s ON s.id = CONVERT(SUBSTRING_INDEX(up.profile_value,'"',-2),UNSIGNED INTEGER); And here the working SQL Fiddle code with quotations.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "mysql, sql" }
Ruby: return a copy of array with [key, value] array from hash In Python there is dict.inspect() method that returns a list of tuples (link). Is there a similar method in ruby to achieve, well, an array of arrays? #input {:a => 1, :b => 2} #result [[:a, 1], [:b, 2]]
Calling `to_a` on the hash will do that. {:a => 1, :b => 2}.to_a #=> [[:b, 2], [:a, 1]] As you can see in the example output, the order is not necessarily preserved (at least not in ruby 1.8, in ruby 1.9 the order is preserved).
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "ruby" }