INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
setting default python version in ubuntu Platform: Ubuntu 12.10 Python version installed: 2.7.3 (with ubuntu installation) output of command (`which python`): `usr/bin/python` recently i installed python2.6.6 (as some applications don't work on 2.7.3 version) output of command (`which python2.6`): `usr/local/bin/python2.6` by default command 'python' runs default version i.e 2.7.3 My requirement is to set python2.6.6 version to be the default one. Thanks
In Ubuntu I would shy away from just changing the sym-links. Looks like the new way of doing this is `update-alternatives`, or `python-virtualenv` if you want to go that route. Check the responses here: how-do-i-make-the-terminal-run-python-3-1
stackexchange-superuser
{ "answer_score": 0, "question_score": 0, "tags": "python, ubuntu" }
Run an application in background As far as I know, it's impossible to run a custom application on Heroku and AppHarbor. I emailed them but there is no answer yet. What I want is run a Linux application (a web app also uses Linux) I made myself in background. Let's say it puts a text-copyright on every uploaded image. Isn't it possible to run such an application? And if not, why not?
AppHarbor has background workers and Heroku has worker dynos.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "linux, heroku, appharbor" }
F# syntax of comma within lambda expression I'm new to F#. Can someone explain what the following lambda expression is saying? Specifically, what the comma after the `Some c.Id` is doing and what all the parenthesis are about? (fun ((b, p), c) -> (b && p.SelectedInnerRow = Some c.Id, c)) I'm a bit confused coming from C#. Thanks.
The parentheses are for deconstruction of tuples. The lambda expression takes a tuple of (a tuple and some value) and some other value; and it returns yet another tuple. Now for the types involved - as the argument named `b` is operand to the boolean operator `&&`, it must be of type `bool`. The argument `p` has to have a property named `SelectedInnerRow`, which in turn ought to produce an option. This option is equality-compared to another option value of argument `c`'s property `Id`, so the whole expression will return a tuple of a bool and the unchanged argument `c`.) (* Dummy types to make it work *) type Foo = { SelectedInnerRow : int option } type Bar = { Id : int } (fun ((b, p), c) -> (b && p.SelectedInnerRow = Some c.Id, c)) (* val it : _arg1:(bool * Foo) * c:Bar -> bool * Bar *)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "lambda, syntax, f#" }
「ずいぶん」と「ずいぶんと」の違い > ****
**** > **** >
stackexchange-japanese
{ "answer_score": 6, "question_score": 3, "tags": "adjectives, adverbs" }
What is the term for a compulsive liar? If a kleptomaniac is compulsive thief, which term is used for a compulsive liar? I have searched extensively but to no avail. Is there an equivalent?
The closest I could think of is mythomaniac. The definition of **mythomania**: > An excessive or abnormal propensity for lying and exaggerating
stackexchange-ell
{ "answer_score": 4, "question_score": 3, "tags": "word request" }
How to convert string to json in c#? I have following string in c#, "2015-9-9,2015-9-10,2015-9-11,2015-9-12,2015-9-13,2015-9-14" now I want to convert that in a javascript variable like following json format.I want to send to server side to client side in one variable and required to use in javascript varialbe. var avadates = ["2015-9-9", "2015-9-10", "2015-9-11", "2015-9-12", "2015-9-13", "2015-9-14"]; so,How to convert in Json from C# or any otherways to do that?
This gets every date, add then convert it to string adding the 0 to the month, then merge all the dates: string toJsonify = "2015-9-9,2015-9-10,2015-9-11,2015-9-12,2015-9-13,2015-9-14"; var dates = toJsonify.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries) .Select(s => DateTime.ParseExact(s, "yyyy-M-d", System.Globalization.CultureInfo.InvariantCulture) .ToString("yyyy-MM-dd")); var res = "[\"" + string.Join("\",\"", dates) + "\"]";
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, json, c# 4.0" }
Direct login on facebook from android app? I want to realize a simple login in on facebook. I have a button "Facebook connect" and when I press this button I want to open the facebook login page, and after introducing the email and password to sign in on facebook. I have seen the examples from < but I can't realize how should I do this. Please help.
Take a look at this tutorial here, it will show you how to set it all up and is easy to follow. Hope this helps.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android, facebook, authentication" }
Referencing elements from two-dimensional array with a single value I am probably missing something fundamental, but i cannot find a solution to the following issue. I have a two-dimensional array of some float elements and i am trying to find a way to be able to reference them by using only a single value. Example: float test[5][50]; test[3][25] = 34.67; cout << test[3][25] << endl; int id = 25; cout << *test[id*5+3] << endl; I am hoping to get same result from both cout. Instead my output looks like this: 34.67 Segmentation fault What am I doing wrong? Thanks!
Without testing, I think something like this might work. Note that C++ arrays are major->minor from left dimension to right dimension. float test[5][50]; test[3][25] = 34.67; cout << test[3][25] << endl; int id = 25; float* test2 = &test[0][0] cout << test2[(3 * 50) + id] << endl;
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 4, "tags": "c++" }
How can you disable qualcomm atheros in ubuntu 13.10 plazma kde desktop? Help me quick for my job!! I have two Internet connections!!
If you wish to disable a networking interface, you can temporarily remove its driver. Find out from the terminal: sudo lshw -C network Your device will show a driver such as ath9k or alx or ath5k or some such at the line including 'driver=.' Simply unload the driver: sudo modprobe -r <some_driver> Of course, substitute the driver you actually found. If you want it to be permanent, blacklist the driver: sudo -i echo "blacklist <some_driver>" >> /etc/modprobe.d/blacklist.conf exit
stackexchange-askubuntu
{ "answer_score": 1, "question_score": 0, "tags": "13.10, internet" }
Control explorer window programmatically I want to be able to change the directory of an existing explorer window. Is there an api call to send a "navigate there" message to a window (perhaps with a handle to it)?
First, add a reference to the Microsoft Internet Control library. Then you can use the following code, assuming you already know the window handle for your explorer window: var shellWindows = new SHDocVw.ShellWindows(); var myFolder = "C:\\temp"; // folder name you want to navigate to var myHwnd = 0; // whatever window handle you're looking for foreach (SHDocVw.InternetExplorer shellWindow in shellWindows) { if (shellWindow.HWND == myHwnd) { shellWindow.Navigate(myFolder); break; } }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "c#, windows 7, explorer" }
how to run a powershell script as administrator On my Windows 7 Desktop, I have script.ps1, which needs admin privileges (it starts a service). I want to click on this script and run it with admin privileges. What's the easiest way to accomplish this?
Here is one way of doing it, with the help of an additional icon on your desktop. I guess you could move the script someone else if you wanted to only have a single icon on your desktop. 1. Create a shortcut to your Powershell script on your desktop 2. Right-click the shortcut and click **Properties** 3. Click the **Shortcut** tab 4. Click **Advanced** 5. Select **Run as Administrator** You can now run the script elevated by simple double-clicking the new shortcut on your desktop.
stackexchange-superuser
{ "answer_score": 85, "question_score": 101, "tags": "windows 7, powershell" }
Convert xmlstring into XmlNode i have one xml string like this string stxml="<Status>Success</Status>"; I also creaated one xml document XmlDocument doc = new XmlDocument(); XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null); doc.AppendChild(docNode); XmlNode rootNode = doc.CreateElement("StatusList"); doc.AppendChild(rootNode); i need an output like this. <StatusList> <Status>Success</Status> </StatusList> How can i achieve this.if we using innerhtml,it will insert.But i want to insert xml string as a xmlnode itself
A very simple way to achieve what you are after is to use the often overlooked XmlDocumentFragment class: XmlDocument doc = new XmlDocument(); XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null); doc.AppendChild(docNode); XmlNode rootNode = doc.CreateElement("StatusList"); doc.AppendChild(rootNode); //Create a document fragment and load the xml into it XmlDocumentFragment fragment = doc.CreateDocumentFragment(); fragment.InnerXml = stxml; rootNode.AppendChild(fragment);
stackexchange-stackoverflow
{ "answer_score": 18, "question_score": 7, "tags": "c#, .net, xml" }
Should I follow the class or instructor's breathing rate during Tai Chi breathing exercises? I'm new to this forum, and new to Tai chi (and martial arts in general). I started last week and have had 2 classes so far, having my third one today. I would like some advice on how to breathe properly during the class breathing exercises, since the way I am currently doing it makes my vision go black and causes nausea, even though I don't feel 'out of breath'. Should I match the Sifu's breathing pace, which is really slow, or is that too slow for a beginner? Are there particular things I should pay attention to during these exercises? Is there a way I can work on this at home? _In case it is important, I am not in a great physical state (sedentary job, no sports, but I do walk everywhere), and we do these breathing exercises after the stretching and holding poses (forms?) part of the class, so at the beginning of these exercises I'm usually somewhat tired already_
You should not try to match your instructor's breathing rate. This would be like trying to lift the same weight as your weightlifting instructor; it does not make sense to do this because your instructor's body is different from yours. The general advice for basic breathing exercises is to make your breathing relaxed, continuous, deep, and even. Pay attention to these elements and don't worry about your breathing rate. Over sustained practice, you will find your breathing rate will slow, but this is more a side effect than something you should force. Taiji is not an art of heavy exertion. You should not be trying to brute force things, and this includes breathing. You do want to gently push your boundaries, but what is a gentle push for your instructor or senior class members may be far beyond your current boundaries. In any martial art, you should practice at home. You should also see your teacher regularly to ask questions and so they can monitor your progress.
stackexchange-martialarts
{ "answer_score": 5, "question_score": 5, "tags": "tai chi, breathing" }
How uninstall SAP Afaria from Android device? I am testing the SAP Afaria in my tablet and I am no longer want use. I try uninstall the app but its locked for uninstall. In the administrator page from SAP, I didn't find how remove the enrollment.
Goto Settings>Location and Security>Device administrators Remove the check mark from Afaria, and select Deactivate, then remove the application
stackexchange-android
{ "answer_score": 2, "question_score": 1, "tags": "settings, device administrator" }
Should we "censor" bad-quality/insulting questions by editing them? I just saw this post demanding our help, telling that the OP doesn't care if this is a duplicate and instead of insulting him/her, he/she will do it first. First, I thought about editing the question by removing all this "intro". I didn't, but someone else did. Should we edit (censor), downvote, or flag such questions?
Considering I edited it: yes, I think we have to. It is very likely that the question will get buried in down- and closevotes and will be stuffed away in a little corner. It is also likely that the asker will not return to the question to try and make something constructive out of it. None of this should stop us from simply removing the rant and carrying on with our day: it's very little effort and nobody that follows you has to waste time reading that stuff. If you feel it is offensive: flag it. If you just think it's a poor question: downvote it. If you think it is not suitable here: closevote it.
stackexchange-meta
{ "answer_score": 11, "question_score": 8, "tags": "discussion" }
Why doesn't this method of solution work? > Solve > > $$\sqrt{2x^2 - 7x + 1} - \sqrt{2x^2 - 9x + 4} = 1 \tag1$$ I tried to do the following: $$(2x^2 - 7x + 1) - (2x^2 - 9x + 4) = 2x-3\tag2$$ Dividing $(2)$ by $(1)$ yields $$\sqrt{2x^2 - 7x + 1} + \sqrt{2x^2 - 9x + 4} = 2x-3 \tag3$$ Now, adding $(1)$ and $(3)$ $$2\sqrt{2x^2 - 7x + 1} = 2x-4$$ $$\implies \sqrt{2x^2 - 7x + 1} = x-2$$ Squaring both sides and simplifying, yields $$x^2 - 3x - 3 = 0$$ Solving this quadratic yields an irrational solution. But the solution given in my textbook are $0, 5$ which do work in $(1)$. Where did I go wrong?
When you add (1) and (3), the right side should be $2x-2$. Then it simplifies to $x^2 - 5x = 0$ which has the solutions 0 and 5.
stackexchange-math
{ "answer_score": 2, "question_score": 3, "tags": "algebra precalculus, radicals, quadratics" }
SQL query for cross column unique values in single table I have a table with two columns and data as follows - +---------+---------+ | Column1 | Column2 | +---------+---------+ | A | B | +---------+---------+ | C | D | +---------+---------+ | B | A | +---------+---------+ | E | F | +---------+---------+ | F | E | +---------+---------+ My query output should return the following data - +---------+---------+ | Column1 | Column2 | +---------+---------+ | A | B | +---------+---------+ | C | D | +---------+---------+ | E | F | +---------+---------+ If we have two rows `row1` and `row2` where `row1.column1=row2.column2` and `row1.column2=row2.column1`, the output should contain either of the two rows `row1` or `row2`. Can you please help me with this.
I think you want: select col1, col2 from t where col1 < col2 union all select col1, col2 from t where col1 > col2 and not exists (select 1 from t t2 where t2.col1 = t.col2 and t2.col2 = t.col1); You might also want: select distinct least(col1, col2) as col1, greatest(col1, col2) as col2 from t; Note that in some cases, this could return pairs are not in the same order in the original data.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "mysql, sql, oracle11g" }
Why is some part of a DVD (video) unskippable and how can it be bypassed? I have found 3 states of a DVD player: * Able to jump to disc menu, able to skip chapter * Unable to jump to disc menu, but still able to skip chapter * Unable to both jump to disc menu and skip chapter Why does my DVD-player/program enforce this? How can it be bypassed?
The DVD licensing authority tries to require that players enforce this, based on flags encoded into the DVD. The way round it is to get an unlicensed player that doesn't; VLC on a computer, or if you want a physical DVD player to connect to your TV then generally the cheap unbranded ones are less likely to enforce the restrictions (including region locking).
stackexchange-superuser
{ "answer_score": 3, "question_score": 4, "tags": "dvd" }
Dinner service out of Los Angeles on Amtrak Southwest Chief Is dinner served in the dining car of the Southwest Chief after it leaves Los Angeles going eastbound at 6:15 pm? I'm asking because usually dinner service starts earlier on Amtrak trains.
A quick Google search finds numerous reports of dinner being served after leaving LA. < : > Hakto told us that our dinner reservation was for 7:45 pm, so we settled into our room. < : > Out of LA we rolled right on time to watch the darkening skies of twilight, and we were enjoying dinner somewhere before San Bernardino. Specials were Chicken Enchiladas, Stuffed Shells, and Trout. < : > Where I Dined: Tuesday dinner through Thursday breakfast Amtrak Southwest Chief Diner (meals included in accommodation price): Tuesday Dinner: 8 pm Trout w/vegetables, roll, salad, and dessert. A 1/2 bottle of Pinot Gris ($13). : > The daily Southwest Chief leaves at 6:55PM [...] Since I wanted to feel a bit like James Bond in Casino Royale (minus the incredibly attractive Eva Green/Vesper Lund), I decided to splurge at the Dining Car, which features classic American dishes in a sensibly appointed rail car.
stackexchange-travel
{ "answer_score": 6, "question_score": 8, "tags": "usa, trains, food and drink, amtrak" }
NSFaceIDUsageDescription is there for Face ID Usage Description. How about touch ID Usage Description? I wanted to understand that Why don't have any key for Touch ID Usage Description. However, we need to specify key NSFaceIDUsageDescription (aka Privacy - Face ID Usage Description) in app's Info.plist. This is because we are using a Privacy feature from iOS. Similarly in case of Touch Id also we are using a Privacy feature of iOS.
Apple documentation says this: In any project that uses biometrics, include the NSFaceIDUsageDescription key in your app’s Info.plist file. Without this key, the system won’t allow your app to use Face ID. The value for this key is a string that the system presents to the user the first time your app attempts to use Face ID. The string should clearly explain why your app needs access to this authentication mechanism. **The system doesn’t require a comparable usage description for Touch ID.**
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "ios, swift, info.plist" }
Oracle PL/SQL: Call DML procedure from a function I have a procedure that has DML commands. the procedure accepts a variable of type out, and it returns a value. i need call this procedure from a function. the goal is that the function will return the value of the variable out returns the procedure. (i need it for SSIS, but I believe that it is useful in other cases.) During attempts, I got these errors: > ORA-14551: cannot perform a DML operation inside a query tips. > ORA-06519: active autonomous transaction detected and rolled back. I'm looking for the right syntax to do it.
Example of a solution that works: The procedure: create or replace procedure MyProc(outRes OUT NUMBER) is begin update some_table set some_description = 'abc'; commit; if (some_condition) then outRes := 666; else outRes := 999; end if; end MyProc; Note: You must do **commit;** at the end of the DML command. The function: CREATE or replace FUNCTION MyFunc RETURN int IS PRAGMA AUTONOMOUS_TRANSACTION; myVar number; begin MyProc(myVar); return myVar; END MyFunc; Note that at the beginning of the function has: `PRAGMA AUTONOMOUS_TRANSACTION;` And this function call: select MyFunc() as res from dual;
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "oracle, function, stored procedures, plsql, ssis" }
How to call my service via repository pattern within MVVM (WPF) app? I have successfully created a asp mvc app which basically has interface, service and dataacces - AKA the repository pattern.. What would be the best way to call my service (my repository pattern) from an MVVM structured WPF app.. From what i see.. in the MODEL in wpf i presume i call my service (repository pattern) from the model and then return data to my viewmodel for displaying on the view?? Should this model be thin i.e. has little code and just call the service.. and return data to the viewmodel for processing or should the MODEL call the repository service and do the processing in the model before retruning to the viewmodel?? I am a little confused how i can use my WORKING repository pattern in the realm of a new WPF MMVM app i am designing... Any ideas? Thanks
I think you are complicating matters by focusing on the fact that your data access uses a repository pattern. It's irrelevant. You could be using Joe's Box' O' Data pattern and your underlying question would be the same. Let's forget you are using that pattern and focus on what you are doing: getting data from a data source. When you get data from a data source, this is generally considered to be your Model. It's data, but it lacks certain behavioral things that make it appropriate for showing on the screen (lack of INotifyPropertyChanged implementation, for example). What people generally do with this is adapt their business objects into something that can be more readily used by a view (a view model). You will use this technique regardless of the pattern in use for getting your data.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "wpf, mvvm, repository pattern" }
Are Common Table Expression's (CTE) available in SQL Server 2000 I recently found the following article: < The article doesn't list which version of SQL server this became available in. **Does this work in SQL Server 2000 and if not what is the earliest version that it is usable in?** **Update:** I did try a quick test and the test doesn't work. I'm asking that it doesn't work in SS2000 to ensure it isn't me or my setup.
Common table expressions were introduced in SQL Server 2005. <
stackexchange-stackoverflow
{ "answer_score": 15, "question_score": 6, "tags": "sql server, tsql" }
Recursively removing/renaming files using powershell I have to go through many levels of child folders and remove special characters that are invalid in SharePoint, mainly '#&' I have scoured the internet trying different commands; rename-item/move-item, variations of the two, all to no avail. The closest i've gotten is using: Get-ChildItem -Recurse | Rename-Item -NewName {$_.Name -replace'[!@#&]','_'} but i keep getting this error: Rename-item: Source and destination path must be different. Could someone point me in the right direction? Regards
That error only happens when you attempt to rename a directory to the same `NewName` as the current name, you can safely ignore it. Add `-ErrorAction SilentlyContinue` to silently suppress the error message: Get-ChildItem -Recurse | Rename-Item -NewName {$_.Name -replace'[!@#&]','_'} -ErrorAction SilentlyContinue
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "powershell" }
Is the Embedded MongoDB Database of Spring in Memory Only? Of course, a fresh install with Spring Boot that includes MongoDB leads lead to an embedded version of MongoDB. I know that the standard way of doing this adds something like the following to either a Maven or Gradle setup: `org.springframework.boot:spring-boot-starter-data-mongodb-reactive` While I have MongoDB already setup on my own computer for other testing purposes, would I be right that MongoDB stays in memory only? Thank you.
Replacing ... org.springframework.boot:spring-boot-starter-data-mongodb-reactive with ... org.springframework.data:spring-data-mongodb:2.1.8.RELEASE ... seems to fix the issue. This points Spring to a locally installed database instead of creating an embedded database. This would go in a _pom.xml_ file for **Maven** or a _build.gradle_ file for **Gradle**.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "spring, mongodb, spring data mongodb" }
How to add a tfoot row to table generated with codeigniter table class I want to add footer row to the table generated by CI table class. There are classes available which extend the table class and add this functionality. I would prefer to use native feature if available without extending the table class. Is it possible in CI table class?
I ended up putting a div under the table with similar formatting to offer an illusion of footer row. Hopefully in future the table class will include the tfoot feature. I am aware of extended classes which will add this feature to CI table class.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "codeigniter" }
Можно ли создать локальный почтовик? Нужно создать 2 локальных почтовика (на одном компе на локальном сервере(использую open server) ). Мне нужны 2 локальных почтовых сервера для тестирования приложения. Можно ли это сделать ? Что для этого нужно ?
Скорее всего, для тестирования проще всего будет сделать виртуальную машину с любым linux-дистрибутивом. И на нём установить, например, `dovecot` и `courier`. Это оптимальный вариант в плане настроек (после установки они уже настроены для локальной работы) и ресурсов. Если обойтись только командной строкой, без графической среды, то для этих двух почтовых серверов будет достаточно 256MB оперативной памяти.
stackexchange-ru_stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "php, веб программирование, администрирование, openserver" }
Illustrator cc divide tool not working I have created a simple ellipse and then from one end to the other created a path using the pen tool that intersects this ellipse. I now want to divide the ellipse into two shapes using the path, however no matter what I do I can't get this to work. I am trying to use the pathfinder - divide tool, but when I apply this effect nothing happens, I have tried grouping the objects but still nothing works. Is there a simple trick that I need to apply to get this to work? The ellipse I am trying to divide in two and the path I want the division to be made along
It's important to realize that the menu item `Effect > Pathfinder` is **not** the same as using the **Pathfinder Panel** (`Window > Pathfinder`). The menu item strives to keep all artwork "live" and editable. So, while operations are completed, not all operations will result in a change to the actual artwork. The menu applies an **Effect** to the existing artwork. it does not change the artwork though. If you are seeking to _actually_ alter the artwork, you should choose to use the buttons on the Pathfinder Panel, rather than the menu items. (Note; you could also use the menu item but then you need to be certain to choose `Object > Expand` to "bake in" the pathfinder effect if needed). Random extra: Holding down the `Option/Alt` key while clicking a button on the Pathfinder Panel will make the buttons work the same way the Pathfinder Menu items work.
stackexchange-graphicdesign
{ "answer_score": 0, "question_score": 1, "tags": "adobe illustrator, pathfinder" }
Getting a crc32 mismatch while working with DynamoDB local After I make a call to `DynamoDB (using PHP)` I get the following exception: > crc32 mismatch. Expected 2745614147, found 2745614147 From the research I've done, it appears to have something to do with gzip but I can't figure out how to fix it. Any suggestions would be appreciated. Also, it probably shouldn't make a difference, but I'm developing with the DynamoDBlocal version at the moment. **Update** : I was using the new version 3 of the SDK but that seems to have a few problems. After spending way too many hours trying to figure this one out, I finally just downgraded to the latest version in the 2.* branch and the problem went away. I'm using the latest version of the local DB that came out just a couple of months ago (2015-04-27).
Please see this post in this AWS forum post for a likely solution to your issue.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, amazon dynamodb" }
Facebook, twitter and mail share without UIActivityViewController on iOS I want my app users to be able to share stuff on facebook, twitter and mail but I do not want to show the UIActivityViewController.. So I want to have seperate buttons for different share types (fb, twitter, mail) instead of just one share button, and show directly the share dialog. Is there a way of doing this? Thank you..
yes there are different way to do it.there is build in framework for it... SLComposeViewController /// for facebook and twitter and MFMailComposeViewController /// for Email check this link here for facebook and twitter and for sharing with Email check here
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "ios" }
EF Code-First table per type with base class DbSet I have a DbSet in the DataContext for the base class: public DbSet<BaseClass> Users {get;set;} I have 2 derived classes client and driver. Both have an foreign key AdminID. When I get data for a specific type there is no problem. Users.OfType<Client>.ToList() However if i try to get both Clients and Drivers something gets messed up in the code generation: Users.ToList() the AdminID property is generated 2 times. AdminID and AdminID1. I think the sql generator gets confused because I have the AdminID in both dervied classes but not in the parent. I cannot put this property in the parent because I have another derived class that does not have this property. Is this a bug or am i doing something wrong.
No it is not bug. It is feature = limitation. Once you move property to derived class it must have unique mapping to database column. Because of that you cannot have shared AdminId between two derived classes. Each class will have its own foreign key column and relation.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": ".net, inheritance, mapping, code first, entity framework 4.1" }
How to Get a Single Line of Data From a Web Service Using Rspec I've written a minitest script to test my ruby web service. Now I would like to do the same in rspec. This a working test using minitest: assert_equal('switch:off',`curl " How do I convert this to rspec? The web service runs standalone using sockets.
The expectation would look like: response = `curl " expect(response).to eq('switch:off') You can write it as a one-liner if you like, but I think that is less readable: expect(`curl " eq('switch:off')
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ruby, curl, rspec" }
From generators as linear space to minimal generators as ideal Let $I$ be a prime ideal in the polynomial ring $\mathbb{C}[x,y,z]$. Suppose we find a family $\\{p_n\\}_n$ of generators of $I$ _as a linear space_. Clearly $\\{p_n\\}_n$ generates $I$ also as an ideal. Is it possible to extract from $\\{p_n\\}_n$ a family of generators of $I$ _as an ideal_ having _minimal cardinality_?
Let $k$ be a field and consider the ideal $I=(x)$ in $k[x]$, which is of course prime and principal. The set $B=\\{x+x^2\\}\cup\\{x^i:i\geq2\\}$ is a basis of $I$ as a $k$-vector space yet no element of $B$ generates $I$ as an ideal. You can play similar games with three variables.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "abstract algebra" }
Show UINavigationController with UIViewController animation I have a storyboard with few `UINavigationControllers` and `UIViewControllers`. ![Main.storyboard]( When I `performSegueWithIdentifier(..)` from the second to third window default animation is right to left slide. But when I `performSegueWithIdentifier(..)` from the third window to `UINavigationController` the animation is from bottom to top slide. How to set `UIViewController` -> `UINavigationController` animation to one like `UIViewController` -> `UIViewController`?
YOURVC *vc = [[YOURVC alloc]init]; UINavigationController *VCNavigation = [[UINavigationController alloc]initWithRootViewController:vc]; And when you are calling from 1 to 3 or any call [self.navigationController pushViewController:vc animated:YES]; or from 2 to 1 also you can call like this and instead you can call [self.navigationController popViewControllerAnimated:YES]; or to root view controller use [self.navigationController popToRootViewControllerAnimated:YES]; or to a particular vc [self.navigationController popToViewController:yourvc Animated:YES]; Then if you want to show navigation keep it, or if you want to hide you can hide it.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ios, swift, storyboard, ios animations" }
Log deleted files to a text file I want to know how to log the actions from this script to a text file because I don't know how to do it as the cmdlet `Start-Transcript` doesn't work for me and I wasn't able to find a solution on the Internet. The problem is that the `Where-Object` cmdlet doesn't output anything captured by `Get-ChildItem`. Does anybody has a good idea to solve this? $limit = (Get-Date).AddDays(-30) $path = Split-Path -Parent $MyInvocation.MyCommand.Definition Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -lt $limit } | Remove-Item -Force Get-ChildItem -Path $path -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse
try something like this $limit = (Get-Date).AddDays(-30) $path =Split-Path -Parent $MyInvocation.MyCommand.Definition Get-ChildItem $path -file -recurse -force | where LastWriteTime -lt $limit | Tee-Object -FilePath "c:\temp\deleted.txt" -Append | Remove-Item Get-ChildItem $path -directory | where {(Get-ChildItem $_.FullName -file -Recurse | select -First 1) -eq $null} | Tee-Object -FilePath "c:\temp\deleted.txt" -Append | Remove-Item
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "powershell" }
Is this "month" a noun adjective? Thank you in advance, Reading **this article,**, 6th passage says, > Parliament has already dealt Johnson a series of setbacks and derailed his promise to take Britain out of the EU by the end of **the month** "come what may." Johnson has now pinned his hopes on an early general election, calling for one on Dec. 12, but how Britain will solve its Brexit stalemate is still completely up in the air. Is this bold line "the month" the noun adjective modifying the "come what may"? It sounds a bit odd to me personally when I read the preceding sentence as a whole. Thank you.
No, "the month" does not modify "come what may." **Come what may** is a set phrase meaning " **regardless of the consequences** " or " **no matter what happens** " and it functions as an adverbial phrase modifying the verb of the sentence/clause. In this case, it modifies "take... out." "...by the end of the month" is another adverbial phrase modifying "take... out."
stackexchange-ell
{ "answer_score": 6, "question_score": 0, "tags": "word usage" }
sql select where (sum of 2 columns) is greater than X I have a dynamic SQL query based on user selections. 2 of the columns (FullBath, HalfBath) need to be counted as one for SELECT operations. EX: a user searches for a property in a specific town and minimum number of bathrooms (HalfBath and FullBath combined) is greater than or equal to x. I tried variations of: SELECT * From Rentals WHERE Town = _town_ AND (SUM(FullBath + HalfBath) >= _bathrooms_ ) ========================= I found answer (don't need SUM...)
SELECT * FROM Rentals WHERE Town = Town AND FullBath + HalfBath >= Bathrooms
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "sql" }
How many dots do I have to write? This seems very odd and silly. But I do not know where else to ask. This question occurs to me whenever I write an infinite sequence, sum or decimal points etc. Ex: $ 1.2 + 2.3 + 3.4 + ……………$ Ex: $1.2345 .....$ How many dots are used to represent that it follows the same pattern endlessly? Is there a certain number of dots that should be written?
Ex : $1.2 + 2.3 + 3.4 + \dotsb$ MathJax: `$1.2 + 2.3 + 3.4 + \dotsb$` (“dots with binary operators/relations”) Ex : $1.2345 \dotso$ MathJax: `$1.2345 \dotso$` (“other dots”) See Martin's MathJax Guide, 4.6. Dots
stackexchange-math
{ "answer_score": 4, "question_score": 1, "tags": "soft question, definition" }
How to load different picklist values other than present in application How can I load different picklist values for a field,values which are not present in application.I have a picklist field is having few values in application,but i have to load values that is different to these values.
To load different values, you'll need to ensure the settings on that field allow it. i.e. turn `Restrict picklist to the values defined in the value set.` off. If you're using global picklists, this may not be an option.
stackexchange-salesforce
{ "answer_score": 2, "question_score": 1, "tags": "data loader, picklist" }
Coderush Unit Test Runner and Assert.Inconclusive Can the coderush unit test runner recognise an NUnit Inconclusive assertion as something other than a failure. Perhaps something more like ignored rather than failed? I am comparing this to resharpers treatment of inconclusive assertions. Is so do I need to configure this and how?
I apologize, but CodeRush can't do that at the moment. If you post a suggestion via the DevExpress Support Center, they will consider implementing it in the future.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "nunit, coderush" }
How compile Eigen for MSVC++ 2013? How compile Eigen for MSVC++ 2013? (Win8 Pro x32) I downloaded cmake and tried do this in cmd: d:\lib\cmake-2.8.12.1-win32-x86\bin\cmake d:\lib\eigen-eigen-ffa86ffb5570\Eigen CMakeOutput.log on github How right to compile a Eigen? I don't know and don't know where I could learn about this.
Eigen is a header library. It doesn't need to be compiled, just included and placed in an include path.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c++, visual c++, cmake, eigen" }
Add a Contextual Menu to WebView An easy one, I think: I want to add a contextual menu to a WebView. In IB, I added a NSMenu to the NIB, connected it to the WebView's menu outlet, launched and expected to be able to control-click in the WebView and see the pop-up menu. The only item I saw on the contextual menu is "reload". I can do the same steps but connect the Menu to some other view and it works as expected. Why doesn't the menu work the same when connect to the webview's menu outlet? Thanks
`WebView` calls the following method of its `WebViewUIDelegate`: webView:contextMenuItemsForElement:defaultMenuItems: Use `setUIDelegate:` to set a custom UI delegate.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 1, "tags": "cocoa, webview, nsmenu" }
How did I eliminate my own steel trap as Junkrat? Sometimes while playing Deathmatch, I'll see a prompt telling me that I've gotten credit for eliminating my own Steel Trap or Concussion Mine while playing as Junkrat. ![Eliminating own Junkrat trap]( I've had this happen to me 2 or 3 times, but only while playing as Junkrat in Deathmatch mode. I haven't been able to figure out how this happened, or how to prevent it. This doesn't seem to be a bug with Junkrat's grenade launcher. When I tried firing directly at the trap, the grenades didn't do any damage. **How is it possible to eliminate my own Steel Trap as Junkrat?**
It's a bug currently present with deployables in Free-For-All Deathmatch. Since there are no teams, a player's own deployables such as Junkrat's trap and Orisa's shield sometimes behave oddly, such as Junkrat's trap being destroyed by his own Concussion Mine and Orisa's shield blocking the pull effect from her alternate fire. There's nothing you can do except wait for a patch to fix it. This link to Overwatch Patch notes for 1.15 confirms the following bug in FFA; > * Junkrat can destroy his own Steel Trap with a Concussion Mine >
stackexchange-gaming
{ "answer_score": 7, "question_score": 2, "tags": "overwatch" }
Dictionary of Arrays to Single Array Simple question that I can't seem to find an answer to: In C#, how do you take a Dictionary< TKey, TValue[] > and make it an TValue[] array - get all values from the dictionary into a single array? I've tried experimenting with LINQ but can't find a solution, probably easier than I think.
You can use `SelectMany` from LINQ: var array = dic.SelectMany(p => p.Value).ToArray();
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 0, "tags": "c#, arrays, linq, dictionary" }
Insert PHP into Echo I am trying to insert the below PHP into an `echo` but having trouble with the correct formatting. PHP: <?php if ( isset($heroloc) ) { echo '@ '.$heroloc;} ?> Would like to place the `if` statement into the below right after `$created_time` echo '<span class="time">'.$created_time.'</span>'; Somethign like this, but formatted properly: echo '<span class="time">'.$created_time. if ( isset($heroloc) ) { echo '@ '.$heroloc;'</span>';
Use a ternary operator <?php echo '<span class="time">'.$created_time.(isset($heroloc) ? '@ '.$heroloc : '').'</span>';
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "php" }
Error : Cannot fit requested classes in a single dex file (# methods: 65978 > 65536) hi Guys Im getting This errer when i tried to run my application . i investgated the issue and i found that the problem happen only when i add this google implementation . when i removed the implementaion the app worked just fine . why is that happening and what it is the solution `implementation 'com.google.android.gms:play-services-auth:20.1.0'` i dont know where the the cause of the probleme can any one help me by gaving me the solution or dercting me to any article
You must add the library in the app gradle : implementation 'com.android.support:multidex:1.0.3' After, add in the defaultConfig of the app gradle : multiDexEnabled true
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 7, "tags": "android, kotlin, google signin" }
ProgressDialog Box Dummy Timer Hey guys i wanted to ask if i can add dummy timer to my progress box. I want my progress box to prompt user to enter his current location then his destination so when the app starts it will prompt him to enter his username, after 2 seconds of msg displaying the msg will dissapear. How can i implement his code so far: int timer = 0; ProgressDialog progressDialog = new ProgressDialog(MainActivity.this); progressDialog.setMessage("Enter Current Location"); progressDialog.show(); // do { ++timer; } while ( timer != 500 ); // hiding after 500 iterations progressDialog.hide(); The do while loop doesn't work for me, so are there other options?
Its called **_delay_** and not dummy timer. To add delay, add this code after `progressDialog.show()` function. 1500 ms delay (1.5 seconds); Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { progressDialog.dismiss(); } }, 1500); or 3000 ms delay (3 seconds); Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { progressDialog.dismiss(); } }, 3000); and remove `progressDialog.dismiss()` from end of your code after adding any of the above one. Cheers.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "android, timer, delay, progressdialog" }
Scalac restrictions on value classes for implicits on traits with type parameters The following does not compile because of `extends AnyVal` as it gives the following compilation error: value class needs to have exactly one val parameter Here's the code (simplified): sealed trait Thing[A] { // stuff } object RichThing { implicit final class ImplicitsA: ClassTag extends AnyVal { def doSomethingB: ClassTag: Thing[A] = { // use f internally } } } The thing is that I cannot touch the library that `Thing[A]` is in and I'm trying to extend it so that for our internal users the additional functions feel seamless as per usual for implicit conversions. I can remove `AnyVal` but is there a way around that restriction for my case (in 2.11)?
A value class must have only one argument, and your `Implicits` class has two: the explicit `val thing: A` and an implicit one with type `ClassTag[A]` coming from the context bound `[A: ClassTag]`. To satisfy the value class requirement, you can move the implicit parameter `ClassTag[A]` from the context bound to individual functions signatures: implicit final class ImplicitsA extends AnyVal { def doSomethingB: ClassTag(implicit tagA: ClassTag[A]): Thing[A] = { // use f internally } } You are using this class just to provide rich methods, so it doesn't really matter at what point the implicits get injected. Of course, you can just remove `extends AnyVal`, but then an actual `Implcits` object will be instantiated for every `doSomething` invocation, which is just needless pessimization.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "scala" }
MacLane coherence theorem for "monoidal" category without 1 MacLane's coherence theorem for a monoidal category states that once the associators for 4-fold products are compatible (i.e., the pentagon axiom holds), it holds for n-fold products, so I can bracket n-fold products in any way I like. What happens if I forget the unit, i.e. I consider "semigroup categories" as they are called in the book "Tensor Categories" by Etingof, Gelaki, Nikshych and Ostrik. Is it still true that the pentagon axiom implies that the bracketing of n-fold products does not matter? The proof of the coherence theorem given in the book relies on the unit. Still, they say that "semigroup categories" categorify semigroups. Then they should better satisfy coherence in my opinion. But I don't know.
Sorry, I noticed this an hour after posting: Yes, it's true, see Theorem 3.1 in MacLane's excellent paper "Natural associativity and commutativity". It's a mystery to my why this is so scarcely mentioned.
stackexchange-mathoverflow_net_7z
{ "answer_score": 8, "question_score": 9, "tags": "ct.category theory, monoidal categories" }
char Array to string conversion results in strange characters - sockets I currently have the following code char my_stream[800]; std::string my_string; iResult = recv(clntSocket,my_stream,sizeof(my_stream),0); my_string = std::string(my_stream); Now when I attempt to convert the char array to string I get the present of weird characters in the string any suggestions on what I might be doing wrong
You're getting weird characters because your strings length is not equal to the number of bytes received. You should initialize the string like so: char* buffer = new char[512]; ssize_t bytesRead = recv(clntSocket,buffer,512,0); std::string msgStr = std::string(buffer,bytesRead); delete buffer; The most common solution is to zero every byte of the buffer before reading anything. char buffer[512]; buffer = { 0 };
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "c++, sockets, client server" }
Asynchronous method in the background in Objective C I want to be able to send data while not blocking the UI. These files are quite big, so synchronously sending them is not an option. I have a class that implements all the methods of sending data through Apache Thrift. All the asynchronous requests I've seen are using NSURLRequest and NSURLConnection, but for my application I want to utilize my class. Basically, I want to asynchronously call this method: - (void)syncLocalData { Manager *stateManager = [[Manager alloc] init]; [stateManager readDirectory]; } In readDirectory, I go through the device directory and send over data if there is a file.
GCD (Grand Central Dispatch) offers easy-to-use functions to execute code asynchronously on a background thread: dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [yourInstance syncLocalData]; }); Depending on your needs, you can use the global queue (which is a "concurrent" queue), or create your own "serial" queue.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 2, "tags": "objective c, asynchronous, background, thrift" }
How to get information out of MS Word to Java based server I have a word document, the data in the word needs to reach a server through a click of a button. The "Button" implies VBA. I was wondering if it would be a nice idea to use SOAP for that. But someone suggested FTP (which I didn't really understand). I also thought of using XML-RPC. could someone please shed some light? cheers
The transport mechanism really depends on the server interface, but since you are going through these options I assume you need to implement the server interface as well. If you need to transfer the whole Word document as such, use File Transfer Protocol (FTP) or direct TCP socket-connection. If you need the data from the Word document, you can serialize it in a machine-readable format, for example XML, and send it to the server using Hyper-Text Transfer Protocol (HTTP), for it's simplicity. XML-RPC and SOAP might be too heavy and perhaps on the wrong abstraction level for your problem. Oh, and for the client side: pick your client-side development tools after choosing your transport mechanism. Some languages and frameworks work better for different tasks than others.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "vba, soap, ftp, xml rpc, rpc" }
Dropping row in pandas if 2 columns in the same row have NAN value in it I am new to pandas and trying to complete the following: I have a dataframe which look like this: row A B 1 abc abc 2 abc 3 abc 4 5 abc abc My desired output would look like this: row A B 1 abc abc 2 abc 3 abc 5 abc abc I am trying to drop rows if there is no value in both A and B columns: if finalized_export_cf[finalized_export_cf['A']].str.len()<2: if finalized_export_cf[finalized_export_cf['B']].str.len()<2: finalized_export_cf[finalized_export_cf['B']].drop() But that gives me the following error: ValueError: cannot index with vector containing NA / NaN values How could I drop values when both columns have an empty cell? Thank you for your suggestions.
You can check whether all rows have a null by using `.isnull()` and `all()` in a chain. `isnull()` produces a dataframe with booleans, and `all(axis=1)` checks whether all values in a given rows are true. If that's the case, that means that all values in the rows are nulls: inds = df[["A", "B"]].isnull().all(axis=1) You can then use `inds` to clean up all rows that have only nulls. First negate it using the tilda `~`, or else you can only missing values: df = df.loc[~inds, :]
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "python, pandas" }
Reading KeePass files in Android app I am currently trying to read KeePass (.kdbx V2) files within my own Android App but I am struggling. I tried to use openkeepass as a .jar but it did not work out. Can anybody tell me a more reliable way to read keepass files in within my app - ideally an easy to use library?
Yea well this question was kind of stupid, I should have googled for "open keepass in Java" -> there seem to be some libs out there doing the job. I chose KeePassJava2 for my app.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android, keepass" }
Determine whether the user opend the app with double click file or context menu open with is there a way to determine whether the user opend the uwp app with a double click on the file or whether the user used "open with" (for example right click on the file open with; or Photos app -> open with). In both scenarios the app will be launched with FileActivetedEventArgs with the verb "open". Any ideas?
> In both scenarios the app will be launched with FileActivetedEventArgs with the verb "open". Any ideas? Currently, you could not figure out the UWP app opened with file double click or _open with_ scenario, because the final executor is same, and the opening action was managed with system. The file and the executor were isolated by operation system. This is for modularity. If you need this new feature, please feel free to ask for this feature on **UserVoice**.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, uwp, win universal app, uap" }
Project a list of strings to a list of SQL statements I have a list of strings: `List<string> NameList = new List<string>()` The list of names contains the following items: `John Doe`, `Tom Jones`, `Bob Sinclair` I want to project these items to a single joined string that looks like: isnull(piv.[John Doe],0) [John Doe], isnull(piv.[Tom Jones],0) [Tom Jones], isnull(piv.[Bob Sinclair],0) [Bob Sinclair] The above is a SQL statement that will be built using the program I am making. I do not need to execute the SQL, just return the joined list of names as a string in the aforementioned format.
This is easy to do with a little bit of LINQ and the `$` string interpolation operator. Try this: var result = string.Join( $",{Environment.NewLine}", NameList.Select(x => $"isnull(piv.[{x}],0) [{x}]")); `string.Join` will combine all the results with commas and newlines after each element. `NameList.Select` projects each element to the format you need. Here's a fiddle with a fully working example. It creates this output: isnull(piv.[John Doe],0) [John Doe], isnull(piv.[Tom Jones],0) [Tom Jones], isnull(piv.[Bob Sinclair],0) [Bob Sinclair]
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 2, "tags": "c#" }
How to turn off auto-capitalization on the HTC One M8? This is bugging me while texting. I don't see an option to turn it off in the text app's settings, or Settings -> Language & keyboard. Here's the screen when I open settings from the keyboard: !Text settings page And here's the submenu when I hit Advanced: !Advanced text settings page
Unfortunately, on the stock HTC keyboard, you **cannot** turn off auto-capitalization. Consider _Google Keyboard_ , which gives better customization options.
stackexchange-android
{ "answer_score": 1, "question_score": 0, "tags": "sms, htc" }
Bash: Storing a command in a variable CMD and then running it with $CMD fails On Bash, I first define a variable CMD for a command line bash instruction, then I run it. An error occurs. Where does it go wrong? $ CMD="VERBOSE=1 ./myscript" $ $CMD bash: VERBOSE=1: command not found
Don't store commands in variables. Variables aren't smart enough to hold commands. They will let you down time and time again like your roommate that never washes the dishes. Use a function. They're the right tool for the job. You can use them like they were regular executables; they can take arguments; there are no quoting/backslash/whitespace issues. $ cmd() { > VERBOSE=1 ./myscript > } $ cmd Functions are where it's at. **See also:** * How can I create a bash environment variable that prefixes an environment variable before a command?
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "bash" }
Android - executePendingTransactions cannot be referenced from static context I know from this answer that > If you want to immediately executing any such pending operations, you can call this function (only from the main thread) to do so. But, if I call it from the static main thread, I get an error that says executePendingTransactions() is non-static and cannot be referenced from static context. How do I fix this? Thank you!
`executePendingTransactions()` is a regular non-static method on `FragmentManager`. You need an _instance_ of `FragmentManager`, such as by calling `getFragmentManager()` (or `getSupportFragmentManager()` if you are using the fragments backport) on your `Activity` or `Fragment`.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "java, android, static, transactions, execution" }
Insert object into array at specific index in React I'm attempting to add an object at a specific point in my 'data' array which is this components state. The following isn't working, the array simply gets emptied. addNewBulletAfterActive = () => { const array = this.state.data; const newBulletPoint = { id: this.state.data.length += 1, title: 'Click to add' }; const newData = array.splice(this.state.activeBulletPointId, 0, newBulletPoint); this.setState({ data: newData }); } The idea is that if I have a list of 10 bullet points, the user can click on the 4th bullet point and press enter to add a new bullet point directly after. I've not had any issues adding items to the end of the array but it looks like .splice is causing issues.
`splice` returns spliced items (which is empty since you splice 0 items) and mutates original array. const newData = array.slice(0); // copy newData.splice(this.state.activeBulletPointId, 0, newBulletPoint); this.setState({ data: newData });
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 10, "tags": "javascript, reactjs" }
Loading Keras dataset mnist After installing `keras` `gpu`, I try the simple example: import keras print(keras.__version__) Prints the following output: 2.2.4 Using TensorFlow backend. However, when I try to load a dataset: form keras.datasets import mnist It gives an error: File "<ipython-input-12-3386782fae62>", line 1 form keras.datasets import mnist ^ SyntaxError: invalid syntax
`form` is not a python keyword. Try `from`. This is the import line from the Keras datasets page: from keras.datasets import mnist
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "keras 2" }
shell script to call ls command every time i change directories I am wondering if there is any way to make a script, that would run in the background and which will call the "ls" command every time I change directories("cd") in Linux. I know that in order to put a process in the background you add a "&" when you run it. Thanks in advance!
You could replace `cd` with a shell function in your `~/.bashrc` or similar startup script: function cd { builtin cd "$@" RET=$? ls return $RET } this would also return the exit code of `cd`, just in case... `builtin` is a shell builtin to execute the shell builtin `cd` instead of the `cd` funciton, to avoid running into a recursive loop - at least in bash - but should also work with other shells...
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "linux, shell, ls, cd" }
How do I move a number between two Alcatel Lucent 4029 Handsets I'm trying to find a manual online and I'm not having any luck. I need to know the deregister/reregister procedure for an Alcatel Lucent 4029 handset. I'm trying to move a number from one desk to another one, so we just need to deregister handset 2, deregister handset 1 and then register the number from handset 1 onto the now blank handset 2. All advice on whether I'm trying to do it the wrong way is greatly appreciated.
Got onto IT. For prosperity: Pick up the handset and dial #05. Then it will ask for a password, if your IT dept didn't change it, it's still 0000. Then you can hang up. To hook on the new phone (or a different number on the same phone) pick up the handset, dail your extension number and then type in the same admin password (0000 default). Note of course you can't move the number till you deregister it from the first handset.
stackexchange-serverfault
{ "answer_score": 1, "question_score": 2, "tags": "telephone, alcatel lucent" }
Zcash z-addr in bitcoin Can a improvement, difficult or easy, to Bitcoin Core implement z-addr like Zcash? Zcash do it possible to send coin anonymous using z-addr. The blockchain do not show z-addr, only t-addr that is like a bitcoin address.
The developers of Zcash did try to implement their solution using the Bitcoin blockchain but it required several changes to Bitcoin core that where both difficult and more importantly difficult to come to consensus for the changes with the rest of the Bitcoin community. So the Zcash developers decided to make a new blockchain. So technically speaking it would be possible (but hard) but convinving the Bitcoin community of the changes would be much harder. Note that there are other anonymity proposals that will use the Bitcoin blockchain (e.g. Confidential Transactions, MimbleWimble) but I do not know the state of their implementation.
stackexchange-bitcoin
{ "answer_score": 2, "question_score": 2, "tags": "bitcoin core, address, zcash" }
2sxc : How to get list of all application Content-Types Is there any public methode in 2sxc for get all Content-Types? Or how to get list of all content-types? (edit / added) When I get all appTypes (from my answer below) i can access all Fields by this code: var fieldList = (myType as ToSic.Eav.Data.ContentType).AttributeDefinitions; the result is Dictionary of AttributeBase with properties: Name, Type, IsTitle, SortOrder,... But I don't find properties for : REQUIRED, Visible In Edit UI, RowCount,... Where or how I can access this properties?
I make this code and work OK var cache = ToSic.Eav.DataSource.GetCache(null, App.AppId) as ToSic.Eav.DataSources.Caches.BaseCache; var allTypes = cache.GetContentTypes().Select(t => t.Value); var appTypes = allTypes.Where(t => t.Scope == "2SexyContent").ToList(); Is this the right way?
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "dotnetnuke module, 2sxc" }
FSA for recognizing bit strings containing sequence "101! ![enter image description here]( Hi, i was trying to write a FSA that recognizes the set of all bit strings that contain the string 101. Could this implementation be considered a correct one? Thanks a lot
![FSA diagram ]( Here is a diagram of an FSA that I think does the job. On the arrow going from S2 back to S0 there should be a label of $0$ but now tht diagram is there I can't edit the diagram.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "discrete mathematics, automata" }
Is there an ordering of two points in space that is stable against small perturbations? / unique parameterization for line segments? I have the Cartesian coordinates of two points in space. (Equivalently, I have a line segment.) I need to order these two points such that small perturbations will not change the ordering. Furthermore, no pair of points will be closer than some distance epsilon. Perturbations can be assumed smaller than epsilon. Is this possible? If so, how? (Equivalently, is there a unique way to parameterize a line segment?) (I don't need to order _all_ points in the plane, just two at a time. It's fine if point A < point B, point B < point C and point C < point A.) An ordering that is _not_ stable is sorting by X, then Y, then Z. That sorts (1, 2, 7) less than (1, 3, 7), but (1.1, 2, 7) greater than (1, 3, 7).
Round each coordinate to the nearest multiple of $2\epsilon$, so that for each point you have a unique representative $(2\epsilon a, 2\epsilon b)$that is independent of any coordinate perturbations smaller than $\pm\epsilon$. Then impose some ordering on the integer pairs $(a,b)$, e.g. lexicographic order. For this to work you need the two points to be at least $2\sqrt{2}\cdot\epsilon$ apart so that they don't round towards the same representative latticepoint.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "geometry" }
Let $K$ be a field with $\mathbb{Q} \subset K \subset \mathbb{C}$ and $[K:\mathbb{Q}]$ odd Let $K$ be a field with $\mathbb{Q} \subset K \subset \mathbb{C}$ and $[K:\mathbb{Q}]$ odd. 1. If $K/\mathbb{Q}$ is Galois, prove that $K$ is contained in $\mathbb{R}$. 2. Find an extension with $[K:\mathbb{Q}]=3$ with $K$ not contained in $\mathbb{R}$. I am looking for a **hint** on each part. For part 1, I was trying to make an argument with indices: $[\mathbb{C}:\mathbb{R}]=2$, so that $[\mathbb{C}:K]$ must be even. This does not use Galois though... Thanks
**Hint for 1:** If a group has an element of order $2$, then its cardinality is even. When does the automorphism _"complex conjugation"_ on a field $K\subset\mathbb{C}$ have order $2$? Now just remember the fundamental theorem of Galois theory. **Hint for 2:** What is the classic first example of a non-Galois field extension that anyone sees in abstract algebra? Now modify that slightly.
stackexchange-math
{ "answer_score": 3, "question_score": 3, "tags": "abstract algebra, field theory, galois theory" }
How to show the given function g is continuous everywhere? How to show that $g(x,y)=\frac{(1-cos(x+y))}{(x+y)^2}$ when $(x,y)\ne(0,0)$ and $g(x,y)=\frac{1}{2}$ when $(x,y)=(0,0)$ is continuous everywhere in $\mathbb R^2$
You have to define $g(x,y)$ to be $\frac 1 2$ whenever $x+y=0$. Only then you can say that the function is defined and continuous everywhere. To prove continuity note that continuity at $(x,y)$ is obvious if $x+y \neq 0$. So consider a point of the type $(a,b)$ with $a+b=0$. Let $(t_n,s_n) \to (a,b)$. To show that $\frac {1-\cos(t_n+s_n)} {(t_n+s_n)^{2}} \to g(a,b)(=\frac 1 2)$ all you need is the following fact: $\\\lim_{\theta \to 0} \frac {1-\cos \,\theta} {\theta^{2}} =\frac 1 2$. [ You can prove this last fact either using the series expansion of cosine function or using L'Hopital's Rule].
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "multivariable calculus" }
Applying Raster Calculation to Image Collection in Google Earth Engine I am trying to perform a raster calculation (EVI) on an imagery collection. This operation is seen on Line 130 and is based on: < (which I know is for single images). In addition to being an imageCollection, my version of this GEE provided code differs in that I've renamed my bands prior to calculating EVI. I am having trouble finding the necessary format to apply a band math equation to an imagery collection. Presently, I am receiving an error: "Cloudfiltered.expression is not a function" Here is my script: < The Region of Interest: "ROI" was made with the Rectangle Tool in GEE and can be totally arbitrary; I don't know how to share it. Here is mine for context: <
The way to add EVI to every image in an image collection in Earth Engine is to `map()` a function over the collection. // First, create function var addEVI = function(image) { var evi = ee.Image(0).expression( '2.5 * ((NIR - RED) / (NIR + 6 * RED - 7.5 * BLUE + 1))', { 'NIR': image.select('NIR'), 'RED': image.select('RED'), 'BLUE': image.select('BLUE') }); return image.addBands(evi.rename('evi')); }; // Second, apply function over your collection var mergedEVI = Cloudfiltered.map(addEVI); The variable mergedEVI is an image collection in which every image has a band named "evi". More information <
stackexchange-gis
{ "answer_score": 3, "question_score": 0, "tags": "google earth engine" }
Difference in minutes between 2 dates and times? I need to compute time difference in minutes with four input parameters, DATE_FROM, DATE_TO, TIME_FROM, TIME_TO. And one output parameter DIFF_TIME. I have created a function module, I need to write a formula which computes the time diff in minutes. Any help would be great! Thanks, Sai.
If the values are guaranteed to be in the same time zone, it's easy enough that you don't need any special function module or utility method. Read this, then get the difference of the dates and multiply that by 24 * 60 and get the difference of the times (which is in seconds) and divide that by 60. Sum it up and there you are.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 4, "tags": "date, datetime, abap" }
Can I prevent an iPad app ever being updated? The latest version of Skype for the iPad has commercials. It will probably be necessary to upgrade at some point, but until then I want to stay with the commercial free version. Is there any way I can prevent it ever being updated? I want to ensure that it will not be updated by accident.
Back up your iPad with iTunes. Back up that hard drive. Unplug that backup and store it far away from any internet connection. If you do update Sykpe by mistake, restore the iPad from the backup. It won't keep Skype from updating, but it will preserve your ability to undo the update.
stackexchange-apple
{ "answer_score": 4, "question_score": 3, "tags": "ipad, applications, software update, skype" }
get table row data td and select Here is what I want to do. In the first row that has tds then `a = the text in the first cell` and `b = the selected value of the drop down that the user selected` How do I do this as my code is not working? $(document).ready(function () { var s = $('table td:first').parents('tr'); var a = s.eq(0).text(); var b = s.eq(1).find('option:selected').val(); alert(a + " " + b); }); <table> <tbody> <tr> <th>ID</th> </tr> <tr> <td> test </td> <td> <select> <option value="yes">yes</option> <option selected="selected" value="no">no</option> </select> </td> </tr> </tbody> </table>
**Working demo** < Rest feel free to play around, & hope it helps your needs `:)` **code** $(document).ready(function () { var s = $('table td:first').parents('tr'); var a = s.find('td').eq(0).text();//s.eq(0).text(); var b = s.find('td').eq(1).find('option:selected').val(); alert(a + " " + b); });​
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "javascript, jquery" }
LWC get element by value Why can't I get element by value? I have tried to get id with var, just data and different quotes. //var = id; <lightning-input value={var}></lightning-input> this.template.querySelector("lightning-input[value='id']"); // but just lightning-input works and value is correct console.log(this.template.querySelector('lightning-input').value);
You can do something like that: //var = id; <lightning-input data-value={var}></lightning-input> let id = '12345'; this.template.querySelector(`[data-value="${id}"]`);
stackexchange-salesforce
{ "answer_score": 1, "question_score": 1, "tags": "lightning web components, lightninginput, js, queryselector" }
Differential equation $d^n/dx^n f(x)=\pm k^2f(x)$ > How to solve this differential equation: > > $$\frac{d^nf(x)}{dx^n}=\pm k^2f(x)$$ > > For $n=1,2,3$ and $\forall n\in\mathbb{N}$, and both signs, if this is possible. I encounter these often in physics, with solutions but no derivations. I would like to know how they are solved.
This equation is linear in $f(x)$, so if you just find $n$ linearly independent solutions by wild-guessing it should be enough to prove that this is the general solution of this equation. For instance, since you know easily that for $n = 1$ you need to substitute $f(x) = e^{rx}$, a wild guess would be the same guess, which leads to $$ r^n e^{rx} = \pm k^2 e^{rx} \quad \Longrightarrow \quad r^n = \pm k^2 \quad \Longrightarrow \quad r = \sqrt[n]{\pm k^2} e^{\frac{2\pi i j}n}, \quad 0 \le j \le n-1. $$ Since all those values of $r$ are distinct, you have $n$ solutions (for a fixed $n^{\text{th}}$ root of $+k^2$ or $-k^2$). Tadam! Hope that helps,
stackexchange-math
{ "answer_score": 0, "question_score": 1, "tags": "calculus, integration, ordinary differential equations" }
(WP) Override WP Plugin Public Function I want override WP public function in plugin files. I want to place it on my theme functions.php file and don't want to directly edit plugin files because I want this function only applicable when using this theme only. How can I override this public function? class WP_Job_Manager_Post_Types { public function application_details_email( $apply ) { get_job_manager_template( 'job-application-email.php', array( 'apply' => $apply ) ); } }
You could instead try the `job_manager_locate_template` filter: add_filter( 'job_manager_locate_template', function( $template, $template_name, $template_path ) { if( 'job-application-email.php' === $template_name ) { // modify $template; } return $template; } , 10, 3 ); to modify the template path.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "wordpress" }
How to write the result of compiling to an output in a batch file? I'm compiling C codes in a windows batch file as follows: set CURRENT_DIR=%cd% for /d /r %CODE_DIRS% %%d in (*src) do ( cd %%~d gcc *.c -o program cd %CURRENT_DIR% ) I need to write compiling errors in a compile.log file if there is any error. How should i do? Thank you.
This works only if `gcc` uses the default `STDERR` for error output: gcc 2>>logfile.log
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "batch file" }
Modular arithmetic, remainder of a term in a sequence when divided by 100 Let $a_n$ be the sequence defined by $a_1$ = 3, $a_{n+1}$ = $3^{a_n}$ . Let $b_n$ be the remainder when $a_n$ is divided by 100. What is $b_{2004}$? I found this question online and I know its modular arithmetic but I'm not sure how I should be dealing with the ${{{3^{3}}^{3}}^{3}}^{...}$. Is there any way to apply Euler's theorem or something? Need a clue... Thanks.
It turns out that $b_n=87$ when $n>2$. In fact, $3^{3^3}=7\,625\,597\,484\,987$ and therefore $b_3=87$. And, by the Euler-Fermat theorem, $3^{40}\equiv1\pmod{100}$. So$$3^{87}\equiv3^7\equiv87\pmod{100}.$$
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "sequences and series, modular arithmetic" }
Compiling/Package a Shoes.app to a standalone Mac.app? Is there a way to package a Shoes.app to a standalone Mac.app?
Shoes maintainer here! There are three ways to package apps with Shoes: 1. Via the GUI option. This is currently broken on OSX. Working on it. 2. Via --shy. This should work. 3. By compiling your app and Shoes together. This is what I do with Hackety Hack. Totally works.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 4, "tags": "ruby, shoes" }
Почему нет правого маргина у красного блока, хотя в блочной модели написано, что правый маргин 10 пикселей? Привет. Вопрос по CSS. Написал разметку: * { margin: 0px; padding: 0px; } #one { width: 100%; height: 100px; margin: 10px; background-color: red; } #two { width: 1500px; height: 100px; background-color: green; } <div id="one"></div> <div id="two"></div> Если это дело открыть в девтулс, то видно это: ![введите сюда описание изображения]( Не понимаю, почему нет правого `margin` у красного блока, хотя в блочной модели написано, что `margin-right: 10px`? Почему нижний и верхний `margin` короткие? Видно, что они не доходят до правого края красного блока. * * * ![введите сюда описание изображения]( В моем примере красный блок вылез за пределы боди и не был обрезан, так как я не задавал `overflow:hidden`
1. Формула горизонтального форматирования для блочного элемента: _width(родителя) = margin-left(потомка) + border-left(потомка) + padding-left(потомка) + width(потомка) + padding-right(потомка) + border-right(потомка) + margin-right(потомка)_ 2. Когда левый _margin-left_ не авто, _width_ не авто и _margin-right_ не авто, то _margin-right_ сбрасывается в ноль, чтобы дополнить нужную длину по формуле. 3. В данном примере нет рамки и паддингов. По этой формуле: 1097 пикселей = 10 пикселей + 1097 пикселей + x x=-10 пикселей, то есть, **правый маргин равен -10 пикселей**. Браузер врет, когда пишет, что правый маргин равен 10 пикселей
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "css, css3" }
View Postgres connection string Is there a way I can view the connection string used by the client to connect to my Postgres instance? Problem: I am connecting to Postgres via jasper and I am setting `prepareThreshold=0` in the connection string to disable prepared statements. I see that it's not being honoured for some reason. So I would like to confirm that jasper is actually passing the setting in the connection string correctly.
You can ask the database server only for information it has. `prepareThreshold` is a setting of the JDBC driver, and the database has no knowledge about it. You can cast the `java.sql.Connection` to an `org.postgresql.PGConnection` and use the `getPrepareThreshold()` method to get the desired information.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "postgresql, jdbc, connection" }
LINQ - filter collection inside collection Let's say I have the following classes: class Parent { bool Gender { get; set; } List<Child> Children { get; set; } } class Child { bool Gender { get; set; } List<Child> GrandChildren { get; set; } } class GrandChild { bool Gender { get; set; } } Using linq, can anyone help me filter a Parent object by returning a `List<Child>` where each Child has `Gender == false` and each Child's GrandChild has `Gender == false`? I've managed to return a `List<GrandChild>` but I really need the hierarchy to be maintained.
Your question is a bit vague. Here's a solution which rebuilds the children and grandchildren lists, I wasn't sure if I needed the child.GrandChildren.All(gc => !gc.Gender) so I left it out for clarity: parents.Select(parent => new Parent { Gender = parent.Gender, Children = parent.Children.Where(child => !child.Gender).Select(child => new Child { Gender = false, GrandChildren = child.GrandChildren.Where(gc => !gc.Gender).ToList() } ).ToList() })
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 5, "tags": "c#, linq" }
How do I tactfully bring up database shortcomings? A little background: I recently inherited responsibility for support and development of a database application after the original developers left. Looking through the application, the database appears to have several... issues. * Weekly shrink and re-index plan * Database account used for web application access has db_owner role * No foreign keys * All tables use GUID column as primary key * Queries built in C# are not parameterized How can I bring these issues up with management? Normally, this should be no trouble, but I have a problem: I have less than six months of SQL experience, whereas the managers and former developers were working on this project for several years.
Ensure you have a mountain of documentation, both of your current system's flaws, and how to fix them. It's no use just saying "everything sucks bad" unless you have a plan, and can show real benefits to the business of making the change.
stackexchange-dba
{ "answer_score": 5, "question_score": 5, "tags": "sql server, security, best practices" }
arduino beginner documentation help I plan to buy these 2 products to begin to play with arduino to learn. 1. Board with LCD touch 2. Yun board expansion I have a mega 2560 which i bought with a starter kit and i love to play with. I have not played with the shield yet. I understand some shields can be used together, some not. and some with modification on the board and in the code. I can't find pins specification for the touch screen and the support on the website doesn't respond. If some one can help me find specifications for the touch screen, or help me choose some shields that will allow me to use a USB host, wifi, and a touchscreen it will be nice. Thanks all.
The link you posted describes a TFT LCD Touch screen unit with the SPFD5408 controller, referenced in this Instructable for use with the Mega. You might start there and migrate to the Yun once you get the screen working.
stackexchange-arduino
{ "answer_score": 0, "question_score": 0, "tags": "arduino mega, shields, arduino yun" }
Create multiple Button with different text in tkinter I was trying to implement some code to produce multiple buttons and at the same time writing different texts on them, for example from a dictionary, is it possible? dict_words={1 : "hello", 2 : "ciao" } for i in range(8): for k,j in dict_words: tk.Button(top_frame, width=20, text=dict_words.values[j], padx=5, pady=5).pack() I am not managing to do this, some help is highly appreciated. Thank you, Cheers
I wasn't sure what you're trying to iterate over using the range. Here's something that iterates over you dictionary, creating a button with the value item of each key-value-pair (kvp). from tkinter import * root = Tk() dict_words = {1 : "hello", 2 : "ciao" } for k,j in dict_words.items(): b = Button(root, width=20, text=j, padx=5, pady=5) b.pack() root.mainloop()
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "python 3.x, dictionary, tkinter" }
Parse through POST I use Stream reader to read `context.Request.InputStream` to the end and end up with a string looking like "Gamestart=true&GamePlayer=8&CurrentDay=Monday&..." What would be the most efficent/"clean" way to parse that in a C# console?
You can use `HttpUtility.ParseQueryString` Little sample: string queryString = "Gamestart=true&GamePlayer=8&CurrentDay=Monday"; //Hardcoded just for example NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring); foreach (String k in qscoll.AllKeys) { //Prints result in output window. System.Diagnostics.Debug.WriteLine(k + " = " + qscoll[k]); }
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 3, "tags": "c#, parsing, post, httplistener" }
Why is attacker revenue in the selfish mining disproportional to its hash-power? It's not clear to me why attacker can gain more revenue if it does "selfish mining" attack than its revenue when it behaves honestly. I'm aware of this paper.
Selfish mining is based on delaying the propagation of the blocks a selfish miner (or pool) has mined. Following such approach, other miners continue mining on the top of an old block, wasting their time and hash power. There are different situations depending on how many blocks a selfish mining pool is able to mine in a row before any other node mines one (all the possible cases are described in the paper you cited). Moreover, selfish mining also requires fast block propagation through the network, since in some of the situations they try to take advantage of other nodes mining on the same block as them, virtually extending the hash power of the selfish mining pool. Block propagation speed matters since when the blockchain forks in two branches of the same length, nodes start mining by default on the top of the first block they hear about.
stackexchange-bitcoin
{ "answer_score": 3, "question_score": 4, "tags": "attack, selfish mining" }
(0.7/0.001)%10 is not returning 0 I am creating a bitcoin based ad platform for a bitcoin learning portal. The reason I mention it is, I believe, it'll help to understand my problem and thereby I may get a better solution. What am I doing is simply passing the amount an user will pay from an HTML form to a PHP page and checking whether it is a multiple of 10. The code snippet is as follows... $orderAmount = $_POST['orderAmount']; $adUnitPrice = 0.001; if((($orderAmount/$adUnitPrice) % 10) == 0) $standardPayment = true; else $standardPayment = false; When I am passing $orderAmount as 0.6 or 0.8, I get the expected return of $standardPayment = true. But, when I am passing $orderAmount as 0.7, I get the unexpected return of $standardPayment = false !!! Can someone please tell me what is the problem and how to fix this ?
bcmath module can help you bcmod(bcdiv("0.7", "0.001"), "10"); // returns 0 in your code $orderAmount = $_POST['orderAmount']; $adUnitPrice = 0.001; if(bcmod(bcdiv($orderAmount, $adUnitPrice), 10) == 0) { $standardPayment = true; } else { $standardPayment = false; } or even $standardPayment = (bcmod(bcdiv($orderAmount, $adUnitPrice), 10) == 0); you can check on command line with `php -m` and look if has the module or write a file with the follow <?php phpinfo(); ?> and look if has enable the module **bcmath**
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "php, bitcoin" }
Correlation and Naive Bayes I would like to ask if the Pearson correlation between fields (but not the class field) of a dataset affects somehow the performance of Naive Bayes when applying it to the dataset in order to predict the class field.
As you probably know, naive here implies that the "fields" are independent. So your question boils down to does correlation imply dependence. Yes, it does. See here. < So, if your features show correlation then this will have an adverse effect on the naive assumption. Despite this fact, Naive Bayes has been shown to be robust against this assumption. If your model still suffers from this, however, you could consider transforming the space to be independent with methods such as PCA.
stackexchange-datascience
{ "answer_score": 4, "question_score": 3, "tags": "predictive modeling, correlation, naive bayes classifier" }
How do I re-enable incoming connections? Over the course of several upgrades, I have been running `monerod` for many months now, and I have always connected to incoming peers. For the last few months, it was always 8+37. After running `git pull`, then backing up my wallet and keys file, then running `make clean`, and then `make`, now when I run `monerod`, my connections are always 8+0. It's been like this for over 24 hours now. Nothing changed with my router, so what might I need to do with my `monerod` config/settings to start accepting incoming connections? If it helps to know, I run `monerod --rpc-bind-ip my.comp's.homenet.ip --confirm-external-bind` (which is the same as I've always run it, though I suppose the `--confirm-external-bind` wasn't needed before) on Ubuntu 16.04.2 LTS, on version v0.10.2.1-1dfed89.
I figured out what my issue was. I checked my `ufw` rules, and there was no rule for allowing port 18080. After allowing that port and reopening `monerod` (not sure if that was necessary), I'm quickly up to 7+44. (@TFI_Charmers, thanks for the push to double check the firewall.) I don't know why ufw allowed it previously, with no rule, but it must have. Nevertheless, it's good to know that it was not a monero issue.
stackexchange-monero
{ "answer_score": 2, "question_score": 3, "tags": "monerod, peer discovery, peer" }
jinja template adds extra line when if condition is not satisfied A `for loop` in my jinja template is like this {% for m in grp %} abc {{ m.length }} pqr xyz {% if m.flag is defined and m.flag == "f" %} yes f {% endif %} {% for r in uv %} abcdef {% endfor %} {% endfor %} Now the problem is in some members of `grp` don't have the `flag` variable. Wherever `flag` is present, the `option true` line is getting added properly. But when if condition is not satisfied, it just adds one blank line. These 4 or 5 lines are supposed to be without extra blank lines otherwise the generated config file gets marked as invalid. Can anyone please help me with this?
Put `{% endif %}` to the next line {% if m.flag is defined and m.flag == "f" %} yes f {% endif %} Whitespace Control might be useful too. > If you add a minus sign (-) to the start or end of a block (e.g. a For tag), a comment, or a variable expression, the whitespaces before or after that block will be removed. {% if m.flag is defined and m.flag == "f" %} yes f {% endif -%}
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "ansible, jinja2" }
pass parameters in reflection C# i have such code Bitmap b = new Bitmap(@"d:\0.bmp"); tessnet2.Tesseract ocr = new tessnet2.Tesseract(); ocr.DoOCR(b, Rectangle.Empty); the i try to make it through reflection Assembly a = Assembly.Load("tessnet2_32"); Type myType = a.GetType("tessnet2.Tesseract"); MethodInfo mymethod = myType.GetMethod("DoOCR"); Object obj = Activator.CreateInstance(myType); mymethod.Invoke(obj, null); how can i pass parameters?
mymethod.Invoke(obj, new object[] { b, Rectangle.Empty });
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "c#, .net, reflection" }
adding timer events with event_base_loop my ebase thread perform the following loop constexpr int kFlag = EVLOOP_ONCE; while ((res = event_base_loop(ebase_, kFlag)) == 1) { yield(); } and the other (main) thread adds periodic timer event. It adds the event _after_ the ebase thread calls `event_base_loop`. event* ev = event_new(base(), -1, EV_PERSIST | EV_TIMEOUT, &PeriodicCb, data); CHECK(0 == event_add(ev, &tv)); However, I see that this timer event does not run. If I change `kFlag` from `EVLOOP_ONCE` to 0 it does run well. What am I missing?
The culprit is in the event base loop. The right code is like this: while ((res = event_base_loop(ebase, EVLOOP_ONCE)) >= 0) { if (start_cancel) break; } i.e. it should continue rolling with return value no less than 0 and not just 1.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "linux, libevent" }
Is O(LogN) == O(3LogN)? I just started a course on Asymptotic Analysis and in one of our assignments I am supposed to add functionality to a function without changing the complexity. The complexity is log(N). The homework guideline asks me specifically to change the runtime by a 'constant'. Would making it 3Log(N) be considered changing it by a constant?
Yes, more specifically, this would be changing it by a multiplicative constant. You could also change it by an additive constant like `log(N)+5`.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "asymptotic complexity" }
Solr Search Query for word must occur after specific position I want to write Solr query for something as below : apple w/5 pear - apple must occur within 5 words of pear How i can achieve the same ? Is their any regex for same ?
This can be done by enclosing the terms in quotations and using a tilde to indicate proximity: `q="apple pear"~5` If just the quotations are present, that is the same as ~0, that is, they should be next to each other.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "solr" }
"which" or "who" after "the work of somebody,"? In the sentence "We refer to the work of Alice and Bob, [] proposed a novel idea of ......". Which word should I use in [], "which" or "who"? Thanks.
**" Which"** is the correct word. "Which" is used to refer to things, whereas "who" is used to refer to people. In this case, we are referring to the **works** of Alice and Bob, _which_ is a **thing.**
stackexchange-english
{ "answer_score": 0, "question_score": -1, "tags": "grammar, word usage" }
Code reading and memory locations short[] foo = new short[45]; assuming that a short occupies 2 bytes and that the array starts at address 5342, which locations does foo[24] occupy? If possible please show how you figure it out and individually list ALL the addresses occupied. This is not homework, i'm asking this because i really don't understand how to do this and it would be a great if i can see the solution so i can study also, is this how i should approach this question, 5342+2*24
after working with a friend i was able to figure out how what to do. the starting address: 5342 short occupied 2 bytes ==> starting address = b+i*s b, base address of array: 5342 i, address of element: 24 s, size in bytes: 2 ==>starting address: 5342 + (24)*2 = 5390 location foo[24] occupied (ALL address occupied) 5390 (1 byte) to 5391 (1 byte) ==> 2 bytes
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, arrays, location" }
flex 3: netconnection - how do i set a timeout? Using flex 3, how do i set a timeout for a NetConnection? code sample: nc=new NetConnection(); nc.addEventListener (NetStatusEvent.NET_STATUS,checkConnect); rtmpNow="rtmpe://host/test/test1"; nc.connect(rtmpNow,fuid,gameName);
Unless you plan to wait for a NetConnection.Connect.Failed, I believe you have to setup your own timeout checks. Using a Timer object, you can check upon Timer.TIMER_COMPLETE whether or not you've received a NetConnection.Connect.Success in your checkConnect function. Can't think of another way to do this.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "apache flex, netconnection" }
Hiding images with same data value jquery Im trying to code a site where the objective is to click on two identical images and it hides the both the images you've managed to match to eachother. $(document).ready(function(){ var animal1; var animal2; $(".memory1").on("click", function(){ animal1 = $(this).data('animal'); }); $(".memory2").on("click", function(){ animal2 = $(this).data('animal'); if (animal1==animal2){ $(this).data('animal').hide(); } else { alert("Wrong, Try again!"); } }); }); so the line where its going wrong is obviously $(this).data('animal').hide(); But I cant figure out a way to hide both images, or a better way of going about it.. :/ <
This doesn't work the way you think it does $(this).data('animal').hide(); When `data` is used with one argument, it get's the data attribute, which you should already know as you're doing it a few lines above. What you get is the string `hund` etc. and that string doesn't have a `hide()` method. You should be using the _attributes selector_ to select the elements with that attribute instead $(document).ready(function () { var animal1, animal2; $(".memory1").on("click", function () { animal1 = $(this).data('animal'); }); $(".memory2").on("click", function () { animal2 = $(this).data('animal'); if (animal1 == animal2) { $('img[data-animal="'+animal1+'"]').hide(); } else { alert("Fel! Försök igen"); } }); });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, jquery" }
How can I avoid performance losses from ResourceFunction? It seems like there is some sort of evaluation overhead related to the `ResourceFunction` wrapper that I'd like to avoid. This is especially pronounced for functions with attributes. Take, for example, `SymbolQ`, which is essentially a wrapper for a built-in function from the `Developer` context: Attributes[mySymbolQ] = {HoldAllComplete}; mySymbolQ[x_] := Developer`HoldSymbolQ[x]; x = 1; ResourceFunction["SymbolQ"][x] // RepeatedTiming mySymbolQ[x] // RepeatedTiming > {0.00068, True} > {5.2*10^-7, True} Is there an easy way to avoid this slowdown without having to copy the source code from the resource function completely?
You can access the local version of the function directly with `ResourceFunction["SymbolQ", "Function"]` to avoid the evaluation semantics associated with `ResourceFunction`. The easiest way to do this, is to "clone" the function into a symbol convenient for you: symbolQ = ResourceFunction["SymbolQ", "Function"]; x = 1; ResourceFunction["SymbolQ"][x] // RepeatedTiming symbolQ[x] // RepeatedTiming > {0.00076, True} > {5.*10^-7, True} This also avoids problems that can occur when you clone the function name naively. See, e.g., this answer.
stackexchange-mathematica
{ "answer_score": 24, "question_score": 14, "tags": "performance tuning, resourcefunction" }