INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Zip list of tuples with flat list I'm wondering if there's an easy way to do the following in Python 3.x. Say I have two lists structured as follows: list_a = [(1,2), (1,2), (1,2), ...] list_b = [3, 3, 3, ...] What's the simplest way to produce a generator (here represented by calling a function `funky_zip`) that would let me iterate through these two lists like so: >>> for a, b, c, in funky_zip(list_a, list_b): >>> print(a, b, c) ... 1 2 3 1 2 3 1 2 3 # and so on I could just do for aa, b in zip(list_a, list_b): print(aa[0], aa[1], b) but I'm wondering if there's a nice way to do this without having to unpack the tuples. Thanks!
You just need parentheses: list_a = [(1,2), (1,2), (1,2)] list_b = [3, 3, 3] for (a, b), c in zip(list_a, list_b): print(a, b, c) Result: 1 2 3 1 2 3 1 2 3
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 5, "tags": "python, python 3.x" }
Is my usage of the word “forthcoming” correct? I truly appreciate your forthcoming by bringing to my notice about the noise I am causing. or I truly appreciate you forthcoming by bringing to my notice about the noise I am causing.
Your sentence is ungrammatical in a couple of respects. **forthcoming** is an adjective that means "candid". So you would have to say > I appreciate you _being_ forthcoming or > I appreciate that you _were_ forthcoming Second, we "bring _something_ to someone's notice". **bring** is a transitive verb that has a direct object, and thus the prepositional phrase "about the noise" is wrong. > ... by bringing the noise I was making to my notice > > ... by bringing to my notice the noise I was making
stackexchange-english
{ "answer_score": 1, "question_score": 0, "tags": "grammar, grammaticality" }
Python Client-Server Script Unit Testing Error I have client and server scripts that serves/reads some data. When i tried to write unit tests with using PyUnit, there raises a error that i cannot reason it. Here is the relevant code snippet: class TestSequenceFunctions(unittest.TestCase): def setUp(self): #some set up operations def testRecieve(self): s = socket.socket() s.connect((FEED_SERVER_HOST, FEED_SERVER_PORT)) sock = socket.socket() #some recieve operations s.close() # When i write this code snippet below, i get error: [Errno 98] Address already in use error. I tried closing 's' socket in tearDown function but still same error raising. def testAnotherRecieve(self): sock = socket.socket() # Results ERRNO 98. As summary, i cannot create second socket in the unittest class. What may cause this error?
Looking at the socket docs for close(), the socket's probably not closed by the time the second test starts up: > close() releases the resource associated with a connection but does not necessarily close the connection immediately. If you want to close the connection in a timely fashion, call shutdown() before close().
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, unit testing, sockets, python unittest" }
How can I deploy to Azure without exposing source code? At my workplace, we have a local git repository. We need to deploy to _Azure_ , but we cannot expose our git repository. Is there any solution to deploying binaries to _Azure_ automatically?
You can go to azure, and in your web app resource in the overview tab you find a button named Get publish profile ![enter image description here]( You can then go to visual studio. On the top menu if you click on Build, the scroll down menu have an option named Publish <"Your project name"> There you load this file and you can deploy directly to your Azure App from your machine without exposing the source code. If you want to automate your deployment you can use a custom deployment script You could also find useful the microsoft documentation page on Local Git deployment to Azure App Service
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "azure" }
How to show the grand total of a column in repeater control of asp.net using C# and SQL I am a beginner in asp.net so I am developing a software in which I want to sum up the the column of total price e.g I have 1,2,3(these values are coming from SQL database) values in total price column and I want to sum up these values (as the result after summing up them is 6) and show the grand total of this column in the footer template of repeater control. I am very grateful if somebody tells me. Thankyou!
int total = 0; protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item) { //using findcontrol method the label and get the amount total += Convert.ToInt32(((Label)e.Item.FindControl("ltrlAmount")).Text); // } else if (e.Item.ItemType == ListItemType.Footer) { Label lbl = (Label)e.Item.FindControl("Label1"); lbl.Text = total.toString(); //set value } }
stackexchange-stackoverflow
{ "answer_score": -1, "question_score": -3, "tags": "c#, sql, asp.net" }
Can a function argument be multiply typed? I'm fairly sure the answer is no, but since it would be quite lovely, I'll ask the question anyway. Example: class Serializable { public: virtual void serialize() = 0; }; class Unserializable { public: virtual void unserialize() = 0; }; class A : public Serializable { public: virtual void serialize() { } }; class B : public A, public Unserializable { public: virtual void unserialize() { } }; Now, is there some way to create a function with one argument that is _both_ an instance of Serializable **and** Unserializable such that an object of class B could be passed (without, of course, referencing the derived type B)? Something like: void readAndWrite(Serializable_Unserializable& object);
The template way: template <typename T> std::enable_if_t<std::is_base_of<Serializable, T>::value && std::is_base_of<Unserializable, T>::value> void readAndWrite(T& object)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "c++, function, class" }
value turned const in lambda capture? I have this simple code: std::shared_ptr<std::string> s; auto bla = [s]() { s.reset(); }; What I meant this to do is that the shared_ptr be captured by the lambda and then reset once the lambda is called. Compiling this with VS yields the following error: `error C2662: 'void std::shared_ptr<std::string>::reset(void) noexcept': cannot convert 'this' pointer from 'const std::shared_ptr<std::string>' to 'std::shared_ptr<std::string> &' 1>...: message : Conversion loses qualifiers` What gives? How come the `shared_ptr` turns to `const shared_ptr`?
When capturing by copy, all captured objects are implicitly `const`. You have to explicitly mark lambda as `mutable` to disable that: auto bla = [s]() mutable { s.reset(); }; Also, if you want to reset actual `s` and not a copy, you want to capture by reference. You don't need `mutable` when capturing by reference, in this case constness is inferred from the actual object: auto bla = [&s]() { s.reset(); };
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "c++, lambda, shared ptr, capture" }
Difference between だの and など/とか I'm reading an old book ( by ) and there's an unfamiliar grammatical phrasing that has fallen out of fashion and/or that he was rather fond of: ~~, e.g.: **** **** The dictionary I use suggests it's similar to / in meaning&usage. Are there any important differences?
There indeed exists a fairly important difference between and the other juxtaposition structures such as , etc. The difference is that would generally imply the speaker's negative feelings about the items being juxtaposed all by itself **_even without using further negative words around it_**. The other forms of juxtaposition do not carry either a positive or negative connotation all by themselves. That value judgement would need to be expressed with other wordings around them. **To put it in the simplest terms possible, you are complaining about something 95% of the time you use .** By "negative feelings" in this case, I am referring to juxtaposing: 1) worthless items or statements by the speaker's judgement (I did not mention juxtaposing statements above but it is a feature of the form.) 2) unrealistic and/or unsubstantial items by the speaker's judgement In OP's example, the part of alone already expresses the speaker's negative feeling, IMHO.
stackexchange-japanese
{ "answer_score": 6, "question_score": 3, "tags": "word usage" }
Chrome Custom Tabs hide address bar I am developing a widget that customers can integrate into their apps. Their users must authenticate themselves (via OAuth). Therefore, it's preferable that my customers use Chrome Custom Tabs so that the user is likely logged in with the OAuth provider (eg. Facebook). Is there some way to hide the address bar for a Chrome Custom Tab? The URL isn't really relevant to the end user.
No, there is no way to hide the address bar. It is critically important for the user to be able to tell which authority they are talking to when they are visiting a website, in particular when they are authenticating. This saves a lot of users from phishing.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 4, "tags": "chrome custom tabs" }
Button in UITableViewCell — identify cell when button is pressed in prepareForSegue Sorry for the long title! The issue here is pretty simple and it's something that I don't have a workaround for — well unless I write redundant code and GUI stuff. Consider two UITableViewCells that have the same cell identifier — basically they look the same but have different kinds of data. Consider the Apple Store app. In the featured section — you have 'Best Games' and 'Best Apps' tableview cells. They both have a 'See All' option. This is pretty similar to what I have. **I wish to identify from which cell was this 'See All' button pressed.** (Considering, I have a single segue going to another view controller when either of the 'See All' buttons are pressed.) Note: I don't want to make another UITableViewCell. I can but I don't want.
-(void)yourButtonPressed:(id)sender { CGPoint hitPoint = [sender convertPoint:CGPointZero toView:tableView]; NSIndexPath *hitIndex = [tableView indexPathForRowAtPoint:hitPoint]; NSLog(@"%i",hitIndex.row); } This is the best way to get " the button's row "
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "ios, uitableview, segue, uistoryboardsegue" }
Is it possible in kotlin serialization without using intermediate options to immediately convert Map <String, Any> to a model This case is in the JS version (Properties.decodeFromMap (map)), but for android, I have not seen. It can also be solved using Jackson The object in which I should get a rather complex type, the approximate form of the fields is much larger data class BaseModel (val value: String,val options: Options,val type: Type ...) The main thing I need to get directly from `Map <String, Any>` in BaseModel
I think it's better to use the properties from the kotlinx-serialization-properties package, it turns out that it is also distributed for android
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "android, kotlin, serialization" }
php Mockery throwing unexpected "must implement interface" exception when function method is typehinted I'm using Mockery to unit test an admittedly edge case. It's failing and I don't think it should fail, so there could be a bug within Mockery. Consider an object that has a method. The method has an argument signature where the first argument is typehinted and defaults to null. The second argument does not have a default. When the method is called on the object with null as first argument, it works fine. When the method is called on a Mocked object with null as the first argument, it fails. Please see sample code here: <
Turns out it was a bug. References: * < * <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "php, mockery" }
Preprocessing audio in android Speech Input recognizer I'm doing some basic command recognition and using Google Search Input API for that. However I want to capture audio myself, preprocess the audio (denoise, boost amplitude, etc), send those modified audio to the recognizer and obtaining results. Is it possible? I know you can use `SpeechRecognizer` along with `RecognitionListener` to obtain audio using `onBufferReceived` method. However I want to do preprocessing instead of postprocessing. Is there any workaround/hack to feed google recognizer with processed data?
> preprocess the audio (denoise, boost amplitude, etc), send those modified audio to the recognizer and obtaining results Usually speech recognition systems suffer from this. Incorrectly implemented denoising can lower speech recognitoin accuracy because it corrupts spectrum in unpredictable way. Amplitude boosting doesn't help because amplitude is normalized on the very beginning of speech recognition. Your preprocessing can only hurt. If you still want to try it, try pocketsphinx <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android, speech recognition, audio processing" }
Google Sheets linking two sheets using a primary key I have two sheets that I want to link using a "primary key". At the moment, I have imported from sheet1 into sheet2 some columns using the function **`=Sheet1!A1`** (for the first cell for instance). My purpose is to complete the data related to each imported line in sheet2. However, sheet1 is shared with other people, thus they can modify the content of a line without deleting or modifying the data I have added in sheet2 (and that doesn't exist in sheet1). Given the fact that my table has a column 'id' that can be considered as a primary key, how can I add new data in sheet2 in so far as it will be related to the 'id' rather than the position of the line (so if I ever change an id in sheet1 the data I added will be deleted or if I move an id to another line, all the data will be moved too)?
you can use `VLOOKUP` and bring over data based on ID, like: =ARRAYFORMULA(IFERROR(VLOOKUP(D:D, Sheet1!A1:B, 2, 0),)) ![]( * * * for more columns add them in an array: =ARRAYFORMULA(IFERROR(VLOOKUP(D:D, Sheet1!A1:B, {2,3,4,5}, 0),)) **demo spreadsheet**
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "arrays, google sheets, vlookup, flatten, google query language" }
Progress bar show only in debug mode. Job plus asynch Display Job job = new Job("Initialize Info ") { @Override protected IStatus run(IProgressMonitor monitor) { //some action in job thread Display.getDefault().asyncExec(new Runnable() { @Override public void run() { // //different actions with UI components. } }); return Status.OK_STATUS; } }; job.schedule(); When I run application in debug mode then progress bar is correctly displayed and all UI components waiting for a job. But in release mode UI components still waiting for a job but progress bar doesn't reflect. What is the reason?
You don't need to run `asycExec`. try use `UIJob`: `The UIJob is a Job that runs within the UI Thread via an asyncExec.` like this: Job job = new Job("") { @Override protected IStatus run(IProgressMonitor monitor) { monitor.beginTask("Task..." -1); // do what i need to do (and doesn't bother my UI) return Status.OK_STATUS; } }; job.setUser(true); job.schedule(); job.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { new UIJob("") { @Override public IStatus runInUIThread(IProgressMonitor monitor) { // Update my UI monitor.beginTask("UI Task..." -1); return Status.OK_STATUS; } }.schedule(); super.done(event); } });
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, swt, eclipse rcp" }
Error 000204 using "Export Feature Attribute to ASCII" Tool on ArcGIS Server 10 I´m trying to export feature attributes to a CSV-File (on ArcGIS Server) to use them in other applications (using the "Export Feature Attribute to ASCII" Tool). While the tool is working ok in a Desktop environment the published model always fails with the following error message: ERROR 000204: Error creating input feature cursor I have no idea how to deal with that or what might be the problem. Any suggestions? Any help would be highly appreciated.
Don´t really know why, but when I changed the "Delimiter" from "SEMI-COLON" to "SPACE" it suddenly worked. Once it worked, I changed it back to "SEMI-COLON" and guess what..... it keeps on working! Isn´t this a strange world??
stackexchange-gis
{ "answer_score": 0, "question_score": 1, "tags": "arcgis server, geoprocessing, export, csv, ascii" }
Actions On Google with TypeScript: How to start? I'm using the Actions Console. When invoking my action with "HookIntent" I always get: { "error": "No intent was provided and fallback handler is not defined." } My index.ts: import * as functions from 'firebase-functions' import { dialogflow } from 'actions-on-google' const app = dialogflow({debug: true}); app.intent('HookIntent', (conv) => { const response = "Hello Test" conv.add(response) }) exports.playMusicFunction = functions.https.onRequest(app); Json: { "handler": { "name": "HookIntent" }, "intent": { "name": "HookIntent", ... I cannot find any working example with typescript. All examples and trainings from google are with Javascript.
I'm going to agree with Jordi in the comments you should instead use `@assistant/conversation` and refactor a bit of your code to use the Actions Builder platform webhook. import * as functions from 'firebase-functions' import { conversation } from '@assistant/conversation' const app = conversation({debug: true}) app.handle('HookIntent', (conv) => { const response = "Hello Test" conv.add(response) }) exports.playMusicFunction = functions.https.onRequest(app)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "typescript, actions on google" }
How can I make nautilus-gsku work in 11.10? I have installed `nautilus-gksu` on 11.10, but it isn't working. How can I make the "Open as administrator" option appear in the context menu?
This is a known bug (link?) and there is a workaround for it: * Copy the old extension into the Nautilus 3 extensions folder with the following command: sudo cp /usr/lib/nautilus/extensions-2.0/libnautilus-gksu.so /usr/lib/nautilus/extensions-3.0/ * Then restart Nautilus: * From the command line with killall nautilus * or, log out and log back in
stackexchange-askubuntu
{ "answer_score": 1, "question_score": 2, "tags": "nautilus, gksu" }
C# Check if List contains a custom object with the same value I have a custom object (the properties must be strings): public class Nemesis { public String Dex_ID; public String Value; } I have a certain function, which creates new instances of that object, adds values to them and then adds them to this List: private List<Nemesis> _nemesisList; public List<Nemesis> NemesisList { get { return _nemesisList; } set { _nemesisList = value; } } Normally, I'd use this to check for existing things: if (!NemesisList.Contains(nemesis)) { NemesisList.Add(nemesis); } But this time I want to check if my List already contains a **nemesis** with the same **nemesis.Dex_ID**. How do I do that?
If you only want to to check against the the ID field and ignore others then you can do : if(!NemesisList.Any(n=> n.Dex_ID == nemesis.Dex_ID)) otherwise if you want to perform comparison for all the fields then you can override `Equals` and `GetHashCode`. See: Correct way to override Equals() and GetHashCode()
stackexchange-stackoverflow
{ "answer_score": 21, "question_score": 14, "tags": "c#" }
SL asynchronicity at startup... Strategies? I'm far from new at threading and asynchronous operations, but SL seems more prone to asynchronous issues, particularly ordering of operations, than most frameworks. This is most apparent at startup when you need a few things done (e.g. identity, authorization, cache warming) before others (rendering a UI usable by your audience, presenting user-specific info, etc.). What specific solution provides the best (or at least a good) strategy for dealing with ordering of operations at startup? To provide context, assume the UI isn't truly usable until the user's role has been determined, and assume several WCF calls need to be made before "general use". My solutions so far involve selective enablement of UI controls until "ready" but this feels forced and overly sensitive to "readiness" conditions. This also increases coupling, which I'm not fond of (who is?).
One useful aspect of Silverlight startup to remember is that the splash xaml will continue to be displayed until the `Application.RootVisual` is assigned. In some situations (for example where themes are externally downloaded) it can be better to leave the assignment of the RootVisual until other outstanding async tasks have completed. Another useful control is the `BusyIndicator` in the Silverlight Toolkit. Perhaps when you are ready to display some UI but haven't got data to populate the UI you assign the RootVisual using a page that has a `BusyIndicator`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "silverlight, silverlight 4.0, asynchronous, startup" }
Geometry Nodes Scaling Issue I am having an issue with "Instance To Points" causing unwanted scaling and rotation of an object. These are tiny "supports" for a neon sign. ![Issue]( Here are the Geometry Nodes: ![Geometry Nodes]( Any help would be greatly appreciated!
you can scale your instances by adding a scale instance like this: ![enter image description here]( result: ![enter image description here]( but now you have more a positioning than a scaling issue... ;) > Note: Normally you should apply your scale before using them because it prohibits a lot of trouble. You didn't apply the scale to your stand. Just select your stand, hit ctrl-a -> scale. Now you won't need the scale instances node ;)
stackexchange-blender
{ "answer_score": 1, "question_score": 1, "tags": "cycles render engine, transforms, geometry nodes" }
Making the right side of divs line up instead of the left I have 2 divs, one on top of another. You see how the left side of the red bordered div is lined up with the left side of the blue bordered div? My question is, is there a way to make the right side of the red bordered div line up with the right side of the blue bordered div? #top { border: 1px solid red; display: inline-block; } #bottom { border: 1px solid blue; width: 25%; display: block; } <div id = 'top'> top </div> <div id = 'bottom'> bottom </div>
Yes, you can have a container and float the elements inside to the right: #top { border: 1px solid red; display: inline-block; float: right; } #bottom { border: 1px solid blue; width: 25%; display: block; clear:both; float: right; } #container { width: 50%; } <div id="container"> <div id = 'top'> top </div> <div id = 'bottom'> bottom </div> </div>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, jquery, html, css" }
installing iTunes Hi guys I’m newbie in Ubuntu world! So guys I’m running Ubuntu 14.04 / 64bits, and I installed iTunes 64 bits version 10.7.0 using wine! While trying to run iTunes I always get this error: Itunes was not properly installed. If you wish to import or burn CDs you need to reinstall iTunes. Then when I click Ok, I get this screen::!enter image description here I tried to run: sudo apt-get update in the terminal, didn't work I also tried to restart my laptop didn't work either. I need help to make it work properly so that I can connect my idevices. Thanks in advance
iTunes is generally considered not to work well under Wine. The default version of Wine in 14.04 is 1.6.2 so you could try upgrading to the PPA development build... But I doubt that'll fix much. I certainly wouldn't try to use it to manage hardware. In my opinion, that is inviting an expensive disaster. * * * The only real alternative I have is running a real copy of Windows in a virtualisation solution like VirtualBox or VMWare. These can pass-through USB devices to let the virtualised software manage them. In my experience this works pretty well but it's fairly slow.
stackexchange-askubuntu
{ "answer_score": 2, "question_score": 0, "tags": "wine" }
Why are interfaces in Java called that way? I have been a developer for past 3 years and I have been seeing `interface` in most of the places as a contract for the developers to write their own implementation or a marker (eg. `Serializable`). But I quite dont understand how this concept is named as INTERFACE in literal meaning. Am I missing something pretty basic?
Interfaces are the points in our world that describe how things interact with _each other_. User interfaces let users interact with applications, machines, and so on. In programming interfaces are to be understood as the pre-defined interaction surface between two pieces of a program, or even multiple programs (hence API). Interfaces are, of course, different in all programming languages but usually they operate on the same principle.
stackexchange-softwareengineering
{ "answer_score": 8, "question_score": -6, "tags": "java, object oriented, interfaces" }
NaN different from NaN in Go? Can anyone explain why this happens? < _Apologies for not pasting the code here as well but I'm on mobile ATM._ I know I could use math.IsNaN() but I'm using the comparison operator for all my tests cases.
Generally, `NaN` is not considered equal to _any_ number, including itself. That's because it represnts a number outside the range of representation. Hence there's no guarantee that you don't have two _different_ numbers outside the representation, such as `0 / 0` and the square root of -1. In fact, many systems rely on this inequality to implement `isNan()` as something like: define isNaN(x): return x != x From the NaN Wikipedia page, IEEE 754 defines that: * `−∞ = −∞`, * `+∞ = +∞` and * `x ≠ NaN` for any `x`, including `NaN`.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 3, "tags": "go" }
Filling an empty dataframe by assignment via loc selection with tuple indices Why does this work? a=pd.DataFrame() a.loc[1,2]=0 > 2 1 0.0 And, this does not work? a=pd.DataFrame() a.loc[(1,2),2]=0 > KeyError: '[1 2] not in index' The latter is what I would like to do. I will be filling the values by assignment via loc selection with tuple specified index, from a dataframe with no values, 0 rows, 0 columns.
Using a tuple as index will work if your dataframe already has a multi-index: import pandas as pd # Define multi-index index = pd.MultiIndex.from_product([[],[]], names=['first', 'second']) # or # index = pd.MultiIndex.from_tuples([], names=['first', 'second']) a = pd.DataFrame(index=index) a.loc[(1,2), 2]=0 # 2 # first second # 1.0 2.0 0.0
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "python, pandas, dataframe, assign" }
Best way to say that I have never heard about some action How to correctly say that _I have never heard she speaks English_ (I am not sure she knows English)? I used a Present Perfect in the first part to say that the action takes place from the moment when I have heard her for the first time to the moment of speaking. And then I am not sure which tense should I use to describe the second part of the sentence. Should I use **Present Simple** or the other one? I am thinking in this way: we can use Present Simple to say she was speaking English all her life, but what if she didn't with me (in this case we should only take that interval from our meeting to the present, right?)? How do I plot the second part on the timeline? ![Timeline diagram](
There are different ways that you can say someone _can do_ something in a variety of tenses, for example: * He can drive. * He drives. * I didn't know he drove. * I didn't know he could drive. * * * Looking at your example, " _I have never heard she speaks English_ " is not grammatically correct. The most idiomatic ways to say this would be: * I didn't know she spoke English. * I never knew she spoke English. But you could also say: * I wasn't aware that she could speak English. * Nobody told me she speaks English. "I never knew" means that you did not know _up until this point_ , so that would cover everything on your timeline from the past until the present. It is tacit in the explanation that you now know.
stackexchange-ell
{ "answer_score": 1, "question_score": 0, "tags": "sequence of tenses" }
Software to record hot end temperature? Is there a software package that when I have my printer connected directly to my PC via USB could record and export hot end temperature data overtime? Ideally this data would be recorded in a way that I could export it and manipulate it in the likes of Excel. E.g. I see Pronterface has a temperature graph but it doesn't seem possible to export this. I know Simplify3D has a temperature plot in the machine control panel, anyone know if you can export from this?
I don't know if using OctoPrint is an option. If so, there is a plugin that claims to do exactly this. And you could probably find a few more if you looked for them. Note that I have no first hand experience with this plugin, but I can vouch for OctoPrint being convenient and by default it shows a temperature graph. It might even be relatively easy to write your own plugin to accomplish this. This will mostly depend on your comfort with coding in Python/JavaScript. As a sidenote: if your printer is connected directly to your computer via USB, chances are pretty high it is a simple serial connection. Having multiple programs use this connection at once is not possible as far as I know. This implies that you will not be able to have your current software send it G-code lines while having another one recording the temperature values sent back from the printer.
stackexchange-3dprinting
{ "answer_score": 3, "question_score": 2, "tags": "software" }
remove admin user vesta panel Ubuntu So I recently uninstalled Vesta Panel in my Ubuntu VPS, and it said "You might also consider to delete admin user account and its cron jobs." Now that I want to reinstall Vesta is says "Error: User admin already exists Please remove admin user account before proceeding" How would I got about removing the admin user account after I've already uninstalled Vesta? Thanks!
`sudo userdel [useraccount]` Followed by `sudo rm -rf /home/useraccount` Followed by `vi /etc/crontab` and inspecting /etc/crond.d for cron jobs are left behind that need to be removed.
stackexchange-serverfault
{ "answer_score": 2, "question_score": -5, "tags": "ubuntu, vps" }
Random String in PHP Hello i want to generate random string in php with repetition like Ag7hlA. is there anyway to do it i am trying this <?php function random_string($length) { $length = (int) $length; if ($length < 1) return ''; $base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789"; $max = strlen($base) - 1; $string = ''; while ($len--) { $string = $base[mt_rand(0, $max)]; } return $string; } ?> But the random string is not being generated
function generateRandomString($length = 10) { $char = 'abcdefghijklmnopqrstuvwxyz'; $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $char[rand(0, strlen($char) - 1)]; } return $randomString; } if u want add numbers too, than the `$char` will be---> $char = 'abcdefghijklmnopqrstuvwxyz1234567890'; and if capital cases---> $char = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "php, javascript" }
Visual Studio Code Track Changes For all CSS, JavaScript and HTML modifications on pages that are handled through Visual Studio Code, is there a way to track changes? I'm looking through the application settings, but failing to see anything OOTB that enables this...
If you integrate any version controlling tool (TFS, Git etc.) with VS Code, it starts to track changes on files. Visual Studio Code version control documentation.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "visual studio code" }
list variables to individual data.frames Let's say I have a `list` of 30 `data.frames`, each containing 2 variables (called **value** , and **rank** ), called `myList` I'd know I can use my.DF <- do.call("cbind", myList) to create the output `my.DF` containing all the variables next to each other. It is possible to `cbind` each variable individually into it's own `data.frame` i.e to just have a new `data.frame` of just the 2nd variable?
We can extract the second column by looping over the `list` (`lapply`) and wrap with `data.frame`. data.frame(lapply(myList, `[`, 2)) If we want to separate the variables, lapply(names(myList[[1]]), function(x) do.call(cbind,lapply(myList, `[`, x))) ### data set.seed(24) myList <- list( data.frame(value=1:6, rank= sample(6)), data.frame(value=7:12, rank=sample(6)))
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "r, list, do.call" }
With SBT, how do I a specify an alternate project root other than the current directory for running a main class? Normally SBT looks for the build files at `./build.sbt` and `./project/Build.scala`. Is it possible to specify an alternate project root, so I can build a project not in the current working directory? I'm looking essentially for an equivalent to `mvn -f /path/to/pom.xml` but the docs have not provided me with any obvious answers. (I should note that I want to do this at runtime rather than compile time. Essentially, I want to use `sbt run-main` to run arbitrary classes from my project, since I **hate** manual classpath wrangling. For various boring reasons I may need to do this from arbitrary location since the code may need the working directory to be something other than the project directory, so using `cd` might not do what I want. It's so trivial in Maven - I just assumed, perhaps unfairly, that there would be a simple equivalent in SBT)
As I discovered from this other answer, the sbt-start-script plugin is a better tool for this than `sbt run-main`. You can simply run `sbt stage` and you get an invocation script, with classpaths resolved, at `target/start`. According to the documentation, it needs to be run from the build root directory for inter-project dependencies to work, but for my simple use cases, this doesn't seem to be a problem.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 3, "tags": "sbt" }
Public property not subclassable Is there a way to prevent a class's public @property from being available to subclasses of that class? Currently, I have a class and its subclass. The subclass uses a lot of its parents properties, but there are a few properties that I want only the parent to own: to the point that the subclass wouldn't even be able call upon these restricted properties when writing code. Long story short, this would make using the class & any of its subclasses "safe". Is it remotely possible?
You make a property private by declaring it in .m file @interface ClassName () @property (nonatomic, strong) NSArray *myproperty; @end @implementation ClassName @synthesize myproperty;
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "objective c" }
Azure AKS pull image from Azure Container Registry I have an Azure AKS cluster on which i'm trying to deploy a custom image that I have pushed to Azure Container Registry. I have created a Service Principal and with that SP I have created my AKS. This SP also has Read Access on my ACR as described in below article: < However my pods are not being created but give the message "Back-off pulling image" Am I missing something?
Seems like I was trying to use windows containers which is not yet supported on Azure AKS. Switched to linux image and worked fine
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "azure container service, azure container registry" }
Filling NaN in a DataFrame Column with Key from a Dictionary by looking up values from a different column I have a dataset that looks like: > Country Code > 'Bolivia' NaN > 'Bolivia, The Republic of' NaN And I also have a dictionary > CountryCode = {'BOL':['Bolivia','Bolivia, The Republic of']} How do I go on about fillna in the dataframe with the respective Key if one of the values is in the dictionary? The desired output is > Country Code > 'Bolivia' 'BOL' > 'Bolivia, The Republic of' 'BOL' Thanks for your help!
Create reverse dictionary of `CountryCode` and `map` it with `Country` column: new_countrycode = {v:key for key,value in CountryCode.items() for v in value} df['Code'] = df['Country'].map(new_countrycode) print(df) Country Code 0 Bolivia BOL 1 Bolivia, The Republic of BOL print(new_countrycode) {'Bolivia': 'BOL', 'Bolivia, The Republic of': 'BOL'}
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, pandas, dictionary" }
onBlur event function needed for my project I need help on javascript code for a project. When a field(A) input value is onblur, I want a situation where the value will pass to an external php file (external.php) and the result computed in the backend external php file (external.php) should the value of another disabled input field(B). Putting in mind the for the internal HTML form action is (index.php).
<input type="text" name="inputA" onBlur="inputA();" id="spend" /><span id="feedback"></span> <input type="text" name="inputB" id="receive" disabled="true"/> <script type="text/javascript"> function inputA(){ var xhr = new XMLHttpRequest(); xhr.open('GET',' xhr.send(null); document.getElementById['feedback'].InnerHTML = xhr.responseText; } </script>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -4, "tags": "javascript, php, jquery, ajax" }
Как поменять строки местами? Помогите, пожалуйста, реализовать следующую программу: > Необходимо подавать строки на вход по очереди, а по завершению подачи строк, они должны быть выведены в обратном порядке. Собственно два вопроса: 1. Можно ли как-то по-другому реализовать выход из циклического ввода, кроме как по слову? 2. Как можно поменять строки местами? Вот мой кусочек кода: a = '' while True: l = input() if l == 'end': break else: a += l + '\n' print(a) Заранее большое спасибо!
1. > Можно ли как-то по-другому реализовать выход из циклического ввода, кроме как по слову? Обычный подход — тест на пустую строку (пользователь уже не задает ничего, только нажмёт клавишу `Enter`). 2. > Как можно поменять строки местами? Методом `.reverse()` списка — значит, надо сделать из заданных строк их список. * * * Всё вместе: PROMPT = 'Введите очередное слово (или только нажмите клавишу Enter для окончания)' lst = [] while True: word = input(PROMPT).strip() # strip() удалит пробелы перед/за вводимым текстом if word: # не надо «word == ''», но может быть lst.append(word) else: break; lst.reverse() for word in lst: print(word)
stackexchange-ru_stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "python 3.x" }
iptables “host/network not found” If I add this line to my `iptables`: `-A INPUT -s /32 -i tcp -p tcp -m tcp --dport 22 -j DROP` I get the error: `iptables-restore v1.4.14: host/network`' not found` When running: `sudo iptables-restore /etc/network/iptables` Is there a problem with that line? If not, I will post the rest of the iptable configuration. **complete configuration** : *filter :INPUT DROP [23:2584] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [1161:105847] -A INPUT -i lo -j ACCEPT -A INPUT -i eth0 -p tcp -m tcp --dport 80 -j ACCEPT -A INPUT -i eth0 -p tcp -m tcp --dport 443 -j ACCEPT # -A INPUT -s /32 -i tcp -p tcp -m tcp --dport 22 -j DROP -A INPUT -s 192.168.0.10/24 -j ACCEPT -A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT -A INPUT -i eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT COMMIT copied from here
There is a problem with that line, specifically the `-s /32` portion. You have to define a host. For example: -A INPUT -s 123.45.67.8/32 -i tcp -p tcp -m tcp --dport 22 -j DROP
stackexchange-serverfault
{ "answer_score": 3, "question_score": 1, "tags": "linux, iptables" }
How are these types differentiated? I read here @ java.sun that _`int[] iarr`_ is a primitive array and _`int[][] arr2`_ is a object array. What is the difference between a primitive type and an object type ? How are the above two different from each other ?
`int[]` is a primitive array because it contains elements of primitive type `int`. Every array itself is Object, so array of primitives is object too. `int[][]` is a array of `int[]`, i.e. each element of `int[][]` contains array of integers. But since array is a object `int[][]` contains objects, not integers.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "java, primitive types" }
Flutter How to not show the [] Brackets of a list when being displayed as a text? I am trying to display a list rendered in text. But when I do I see the [] I have tried the following. Text(hashList.toString().replaceAll("(^\\[|\\])", "")) Brackets are still there.
You can do it like this Text(hashList.join()) or you can use a delimiter Text(hashList.join(','))
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "flutter, dart" }
Max-height with Quill rich editor I try to set the `max-height:200px` CSS property to the Quill rich editor. I would like a scrollbar to appear when the entry is more than 200px. As you can see on the following JSfiddle, it is not working properly: < On GitHub, the Quill founder say it should work : < Any idea what I'm doing wrong?
Add `overflow: auto;` in your CSS, it will add the scrollbar.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "css, quill" }
Importing crude oil prices from WolframAlpha WolframAlpha has knowledge of crude oil prices, as a simple query will show. I am trying to obtain this data for use in Mathematica but I am not able to figure out the input. If I try FinancialData["SC.NYMEX"] The result is that this is not a known entity. Do I need to find another source or is there a simple way to access historical prices for the past 10 years directly from the Wolfram database ?
You can import the prices from the Energy Information Administration. RCLC1d = Import[" c1 = RCLC1d[[2, All, {1, 2}]]; c1prices = Cases[Drop[c1, 3], {_, _?NumberQ}]; DateListPlot[c1prices, Joined -> True, PlotLabel -> "WTI Oil Price since " <> DateString[ c1prices[[1, 1]], {"Day", " ", "MonthNameShort", " ", "Year"}], FrameLabel -> {None, Style["$", Large]}, RotateLabel -> False] ![enter image description here](
stackexchange-mathematica
{ "answer_score": 4, "question_score": 3, "tags": "wolfram alpha queries, databases" }
gnu-parallel encrypting files with spaces or special characters? I'm trying to encrypt a bunch of files with the code below: find . -name "*.vi" | sort | parallel --gnu -j 4 --workdir "$PWD" ' echo "Encrypting {/.} ..." gpg -r [email protected] -o "/tank/test/{/.}.gpg" -e "{}" '; This works fine, but only if the filenames have no spaces nor special characters (! or ') in them. Other than re-naming all the files, is there a way to make this code work?
It looks like too much quoting. Remember that GNU Parallel assumes {} is being parsed directly by the shell. Try removing "" around {} and {/.}: # Avoid typing --gnu ever again echo '--gnu' >> ~/.parallel/config find . -name "*.vi" | sort | parallel echo Encrypting {/.} ...";" gpg -r [email protected] -o /tank/test/{/.}.gpg -e {}
stackexchange-superuser
{ "answer_score": 2, "question_score": 2, "tags": "linux, gnu parallel" }
$f \in\mathcal{C}(K,\mathbb{R})$ implies $f(\overline{E})\subseteq\overline{f(E)}$ for every $E\subseteq\mathbb{R}^{n}$ s.t $\overline{E}\subseteq K$. Show that if $f \in \mathcal{C}(K,\mathbb{R})$, then $f(\overline{E}) \subseteq \overline{f(E)}$ for every subset $E$ of $\mathbb{R}^{n}$ that satisfies $\overline{E} \subseteq K$. My attempt is: Let $f \in \mathcal{C}(K,\mathbb{R})$ and $y \in f(\overline{E})$. That implies there exists $x \in \overline{E}$ such that $y =f(x)$. Let $U$ be an open set of $\mathbb{R}$ such that $y \in U$. By definition of continuous function, $f^{-1}(U)$ is an open set of $K$ such that $x \in f^{-1}(U)$. Therefore, $f^{-1}(U) \cap E \neq \emptyset$ as $x \in \overline{E}$. Therefore, $\emptyset \neq f\left ( f^{-1}\left ( U \right )\cap E \right ) \subseteq U \cap f(E)$. That is, $f(\overline{E}) \subseteq \overline{f(E)}$. I would like to know if there is any mistake in my reasoning. Thanks.
Your reasoning is correct. Another proof (which doesn't rely on any specifics of the topology of $\mathbb{R}^n$, and thus applies whenever $f : X \to Y$ is a function between any two spaces): Consider that $f(E) \subseteq \overline{f(E)}$, and therefore $E \subseteq f^{-1}(f(E)) \subseteq f^{-1}(\overline{f(E)})$. Now since $f$ is continuous and $\overline{f(E)}$ is closed, we have $f^{-1}(\overline{f(E)})$ is closed. Therefore, $\overline{E} \subseteq f^{-1}(\overline{f(E)})$. Then we have $f(\overline{E}) \subseteq f(f^{-1}(\overline{f(E)})) \subseteq \overline{f(E)}$.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "real analysis, calculus, general topology" }
anything wrong with using a solid state relay to trigger a magnetic relay? !schematic simulate this circuit - Schematic created using CircuitLab I'm thinking to use a MOSFET solid state relay triggered by a MCU to trigger a micro magnetic relay. I will be using a sufficiently rated flyback diode at the magnetic relay. This doesn't seem to be commonly done. My reason is that high current solid state relays are way more costly than a low current SSR and a micro magnetic relay together. Is there any reason to not do this? EDIT - added schematic
This circuit is fine: - ![enter image description here]( Choose a MOSFET that has a low enough gate-source threshold voltage to ensure that at the logic drive voltage, the MOSFET adequately turns on.
stackexchange-electronics
{ "answer_score": 2, "question_score": 0, "tags": "mosfet" }
How would you reduce this array? (Read description for more info) My mind is boggled, maybe because i've been stuck on this issue for a bit. I have an array (redacted for readability): variants = [ {title: 'color', children: [{title: 'red'}, {title: 'blue'}] {title: 'size', children: [{title: 'large'}] ] But need the following output: variants = [ 'color/red/size/large', 'color/blue/size/large', ] or if the initial array is: variants = [ {title: 'color', children: [{title: 'red'}, {title: 'blue'}] {title: 'size', children: [{title: 'large'}, {title: 'medium'}] ] the new array would be: variants = [ 'color/red/size/large', 'color/blue/size/large', 'color/red/size/medium', 'color/blue/size/medium', ]
Here is a fairly succinct reduce, but it has a nested `flatMap(() => map())` call in its midst so I can't vouch for its efficiency. const variants = [ { title: 'color', children: [{ title: 'red' }, { title: 'blue' }] }, { title: 'size', children: [{ title: 'large' }, { title: 'medium' }] }, ] variants.sort((a, b) => b.children.length - a.children.length); const out = variants.reduce((acc, { title, children }) => { const props = children.map(({ title: child }) => `${title}/${child}`); acc = acc.length === 0 ? props : acc.flatMap(a => props.map(p => `${a}/${p}`)); return acc; }, []) console.log(out)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "javascript, arrays, combinatorics" }
What was added in Monument Valley+? There is a new version of _Monument Valley_ on Apple Arcade called _Monument Valley+_. The description doesn't mention any new features, and the original game is still available for purchase. How is Monument Valley+ different from the original Monument Valley?
According to this Reddit: > It comes with the DLC chapters. So the regular version + DLC should be the same as the Apple Arcade version.
stackexchange-gaming
{ "answer_score": 2, "question_score": 1, "tags": "monument valley" }
Xamarin.Forms: как из одного класса обращаться к элементам другого? Доброе время суток! Дано: 1. Есть ContentPage **Page1** , в ней через XAML вставляется ContentView **MyView** таким образом: `<local:MyView x:Name="MyView" />`; 2. В ContentView MyView есть некоторые элементы (Label, ListView и т.п.). Вопрос: Как из **Page1** обращаться к элементам **MyView**? Ведь это 2 разных класса: Page1.xaml.cs, и MyView.xaml.cs
**Разобрался**. 1. В **MyView** сделал свойство **MyElement** , которое возвращает элемент (например, Listview); 2. В **Page1** обращаюсь к свойству из п.1 через указанное имя **x:Name**. Т.е. MyView.MyElement.
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c#, wpf, классы, xaml, xamarin" }
gdal_grid, how to set pixel size? I'm using `gdal_grid` to convert a shapefile with points and I would like to set the pixel size of the output. I've only found the `-outsize` flag that lets me set the size of the output raster, but I would prefer to just say that I want 2 x 2 m pixels and let the tool figure out the size of the output raster. With `gdal_rasterize` you can set the `-tr` flag, but that tool won't do interpolation.
**GDAL version <3.2** To set the pixel size in `gdal_grid`, you have to play with the following options: > **-txe xmin xmax:** > > > Set georeferenced X extents of output file to be created. > > > **-tye ymin ymax:** > > > Set georeferenced Y extents of output file to be created. > > > **-outsize xsize ysize:** > > > Set the size of the output file in pixels and lines. > because: xcellsize = (xmax - xmin) / xsize ycellsize = (ymax - ymin) / ysize * * * _**New in GDAL version 3.2.**_ > **-tr xres yres** > > > Set output file resolution (in target georeferenced units). Note that -tr just works in combination with a valid input from -txe and -tye >
stackexchange-gis
{ "answer_score": 6, "question_score": 3, "tags": "gdal, gdal grid" }
Overpass Turbo: query for administrative level results in empty dataset If I look up a city on openstreetmap, I can see it has an administrative level of 10. For example: < Subsequently, I run a query in Overpass Turbo to extract the aministrative boundary of this city: [out:json][timeout:60]; {{geocodeArea:'s-Hertogenbosch}}->.searchArea; relation"admin_level"="10"; ); out body; >; out skel qt; {{style: area { color:gray; fill-color:DarkGray; } }} However, this does not work (returns an empty dataset). If I set the admin_level to 8, it returns a much bigger area compared to what openstreetmap shows. For other cities, the admin_level 10 does work, so why not for 's-Hertogenbosch? Am I missing something here?
If you already know the name and the admin_level then just query directly for this element: [out:json][timeout:60]; relation["name"="'s-Hertogenbosch"]["admin_level"="10"]; out body; >; out skel qt; Unfortunately I can't tell why your original query fails.
stackexchange-gis
{ "answer_score": 0, "question_score": 2, "tags": "openstreetmap, administrative boundaries, overpass turbo" }
Best program or clipboard manager to trim whitespace from Windows clipboard on copy/paste? **Is there a program, or a clipboard manager with a plugin** for Windows that can automatically trim the beginning and ending whitespace from text copied into the clipboard before pasting? I've found **many** clipboard manager programs, but none that specifically list this feature. There is a discussion in the AutoHotkey forums about doing this, with no solid answer. I emailed the developer of PureText my idea and he said he will try to work this option into his program when he gets the chance. Is there a good clipboard manager which auto-trims whitespace?
I looked up every single clipboard manager program and **finally found one that automatically scrubs whitespace from the beginning and end of copied text**. < It can play a sound when the whitespace is "scrubbed" and there are optional find-and-replace options too. Really nice.
stackexchange-softwarerecs
{ "answer_score": 6, "question_score": 10, "tags": "windows, clipboard" }
html/css: Grid for images with varying heights – why are images not wrapping properly? I am working on the the following, Wordpress-based web project: < As you can see, there is a grid for the post/the post thumbnails. Someone else has set this up under the premise that all thumbnails will be the same height. I would like to change it so that the thumbnails can have varying heights and wrap properly, without creating wholes between the rows in which the images are lined up. Can I do that by altering the current version or do I have to set up a completely new approach for the grid?
This is only possible with javascript not with CSS only. You need something like "Masonry" (<
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "html, css, wordpress, grid" }
how to run amd64 docker images on arm64 host platform I have an m1 mac and I am trying to run a amd64 based docker image on my arm64 based host platform. However, when I try to do so (with docker run) I get the following error: WARNING: The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8) and no specific platform was requested. When I try adding the tag `--platform linux/amd64` the error message doesn't appear, but I can't seem to go into the relevant shell and `docker ps -a` shows that the container is immediately exited upon starting. Would anyone know how I can run this exact image on my machine given the circumstances/how to make the `--platform` tag work?
Using `--platform` is correct. On my M1 Mac I'm able to run both arm64 and amd64 versions of the Ubuntu image from Docker Hub. The machine hardware name provided by uname proves it. # docker run --rm -ti --platform linux/arm/v7 ubuntu:latest uname -m armv7l # docker run --rm -ti --platform linux/amd64 ubuntu:latest uname -m x86_64 Running amd64 images is enabled by Rosetta2 emulation, as indicated here. > Not all images are available for ARM64 architecture. You can add `--platform linux/amd64` to run an Intel image under emulation. If the container is exiting immediately, that's a problem with the specific container you're using.
stackexchange-stackoverflow
{ "answer_score": 82, "question_score": 55, "tags": "macos, docker, containers, x86 64, apple silicon" }
broken handler for custom handlers I'm using Drupal 7 with views 3. I have defined a custom handler for a field and is working on my development machine. When I revert same view in live environment I am getting issue of broken handler, even the handler class s present. Thanks in advance for your help.
I have fixed this issue by using hook_views_data_alter(). Earlier the custom handler for the select field was defined in hook_views_data().
stackexchange-drupal
{ "answer_score": 0, "question_score": 0, "tags": "7, views" }
How can I eject a memory card or other removable media from the command line (without removing the reader)? I can eject a network drive using `net use X: /DELETE` but when I try to use this same command on removable media I get an error: The network connection could not be found. More help is available by typing NET HELPMSG 2250. Yes, obviously it isn't a network connection, so how do I eject the device from a script?
There doesnt appear to be a built in Windows command to do this. There may be scripting functionality in VBScript or PowerShell, but I didnt see any. However, you are not the only person to ask this. I found this in a quick Google search. Some C++ code to compile to give you a CLI command to eject media. Look at the first answer to the question for a link to the code. Here is a precompiled program that does something similar.
stackexchange-superuser
{ "answer_score": 2, "question_score": 1, "tags": "windows vista, sd card, eject" }
Matlab editor not using emacs shortcuts Is there some way I can make the matlab integrated editor not use emacs shortcut, but use more normal shortcuts such that I can press `Ctrl` \+ `C` and `Ctrl` \+ `V` and not be completely confused by the editor doing weird stuff? I'm using matlab on linux btw.
File -> Preference -> Keyboard -> Choose windows
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 9, "tags": "matlab, editor, keyboard shortcuts" }
Does LINQPad load entire SQL result set into memory before displaying it? I'm attempting to use LINQPad as an SSMS replacement, but it takes an inordinate amount of time to return large result sets. I usually give up waiting after a few minutes, but if I leave it alone LINQPad will often time out with an out of memory error. Does LINQPad load the entire result set into memory before displaying it in the grid? Is it capable of returning records in chunks, adding records to the output grid as more results become available from the database -- similar to the way SSMS works? Cross-posted (and revised) from the LINQPad formus (< as I haven't had a response there.
This shouldn't happen in rich text mode, because LINQPad implicitly limits the amount of data it fetches (by default, 1000 rows). After some investigation, it appears the problem is due to a bug in ADO.NET's SqlDataReader. When you dispose a data reader after reading only a portion of the rows, it "cleans" the reader by enumerating all remaining data. It certainly is annoying, so I'm looking into whether it's possible to detect this condition and cancel the underlying command. Edit: there's a workaround for this in the latest beta, so in rich text mode, the query should now complete quickly with the first 1000 rows.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "linqpad" }
MS Access Force Update on Combobox How do I force an update when the ComboBox value is changed in code. Below is piece of code I have tried but does not seem to work If (Not Mid(sCode, 1, 2) = ddlLevelID1) Then ddlLevelID1 = Mid(sCode, 1, 2) 'force change/force AFTER_UPDATE event to run. End If
Assuming `ddlLevelID1` is the ComboBox: ddlLevelID1.value = foo will change the value. I do not believe you can link a value displayed in a ComboBox to a variable value without pushing changes up to the userform after the value is changed. * * * Regarding the AfterUpdate method, from msdn: > Changing data in a control by using Visual Basic or a macro containing the SetValue action doesn't trigger these events for the control. However, if you then move to another record or save the record, the form's AfterUpdate event does occur. <
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "vba, ms access" }
How to understand the meaning of 愛{いと}しさ I know that from adjective we can make adjectival noun like: {} -> - means _high_ and _hight_. But how to understand/translate the word ? I heard it in one of _C-ute_ songs.
I think I've figured out what you are asking about. Mental adjective + can refer to _**one's feeling**_ as well as _quality_ invokes the emotion. I'm not sure I'm able to tell their difference using English words, but you can paraphrase it with when it means the feeling. Maybe what you encountered was this kind of usage, where in this case = → ≈ "earnest love for you".
stackexchange-japanese
{ "answer_score": 4, "question_score": 1, "tags": "grammar, meaning" }
I can't sys.stdout.seek From what I know, `sys.stdout` is a file that represents the stdout of a terminal. However, when I try to use `sys.stdout.seek`, whatever parameters I give it, it throws an error: IOError: [Errno 29] Illegal seek What's going on? Is it the fact that I'm using the TTY itself and not a virtual terminal like xterm? How can I resolve this?
When stdout is a TTY it's a character device and it's not seekable, you cannot `seek` in a TTY. Same for `tell`, it's not implemented: >>> sys.stdout.tell() IOError: [Errno 29] Illegal seek However, when you redirect standard streams to a file for example in a shell: $ my program > ouput.txt Now you can `seek` from stdout, stdout now is a file. Please look at this reference if you're working with Unix: Understanding character device (or character special) files.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "python, stdout, tty" }
Set custom style attribue doesn't work in IE11 I have this simple Javascript code to change custom CSS attribute var root = document.documentElement; root.style.setProperty("--custom-bg", "#4f5357"); This works fine in Firefox Google Chrome but it doesn't work in IE 11 also tried root['--custom-bg'] = "#4f5357"; root.attr("--custom-bg", "#4f5357"); root.style['--custom-bg'] = "#4f5357"; none of them worked .
IE11 **doesn't** support css custom properties, therefore it doesn't supports this `setProperty` method. Checkout this css-vars-ponyfill, which aims to add basic support.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, html, jquery, css, styles" }
What's the difference between the short rate model projection and the 3M forward curve? A term structure has a forward curve So what is it that the short rate model is projecting exactly? Why is it needed? How are they different?
A yield curve is a deterministic function as set and seen at time T=0. One can project any short-term (e.g. 1 mth, 1 wk or 1 day) forward rates from the curve and they are deterministic. A short rate model only projects the behaviour of the instantaneous short rate (again can be defined as any tenor). The forward rates from this model are generated from the model parameters and might not necessarily match the yield curve.
stackexchange-quant
{ "answer_score": 0, "question_score": 0, "tags": "interest rates, forward rate, short rate" }
Why won't propane come out of my nearly-new propane tank? I bought a new propane tank (< and had it filled up, then used it on two separate days to fuel a weed burner torch. Worked fine. The last use was last Sunday, just a few days ago. I went to fire up the weed burner again today and nothing came out of the tank. No gas, and no hissing sound when the valve is first opened. I can open the valve all the way and stick my nose right against the tank's outlet and I don't smell any gas coming out at all. There's clearly propane still in there because the tank's heavy and I can both hear and feel it sloshing around if I give the tank a shake. What could be the problem?
Open the tank supply valve **very slowly** and make sure the weed burner valve is closed when you do it. I mean if you think you are opening it slowly you are still opening it too fast. Some of these newer tanks have a safety feature that cuts back on flow if high flow is detected. You may also have a tank with a defective valve, if the above method does not work, take it and exchange it for a different tank at one of those places that will trade a filled tank for an empty. It could also be your weed burner valve, a lot of those weed burners are lame Chinese pieces of crap. Try it on an alternate appliance like a camp stove or BBQ.
stackexchange-diy
{ "answer_score": 9, "question_score": 4, "tags": "propane" }
Dynamic $in operator based on a variable I have a variable and based on that value I would like to change the $in operator within mongo query. My code - var query_op = "$in"; if (criteria.group === "abc") { var query_op = "$nin"; } And then var query = Model.find( { _id: { $in: query_op } , ........................... }); Would it be possible to use in this way? Any help is highly appreciated.
I think in JavaScript you can dynamically define object's key using square brackets, try: var query_op = "$in"; if (criteria.group === "abc") { var query_op = "$nin"; } var query = Model.find( { _id: { [query_op]: listOfIds } });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, mongodb, mongodb query" }
Movie in which two men ask a dragon three questions I'm trying to remember the name of a movie in which two young men ask a dragon three questions. I remember that one of the men asks the dragon, "Don't we get three questions?" The dragon responds, "Yes, but now you have only two remaining." Or something along those lines. What movie was this from?
I think this may be the _Earthsea_ miniseries. > With the help of Ogion, Ged confronts the Gebbeth and attempts to drown him using a rock, however, it escapes with Ged's likeness and voice. Ged's impersonator becomes a murderer, and Vetch, a magus himself, chases Ged until he realizes Ged is not possessed by the Gebbeth and they decide to hunt it together. > > They are attacked by the dragon, Orm Embar, but Ged uses the dragon's true name to bind him and ask three questions. He wastes his first question, but with his second, he learns the Gebbeth's location. The dragon tells him where to find the two pieces of the Amulet of Peace, which when reunited would save Earthsea, but Ged could have asked the true name of the demon. Here's a clip at the relevant part. In case that gets taken down, here's a screenshot with them and the dragon around that point: ![Image of Ged and Vetch with the dragon, Orm Embar](
stackexchange-scifi
{ "answer_score": 21, "question_score": 13, "tags": "story identification, movie, dragons" }
How can I do safe split() I have some object { title: "Some title", value: "Some value" } I store my object like a string with `:` separator: `${title}:${value}` But when I transform my string to object again I want to be sure that it is safe. Because `title` and `value` can contain separator `:` const [value, title] = string.split(":"); const obj = { value, title } How can I do it? I think I need something like this: `${replacer(title)}:${replacer(value)}` const [value, title] = string.split(":"); const obj = { value: invertReplacer(value), title: invertReplacer(value) }
Instead of storing objects like `${title}:${value}`, you could store object like `${title}${value}:${title.length}`. From that, you can extract the length of the title and split your string at the certain position.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript" }
how to style pure html title for specific anchor tags or div? I am trying to style the title (not the tool tip) for a link. But I can't get any idea that how to style it. My code is here. I dont want to style it by adding the pseudo-element and before and after elements. <!DOCTYPE html> <html lang="en-US"> <body> <h2>Link Titles</h2> <p>The title </p> <a href="#" title="this is the title i want to style">Visit our HTML Tutorial</a> </body> </html> How can I style the title that appears when you hover on the anchor tag.
You can't style it directly, but you can create the same effect using a pseudoelement. a[myTitle]:hover { position: relative; } a[myTitle]:hover:after { content: attr(myTitle); position: absolute; left: 0; top: 100%; background: #000; color: #fff; padding: .5rem 1rem; z-index: 1000; white-space: nowrap; } <h2>Link Titles</h2> <p>The title </p> <a href="#" myTitle="this is the title i want to style">Visit our HTML Tutorial</a>
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": -1, "tags": "html, css" }
How to make window application in ANSI C? Until now I've been only writing console applications but I need to write a simple window application for a school assignment. Could somebody point me to a good tutorial how to create windows and other ordinary windows elements such as buttons, 2d graphs etc in ANSI C? is there some good library I should use? I tried googling but there are no tutorial websites devoted to C. If you can, I would also appreciate some example code. Thank you. By the way, I use Dec C++.
There's nothing in the ANSI C standard about windows. If you want to make a windowed application, you'll have to use platform-specific libraries (e.g. Win32, Cocoa, or X11), or some sort of cross-platform library that encapsulates that (e.g. SDL, wxWidgets, or many more).
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "c, user interface" }
Can I change icon in this case? I have associated txt file and xml file with Notepad++ (both opened with it), so both of them have the same icon with Notepad++. Is there any way to change the txt icon to a different icon than the xml icon?
Check this out. It explains how to use custom icons for file types but may require some registry editing. <
stackexchange-superuser
{ "answer_score": 0, "question_score": 2, "tags": "notepad++, icons, window" }
What is the proper word order when a sentence contains an adverb using 地 and a coverb phrase? Can anyone provide some guidance on word order of a sentence if it has an adverb using and coverb phrases. I thought always came directly in front of the verb, but then I saw this site: < Which showed the "manner" part coming before all the coverb phrases. So, I started doing some searching and found this sentence which has the coverb after the adverb and before the verb: > . But, I also found this sentence with the coverb first, and then the adverb after: > . So, what is the difference between the two word orders?
In Chinese you can also say "" in this way: "" Then the order of coverb and adverb is the same as the sentence "." Example: the following 2 sentences have the same meaning coverb first, adverb after: * __ * adverb first, coverb after: * __ *
stackexchange-chinese
{ "answer_score": 5, "question_score": 6, "tags": "grammar, adverbs" }
Have Legends been implemented for ESRI's REST API? ESRI's 10.0 documentation for legend indicates that this url should return a legend: < But it doesn't work. Is there something special I need to do when publishing a mapservice to enable legends? If not, does anyone know of a url that returns a legend?
The REST legend service was added in Service Pack 1. Has this server had Service Pack 1 installed? It appears that it has not. 'currentVersion' was added to serveral resources to indicate the version and patch level. See the latest ArcGIS 10 API documentation for more details.
stackexchange-gis
{ "answer_score": 4, "question_score": 6, "tags": "arcgis server, rest" }
"Quelques fois" for "a few times"? "I've watched this film a few times." > J'ai regardé ce film quelques fois. Is the use of _quelques fois_ correct here? If this sentence is spoken, would _quelques fois_ get confused with _quelquefois_ that means "sometimes" ( _parfois_ / _des fois_ )? Are there any other alternatives for translating "a few times"?
It can mean "a few times", but you're right that there is some ambiguity (though less in the passé than in the présent). Some other options are _plusieurs fois_ , _à quelques/plusieurs reprises_ (same quantifier but with this noun no confusion is possible), _en quelques occasions_ (same deal) ...
stackexchange-french
{ "answer_score": 2, "question_score": 1, "tags": "traduction, adverbes" }
How to Switch rows into columns and columns into rows in SQL Server? Hi I have a table like below,. Stat Points TeamA TeamB Date Highest Total 248 5 387 2016-05-14 Lowest Total 153 2 5 2016-05-11 Highest Successful Chase 195 5 386 2016-05-07 Lowest Score Defended 211 5 4 2016-05-18 I want the result like, Highest Total Lowest Total Highest Chase Low Defended A 248 153 195 211 B 5 2 5 5 C 384 5 386 4 D 2016-05-14 2016-05-11 2016-05-07 2016-05-18 Help me to get the result, I'm newer one for the sql server.
Pivot and unpivot, whatever this 'A', 'B', .. really mean. It also shows casting different types to common `varchar(20)`. You may need different cast according to your requierments. select rowType, max(case ut.stat when 'Highest Total' then value end) as [Highest Total], max(case ut.stat when 'Lowest Total' then value end) as [Lowest Total], max(case ut.stat when 'Highest Chase' then value end) as [Highest Chase], max(case ut.stat when 'Lowest Score Defended' then value end) as [Lowest Defended] from t cross apply ( select * from ( values ('A', cast(points as varchar(20)), stat), ('B', cast(TeamA as varchar(20)), stat), ('C', cast(TeamB as varchar(20)), stat), ('D', cast(Date as varchar(20)), stat) ) ut(rowType, value, stat) )ut group by rowType
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "sql, sql server, rows" }
Avoiding unexistent metadata in Perforce Server My question might be simple, and the solution as well, however, i want to know, supposing that a user syncs a branch, and later delete the physical files from his local machine manually, the metadata about these files wil still exist in the server... In the long run i'm afraid this could slow down the server. I haven't found much about this issue, this is why i'm asking here, how do companies usually manage their Perforce metadata? A trigger that verifies the existing metadatas? a program that runs `sync #none` for client directories that does not exist anymore from time to time? As i said, there might be many simple ways to solve that, but i'm looking for the best one. Any help is appreciated.
In practice I don't think you'll have too much to worry about. That being said, if you want to keep the workspace metadata size to a minimum, there are two things you'll need to do: 1. You'll need to write the `sync #none` script you referenced above, and also make sure to delete any workspaces that are no longer in use. 2. Create a checkpoint, and recreate the metadata from that checkpoint. When the metadata is recreated, that should remove any data from deleted clients. My understanding of the Perforce metadata is that it won't shrink unless it's being recreated from a checkpoint.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "metadata, perforce" }
Write a simple program to solve (x3 - 17x + 12 = 0) by direct substitution Like the title says, I need to write a simple program to solve (x3 - 17x + 12 = 0) by direct substitution. Can someone explain to me what this even means? I was under the impression that direct substitution required a Y component of some kind? Not really looking for code help, just the logic of it, I suppose.
This is one possible implementation of Pieter's answer. We can re-write this equation as: !enter image description here We put an initial value for **x** in **A1** and in **A2** we put: =(A1^3+12)/17 and copy down _(earch row is an iteration on the row above)_ To see how close **A2** is to the actual answer in **B2** we put: =A2^3-17*A1+12 and copy down. Here is a sample with **1** in **A1** : !enter image description here
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "excel, vba" }
MySQL where in and not in Can anyone help on this query please on how to get the output i want? I am looking for client who has a tag "Kane" but not "Andrew". I am expecting the output: > "client 3" only because on "client 1" has a tag Andrew INSERT INTO `client` (`id`, `name`) VALUES ('1', 'Client 1'), ('2', 'Client 2'), ('3', 'Client 3'), ('4', 'Client 4'); INSERT INTO `tag` (`id`, `client_id`, `tag`) VALUES ('1', '1', 'Kane'), ('2', '1', 'Andrew'), ('3', '2', 'Andrew'), ('4', '3', 'Kane'), ('5', '3', 'James'), ('6', '4', 'Andrew'); ## mysql query select * from client where exists ( select client_id from tag where tag.client_id = client.id and tag in ('Kane') and tag not in ( 'Andrew' ) ) <
Perhaps not the most efficient way, but this will work: select * from client where exists ( select client_id from tag where tag.client_id = client.id and tag in ('Kane') ) and not exists ( select client_id from tag where tag.client_id = client.id and tag in ('Andrew') ) The problem with your query was it was trying to apply both `tag in ('Kane')` and `tag not in ( 'Andrew' )` to each and every row at the same time. Since the first clause is restrictive, it made the second clause redundant. You have to ask the two questions separately.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "mysql, sql" }
Non existence of non-constant periodic orbits for gradient flows I am stuck with the following ODE problem: Let $V \in C^2(\mathbb{R}^n,\mathbb{R})$ and $x_0 \in \mathbb{R}^n$, where $n \ge 2$. Let $\phi_{x_0}: (t^-,t^+) \to \mathbb{R}^n$ be the maximal solution to the initial value problem $$ \dot{x}=-\nabla V(x),\quad x(0)=x_0. $$ 1. Prove that the function $V\circ\phi_{x_0}$ is non-increasing on $(t^-,t^+)$. 2. Suppose $\phi_{x_0}(p)=\phi_{x_0}(0)$ for some $p>0$. Prove that $t^+=-t^-=\infty$, and that $\phi_{x_0}(t)=x_0$ for every $t$. My problem is with the second question. Any help will be appreciated.
We know by theorems of uniqueness for autonomous equations that if the solution self intersecting($\phi_{x_0}(0)=\phi_{x_0}(p)$ then the solution must be periodic. Therefore your solution $\phi_{x_0}$ is periodic of period $p$(defined in all $\mathbb R$). By a) we know that $$ V(\phi_{x_0}(t))=V(\phi_{x_0}(0))$$ for all $t\in[0,p]$. Differentiating both sides we have $$<\text{grad}V(\phi_{x_0}(t),\phi_{x_0}'(t)>=0\implies <-\phi_{x_0}'(t),\phi'_{x_0}(t)>=0$$ Therefore $ \phi'_{x_0}(t)=0$ for all $t$
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "ordinary differential equations" }
Arduino загрузчик мапит память? `Arduino` загрузчик мапит память? Когда из запущенной программы я работаю с памятью – это уже не прям голая RAM? Если да – есть ли способ перемапить память без прошивки загрузчика?
Нет, загрузчик Arduino не маппит память. Маппить память - так называется процесс отображения файла в оперативную память компьютера. Программа как бы обращается к виртуальной памяти, а на самом деле читает и записывает данные в файл. Это один из способов организации так называемой виртуальной памяти. В микроконтроллере Arduino данные хранятся в оперативной памяти, размером всего 2 КБайта, но чтобы маппить память, нужно чтобы ядро микроконтроллера умело это делать. Для этого процессор AVR должен был бы поддерживать многопоточность, что например умеют процессоры, совместимые с Intel 80386.
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "arduino" }
Vectorization of multiple embedded for loops I have the following code that includes 3 iterated for loops in order to create an upper diagonal matrix, I plan on performing on large data set many times and want to make as computationally efficient as possible. data = magic(3); n = size(data,1); W = zeros(n,n); for i = 1:n for j = i:n if i==j W(i,j)=0; else for k = 1:n temp(1,k) = (data(i,k)-data(j,k))^2; sumTemp = sumTemp + temp(1,k); end W(i,j)=sqrt(sumTemp); end temp = 0; sumTemp = 0; end end Answer should look like: [0 6.4807 9.7980 0 0 6.4807 0 0 0] I am working it hard right now, but figure I would throw it out there in case anyone has any suggestions that would save me hours of fiddling around.
This is hat I have at the moment: data = magic(3); n = size(data,1); W = zeros(n,n); for i = 1:n for j = i+1:n W(i,j)= norm(data(i,:)-data(j,:)) %W(i,j)= sqrt(sum((data(i,:)-data(j,:)).^2)); end end What I did: * vecorized the inner loop * removed www, which is unused * changed 2nd loop, start at i+1 because nothing is done for i=j * Replaced sqrt((a-b).^2) with norm(a-b) And now the "full" vectorization: data = magic(3); n = size(data,1); W = zeros(n,n); tri=triu(ones(n,n),1)>0; [i,j]=find(tri); W(tri)=arrayfun(@(i,j)norm(data(i,:)-data(j,:)),i,j)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "matlab, for loop, vectorization" }
On UPDATE Trigger - Triggered during its own Execution? I have the following trigger definition PROMPT CREATE OR REPLACE TRIGGER C_BUSINESS_TABLE CREATE OR REPLACE TRIGGER C_BUSINESS_TABLE BEFORE INSERT OR UPDATE OF OC ON OUT_TAB FOR EACH ROW DECLARE v_OC OUT_TAB.OC%type; BEGIN SELECT OC into v_OC from ORDERS WHERE ORDER_ID=:NEW.ORDER_ID and ORDER_SEQ=:NEW.ORDER_SEQ and rownum=1; IF :NEW.OC != v_OC and v_OC is not NULL THEN :NEW.OC:=v_OC; END IF; EXCEPTION WHEN OTHERS THEN NULL; END; / The trigger is intended to be executed in the following scenarios 1. INSERTION of a record in OUT_TAB OR 2. UPDATE OF the field OC ON OUT_TAB Inside the Trigger Body the field OC itself is updated. Will that update invoke the trigger again (and recursively) for that matter? Do i need to code it to avoid that recursion?
no it won't, this will be fine, when you set the value of :NEW.OC this is not actually updating the table, only once the trigger code completes is the table updated/inserted using the value you set :NEW.OC to
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "oracle, plsql, oracle11g, oracle10g" }
Meaning of 何も in this sentence > **** > Russia says that they have no connection to the incident in the UK, and say they are deciding what to do next. I can't understand the function of in this sentence. I'm sure that I'm wrong, but it doesn't seem to be needed to me. I can't fit it into the sentence grammatically, or give it a useful meaning. I wonder if it's the same as in this answer. If so then please close as duplicate.
> {} **{}** {} **** {}{} when used in conjunction with a negative expression ( in this case) simply means " ** _not anything_** " or " ** _nothing_** ". This is completely different from the in the other question that you linked to. This one is pronounced {LHH} and the other, {HLL} The function of this is to mainly emphasize the following phrase . An English equivalent would be "Nothing vs. absolutely nothing". Both mean "zilch", but you do use the latter quite frequently as well. > "Russia says that it has absolutely nothing to do with the incident in England and ~~~." Other examples: {} **** {}= "Yay! There is (absolutely) no homework today." **** = "There is (absolutely) nothing yummy in this restaurant."
stackexchange-japanese
{ "answer_score": 5, "question_score": 3, "tags": "grammar" }
Yeoman pass prompt answers to subgenerator I have a yeoman generator with some subgenerators. I know I can pass options from the parent- to the subgenerators when calling `composeWith(...).` But how can I pass the answers I get from prompting? The are not available at the point when composeWith is called. For example I prompt in the generator for an app name and want to provide this to all the subgenerators as options?
Oh, found in the related questions that I could call the subgenerator after prompting, instead of the initialize-method (as in the quite outdated tutorial)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "yeoman, yeoman generator" }
How to refer to redirection file from within a bash script? I'd like to write a bash script myscript such that issuing this command: myscript > filename.txt would return the name of the filename that it's output is being redirected to, filename.txt. Is this possible?
If you are running on Linux, check where `/proc/self/fd/1` links to. For example, the script can do the following: #!/bin/bash readlink /proc/self/fd/1 And then run it: $ ./myscript > filename.txt $ cat filename.txt /tmp/filename.txt Note that if you want to save the value of the output file to a variable or something, you can't use `/proc/self` since it will be different in the subshell, but you can still use `$$`: outputfile=$(readlink /proc/$$/fd/1)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "bash, redirect" }
Do I need a framework in order to use Dependency Injection? I have been reading for and practicing dependency injection for the past two days but nothing is working out, and suddenly I found out that there were some frameworks required in order for dependency injection to work. Is that true? Isnt it a bad practice to make my project depend on some framework? Could it be done without the use of a framework? EDIT: Im new to programming so I dont understand what is the difference between instatiating a class and using its methods (i dont need a framework for that) and using dependency injection and what is better about it EDIT: Here is an example of me not using a framework and things not working TestNG @Factory annotation + not enough knowledge on Dependency Injection
No, you don't have to use a framework: Dependency Injection Of course you can use a framework too, As someone said you can use `Spring Framework` and use their annotations. Here you have a tutorial: Dependency Injection with the Spring Framework
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 10, "tags": "java, dependency injection" }
Stuck in trying to find integral I'm trying to find the integral of $$ \int\sqrt{(a^2-x^2)^3}dx $$ yet I've been stuck on this section for a long time, the integral calculator I'm using does not help me understand the process of determining the integral. Any advice/assistance is happily accepted and appriciated. Cheers.
Firstly, we substitute $$ x = a \sin{u}, \text{ } dx = a\cos{u}$$ Then $(a^2-x^2)^\frac{3}{2}=(a^2-a^2\sin^2{u})^\frac{3}{2} = a^3\cos^3{u}$ and $u=\sin^{-1}(\frac{x}{a})$, so our integral is equal to: $$a^4\int \cos^4(u) du$$ Using the integral reduction formula we obtain that $$a^4\int cos^4(u)du = \frac{a^4}{4}\sin{u}\cos^3{u}+\frac{3a^4}{4}\int \cos^2(u)du$$ Using the formula again: $$\int \cos^2(u)du = \frac{1}{2}(u + \cos{u}\sin{u})$$ So our whole integral is equal to: $$\frac{a^4}{4}\sin{u}\cos^3{u}+\frac{3a^4}{8}(u + \cos{u}\sin{u})$$ We substitute back $u=\sin^{-1}(\frac{x}{a})$ to obtain: $$\frac{a^4}{4}\sin({\sin^{-1}(\frac{x}{a})})\cos^3{(\sin^{-1}(\frac{x}{a}))}+\frac{3a^4}{8}(\sin^{-1}(\frac{x}{a}) + \cos{(\sin^{-1}(\frac{x}{a}))}\sin{(\sin^{-1}(\frac{x}{a})}))$$ $$\frac{a^3x}{4}\cos^3{(\sin^{-1}(\frac{x}{a}))}+\frac{3a^4}{8}(\sin^{-1}(\frac{x}{a}) + \cos{(\sin^{-1}(\frac{x}{a}))}\frac{x}{a})$$ We may use that $\cos(\sin^{-1}(x))=\sqrt{1-x^2}$ to simplify further.
stackexchange-math
{ "answer_score": 1, "question_score": -1, "tags": "calculus, integration" }
Clearing C# Events after execution? Say I have the following code: public event EventHandler DatabaseInitialized = delegate {}; //a intederminant amount of subscribers have subscribed to this event... // sometime later fire the event, then create a new event handler... DatabaseInitialized(null,EventArgs.Empty); //THIS LINE IS IN QUESTION DatabaseInitialized = delegate {}; Will this clear out the subscribers, replacing it with new empty default? And, will the event notify all subscribers before they get cleared out? I.E. Is there a chance for a race condition?
Yes it will clear it out. And because events fire syncronously in the same thread there shouldn't be race condition. My advice: when in doubt, write a small test application and... well, test it. _UPDATE:_ I tested it before posting. (In response to minuses.)
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 5, "tags": "c#, events" }
Addition to equally substituted carbons I was wondering whether there is a trick in the following problem: > ![enter image description here]( Since both carbons are equally substituted, shouldn't the products be the same with or without the use of peroxides?
The use of HBr with peroxide leads to an anti-Markonikov's product(known as the peroxide effect).The carbons are both substituted once, but not equally! One has a methyl group while the other side has a phenyl group. The chemical basis for the Markovnikov's rule is the formation of a a stable carbocation during the addition process. So, with just HBr a nomal Markovnikov's addition takes place i.e the Br group gets attached adjacent to the phenyl group while the H on the next carbon(as a benzylic carbocation is more stable).Final product: Ph-CHBr-CH2-CH3. With the peroxide however , the opposite happens leading to the formation if Ph-CH2-CHBr-CH3.
stackexchange-chemistry
{ "answer_score": 1, "question_score": 2, "tags": "organic chemistry, c c addition" }
Are multiline labels with the tikzlibrary quotes possible? MWE: %! TEX program = lualatex \documentclass{article} \usepackage{tikz} \usetikzlibrary{ graphs, graphdrawing, positioning, quotes, } \usegdlibrary{trees} \begin{document} \begin{tikzpicture} \graph [ tree layout, edge quotes center, edges={nodes={fill=white}}, level distance=30mm, ] { a ->["first line\\second line"] b ->["y"] c ->["z"] d; }; \end{tikzpicture} \end{document} returns ![enter image description here]( As you can see the linebreak is ignored. What do I have to do when using the tikzlibrary `quotes` to use linebreaks in edge labels?
The additional options for the quote is taken as label options. Hence any linebreaking-option would cause it to have multilines such as `align=...` or `text width=<dimension>`. With a ->["first line\\second line", align=center] b ->["y"] c ->["z"] d; we get ![enter image description here](
stackexchange-tex
{ "answer_score": 5, "question_score": 5, "tags": "tikz pgf, line breaking" }
The $i$-th center $Z_{i}(G)$ > Let $H$ be a normal subgroup of a $p$-group $G$, $H$ is of order $p^i$. Prove that $H$ is contained in the $i$-th center $Z_{i}(G)$. Recall that we define $Z_{0}(G)=1$, and for $i>0$, $Z_{i}$ is the subgroup of $G$ corresponding to $Z(G/Z_{i-1})$ by the Correspondence Theorem: $Z_{i}/Z_{i-1}=Z(G/Z_{i-1})$ The sequence of subgroups $Z_{0}\subset Z_{1}\subset Z_{2}\subset\ldots$ is called the upper central series of $G$ I use induction on $i$ and consider $G/Z(G)$. The case $i=0$ is trivial ($H=1$ and $Z_{0}(G)=1$). How should I continue the proof? Thanks for any insight.
That is exercise $9$, page $222$ of the book Groups: An Introduction to Ideas and Methods of the Theory of Groups, Antonio Machi. A detailed hint can be found on that book. P/s: that exercise of that book is a stronger version of this problem.
stackexchange-math
{ "answer_score": 3, "question_score": 9, "tags": "abstract algebra, group theory, p groups" }
I am not able to connect github using bamboo Installed latest version of bamboo. I am not able to pull the repository from the github. I am getting below error.. Bamboo Server Edition Version : 6.9.0 I am getting below error [Git credentials storage exception.])
Look at agent logs. It should contain more details. Usually it means Bamboo was not able to create or access credentials file.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "bamboo" }
How to round up a decimal? How can I use `round()` to round a number to the superior number as soon as there is a decimal? For example: 1.00001 = 2 1.1 = 2 1.4785834975 = 2 1.00 = 1 1.99 = 2 3.01 = 4
Yes, what you are looking for is called `ceil` <?php echo ceil(4.3); // 5 echo ceil(9.999); // 10 echo ceil(-3.14); // -3 ?>
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 3, "tags": "php, math, rounding" }
possible values for sig in kill function The man page for the kill function mentions - `int kill(pid_t PID, int sig)` It doesn't mention anything about the possible values of the sig argument. Although I see many sample codes calling it with `SIGKILL`. Where did this SIGKILL come from and how to search for it in man pages. And does this value matters? In the sense I assume no matter what value you specify The process with the pid pid_t will indeed get killed
> And does this value matters? Yes, it does. While most signals kill the program, they mean different things and the program can handle them differently. For example, programs can set a SIGSEGV handler then sending a SIGSEGV will no longer kill that program. However, SIGSTOP and SIGKILL (pausing a process and force-killing a process, respectively) are special in that they can't be handled. You can find a list of signals on the manpage for signals.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c, kill" }
Magento - Check for Customer's First Order Is there a quick way to programatically check if the currently logged in customer has ever placed an order? I'm writing an observer and at a point I want to simply say if ($this->isCustomerLoggedIn() && (has never placed an order)) { do this } possible? Thanks!
$orders = Mage::getResourceModel('sales/order_collection') ->addFieldToSelect('*') ->addFieldToFilter('customer_id', $customer->getId()); if ($this->isCustomerLoggedIn() && (!$orders->getSize())) { // has never placed an order } The above assumes that you have a `$customer` but if it is not accessible from the event you can usually get the currently logged in customer with: $customer = Mage::getSingleton('customer/session')->getCustomer();
stackexchange-stackoverflow
{ "answer_score": 16, "question_score": 1, "tags": "magento" }
How to fetch specific value first then ascending order using Laravel Elequent? How to fetch specific value first then ascending order using Laravel Eloquent? I want to show `India` first then other countries in ascending. I am using $country_data= country::orderBy('country_id','India')->get();
You can user `orderByRaw` with `mySQL` `FIELD` function So try this: `$country_data= country::orderByRaw("FIELD(country_id,'India') DESC")->orderBy("country_id","asc")->get();`
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "laravel, eloquent, laravel 5.5" }
what is the difference between objects.all() and objects.values()? what is the difference between objects.all() and objects.values() ? i used like this queryset = Consulting.objects.values() queryset = queryset.filter(consultant_id=consultant_id) occurs some errors but queryset = Consulting.objects.all() queryset = queryset.filter(consultant_id=consultant_id) is okay i think these two return objects in my short knowledge what is difference?
The `values()` function return dictionary. And the `filter` function does not exist in dictionary, so error occurs. But `all()` function returns `QuerySet` class so `filter` function can be used. The `filter` function is defined in the `QuerySet` class.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, django rest framework" }
chat client using Openfire, Javascript (strophe.js), and html5 websockets? I want to build a XMPP web-based chat client to add on to outlook web access. I've read that Javascript is problematic. Could I use html5 websockets using the openfire server and the Javascript(strophe)? I've read on other solutions that include using flxHR, a flash library. Which would be better?
A lot of the WebSocket libraries, technologies and services provide fallback for browsers that don't support WebSockets. This is generally done via Flash but some libraries also fallback to HTTP streaming or polling. Have a search for WebSockets on the following page for available technologies: <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, html, xmpp, websocket, openfire" }
Assign values in Action list? i had a null value error in my test class [Test] public void when_send_the_command_it_execute_correct_command_handler() { //Arrange var commandBus = new CommandBus(); ICommand commandforsend=null; IMetaData metaDataforsend=null; Action<ICommand, IMetaData> fakeHandler = (fakecommand, fakemetadata) => { commandforsend = fakecommand; metaDataforsend = fakemetadata; }; commandforsend and metaDataforsend values are still null what can happen ? help me thank you !
You are defining an `Action` but you are never calling it. Your code is equivalent to a separate method that assigns the values but that you don't call so the code inside the method never runs. If you want to execute the `fakeHandler` you should add the following line below the declaration: fakeHandler(aFakeCommand, aFakeMetadata);` As you can see, this is the same as calling a regular method. You need to supply values for both parameters (`fakecommand` and `fakemetadata`). You can find more info in the MSDN documentation.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c#, generics, nunit" }
how do i change an old project I had so it can use ARC? I started an old project in an xcode that did not support ARC, how can I change my project into using ARC and how do I know what to remove from the project?
In Xcode, Edit => Refactor => Convert to Objective-C ARC... and follow the instructions.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "ios, xcode, automatic ref counting" }
Can I use throw without any message? Here is my code: try { if ( condition 1 ) { throw; } else { // do something } // some code here if ( condition 2 ){ throw; } } catch (Exception $e) { echo "something is wrong"; } As you see, my `catch` block has its own error message, And that message is a constant. So really I don't need to pass a message when I use `throw` like this: throw new Exception('error message'); Well can I use `throw` without anything? I just need to jump into `catch` block. Honestly writing an **useless** error message is annoying for me. * * * As you know my current code has a syntax error: _(it referring to`throw;`)_ > **Parse error:** syntax error, unexpected ';' in {path}
`message` parameter is optional in the `Exception` constructor. So if you don't have/want to put - just don't: throw new Exception; But you still must throw an instance of the `Exception` class (or a class that extends it), since it is a part of the php language syntax.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 2, "tags": "php, exception, try catch" }