qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
list
response
stringlengths
0
115k
30,362
My mate always tells me to remove the germ (the center) from garlic and onions, especially if it's turning green. What are the pros and cons of the germs of these plants?
2013/01/24
[ "https://cooking.stackexchange.com/questions/30362", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/15265/" ]
So... I was always taught that you remove it because it's bitter. I generally remove it if it's big enough. However, there seems to be some contention as to whether this is true (and to what degree it's true). See: <http://www.examiner.com/article/remove-the-garlic-germ-few-do-this-anymore> and <http://ruhlman.com/2011/02/garlic-germ/> In short, there are mixed teachings as to whether you should remove it. But essentially the germ DOES affect the taste of garlic. Some call it bitter, some call it "more garlicky". Ruhlman suggests that if you're hitting it with heat immediately, then there isn't a point in removing it. If he's doing something that will have the garlic sitting around, then he doesn't. From this what I'd suggest (and what I'm going to try doing from now on) is to ignore it and if you notice a difference in taste, or more importantly find the result objectionable. then take it out next time. Otherwise don't bother as you won't know the difference.
47,611,557
I'm working on an optimization problem that involves minimizing an expensive map operation over a collection of objects. The naive solution would be something like ``` rdd.map(expensive).min() ``` However, the map function returns values that guaranteed to be >= 0. So, if any single result is 0, I can take that as the answer and do not need to compute the rest of the map operations. Is there an idiomatic way to do this using Spark?
2017/12/02
[ "https://Stackoverflow.com/questions/47611557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3818777/" ]
> > Is there an idiomatic way to do this using Spark? > > > No. If you're concerned with low level optimizations like this one, then Spark is not the best option. It doesn't mean it is completely impossible. If you can for example try something like this: ``` rdd.cache() (min_value, ) = rdd.filter(lambda x: x == 0).take(1) or [rdd.min()] rdd.unpersist() ``` short circuit partitions: ``` def min_part(xs): min_ = None for x in xs: min_ = min(x, min_) if min_ is not None else x if x == 0: return [0] return [min_] in min_ is not None else [] rdd.mapPartitions(min_part).min() ``` Both will usually execute more than required, each giving slightly different performance profile, but can skip evaluating some records. With rare zeros the first one might be better. You can even listen to accumulator updates and use `sc.cancelJobGroup` once 0 is seen. Here is one example of similar approach [Is there a way to stream results to driver without waiting for all partitions to complete execution?](https://stackoverflow.com/q/41810032/8371915)
69,853,145
I'm studying pointers in C language with Ted Jensen's "A TUTORIAL ON POINTERS AND ARRAYS IN C" manual. It's a very prickly argument. **Question 1**. I have come to program 3.1 and would like a clarification. This is the program: ``` #include <stdio.h> char strA[80] = "A string to be used for demonstration purposes"; char strB[80]; int main(void) { char *pA; char *pB; puts(strA); pA = strA; puts(pA); pB = strB; putchar('\n'); while(*pA != '\0') { *pB++ = *pA++; } *pB = '\0'; puts(strB); return 0; } ``` Regarding the line `pA = strA;`, the book says "We then [point] the pointer pA at strA. That is, by means of the assignment statement we copy the address of strA [0] into our variable pA", which is what I don't understand. To copy the address of `strA[0]` into our variable pA via the assignment declaration, shouldn't we write `pA = & strA`? **Question 2**. The expression `c = * ++ p;` increases the value of `p` or the address of `p`? Does the indirection operator (`*`) not indicate the value of the pointed variable?
2021/11/05
[ "https://Stackoverflow.com/questions/69853145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13975322/" ]
> > To copy the address of strA [0] into our variable pA via the assignment declaration, shouldn't we write `pA = & strA`? > > > `&strA` is the address of `strA`. `&strA[0]` is the address of `strA[0]`. These are the “same” in the sense they point to the same place in memory, but they have different types, and the compiler would complain if we wrote `pA = &strA` when the type of `pA` is a pointer to the type of the elements of `strA`. When we write `pA = strA`, the array `strA` is automatically converted to a pointer to its first element, so `pA = strA` is equivalent to `pA = &strA[0]`. > > Question 2: the expression `c = * ++ p;` increases the value of p or the address of p? > > > The C grammar organizes this as `c = *(++p);`, and `++p` increases the value of `p`. If `p` is a pointer, it increases the value of that pointer. The `*` operator uses the increased value. Be careful about speaking of the address of a pointer. The value of the pointer is an address, but you should not say that is the address of the pointer. The pointer is itself an object in memory, and so it has an address in memory where its value is stored. The address where a pointer is stored is different from the address stored in it. The “address of a pointer” is the address where the pointer is stored, not the value of the pointer.
57,637,594
I guys, I am new in angular. I created an angular app and in it I have 3 other generated components to test angular navigation. Here is what I need help with, in the "index.html" when I use "[(ngModel)]" in the an input element, it flags no error but if I try to use **"[(ngModel)]"** in any of the 3 created components html file, it gives my error. I have imported "FormsModule" in the app.module.ts. Please I do I make the ngModel property available in my sub html components? It will be appreciated if you answer with examples. Cheers
2019/08/24
[ "https://Stackoverflow.com/questions/57637594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7408335/" ]
I've been fighting similar problems today (which is how I found your post). To get rid of the libEGL warning run raspi-config and select the "Full KMS" option from Advanced Options->GL Driver (then reboot). That likely won't fix your styling problem though - I'm seeing styling differences between the Pi (my target system) and my Linux Mint development system.
66,110,773
I need help whit my Code (PostgreSQL). I get in my row Result `{{2.0,10}{2.0,10}}` but I want `{{2.0,10}{3.0,20}}`. I don't know where my error is. Result is text `[ ]` its must be a 2D Array This is Table1 | Nummer | Name | Result | | --- | --- | --- | | 01 | Kevin | | This is Table2 | Nummer | Exam | ProfNr | | --- | --- | --- | | 01 | 2.0 | 10 | | 01 | 3.0 | 20 | My Code is ``` update public."Table1" as t1 set "Result" = ARRAY[[t2."Exam", t2."ProfNr"],[t2."Exam",t2."ProfNr"]] from public."Table2" as t2 where t1."Nummer"= 01 and t2."Nummer"=01; ```
2021/02/08
[ "https://Stackoverflow.com/questions/66110773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15172345/" ]
After your `$mail->send();` function, you could try using the PHP in-built function `header();` So for instance in your case: ``` header('Location: /'); ``` This should redirect to home page after submission, where / is the main root of home page. Some more information on header(): <https://www.php.net/manual/en/function.header.php>
10,217,558
To explain my problem more easily I will create the following fictional example, illustrating a very basic many-to-many relationship. A **Car** can have many **Parts**, and a **Part** can belong to many **Cars**. **DB SCHEMA:** ``` CAR_TABLE --------- CarId ModelName CAR_PARTS_TABLE --------------- CarId PartId PARTS_TABLE ----------- PartId PartName ``` **CLASSES:** ``` public class Car { public int CarId {get;set;} public string Name {get;set;} public IEnumerable<Part> Parts {get;set;} } public class Part { public int PartId {get;set;} public string Name {get;set} } ``` Using this very simple model I would like to get any cars that have all the parts assigned to them from a list of parts I am searching on. So say I have an array of PartIds: ``` var partIds = new [] { 1, 3, 10}; ``` I want to mimic the following c# code in terms of a database call: ``` var allCars = /* code to retrieve all cars */ var results = new List<Car>(); foreach (var car in allCars) { var containsAllParts = true; foreach (var carPart in car.Parts) { if (false == partIds.Contains(carPart.PartId)) { containsAllParts = false; break; } } if (containsAllParts) { results.Add(car); } } return results; ``` To be clear: I want to get the Cars that have ALL of the Parts specified from the partIds array. I have the following query, which is REALLY inefficient as it creates a subquery for each id within the partIds array and then does an IsIn query on each of their results. I am desperate to find a much more efficient manner to execute this query. ``` Car carAlias = null; Part partAlias = null; var searchCriteria = session.QueryOver<Car>(() => carAlias); foreach (var partId in partIds) { var carsWithPartCriteria = QueryOver.Of<Car>(() => carAlias) .JoinAlias(() => carAlias.Parts, () => partAlias) .Where(() => partAlias.PartId == partId) .Select(Projections.Distinct(Projections.Id())); searchCriteria = searchCriteria .And(Subqueries.WhereProperty(() => carAlias.Id).In(carsWithPartCriteria)); } var results = searchCriteria.List<Car>(); ``` Is there a decent way to execute this sort of query using NHibernate?
2012/04/18
[ "https://Stackoverflow.com/questions/10217558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/350933/" ]
This should be exactly what you want... ``` Part part = null; Car car = null; var qoParts = QueryOver.Of<Part>(() => part) .WhereRestrictionOn(x => x.PartId).IsIn(partIds) .JoinQueryOver(x => x.Cars, () => car) .Where(Restrictions.Eq(Projections.Count(() => car.CarId), partIds.Length)) .Select(Projections.Group(() => car.CarId)); ```
40,280,440
I've been looking but can't find an answer to this so I'm hoping someone can help. I have two tables Table 1 (audited items) ``` audit_session_id asset_number Audit1 1 Audit1 2 Audit2 3 ``` Table 2 (asset) ``` asset_number location<br> 1 15 2 10 3 15 ``` What I want is a table of assets that appear in Table 2 but not in Table 1 for a given location and audit\_session\_id. What I have is: ``` SELECT a.asset_number FROM auditeditems ai RIGHT JOIN asset a on ai.asset_number = a.asset_number WHERE ai.asset_number IS NULL AND a.location_id=15; ``` However I can't filter on audit\_session\_id as it is NULL. So I get the result: 1,3 when it should just be 1. (assuming I was looking at the audit1 session) I keep thinking this should be straight forward but can't see where I'm going wrong. Thanks in Advance
2016/10/27
[ "https://Stackoverflow.com/questions/40280440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7079298/" ]
Unfortunately, there is little the SO community can help with if you don't provide even a log trace or a code snippet (doesn't have to be directly executable, but an MWE helps). First, you should use [DCMI `hasPart` term](http://dublincore.org/documents/dcmi-terms/#terms-hasPart) for representing `hasPart` relationship. I recommend that you [check all Model statements](https://jena.apache.org/tutorials/rdf_api.html#ch-Statements) before you save it. After that [make sure you are in a Transaction](https://jena.apache.org/documentation/javadoc/arq/org/apache/jena/query/Dataset.html#isInTransaction--). If this helps you, please update the question properly so that this can become an answer to a *real question*, not just a vague description of the problem.
257,454
I don't know if this can be done in an home environment but I would like to make a powerful system and have that providing a way for all my home computers to connect to having their own profile as if they were logging into their own account on a windows machine. I would prefer a Windows 7 Based OS. Is there such thing? I would think Windows Server 2008 R2 with Hyper V machines associated to each account for logging in? Is that the only concept? Thanks
2011/03/14
[ "https://superuser.com/questions/257454", "https://superuser.com", "https://superuser.com/users/46390/" ]
That sounds like the basic Roaming Profiles facility that all Windows Server editions (certainly since Server 2000) provides. 1. Install a windows server, and set it up as an Active Directory Server. 2. Join the workstations into the Domain you created as part of Step 1. You now have centralised user management and profile storage at your fingertips.
13,348,002
So I need my objects to be able to use functions that are within the main class, so when they are created I want them to get it through their parameters. ``` int main(int argc, char* args[]) { Unit units[3]={{5,5,this},{8,8,this},{12,12,this}}; units[0].init(true); for (int i=1;i<sizeof(units) / sizeof(units[0]);i++) { units[i].init(false); } ``` Where i put "this" it should be the main class, this is how I would do it in java but I am unsure how to do it here. I tried "\*this" and "this" but all I get is an error: Invalid use of 'this' in non-member function. Searching for the error gave me nothing to work with since I am rather unknowing on c++'s class systems. The two first parameters are for the location. The Init commands parameter sets whether they are allies or not. I want the Unit classes to be able to access: ``` int getClosestHostileX(int ask_x,int ask_y,bool team) { return 55; } ``` There is supposed to be more code here later I am just trying to get them to return. I am using Code::Blocks IDE and GNU GCC compiler. TL;DR How do I make my other classes access functions from my main class?
2012/11/12
[ "https://Stackoverflow.com/questions/13348002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1818669/" ]
You couldn't do that in Java, either. In Java, the entrypoint is a static method and has no associated object instance. The solution is the same -- instantiate your type. ``` int main(int argc, char** argv) { MainClass main_object; // creates an instance Unit units[3]={{5,5,&main_object},{8,8,&main_object},{12,12,&main_object}}; units[0].init(true); for (int i=1;i<sizeof(units) / sizeof(units[0]);i++) { units[i].init(false); } ```
740
I'm trying to override a view table from within my module. I can't locate what the arguments are suppose to be and in what order (for my hook\_theme func). I copied the theme file from views/themes and did no modifications. Does anyone know what is going wrong, and what should the arguments value be below? My theme configuration is currently: ``` 'views_view_table__opportunities_mentions' => array( 'arguments' => array( 'view' => NULL, 'title' => NULL, 'header' => NULL, 'fields' => null, 'class' => null, 'row_classes' => null, 'rows' => null ), 'template' => 'views-view-table--opportunities-mentions', 'original hook' => 'views_view_table', 'path' => drupal_get_path('module', 'smd') . '/theme', ), ```
2011/03/14
[ "https://drupal.stackexchange.com/questions/740", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/69/" ]
The easiest way to theme views is to edit the particular view in question and scroll down to find the link 'theme information'. This screen will tell you exactly what views theming templates that it is currently using and what templates you can make in your theme to override this output. That essentially all views theming is - overriding the default markup with something to suit you designs. @see <http://www.group42.ca/theming_views_2_the_basics> for an excellent tutorial on views theming **EDIT** If you want full control over the markup produced, *and* for this to be portable across themes, the only option you have is to create a custom module. This custom module could also have themeable components, and could even use a view to perform any heavy SQL (or you could just hand-write the SQL) Take a look at a similiar module to get you started, and have a read through [hook\_theme](http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_theme/6)
28,714,622
my project is in **vbnet**. i have a **stored procedure**, and get the results with **linq**. i know how to get it with sql adapter, which is easy in sorting and filtering, but i have to do it with linq. my code is like that. ``` dgv.DataSource = db.Egitek_Gorev_Listesi(LoggedUserID) ``` data is shown in datagridview, but i can not filter,**search** or **order** in it. does anybody know a better way todo it.
2015/02/25
[ "https://Stackoverflow.com/questions/28714622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3950877/" ]
The corresponding entity for `dbo.AspNetUserLogins` table is `IdentityUserLogin` class. So we just need to declare an appropriate `IDbSet<IdentityUserLogin>` or `DbSet<IdentityUserLogin>` property in the `ApplicationDbContext` class as follows: ``` public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { // ... public IDbSet<IdentityUserLogin> UserLogins { get; set; } // ... } ``` and then query it as usually: ``` using (var dbContext = new ApplicationDbContext()) { var userLogins = dbContext.UserLogins.ToList(); } ```
68,746,355
i'm mapping a reviews API's array and i want to show only the clicked review when i click on "read more" but at the moment is expanding all the reviews of my array, i'm using typescript and it's all new to me so i don't know how to move, how should i pass the information of the index to my state? ``` interface State { reviews: Review[]; isReadMore: boolean; } export default class MoviePage extends Component<{}, State> { state: State = { reviews: [], isReadMore: false, }; componentDidMount() { this.asyncAwaitFunc(); this.toggle(arguments); } asyncAwaitFunc = async () => { try { const reviewmovie = await axios.get<ReviewResponse>( `https://api.themoviedb.org/3/movie/${this.props.match.params.id}/reviews?api_key=` ); this.setState({ reviews: reviewmovie.data.results, }); } catch (error) {} }; toggle(index: any) { this.setState({ isReadMore: !this.state.isReadMore, }); render() { const { isReadMore, reviews } = this.state; return ( <> <ReviewGrid> {reviews.map((review, index) => ( <ReviewContent key={index}> {this.state.isReadMore ? review.content.substring(0, 650) : review.content} <Button onClick={() => this.toggle(index)}> {isReadMore ? "...read more" : " show less"} </Button> </ReviewContent> ))} </ReviewGrid> </> ); } } ```
2021/08/11
[ "https://Stackoverflow.com/questions/68746355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've modified your code a bit to make this work since I don't have access to the API or the various interfaces and components you're using, but this should give you an idea. You're tracking `isReadMore` as a single piece of state, which is why it's toggling for every item in the array. You need to track state individually for each review. This is one of several solutions that could work, but the idea here is to take the API's response, and map it to a new set of objects which includes a new key that you'll add, `isReadMore`, then you can toggle this property individually for each review. [Here](https://codesandbox.io/s/stack-overflow-answer-2moxl?file=/src/index.tsx) is the working example on CodeSandbox. **EDIT:** [Here is a link](https://codesandbox.io/s/stack-overflow-answer-forked-ucgkk?file=/src/index.tsx) to a second example which does not require you to map over the results of the api call to add a new key to track `isReadMore` state. This approach tracks the state separately in a `Map<Review, boolean>` instead. An ES6 map works well here because you can use the review object itself as the key and the boolean value can track your hide/show state. --- **Original Solution** ``` interface Review { title: string; content: string; } interface MyReview extends Review { isReadMore: boolean; } interface State { reviews: MyReview[]; } export default class MoviePage extends React.Component<{}, State> { state: State = { reviews: [] }; componentDidMount() { this.asyncAwaitFunc(); } asyncAwaitFunc = () => { try { const reviewsFromApi: Review[] = [ { title: "Some Movie", content: "some movie review that's pretty long" }, { title: "Some Other Movie", content: "an even longer super long movie review that's super long" } ]; this.setState({ reviews: reviewsFromApi.map((r) => ({ ...r, isReadMore: false })) }); } catch (error) { console.log(error); } }; toggle(index: number) { this.setState({ reviews: this.state.reviews.map((r, i) => { if (i === index) { return { ...r, isReadMore: !r.isReadMore }; } return r; }) }); } render() { const { reviews } = this.state; return ( <> <div> {reviews.map((review, index) => ( <div key={index}> <p> {review.isReadMore ? review.content.substring(0, 10) + "..." : review.content} </p> <button onClick={() => this.toggle(index)}> {review.isReadMore ? "Read more" : " Show less"} </button> </div> ))} </div> </> ); } } ```
38,286
I know that memorising the whole the Quran is fard kifaya but are there any other fard kifaya acts ?
2017/03/05
[ "https://islam.stackexchange.com/questions/38286", "https://islam.stackexchange.com", "https://islam.stackexchange.com/users/20796/" ]
The most known examples are the funeral prayer (salat al-Janazah beside the janazah -burying itself- and the ghusl of the dead person), jihad, memorizing quran, getting or seeking knowledge, enjoining what is good and forbidding what is evil and ijtihad. What constitutes fard al-kifaya فرض كفاية is that it is an obligation on the Ummah, but if any of them perform this obligation the rest would be exempt from performing it, but if nobody does it the Ummah would be considered as sinning. > > قال الإمام الشافعي رحمه الله : "حق على الناس غسل الميت ، والصلاة عليه ودفنه ، لا يسع عامتهم تركه. وإذا قام به من فيه كفاية أجزأ عنهم ، إن شاء الله تعالى" انتهى من "الأم" (source [islamqa#131270](https://islamqa.info/ar/131270)) > > > Al-Imam a-Shafi'i has written in his al-Umm: "a right people must fulfill is washing the dead, praying on him and burying him, and they can't leave it all of them, if enough people did it those would be rewarded and the rest exempt from it, if Allah wills" > > > But a fard kifaya can easily move from this state to the state of fard 'ayn فرض عين, an obligation which must be performed by anybody (except people who have special conditions). For example if Muslims don't have their own physicians anybody would be asked to learn this science until we would have a capable person, if nobody re-reads the sources and does ijtihad we are all asked to do so until we find at least one capable person. And for jihad it is fard kifaya for jihad to attack the enemy (if this is an allowed option) or help oppressed Muslims in a place far away, but if the enemy is in your country it would be fard 'ayn to fight him! Some relevant posts: [Is ijtihad open in Islam (Sunni view)?](https://islam.stackexchange.com/questions/17371/is-ijtihad-open-in-islam-sunni-view/26101#26101) [Levels of approval/disapproval](https://islam.stackexchange.com/questions/35381/levels-of-approval-disapproval/35385#35385)
35,121
While leveling in Skyrim I put a perk in a tree, but now I feel like it is wasted, since I've found blowing things up with spells is much more fun than stabbing things with a giant sword. Is there anyway for me to recover the wasted perk? I'm on the PC so I was guessing console commands could help.
2011/11/11
[ "https://gaming.stackexchange.com/questions/35121", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/3015/" ]
If you are on PC, you can use the console to add and remove perks. **Finding a perk id:** help [name of perk] 4 *help Armsman 4* **Removing a perk** player.removeperk [perk id] *player.removeperk 00079342* **Adding a perk** player.addperk [perk id] *player.addperk 00079342* Notes: * You can use the PageUp/PageDown keys to scroll the console. * Use double quotes when searching for a perk with a space: "Steel Smithing" -yx * The [UESP](http://www.uesp.net/wiki/Template:Skills_in_Skyrim) has the perk id for all the skills. -Mark Trapp
1,086,806
Since I upgraded from Ubuntu 16.04 to 18.04, both Filezilla and Firefox always open in full-screen mode, no matter how I have adjusted them before closing. What can I do to change this annoying behaviour?
2018/10/24
[ "https://askubuntu.com/questions/1086806", "https://askubuntu.com", "https://askubuntu.com/users/885664/" ]
Either: 1. Double-click on the application's titlebar to minimize/maximize the window. 2. Use the GNOME Tweaks tool, and enable the following, and then click the little square icon in the top-right corner of the application's window. [![enter image description here](https://i.stack.imgur.com/nihCZ.png)](https://i.stack.imgur.com/nihCZ.png) **Update #1:** In `terminal`... ``` cd ~/.mozilla/firefox # change to firefox prefs directory ls -al *.default # the one with the newest date is yours cd {.default directory found before} # change to your user directory ls -alt | grep "Oct 25" # note which files changed today ``` one of these files is causing your problem...
521,702
I am a LaTeX newbie. I am curious to hear your recommendations about the best places to learn it. More precisely, I am going to start writing my doctoral thesis in it. Our school already has a template but I would like to get the basics first before diving into that template. With that, I plan to continue writing my journal articles in LaTeX instead of MS Word (which is, as you may relate, sometimes painfully unfriendly to scholars when it comes to formatting).
2019/12/23
[ "https://tex.stackexchange.com/questions/521702", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/203832/" ]
My go to is [Wiki](https://en.wikibooks.org/wiki/LaTeX). It literally has everything you need. It is laid out pretty great where you can both learn, and use it as a reference. I use it often. Also, the TeX - LaTeX StackExchange is an excellent place to get answers to specific problems. Once you have an appropriate template, this will give you everything you need to format your thesis. Good luck! Also, don't bog yourself down with the details (in my opinion). Understanding exactly what the LaTeX code is doing is going down a rabbit hole. Just focus on understanding what you need to do what you want.
61,197,916
I've got myself a bit confused regarding variables in Python, just looking for a bit of clarification. In the following code, I will pass a global variable into my own Python function which simply takes the value and multiplies it by 2. Very simple. It does not return the variable after. The output from the print function at the end prints 10500 rather than 21000, indicating that the local variable created within the function did not actually edit the global variable that was passed to, but rather used the value as its argument. ``` balance = 10500 def test(balance): balance = balance * 2 test(balance) print(balance) ``` However, in my second piece of code here, when I pass a list/array into a separate function for bubble sorting, it is the actual array that is edited, rather than the function just using the values. ``` def bubble_sort(scores): swapped = True while swapped: swapped = False for i in range(0, len(scores)-1): if scores[i] > scores[i+1]: temp = scores[i] scores[i] = scores[i+1] scores[i+1] = temp swapped = True scores = [60, 50, 60, 58, 54, 54] bubble_sort(scores) print(scores) ``` Now when I print my scores list, it has been sorted. I am confused as to why the top function did not change the global variable that was passed to it, while the second function did? I understand using the global keyword within functions means I am still able to write code that will edit a global variable within my own functions, but maybe I am missing some basic understanding.
2020/04/13
[ "https://Stackoverflow.com/questions/61197916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9200058/" ]
Thank You Botje! Thank You very much for trying to help me. But I have no time anymore for learning openssl. So I found a great one: **<https://github.com/Thalhammer/jwt-cpp>** from here **jwt.io** It doesn't support the 'scope' field for the jwt-claim, so I just added a method into a class into a header: 'set\_scope(...);'. Ten, 10... Nooo, You just can't feel my pain beacuse of openssl\_from\_devs\_with\_crooked\_hands\_with\_no\_human\_docs. 10 strings of a code and it's done! It has simple sources, so You can find out how to work with ssl from there. If You want to use OpenSSL lib and don't know how it works - **think twice**, may be it's the worst choice of Your life. Good luck!
40,671,349
As per the title, I need a string format where ``` sprintf(xxx,5) prints "5" sprintf(xxx,5.1) prints "5.1" sprintf(xxx,15.1234) prints "15.12" ``` That is: no leading zeros, no trailing zeros, maximum of 2 decimals. Is it possible? if not with sprintf, some other way? The use case is to report degrees of freedom which are generally whole numbers, but when corrected, may result in decimals - for which case only I want to add two decimals).
2016/11/18
[ "https://Stackoverflow.com/questions/40671349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2986596/" ]
Maybe `formatC` is easier for this: ``` formatC(c(5, 5.1, 5.1234), digits = 2, format = "f", drop0trailing = TRUE) #[1] "5" "5.1" "5.12" ```
28,861,972
This should be quite simple but I didn`t manage to find it. If I am running some batch script in cmd, how do I get process id of the hosting cmd? ``` set currentCmdPid= /* some magic */ echo %currentCmdPid% ``` I have found a lot of solutions that use `tasklist` and name filtering but I believe that this won`t work for me, since there can be launched many instances of cmd. Again, I`d like to have some simple elegant and bullet-proof solution. Thanks.
2015/03/04
[ "https://Stackoverflow.com/questions/28861972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/945343/" ]
Here the topic has been discussed -> <http://www.dostips.com/forum/viewtopic.php?p=38870> Here's my solution: ``` @if (@X)==(@Y) @end /* JScript comment @echo off setlocal for /f "tokens=* delims=" %%v in ('dir /b /s /a:-d /o:-n "%SystemRoot%\Microsoft.NET\Framework\*jsc.exe"') do ( set "jsc=%%v" ) if not exist "%~n0.exe" ( "%jsc%" /nologo /out:"%~n0.exe" "%~dpsfnx0" ) %~n0.exe endlocal & exit /b %errorlevel% */ import System; import System.Diagnostics; import System.ComponentModel; import System.Management; var myId = Process.GetCurrentProcess().Id; var query = String.Format("SELECT ParentProcessId FROM Win32_Process WHERE ProcessId = {0}", myId); var search = new ManagementObjectSearcher("root\\CIMV2", query); var results = search.Get().GetEnumerator(); if (!results.MoveNext()) { Console.WriteLine("Error"); Environment.Exit(-1); } var queryObj = results.Current; var parentId = queryObj["ParentProcessId"]; var parent = Process.GetProcessById(parentId); Console.WriteLine(parent.Id); ```
3,650,353
Show that $2^n>\frac{(n-1)n}{2}$ without using induction. MY attempt : $$1+2+3+...+(n-2)+(n-1)=\frac{n(n-1)}{2}$$ Since $2^n>n$, $$2^n+2^n+2^n+...+2^n+2^n>\frac{n(n-1)}{2}$$ $$(n-1)2^n>\frac{n(n-1)}{2}$$ SO I'm getting an obvious fact :( How to do it without induction?
2020/04/29
[ "https://math.stackexchange.com/questions/3650353", "https://math.stackexchange.com", "https://math.stackexchange.com/users/280637/" ]
Suppose you have a finite set of $n$ elements. $2^n$ is the number of all possible subsets. $n(n-1)/2$ is the number of subsets of size exactly two, which is strictly less than the number of all possible subsets.
52,747,847
Write a function named "find\_value" that takes a key-value store as a parameter with strings as keys and integers as values. The function returns a boolean representing true if the value 7 is in the input as a value, false otherwise. (My code below) ``` function find_value(key){ for (var i of Object.values(key)){ if (i == 7){ return true; } else{ return false; } } } ``` When I call with the input `[{'effort': 4, 'doctrine': 8, 'item': 11, 'behavioral': 7, 'occasional': 11}]`, I should get `true`, but I am getting `false` instead. What am I doing wrong?
2018/10/10
[ "https://Stackoverflow.com/questions/52747847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Your loops is returning false on your first item, most likely. You should keep the condition and return true statement in the loop, but after the loop you should return false. P.S. You should name your parameter and set a default value for good practice. I renamed it in my example below. ``` function find_value(myObject = {}){ for (var i of Object.values(myObject)){ if (i == 7){ return true; } } return false; } ```
13,042,459
I have two tables. One is the "probe" and the other "transcript". Probe table: "probe" ProbeID-------TranscriptID---- ``` 2655 4555555 2600 5454542 2600 4543234 2344 5659595 ``` ...etc Transcript table: "transcript" TranscriptID----Location---- ``` 7896736 chr1 5454542 chr1 ``` ...etc I need to find out how many transcripts per chromosome? AND How many probes per chromosome? ``` SELECT COUNT(*) FROM transcript ``` = '28869' #Above I think gives me the transcripts per chromosome (i.e. location). I need help with answering the second part (and first, if its wrong). I am assuming I need to use the `JOIN` clause. Thank you.
2012/10/24
[ "https://Stackoverflow.com/questions/13042459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1698774/" ]
I did this exact thing on a client site. I re-used the same product grid across the entire site and it was 100% DRY. I used the dev branch of Stash and used the new embed feature. While regular embeds are always an option that *work*, Stash embeds are more efficient and more powerful. The real difference is how you pass variables, and when the embed is parsed. With stash embeds can be used inside a looping tag, and parse the data just once. (Where as regular embeds get parsed with each iteration of the loop.) Here is a Gist I posted a while back for another user on Twitter. <https://gist.github.com/2950536> Note, the example represents multiple files and code blocks, or I would just post here. IMO, it would make this post hard to follow and read if I posted it here. Essentially it follows a modified template partials approach. More information on template partials. <http://eeinsider.com/blog/ee-podcast-stash-template-partials/> But to more directly answer the question of, "How does one replace embed variables with Stash?". The solution is rather simple and based on core programming concepts of "setters" and "getters".The theory is, if one sets a variable it can be retrieved at any later point in the template. The trick is settings the variables before the getters are parsed. ``` {exp:stash:set} {stash:page_content} {exp:channel:entries channel="your-channel"} {stash:your_var_1}Some value 1{/stash:your_var_1} {stash:your_var_2}Some value 2{/stash:your_var_2} {stash:your_var_3}Some value 3{/stash:your_var_3} {stash:your_var_4}Some value 4{/stash:your_var_4} {stash:embed name="your-template" process="start"} {/exp:channel:entries} {/stash:page_content} {/exp:stash:set} {stash:embed name="header" process="end"} ``` That's where the *process* parameter comes into play. This will allow you to embed your template *before* the entries loop is ran, and to embed the header which would contain the site wrapper and output the page content. Once you get the hang of it, it becomes really powerful and makes your sites so much cleaner.
26,932,366
As a previous result of a bad TFS project management, several tasks has been created in the wrong work item. Now I need to move several tasks to different work items. Is there an easy way to do it? So far, I have to edit each task, remove the previos link to primary element and create a new one, but this is taking a lot of my time.
2014/11/14
[ "https://Stackoverflow.com/questions/26932366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/897383/" ]
I suspect that the easiest way to do it would be from Excel. Create a Tree-based query that shows everything, then move the child records in Excel using simple cut and insert cut cells. Excel will then allow you to publish the new structure in one go. If you need to move items up to a higher or lower level, place the Title Field in the column representing the level. [See this little video I captured to show how it is done.](https://www.youtube.com/watch?v=86-8cb4LhS8&hd=1)
16,375,500
I'm creating a hibernate app and I'm able to save data to dtb via `hibernate`. Nevertheless I wasn't able to figure out, how to retrieve data from database. Could anybody show me, how to do that in some way, that will be similar to the way, I save data? I've been googling a lot, but everything, I didn't find anything, that would look like my way... E.g. they used a lot of annotations etc. I'm quite new to hibernate, so it's possible, that this is not a good way, how to create hibernate applications. If so, pls write it in a comment. Part of my `UserDAOImpl`: ``` UserDAO user; public UserDAOImpl() { user = new UserDAO(); } public void createUser(int id, String Username, String CreatedBy) { user.setUserId(id); user.setUsername(Username); user.setCreatedBy(CreatedBy); user.setCreatedDate(new Date()); } public void saveUser() { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); session.save(user); // save the data to the database session.getTransaction().commit(); // close the connection session.disconnect(); } public void findUser() { // ???????????? } ``` UserDAO: ``` public class UserDAO implements java.io.Serializable { /** * generated serialVersionUID */ private static final long serialVersionUID = -6440259681541809279L; private int userId; private String username; private String createdBy; private Date createdDate; public UserDAO() { } public UserDAO(int userId, String username, String createdBy, Date createdDate) { this.userId = userId; this.username = username; this.createdBy = createdBy; this.createdDate = createdDate; } public int getUserId() { return this.userId; } public void setUserId(int userId) { this.userId = userId; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getCreatedBy() { return this.createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public Date getCreatedDate() { return this.createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } } ```
2013/05/04
[ "https://Stackoverflow.com/questions/16375500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1364923/" ]
Assuming the table name is User, here is the sample code to get a User data for an input userId: ``` public User findUserById(int userId) { Session session = HibernateUtil.getSessionFactory().openSession(); String queryString = "from User where userId = :userId"; Query query = session.createQuery(queryString); query.setInteger("userId", userId); Object queryResult = query.uniqueResult(); UserDAO user = (UserDAO)queryResult; } ```
56,778,762
I am using SQL Server and in my database I have a date column of type `varchar` and has data like `04042011`. I am trying to write a query that is being used for another program and it is requesting the format in a military format such as `YYYY-MM-DD`. Is there any way to do this on the fly for `HireDate` and `SeparationDate`? ``` SELECT [EmployeeTC_No] AS "Employee TC #" ,[pye_nlast] AS "Name Last" ,[pye_nfirst] AS "Name First" ,[Dept] AS "Department" ,CASE WHEN [pye_status] = 'A' THEN 1 WHEN [pye_status] = 'T' THEN 0 ELSE NULL END AS "Active" ,[HireDate] AS "Hire Date" ,[SeparationDate] AS "Separation Date" FROM [OnBaseWorking].[dbo].[Employees] WHERE EmployeeTC_No != 'Not Assigned' AND LOWER(EmployeeTC_No) = LOWER('@primary') ``` Any help would be greatly appreciated. I only have read rights. So I am hoping I can do this on the fly I know dates should not be data type `varchar` and should be data type date. But I have no control over this and just trying to do what I can.
2019/06/26
[ "https://Stackoverflow.com/questions/56778762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4106374/" ]
If truly 8 characters. I would stress use try\_convert() in case you have some bogus data. ``` Select try_convert(date,right(HierDate,4)+left(HierDate,4)) From YourTable ``` To Trap EMPTY values. This will return a NULL and not 1900-01-01 ``` Select try_convert(date,nullif(HierDate,'')+left(HierDate,4)) From YourTable ```
71,815
Most of the work being done at my company is Qt-based C++, and it's all checked into a Subversion repository. Until now, all work on the codebase has been done purely with nano, or perhaps Kate. Being new here, I would like to take advantage of setting up Eclipse -properly- to edit my local copy of the tree. I have the CDT "version" of Eclipse, and the Qt integration, and the Subclipse module. At this point, though, I don't know what to do. Do I "import" the projects into an Eclipse-controlled workspace? Do I edit them in place? Nothing I've tried to do gets Eclipse to recognize that the "project" is a Qt application, so that I can get the integration working.
2008/09/16
[ "https://Stackoverflow.com/questions/71815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11959/" ]
I would create a new QT project in eclipse, then switch perspectives to subclipse and simply do a SVN checkout into the new eclipse project. You should be good to go.
16,622
What are some real-life exceptions to the PEMDAS rule? I am looking for examples from "real" mathematical language --- conventions that are held in modern mathematics practice, such as those appearing in papers, books, and class notes, that are not covered (or contradicted) by PEMDAS. I am not interested in contrived examples, such as those constructed [to confuse people on Facebook](https://slate.com/technology/2013/03/facebook-math-problem-why-pemdas-doesnt-always-give-a-clear-answer.html). The PEMDAS convention says that order of operations are evaluated as: 1. Parentheses 2. Exponents 3. Multiplication and Division, from left to right 4. Addition and Subtraction, from left to right So far I know of one exception: sometimes the placement of text indicates "implicit" parentheses: text that is a superscript, subscript, or above/below a fraction. * $2^{3 + 5}$ Here, $3 + 5$ is evaluated before the exponentiation * $\frac{3+5}{2}$ Here, $3 + 5$ is evaluated before the division Are there other exceptions?
2019/05/16
[ "https://matheducators.stackexchange.com/questions/16622", "https://matheducators.stackexchange.com", "https://matheducators.stackexchange.com/users/200/" ]
The examples you give aren't exceptions. The parentheses aren't needed because there is no other way to interpret the expressions. In applications in engineering and the physical sciences, variables have units associated with them, and the units often disambiguate the expression without the need for parentheses. For example, if $\omega$ has units of radians per second, and $t$ has units of seconds, then $\sin\omega t$ has to be interpreted as $\sin(\omega t)$, not as $(\sin\omega) t$, because the sine function requires a unitless input. Omitting the parentheses is preferable in examples like these because it simplifies the appearance of expressions and makes them easier to parse. Similarly, if a force $F$ acts on an object of mass $m$ for a time $t$, then, starting from rest, the object is displaced by $Ft^2/2m$. This can only be interpreted as $(Ft^2)/(2m)$, because otherwise the units wouldn't come out to be units of distance. Examples like this aren't just typewriter usages. Built-up fractions that occur inline in a paragraph of text are awkward typographically: $\frac{Ft^2}{2m}$. They either have to be written very small, which makes them hard to read, or they force the spacing of the lines to be uneven, which looks ugly. These are examples involving physics and units, but more generally, when people read mathematics, they apply their understanding of the content, which could be economics or number theory. People are not computers. Mathematical notation is a human language written for humans to read. Human languages are ambiguous, and that's a good thing. When we don't require all ambiguities to be explicitly resolved, it helps with concision and expressiveness. Besides the meaning, another factor that resolves ambiguities and allows concise and readable notation is that we have certain conventions that we follow, such as the convention that tells us to write $2x$ rather than $x2$. If someone means $(\sin x)(y)$, then they'll write it as $y\sin x$, not $\sin xy$. There is also a convention that if we have a long chain of multiplications and divisions, such as $abcdefgh/ijklm$, we put all the multiplicative factors to the left of the slash, and then it's understood that we mean $abcdefgh/(ijklm)$. We wouldn't write this as $a/ibc/j/kdef/lgh/m$, which would be extremely difficult to read. We wouldn't interpret $abcdefgh/ijklm$ as $(abcdefgh/i)jklm$, because if that had been the intended meaning, it would have been written like $abcdefghjklm/i$.
39,080,703
I have a bootstrap popover element with a form inside. I do a `preventDefault()` when the form is submitted but it doesn't actually prevent the submit. When I don't use the popover and a modal instead it works perfectly. Here is my HTML: ``` <div class="hide" id="popover-content"> <form action="api/check.php" class="checkform" id="requestacallform" method="get" name="requestacallform"> <div class="form-group"> <div class="input-group"> <input class="form-control" id="domein" name="name" placeholder="domein" type="text"> </div> </div><input class="btn btn-blue submit" type="submit" value="Aanmelden"> <p class="response"></p> </form> </div> ``` Here is my JavaScript file where I create the popup (main.js) ``` $('#popover').popover({ html: true, content: function() { return $("#popover-content").html(); } }); ``` And this is where I do my `preventDefault()` in an other JavaScript file ``` $(".checkform").submit(function(e) { e.preventDefault(); var request = $("#domein").val(); $.ajax({ // AJAX content here }); }); ``` Why the `preventDefault()` isn't working?
2016/08/22
[ "https://Stackoverflow.com/questions/39080703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6730270/" ]
You're trying to append event handler for `.checkform` before adding it to DOM. You need to load second javascript file after loading contents html or append event globaly: ``` $("body").on("submit",".checkform", function(e){ e.preventDefault(); var request = $("#domein").val(); $.ajax({ ... }); ``` You can read more about events binding on dynamic htmls [here](https://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements)
21,859,041
Here is what I want to do... I have a bunch of text files that I need to go through and keep only the top 5 lines. If I do `top` then output to a file that is part way there. I need the file name to be the same as it was earlier. Ex.: `file.name` - take top 5 lines (delete everything below line 5), then save file as `file.name`. There are a number of files that this will need to be done on as a batch.
2014/02/18
[ "https://Stackoverflow.com/questions/21859041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3324211/" ]
You can use `head` to do this. ``` head -n 5 file.name > file.name.tmp && mv file.name.tmp file.name ``` You can structure this as a script to do it for all files, passing `file.name` as an argument in each run later.
523,003
I have a text file where column and row number will always vary, and want to remove entire rows from the txt file only if every column within it is equal to either $VAR1 or $VAR2. For example: Lets say $VAR1="X" and $VAR2="N" and I want to remove any row where $VAR1 and $VAR2 makes up the entire column. This would be my input: ``` hajn 32 ahnnd namm 5 543 asfn F X X N X X X N X 5739 dw 32eff Sfff 3 asd 3123 1 ``` And this would be my desired output: ``` hajn 32 ahnnd namm 5 543 asfn F 5739 dw 32eff Sfff 3 asd 3123 1 ``` I can solve this with a loop, but I was wondering if there's a powerful one liner way of doing this, preferably awk.
2019/06/05
[ "https://unix.stackexchange.com/questions/523003", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/170497/" ]
``` $ VAR1=N $ VAR2=X $ awk -v a="$VAR1" -v b="$VAR2" '{ for (i=1; i<=NF; ++i) if ($i != a && $i != b) { print; next } }' file hajn 32 ahnnd namm 5 543 asfn F 5739 dw 32eff Sfff 3 asd 3123 1 ``` Here, we transfer the values `$VAR1` and `$VAR2` into our short `awk` script and its `a` and `b` variables using `-v` on the command line. Inside the `awk` script, we iterate over the fields of each line, and if any field is different from both the `a` and the `b` value, we print the full line and continue with the next line immediately. If no field is different from both `a` and `b`, nothing happens (the line is not printed).
48,305,293
I am using the the jQuery animate function for smooth scrolling inside a div however this function only works properly when you are scrolled at the top. after many console logs on the positions of the tags and hours trying to figure this out i know why this is. this is due to the position of the elements inside the overflow changing when you scroll. the problem is that when you click on one of the tags it will only scroll to the correct position if the div is scrolled to the top, however if the div is anywhere but the top it doesn't do so. for example if you click on the 4th tag and then immediately click on the 3rd it wont go to the correct position when you click on the 3 due to you not being scrolled to the top. i couldn't come up with the correct equation or something to make the div scroll to the correct tag regardless of scroll position. Here is the simple code for the animation the rest is on jsfiddle ``` $('#iddescription').animate({ scrollTop: target.position().top - $('#iddescription').position().top } ``` I did think about doing double animations scrolling to the top first and then scrolling to the correct position but this isn't really what I want. Could somebody help me please without using a plugin just jQuery, here is the code <https://jsfiddle.net/509k8stu/3/> .
2018/01/17
[ "https://Stackoverflow.com/questions/48305293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8233463/" ]
Animating `scrollTop` to the following position seems to fix the issue: ``` target.offset().top + $('#iddescription').scrollTop() - $('#iddescription').offset().top ``` I would also recommend you abort previous scroll animations using the `.stop()` method. So your full animation method would look something like this: ``` $('#iddescription').stop().animate({ scrollTop: target.offset().top + $('#iddescription').scrollTop() - $('#iddescription').offset().top }, 1000, function() { }); ``` See the result in [this updated fiddle](https://jsfiddle.net/509k8stu/5/)
45,731,858
i am running the airflow pipeline but codes looks seems good but actually i'm getting the airflow.exceptions.AirflowException: Cycle detected in DAG. Faulty task: can u please help to resolve this issue
2017/08/17
[ "https://Stackoverflow.com/questions/45731858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8259305/" ]
This can happen due to duplicate task\_id'a in multiple tasks.
51,499,697
I am trying to solve Sherlock and Square problem in Hackerrank [(link)](https://www.hackerrank.com/challenges/sherlock-and-squares/problem) for finding the perfect square within a range of data. 4 test cases passed but i am getting a timeout error for large numbers. Please suggest something to improve its performance My code is as follows: ``` #include<iostream> #include<cmath> using namespace std; int squares(int a, int b) { long double i; long long int count=0; for(i=a;i<=b;i++) { long double b = sqrt(i); if(fmod(b,1)==0.000000) { count++; } } return count; } int main() { int q,i,a,b; cin>>q; for(i=0;i<q;i++) { cin>>a>>b; int result = squares(a, b); cout<<result<<"\n"; } } ```
2018/07/24
[ "https://Stackoverflow.com/questions/51499697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9256840/" ]
Kindly use div into div as you have 2 divs. one is for background and other one for Heading it will be like ``` <div class="bg"> <div id="heading">Some stuff</div> // All the staff for background will goes here </div> ``` it will work in your case and if you use other divs after this they will not have the background image.
7,812
I'd like to make some extra icepacks to put in my coolbag. The 2 commercial icepacks it comes with don't maintain the temperature for long enough, so I've tried supplementing them with plastic bottles of water that I've frozen. This works reasonably well but are there other containers that would work better and is there anything I could add to the water?
2015/07/27
[ "https://lifehacks.stackexchange.com/questions/7812", "https://lifehacks.stackexchange.com", "https://lifehacks.stackexchange.com/users/5304/" ]
### Use a mixture to modify the water's properties You could use an antifreeze/water mixture that you put in a bottle. You will have a much lower freezing and higher boiling point that just water. This will allow you to keep your frozen packs at a lower temperature than plain ice for longer. ### Safety Concerns You will also need to be **extremely careful with antifreeze around food and/or drinks as it is toxic to almost all mammals.** Other creatures may also have toxic reactions to the antifreeze. Insure that if you use a recycled water bottle that it is **extremely difficult** (*aim for impossible*) for you and/or **children** to get into it. ### Options You could also try using alcohol instead of water. It is the same principle as mixing antifreeze with water. It is also much safer than antifreeze, but you will still need to modify the bottle to prevent child access.
175,583
> > **Possible Duplicate:** > > [Where does this concept of “favor composition over inheritance” come from?](https://softwareengineering.stackexchange.com/questions/65179/where-does-this-concept-of-favor-composition-over-inheritance-come-from) > > > I have colleagues at work who claim that "Inheritance is an anti-pattern" and want to use composition systematically instead, except in (rare, according to them) cases where inheritance is really the best way to go. I want to suggest an alternative where we continue using inheritance, but it is strictly forbidden (enforced by code reviews) to use anything but public members of base classes in derived classes. For a case where we don't need to swap components of a class at runtime (static inheritance), would that be equivalent enough to composition? Or am I forgetting some other important aspect of composition?
2012/11/12
[ "https://softwareengineering.stackexchange.com/questions/175583", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/65385/" ]
You're sort of looking at it backwards. Composition isn't preferred because of some unseen benefit of composition, it's preferred because it avoids the drawbacks of inheritance. Inheritance adds the significant benefit of substitutability. However, that benefit comes with the significant cost of tight coupling. Inheritance is the strongest coupling relationship possible. If you don't need the substitutability, the coupling cost isn't worth it. Your restricted version of inheritance addresses its other cost, a loss of encapsulation, but does nothing about the much more significant cost of coupling.
11,708,005
I want to know how to put text to a website's textbox with VB.NET. Like when you complete a textbox and press enter. Something like this: Dim web as webbrowser web.document.textbox(1).insert("text")
2012/07/29
[ "https://Stackoverflow.com/questions/11708005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1494250/" ]
it would look something like this: ``` WebBrowser1.Document.GetElementById("login_password").SetAttribute("value", TextBox2.Text) ```
725,817
I'm seeing a strange problem with the ADFS updatepassword page. We're batch-creating users, and they are trying to change their passwords. However, roughly 50% of the accounts can't change their password, the following event is logged: > > Password change failed for following user: > > > Additional Data > > > User: DOMAIN\username > > > Device Certificate: > > > Server on which password change was attempted: ad01.ad.domain Error > details: NewPasswordHistConflict > > > The error would indicate that the password is the same as the previous, but we've tested several different passwords, and still get the same error. I can't find anything special common between the accounts that have problems and those who don't. The users are created with this Powershell line: ``` New-ADUser -Name $displayName -DisplayName $displayName -SamAccountName $accountName` -GivenName $FirstName -Surname $LastName -EmailAddress $Email -Path $oupath` -UserPrincipalName "[email protected]" -AccountPassword $securePassword ` -Enabled $true ``` Any ideas? The domain controllers and ADFS is Windows 2012R2.
2015/09/30
[ "https://serverfault.com/questions/725817", "https://serverfault.com", "https://serverfault.com/users/38771/" ]
I've seen these types of problems (though not that specific one) because of the minimum password age policy. If set to 1 day it means that once the user changes their password, they cannot do so again for 1 day. So when you bulk create you need a dummy password because you can't create a user without one and then the user changes the password on the same day etc.
242,604
Working to remove the Gift Card feature on Magento 2 Cart summary section. Having issue getting this working. Have created the following file: ``` .../app/design/frontend/***/***/Magento_Checkout/layout/checkout_cart_index.xml ``` The following code is not working to remove the giftcard block: ``` <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceBlock name="cart.summary"> <arguments> <argument name="jsLayout" xsi:type="array"> <item name="components" xsi:type="array"> <item name="block-giftcard" xsi:type="array"> <item name="config" xsi:type="array"> <item name="componentDisabled" xsi:type="boolean">true</item> </item> </item> </item> </argument> </arguments> </referenceBlock> </body> </page> ```
2018/09/17
[ "https://magento.stackexchange.com/questions/242604", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/48552/" ]
After reading the first proposed solution which had already been tested, searched and found the module block in gift-card-account and this is the solution in the same file I was using in my question: ``` <?xml version="1.0"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceContainer name="cart.summary"> <referenceBlock name="checkout.cart.giftcardaccount" remove="true"/> </referenceContainer> </body> </page> ``` As it may be useful for removing the gift card from the checkout page you can add/edit this file: ``` .../app/design/frontend/***/***/Magento_Checkout/layout/checkout_index_index.xml ``` with this code: ``` <?xml version="1.0"?> <page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceBlock name="checkout.root"> <arguments> <argument name="jsLayout" xsi:type="array"> <item name="components" xsi:type="array"> <item name="checkout" xsi:type="array"> <item name="children" xsi:type="array"> <item name="steps" xsi:type="array"> <item name="children" xsi:type="array"> <item name="billing-step" xsi:type="array"> <item name="children" xsi:type="array"> <item name="payment" xsi:type="array"> <item name="children" xsi:type="array"> <item name="afterMethods" xsi:type="array"> <item name="children" xsi:type="array"> <item name="giftCardAccount" xsi:type="array"> <item name="config" xsi:type="array"> <item name="componentDisabled" xsi:type="boolean">true</item> </item> </item> </item> </item> </item> </item> </item> </item> </item> </item> </item> </item> </item> </argument> </arguments> </referenceBlock> </body> </page> ```
469,925
I need to find extension for mentioned wires but don't know how to google them, since I don't know their name. Here is a picture: ![wires](https://i.stack.imgur.com/n6D3s.jpg)
2012/09/04
[ "https://superuser.com/questions/469925", "https://superuser.com", "https://superuser.com/users/134925/" ]
They're called wires. Really, they're just copper wires. Having said that, you may have more luck if you search on system panel cables/wires or motherboard cables/wires.
38,330
Well, the faq does say no question is too small and I haven't found this question asked elsewhere so... I'd like to suggest the introduction of icons for the badges, as seen in Team Fortress 2, Day of Defeat: Source or even Kongregate. Imagine your favourite badge transformed with a colourful and amusing image! With a community as large and diverse as this one, we ought to be able to come up with some decent badge icons. What say ye? EDIT: How about them apples? (Just a sample of what's possible..) <http://www.freeimagehosting.net/uploads/708d33b019.jpg> Commentor <http://www.freeimagehosting.net/uploads/e367b04bbe.jpg> Epic
2010/02/04
[ "https://meta.stackexchange.com/questions/38330", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/142697/" ]
My eyes are already bleeding
32,156,993
How do I override the string representation for a single function in Python? What I have tried: ``` >>> def f(): pass ... >>> f <function f at 0x7f7459227758> >>> f.__str__ = lambda self: 'qwerty' >>> f <function f at 0x7f7459227758> >>> f.__repr__ = lambda self: 'asdfgh' >>> f <function f at 0x7f7459227758> >>> f.__str__(f) 'qwerty' >>> f.__repr__(f) 'asdfgh' ``` I know I can get the expected behavior by making a class with `__call__` (to make it look like a function) and `__str__` (to customize the string representation). Still, I'm curious if I can get something similar with regular functions.
2015/08/22
[ "https://Stackoverflow.com/questions/32156993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/852604/" ]
You can't. `__str__` and `__repr__` are special methods and thus are [always looked up on the type](https://docs.python.org/2/reference/datamodel.html#special-method-lookup-for-new-style-classes), not the instance. You'd have to override `type(f).__repr__` here, but that then would apply to *all* functions. Your only realistic option then is to use a wrapper object with a `__call__` method: ``` def FunctionWrapper(object): def __init__(self, callable): self._callable = callable def __call__(self, *args, **kwargs): return self._callable(*args, **kwargs) def __repr__(self): return '<custom representation for {}>'.format(self._callable.__name__) ```
2,231
I'm not security literate, and if I was, I probably wouldn't be asking this question. As a regular tech news follower, I'm really surprised by the [outrage](http://en.wikipedia.org/wiki/Anonymous_%28group%29#Activities) of [Anonymous (hacker group)](http://en.wikipedia.org/wiki/Anonymous_%28group%29), but as a critical thinker, I'm unable to control my curiosity to dig out how exactly they are doing this? Frankly, this group really scares me. One thing that I don't understand is how they haven't been caught yet. Their IP addresses should be traceable when they DDOS, even if they spoof it or go through a proxy. * The server with which they are spoofing should have recorded the IPs of these guys in its logs. If the govt. ask the company (which owns the server) don't they give the logs? * Even if it is a private server owned by these guys, doesn't IANA (or whoever the organization is) have the address & credit card details of the guy who bought & registered the server? * Even if they don't have that, can't the ISPs trace back to the place these packets originated? I know, if it was as simple as I said, the government would have caught them already. So how exactly are they able to escape? PS: If you feel there are any resources that would enlighten me, I'll be glad to read them. [Update - this is equally appropriate when referring to the [Lulzsec group](http://en.wikipedia.org/wiki/LulzSec), so have added a quick link to the Wikipedia page on them]
2011/02/21
[ "https://security.stackexchange.com/questions/2231", "https://security.stackexchange.com", "https://security.stackexchange.com/users/1152/" ]
My answer pokes at the original question. What makes you think that they don't get caught? The CIA and DoD found Osama bin Laden. Typical means include OSINT, TECHINT, and HUMINT. Forensics can be done on Tor. Secure deletion tools such as sdelete, BCWipe, and DBAN are not perfect. Encryption tools such as GPG and Truecrypt are not perfect. Online communications was perhaps Osama bin Laden's biggest strength (he had couriers that traveled to far away cyber-cafes using email on USB flash drives) and Anonymous/LulzSec's biggest weakness. They use unencrypted IRC usually. You think they'd at least be using OTR through Tor with an SSL proxy to the IM communications server(s) instead of a cleartext traffic through an exit node. Their common use of utilities such as Havij and sqlmap could certainly backfire. Perhaps there is a client-side vulnerability in the Python VM. Perhaps there is a client-side buffer overflow in Havij. Perhaps there are backdoors in either. Because of the political nature of these groups, there will be internal issues. I saw some news lately that 1 in 4 hackers are informants for the FBI. It's not "difficult" to "catch" anyone. Another person on these forums suggested that I watch a video from a Defcon presentation where the presenter tracks down a Nigerian scammer using the advanced transform capabilities in Maltego. The OSINT capabilities of Maltego and the i2 Group Analyst's Notebook are fairly limitless. A little hint; a little OPSEC mistake -- and a reversal occurs: the hunter is now being hunted.
53,928,105
I am trying to access my database every 30 seconds, however, whenever the method executes I can clearly see a performance dip in the application. So far this is my current code: ``` var timer = Timer() override func viewDidLoad() { super.viewDidLoad() scheduledTimerWithTimeInterval() } func scheduledTimerWithTimeInterval(){ timer = Timer.scheduledTimer(timeInterval: 30, target: self, selector: #selector(self.updateCounting), userInfo: nil, repeats: true) } @objc func updateCounting(){ getDatabaseInfo() } ``` I am trying to do the same thing, except I would like to execute the getDatabaseInfo() method on a background thread so that the app's performance is not compromised.
2018/12/26
[ "https://Stackoverflow.com/questions/53928105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9964910/" ]
Use Grand Central Dispatch : ``` DispatchQueue.global(qos: .background).async { getDatabaseInfo() } ```
1,812,405
Determining the image of a function $\psi:\mathbb{R}^2 \rightarrow \mathbb{R}^2$, $\psi(x,y) = (x^2 - y^2, x^2 + y^2)$ I made some observations about $\psi$: $\psi$ isn't injective, since $\psi(-x,-y) = \psi(x,y)$. The restriction $\psi\_{|D}$, where $D = \{(x,y) \in \mathbb{R}^2 | x,y>0\}$ makes $\psi$ injective, since: $(x\_{1}^2-y\_{1}^2,x\_{1}^2+y\_{1}^2) = (x\_{2}^2-y\_{2}^2,x\_{2}^2+y\_{2}^2)$ occurs when $x\_{1}^2-y\_{1}^2=x\_{2}^2-y\_{2}^2$ and $x\_{1}^2+y\_{1}^2=x\_{2}^2+y\_{2}^2$, which will lead to $(x\_1,y\_1)=(x\_2,y\_2)$. How do I determine the image of $\psi\_{|D}$? (My objective here is to create a bijection)
2016/06/04
[ "https://math.stackexchange.com/questions/1812405", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
Let $(a,b)$ be arbitrary in $\mathbb{R}^2$ and consider $\phi(x,y) = (a,b)$, so: $$\left\{\begin{array}{rcl} x^2-y^2 & = & a \\ x^2+y^2 & = & b \end{array}\right. \iff \left\{\begin{array}{rcl} x^2 & = & \frac{a+b}{2} \\ y^2 & = & \frac{b-a}{2} \end{array}\right.$$ This is only possible when $a+b \ge 0 \iff b \ge -a$ and when $b-a \ge 0 \iff b \ge a$ which can be combined into the condition $b \ge |a|$. In that case, you can solve for $x$ and $y$. This condition is satisfied by points in the 'infinite triangle' in the $xy$-plane where $y \ge |x|$; top in the origin and extending above along the lines $y=x$ and $y=-x$.
15,417,588
OK now I know that this question has been asked before several times on SO but none of the answers have worked for me. I am attempting to create a custom preference for my project. More specifically it is a preference with a [`HorizontalListView`](http://www.dev-smart.com/archives/34) attached directly underneath it. I basically created it by modifying [this code](http://robobunny.com/wp/2011/08/13/android-seekbar-preference/) for a `SeekBarPreference` (which I am also using and is working fine). My `ListViewPreference` is located in exactly the same folder as the `SeelkBarPreference` (which, as I said is having no problem) but I am constantly getting a `ClassNotFoundException` (see logcat below). Here is my `ListViewPreference` class: ``` package com.example.ebookreader; import android.content.Context; import android.content.res.TypedArray; import android.preference.Preference; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.ViewParent; import android.widget.RelativeLayout; import android.widget.TextView; public class ListViewPreference extends Preference { private final String TAG = getClass().getName(); private static final String ROBOBUNNYNS = "http://robobunny.com"; private static final int DEFAULT_VALUE = 50; private int mCurrentValue; private String mUnitsLeft = ""; private String mUnitsRight = ""; private HorizontalListView mListView; private TextView mStatusText; public ListViewPreference(Context context, AttributeSet attrs) { super(context, attrs); initPreference(context, attrs); } public ListViewPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initPreference(context, attrs); } private void initPreference(Context context, AttributeSet attrs) { setValuesFromXml(attrs); mListView = new HorizontalListView(context, attrs); LayoutParams params = mListView.getLayoutParams(); params.width = LayoutParams.MATCH_PARENT; params.height = LayoutParams.WRAP_CONTENT; mListView.setLayoutParams(params); } private void setValuesFromXml(AttributeSet attrs) { mUnitsLeft = getAttributeStringValue(attrs, ROBOBUNNYNS, "unitsLeft", ""); String units = getAttributeStringValue(attrs, ROBOBUNNYNS, "units", ""); mUnitsRight = getAttributeStringValue(attrs, ROBOBUNNYNS, "unitsRight", units); } private String getAttributeStringValue(AttributeSet attrs, String namespace, String name, String defaultValue) { String value = attrs.getAttributeValue(namespace, name); if (value == null) value = defaultValue; return value; } @Override protected View onCreateView(ViewGroup parent) { RelativeLayout layout = null; try { LayoutInflater mInflater = (LayoutInflater) getContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); layout = (RelativeLayout) mInflater.inflate( R.layout.horizontal_list_view_preference, parent, false); } catch (Exception e) { Log.e(TAG, "Error creating seek bar preference", e); } return layout; } @Override public void onBindView(View view) { super.onBindView(view); try { // move our seekbar to the new view we've been given ViewParent oldContainer = mListView.getParent(); ViewGroup newContainer = (ViewGroup) view .findViewById(R.id.listViewPrefBarContainer); if (oldContainer != newContainer) { // remove the seekbar from the old view if (oldContainer != null) { ((ViewGroup) oldContainer).removeView(mListView); } // remove the existing seekbar (there may not be one) and add // ours newContainer.removeAllViews(); newContainer.addView(mListView, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } } catch (Exception ex) { Log.e(TAG, "Error binding view: " + ex.toString()); } updateView(view); } /** * Update a SeekBarPreference view with our current state * * @param view */ protected void updateView(View view) { try { RelativeLayout layout = (RelativeLayout) view; mStatusText = (TextView) layout .findViewById(R.id.listViewPrefValue); mStatusText.setText(String.valueOf(mCurrentValue)); mStatusText.setMinimumWidth(30); TextView unitsRight = (TextView) layout .findViewById(R.id.listViewPrefUnitsRight); unitsRight.setText(mUnitsRight); TextView unitsLeft = (TextView) layout .findViewById(R.id.listViewPrefUnitsLeft); unitsLeft.setText(mUnitsLeft); } catch (Exception e) { Log.e(TAG, "Error updating seek bar preference", e); } } @Override protected Object onGetDefaultValue(TypedArray ta, int index) { int defaultValue = ta.getInt(index, DEFAULT_VALUE); return defaultValue; } @Override protected void onSetInitialValue(boolean restoreValue, Object defaultValue) { if (restoreValue) { mCurrentValue = getPersistedInt(mCurrentValue); } else { int temp = 0; try { temp = (Integer) defaultValue; } catch (Exception ex) { Log.e(TAG, "Invalid default value: " + defaultValue.toString()); } persistInt(temp); mCurrentValue = temp; } } } ``` For most people this problem is the result of not having a constructor with parameters `Context` and `AttributeSet` but as you can see, I clearly have it. Here is the XML file where the error keeps on occurring: ``` <?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" xmlns:custom="http://schemas.android.com/apk/res/com.example.ebookreader" android:background="@drawable/wallpaper" > <android:PreferenceCategory android:key="device_settings" android:title="Device Settings" > <android:CheckBoxPreference android:key="wifi" android:summary="Enable or Disable Wi-Fi" android:title="Wi-Fi" /> <android:CheckBoxPreference android:key="bluetooth" android:summary="Enable or Disable Bluetooth" android:title="Bluetooth" /> <android:CheckBoxPreference android:key="autosync" android:summary="Enable or Disable AutoSync" android:title="AutoSync" /> <custom:SeekBarPreference android:id="@+id/brightness_adjust" android:defaultValue="100" android:key="brightness" android:max="200" android:summary="Adjust Brightness Levels" android:title="Brightness" /> </android:PreferenceCategory> <android:PreferenceCategory android:key="account_settings" android:title="Account Settings" > <custom:ListViewPreference> <!-- Error happens here --> android:id="@+id/font_selector" android:key="font" android:title="Font" android:summary="Edit Font" /> </custom:ListViewPreference> </android:PreferenceCategory> </PreferenceScreen> ``` Below is my full Logcat: ``` 03-14 17:53:14.290: E/AndroidRuntime(449): FATAL EXCEPTION: main 03-14 17:53:14.290: E/AndroidRuntime(449): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ebookreader/com.example.ebookreader.SettingsActivity}: android.view.InflateException: Binary XML file line #40: Error inflating class ListViewPreference 03-14 17:53:14.290: E/AndroidRuntime(449): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1736) 03-14 17:53:14.290: E/AndroidRuntime(449): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1752) 03-14 17:53:14.290: E/AndroidRuntime(449): at android.app.ActivityThread.access$1500(ActivityThread.java:123) 03-14 17:53:14.290: E/AndroidRuntime(449): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:993) 03-14 17:53:14.290: E/AndroidRuntime(449): at android.os.Handler.dispatchMessage(Handler.java:99) 03-14 17:53:14.290: E/AndroidRuntime(449): at android.os.Looper.loop(Looper.java:126) 03-14 17:53:14.290: E/AndroidRuntime(449): at android.app.ActivityThread.main(ActivityThread.java:3997) 03-14 17:53:14.290: E/AndroidRuntime(449): at java.lang.reflect.Method.invokeNative(Native Method) 03-14 17:53:14.290: E/AndroidRuntime(449): at java.lang.reflect.Method.invoke(Method.java:491) 03-14 17:53:14.290: E/AndroidRuntime(449): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841) 03-14 17:53:14.290: E/AndroidRuntime(449): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599) 03-14 17:53:14.290: E/AndroidRuntime(449): at dalvik.system.NativeStart.main(Native Method) 03-14 17:53:14.290: E/AndroidRuntime(449): Caused by: android.view.InflateException: Binary XML file line #40: Error inflating class ListViewPreference 03-14 17:53:14.290: E/AndroidRuntime(449): at android.preference.GenericInflater.createItemFromTag(GenericInflater.java:441) 03-14 17:53:14.290: E/AndroidRuntime(449): at android.preference.GenericInflater.rInflate(GenericInflater.java:481) 03-14 17:53:14.290: E/AndroidRuntime(449): at android.preference.GenericInflater.rInflate(GenericInflater.java:493) 03-14 17:53:14.290: E/AndroidRuntime(449): at android.preference.GenericInflater.inflate(GenericInflater.java:326) 03-14 17:53:14.290: E/AndroidRuntime(449): at android.preference.GenericInflater.inflate(GenericInflater.java:263) 03-14 17:53:14.290: E/AndroidRuntime(449): at android.preference.PreferenceManager.inflateFromResource(PreferenceManager.java:269) 03-14 17:53:14.290: E/AndroidRuntime(449): at android.preference.PreferenceActivity.addPreferencesFromResource(PreferenceActivity.java:1333) 03-14 17:53:14.290: E/AndroidRuntime(449): at com.example.ebookreader.SettingsActivity.onCreate(SettingsActivity.java:31) 03-14 17:53:14.290: E/AndroidRuntime(449): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048) 03-14 17:53:14.290: E/AndroidRuntime(449): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1700) 03-14 17:53:14.290: E/AndroidRuntime(449): ... 11 more 03-14 17:53:14.290: E/AndroidRuntime(449): Caused by: java.lang.ClassNotFoundException: android.preference.ListViewPreference in loader dalvik.system.PathClassLoader[/data/app/com.example.ebookreader-2.apk] 03-14 17:53:14.290: E/AndroidRuntime(449): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:251) 03-14 17:53:14.290: E/AndroidRuntime(449): at java.lang.ClassLoader.loadClass(ClassLoader.java:548) 03-14 17:53:14.290: E/AndroidRuntime(449): at java.lang.ClassLoader.loadClass(ClassLoader.java:508) 03-14 17:53:14.290: E/AndroidRuntime(449): at android.preference.GenericInflater.createItem(GenericInflater.java:375) 03-14 17:53:14.290: E/AndroidRuntime(449): at android.preference.GenericInflater.onCreateItem(GenericInflater.java:417) 03-14 17:53:14.290: E/AndroidRuntime(449): at android.preference.GenericInflater.createItemFromTag(GenericInflater.java:428) 03-14 17:53:14.290: E/AndroidRuntime(449): ... 20 more ``` Any help would be greatly appreciated.
2013/03/14
[ "https://Stackoverflow.com/questions/15417588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1679658/" ]
but why you wrote ``` <custom:ListViewPreference ``` it should be ``` <com.example.ebookreader.ListViewPreference ``` As your package, where class placed, called
47,788,964
When I run the following code ``` public class Program { public static void Main() { string s = "480"; Console.WriteLine(1 == -1 ? 0 : s[1]); Console.WriteLine(s[1]); } } ``` I get ``` 56 8 ``` I don't understand how I get 56.
2017/12/13
[ "https://Stackoverflow.com/questions/47788964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208848/" ]
Your `0 : s[1]` converts the `char` in `s[1]` to an integer. And the value of `8` in the ASCII table is `56`. You want to use a `char` on the left hand side too (using single quotes): ``` Console.WriteLine(1 == -1 ? '0' : s[1]); ```
22,204
Ven. Members of the Sangha (of Bhikkhus), Ven. fellows, valued Upasaka and Upasika, dear readers and interesed, This question is intellectual and theoretical, or literary, but also/merely inviting self-reflection; but of course it can also be answered with words of the Buddha in "should-form" (in the later case, exchange "you" with "a serious follower of the Buddha, a person in general, to find peace", how ever you wish and feel obligated or loyal to). So, about loyalty, * In regard of what are you able to claim being loyal? * Whom are you loyal to? * How far goes your loyalty? * Where and how does it end? Also, finally: * What must one be loyal to, to find, to reach the highest aim all Buddha-following seekers are after? * What are you loyal and/or are you not loyal to, so that you have't found final peace already, or you highest desired goal? * What is an Arahat loyal to? Has loyality, then, an end (no more required)? Maybe you try to give a loyal answer. Much joy and inside in giving a benefical answer, at least for youself.
2017/08/19
[ "https://buddhism.stackexchange.com/questions/22204", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/11958/" ]
Generally Buddhist take refuge in Buddha, Dhamma, and Sangha. In that regard, I would say I support Sangha. Because they protect Dhamma. Which helps to attain Buddhahood. Generally, Sangha means Ariya Sangha. But here I meant any person who can guide me in the right direction.
10,422,335
that opens Minecraft.exe, and logs in when clicked. Is this possible?
2012/05/02
[ "https://Stackoverflow.com/questions/10422335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Hmm, Is this what you want; it should work: ``` @echo off "%cd%\minecraft.exe" username password serverip ``` edit the username, password and ip to your liking. --- A Better Solution in my opinion: Just figured it out, the batch file doesn't work, however; when set up as a shortcut it does! So create a new shortcut and for the path use this: Format: ``` "<FilePath>" <username> <password> <server> ``` Example: ``` "C:\Program Files\Minecraft\Minecraft.exe" bobjones passchuck 123.123.123.123 ``` Hope that works out for you, alot simpler then a bath file IMO. also if you don't include IP, it just goes and logins in to minecraft. Stopping at the title screen.
42,537,222
I have functions that include different javax Query annotations like : `@QueryParam` , `@Context` , `@PathParam` etc.. is there a way to exclude these parameters when calling joinPoint.getArgs()? Example: ``` @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("{pathParam}/v1/{pathParam2}/") @MyAnnotation public Response update(@PathParam("pathParam") String p1, @PathParam("pathParam2") int p2, MyObject x); @Before("@annotation(MyAnnotation)") public void doSomething(JoinPoint joinPoint){ Object[] objects = joinPoint.getArgs(); // HERE - is there a way to get only MyObject and not other params..? } ``` The reason I want to do it is that I have several urls, while marking ~10% as persistent. It means that I want the input data to be saved in some persistent service. The Query & Context params are not important to me, but the input data itself is.
2017/03/01
[ "https://Stackoverflow.com/questions/42537222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1386966/" ]
Assuming you really use **full AspectJ and not Spring AOP** like so many others, you should be aware of the fact that in full AspectJ `@annotation(XY)` potentially matches not just `execution()` joinpoints but also `call()`, i.e. your advice will be triggered twice. Even worse, if other places than method executions are also annotated - e.g. classes, fields, constructors, parameters - the pointcut will also match and your try to cast to `MethodSignature` will cause an exception as a consequence. Furthermore, please note that in @AspectJ syntax you need to provide the fully qualified class name of the annotation you want to match against, i.e. don't forget to also prepend the package name. Otherwise there will be no match at all. So before doing anything else you want to change your pointcut to: ```java @annotation(de.scrum_master.app.MyAnnotation) && execution(* *(..)) ``` Now here is a fully self-consistent example, an [SSCCE](http://sscce.org/) producing repeatable results, as requested by me in the comment under your question: **Annotation:** ```java package de.scrum_master.app; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation {} ``` **Driver application:** As you can see, the test method has parameters with different types of annotations: 1. only javax annotation 2. javax + own annotation 3. only your own annotation 4. no annotation We want to ignore #1/2 and only print #3/4. ```java package de.scrum_master.app; import javax.ws.rs.PathParam; import javax.ws.rs.core.Response; public class Application { public static void main(String[] args) { new Application().update("foo", 11, "bar", 22); } @MyAnnotation public Response update( @PathParam("pathParam") String p1, @PathParam("pathParam2") @MyAnnotation int p2, @MyAnnotation String text, int number ) { return null; } } ``` **Aspect:** Just as user *Andre Paschoal* started to show in his code fragment, you need to iterate over both the arguments and annotations arrays in order to pull off the filtering trick. I think it is quite ugly and possibly slow just for logging's sake (and I assume this is what you want to do), but for what it is worth, here is your solution: ```java package de.scrum_master.aspect; import java.lang.annotation.Annotation; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.reflect.MethodSignature; @Aspect public class ParameterFilterAspect { @Before("@annotation(de.scrum_master.app.MyAnnotation) && execution(* *(..))") public void doSomething(JoinPoint joinPoint) { Object[] args = joinPoint.getArgs(); MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Annotation[][] annotationMatrix = methodSignature.getMethod().getParameterAnnotations(); for (int i = 0; i < args.length; i++) { boolean hasJavaxAnnotation = false; for (Annotation annotation : annotationMatrix[i]) { if (annotation.annotationType().getPackage().getName().startsWith("javax.")) { hasJavaxAnnotation = true; break; } } if (!hasJavaxAnnotation) System.out.println(args[i]); } } } ``` **Console log:** ```none bar 22 ``` Tadaa! :-)
134,341
I am designing a simple 16 bit adder circuit in Digilent's Xilinx Spartan 6 FPGA. The Verilog design accepts two 16 bit inputs A and B and returns the 16 bit sum C = A+B. I am ignoring carry in and carry out. I want to send A and B from PC to FPGA using serial port as well send the sum C from FPGA to PC using serial port. I am not sure how to do this. I have googled but could not find something simple. Can i send A and B as decimals like A = 5, B = 3? or do i have to send it as ASCII? How do i distinguish A from B if A = 255 and B = 512 (i.e., both A and B have multiple digits). How does FPGA deal with ASCII. Some pointers or explanations will be really appreciated
2014/10/14
[ "https://electronics.stackexchange.com/questions/134341", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/35416/" ]
I would suggest either writing a UART module from scratch or finding one online. Then all you would need to do is write a wrapper that interfaces the UART to your registers. Here is one possible open source Verilog UART module that I wrote a while ago: <https://github.com/alexforencich/verilog-uart> This particular module uses the AXI stream interface, so it should not be very difficult to interface with your design. The AXI stream interface has three signals: tdata, tvalid, and tready. tvalid indicates that tdata contains valid data, and tready indicates that the sink is ready to receive the data. Data bytes are transferred only when tvalid and tready are both high. What I would recommend doing is defining a simple serial protocol that supports some basic framing. Say, to send A and B to the FPGA, you would send some sort of start indication (e.g. 0 or perhaps ASCII S or W), then the MSB of A, then the LSB of A, then the MSB of B, then the LSB of B. Then you can write a state machine that looks for the start indication, then loads the next four bytes into the appropriate registers. Then once the operation is complete, the state machine can send the result back to the computer. If you want to use ASCII instead of binary, you can do that too, but it's a bit more complicated to convert everything. I would recommend using hex if you want something human readable as it is much easier to divide by 16 than it is to divide by 10 (bit shift/bit slice instead of an actual division operation).
199,696
Long story short, I am trying to find a pre-made Linux development environment for VirtualBox so I don't have to worry about installing a distro, getting all packages installed, and so forth, since last time I did that it took me a full day to get something that remotely did what I wanted. I've got a few semi-weird requirements, which doesn't help... * Preferably SSH only, no slick GUI etc installed, as the laptop host is not endowed with a lot of HD space or RAM. (Which is also why I cannot dual boot, so please do not suggest that option.) I intend to do pretty much all using PuTTy, as it is a workflow I'm already accustomed to. * Basic gcc, automake etc are all I need. I really don't care about the distro itself, or the packaging system, or anything else really. I just want to download it, set up some mounts, and be ready to go. If such a thing doesn't exist, I'd still appreciate suggestions of the best distro to use that will get me to my requirements fastest without a lot of tweaking.
2010/10/15
[ "https://superuser.com/questions/199696", "https://superuser.com", "https://superuser.com/users/50442/" ]
Turnkey linux has a number of preconfigured server images that will work in virtualbox <http://www.turnkeylinux.org/> <http://www.turnkeylinux.org/docs/installation-appliances-virtualbox>
160,224
I've read everywhere that you can't have more than 4 partitions because of GPT on intel Macs. But what happens if you make more than 4? On my iMac I have EFI, Macintosh HD, Windows, Linux, and Linux swap partitions and I am able to boot from all three operating systems with rEFIt. So, I have 5 partitions, so why does it work? I made the partitions with Snow Leopard's Disk Utility by the way.
2010/07/05
[ "https://superuser.com/questions/160224", "https://superuser.com", "https://superuser.com/users/5408/" ]
Intel-based Macs use the GUID Partition Table (GPT) by default. GPT in turn supports up to 128 partitions by default (that value can be increased if necessary, although most partition tools don't enable you to do so). Thus, there's no problem with having more than four partitions on an Intel-based Mac. The limitation you've heard about is a distortion of the limitation on hybrid MBRs, which are a dangerous and standards-violating hybridization of GPT with the older Master Boot Record (MBR) partitioning system used on most PCs. In a hybrid MBR, up to *three* of the GPT's partitions are duplicated in an MBR data structure. MBR is limited to four *primary* partitions, and in a hybrid MBR the fourth primary partition is occupied by a special partition that identifies the disk as being a GPT disk. This fourth partition is often mistaken for an MBR-side duplicate of the EFI System Partition (ESP) that's present on most GPT disks, but it's not that. Apple uses hybrid MBRs to enable Windows to dual-boot with OS X on Macs. Windows favors the MBR data structures, so it sees the disk as being an MBR disk, whereas OS X favors GPT data structures, so it sees the disk as being a GPT disk. (Linux, like OS X, sees a hybrid MBR as a GPT disk.) A hybrid MBR doesn't limit the number of GPT partitions you may have, but it does limit the number of partitions that the Windows installation can see, to no more than three. Note that extended partitions and Extended Boot Records (EBRs) have nothing to do with hybrid MBRs -- or at least, they shouldn't! In the MBR scheme, extended partitions serve as placeholders for logical partitions, which are defined by EBRs. Using this scheme, an MBR disk can support a huge number of partitions -- theoretically about half as many as there are sectors on the disk, although practical limits are much lower than that. Disks with hybrid MBRs don't use extended partitions, though, because maintaining consistency between the GPT and MBR sides of the disk -- already a challenging enough task with regular hybrid MBRs -- would become much tougher.
20,011,854
What I want to do might be better achieved with a database, however I have very limited experience with them, and only have to change the information infrequently. What I have is a sheet where each row has 8 cells of relevant data. What I want to do in another sheet is to enter a number into 1 cell, and have a group of cells below use that number to reference data in the other sheet. For example, in Sheet1 I could have the following (fig 1): ``` | A | B | C | D | E | F | G | H -----+-----+-----+-----+-----+-----+-----+-----+----- 101 | Dep | 700 | Sta | 100 | Sta | 300 | Dep | 900 ``` What I want to achieve in sheet 2, by typing the row number into 1 cell, is to have the data in those 8 cells copied below, for example (fig 2): ``` | A | B | C | D | -----+-----+-----+-----+-----+ 1 | "Row Number" | -----+-----+-----+-----+-----+ 2 | =A# | =B# | =D# | =C# | -----+-----+-----+-----+-----+ 3 | =E# | =F# | =H# | =G# | -----+-----+-----+-----+-----+ ``` And yes, I am aware those formulae above do not reference the other sheet - this was to save space. Which, if using the example row above, should look like this (fig 3): ``` | A | B | C | D | -----+-----+-----+-----+-----+ 1 | 101 | -----+-----+-----+-----+-----+ 2 | Dep | 700 | 100 | Sta | -----+-----+-----+-----+-----+ 3 | Sta | 300 | 900 | Dep | -----+-----+-----+-----+-----+ ``` So, in that example above (fig 3), what do I need to put in as a formula in cells A2-D2 & A3-D3 to automatically use the number in A1 as part of the cell reference to print the data from the other sheet. Does that make sense? I hope so because I have over 300 lines to enter into my 1st sheet and another 70 lines x 7 blocks of columns on the second sheet. Lastly I just want to say I want to avoid programming languages, like VBA, wherever possible.
2013/11/15
[ "https://Stackoverflow.com/questions/20011854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2329155/" ]
Check out the INDIRECT() function. For cell A2 in your example on the second sheet, enter: ``` =INDIRECT("Sheet1!"&"A"&$A$1) ``` Expand this formula to the apply to other target cells by changing the "&"A" portion to reference columns B, C, D, etc. from Sheet1 as needed in your grid per the following example: ``` =INDIRECT("Sheet1!"&"B"&$A$1) =INDIRECT("Sheet1!"&"C"&$A$1) =INDIRECT("Sheet1!"&"D"&$A$1) ``` These formulas will reference your selected "Row Number" in cell A1 and pull the related data from Sheet1 into Sheet2.
46,213,121
**The full story** I have a list of namedtuples which itself holds a tuple and a string as follows: ``` a = [ X(( 1, 1), "a"), X(( 2, 1), "b"), X(( [3, 4], 1), "c"), X((range(25, 30), 4), "d") X(( 13, [6, 14]), "e") ] ``` I want to return the namedtuple by comparing the value of a given tuple to the value in the first tuple. Eg. ``` b = (1, 1) return [x for x in a if a.val == b] ``` The problem that I face is for the case `b = (3, 1)` it should return the third tuple. I tried looking at `zip`, but that only works if the length of the iterables are the same. I also looked at `itertools.product` but for that I need to have all elements to be iterable. **The short question** I'm trying to see if there's a way to iterate over the elements in the internal tuple and make it a tuple of iterables. Something as follows: ``` a = ([3, 4], 1) b = [[x] for x in a] c = product(*b) ``` The problem with this is that `[3, 4]` becomes `[[3, 4]]`. Which then results in only a single product. I'm trying to avoid making every `int` a `list` non-programaticatlly.
2017/09/14
[ "https://Stackoverflow.com/questions/46213121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1372199/" ]
I managed to solve it as follows: ``` a = ([3, 4], 1) b = ([x] if type(x) is int else x for x in a) c = product(*b) ``` Looping over `c` returns `(3, 1)` and `(4, 1)`. So my full code is as follows: ``` from itertools import product def find_matching(requested): return [found for found in list_of_tuples if requested in product( *([val] if type(val) is int else val for val in found.val))] ```
62,565,369
I tried to add jquery library file to assets folder and I added the directory to scripts in angular.json but when I run `ng serve` Angular told me Jquery library does not exist and I am using angular version 9. I don't know where the problem any help please. This the error message: ``` An unhandled exception occurred: Script file assets/js/jquery-3.5.1.slim.min.js does not exist. ``` angular.json file: ``` { "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "HorsesClubFrontend": { "projectType": "application", "schematics": {}, "root": "", "sourceRoot": "src", "prefix": "app", "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", "options": { "outputPath": "dist/HorsesClubFrontend", "index": "src/index.html", "main": "src/main.ts", "polyfills": "src/polyfills.ts", "tsConfig": "tsconfig.app.json", "aot": true, "assets": [ "src/favicon.ico", "src/assets" ], "styles": [ "src/styles.css", "assets/css/bootstrap.min.css" ], "scripts": [ "assets/js/jquery-3.5.1.slim.min.js", "assets/js/bootstrap.min.js", "assets/js/popper.min.js"] }, "configurations": { "production": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod.ts" } ], "optimization": true, "outputHashing": "all", "sourceMap": false, "extractCss": true, "namedChunks": false, "extractLicenses": true, "vendorChunk": false, "buildOptimizer": true, "budgets": [ { "type": "initial", "maximumWarning": "2mb", "maximumError": "5mb" }, { "type": "anyComponentStyle", "maximumWarning": "6kb", "maximumError": "10kb" } ] } } }, "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "HorsesClubFrontend:build" }, "configurations": { "production": { "browserTarget": "HorsesClubFrontend:build:production" } } }, "extract-i18n": { "builder": "@angular-devkit/build-angular:extract-i18n", "options": { "browserTarget": "HorsesClubFrontend:build" } }, "test": { "builder": "@angular-devkit/build-angular:karma", "options": { "main": "src/test.ts", "polyfills": "src/polyfills.ts", "tsConfig": "tsconfig.spec.json", "karmaConfig": "karma.conf.js", "assets": [ "src/favicon.ico", "src/assets" ], "styles": [ "src/styles.css" ], "scripts": [] } }, "lint": { "builder": "@angular-devkit/build-angular:tslint", "options": { "tsConfig": [ "tsconfig.app.json", "tsconfig.spec.json", "e2e/tsconfig.json" ], "exclude": [ "**/node_modules/**" ] } }, "e2e": { "builder": "@angular-devkit/build-angular:protractor", "options": { "protractorConfig": "e2e/protractor.conf.js", "devServerTarget": "HorsesClubFrontend:serve" }, "configurations": { "production": { "devServerTarget": "HorsesClubFrontend:serve:production" } } } } }}, "defaultProject": "HorsesClubFrontend" } ``` assets folder: [![enter image description here](https://i.stack.imgur.com/xB7gA.png)](https://i.stack.imgur.com/xB7gA.png)
2020/06/24
[ "https://Stackoverflow.com/questions/62565369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8297550/" ]
To add jquery in angular have to follow below steps. Step-1 > > Add jquery file in **index.html** file into the head tag > > > ```js <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> ``` Step-2 > > Also need to install two npm packages > > > ```js npm i [email protected] npm i @types/jquery ``` Step-3 > > Add jquery into **angular.json** file into the **script** array > > > ```js "scripts": [ "node_modules/jquery/dist/jquery.js" ] ``` Try above steps, I hope this will help you out.
3,742
Usually one constructs a graph and then asks questions about the adjacency matrix's (or some close relative like the [Laplacian](http://en.wikipedia.org/wiki/Laplacian_matrix)) eigenvalue decomposition (also called the [spectra of a graph](http://en.wikipedia.org/wiki/Spectral_graph_theory)). But what about the reverse problem? Given $n$ eigenvalues, can one (efficiently) find a graph that has this spectra? I suspect that in general this is hard to do (and might be equivalent to GI) but what if you relax some of the conditions a bit? What if you make conditions that there is no multiplicity of eigenvalues? What about allowing graphs that have "close" spectra by some distance metric? Any references or ideas would be welcome. **EDIT**: As Suresh points out, if you allow undirected weighted graphs with self loops, this problem becomes pretty trivial. I was hoping to get answers on the set of undirected, unweighted simple graphs but I would be happy with simple unweighted directed graphs as well.
2010/12/11
[ "https://cstheory.stackexchange.com/questions/3742", "https://cstheory.stackexchange.com", "https://cstheory.stackexchange.com/users/834/" ]
Cvetcovic et all in Section 3.3 of "Recent results in the theory of graph spectra" [goes over](http://yaroslavvb.com/upload/save/cstheory-cvetcovic-spectra.pdf) algorithms for constructing graphs given spectrum in some special cases
15,337
I have a Vauxhall Corsa "C" (2003)(EU) which is a standard 16v 1.2 petrol, the engine is chain driven and sits at 50k. I don't think it was well looked after (service wise) in previous lifes. Recently it sounds a bit more like a diesel when cold, but not too loud -and a common issue with the Corsa, however at the moment when the engine hits ~80-90 degrees it starts to "tick" loudly, to the point I can hear it in the cabin. Observations ------------ * When I accelerate the ticking gets faster, if I depress the clutch and throttle, it gets faster, once the ticking starts it doesn't go away till the engine is cool. It will be audible when Idle and parked too. * "slight" loss of power, hardly noticable not anything serious though, and no misfiring or overheating. Taking ~10min to get to temperature in 20-35mph traffic. * prior to the ticking starting, when moving off in 1st, it sounds a bit "throaty" like an exhaust rattle but being in the car I can't work out where this is. No noticable smoke or anything from the exhaust as far as I can tell. * Plenty (almost full) oil and coolant. Oil is fairly dark and theres a bit of gunk around from a bit of moisture (Not HGF, a common mistake when diagnosing things with this engine!) It's from doing short journeys and the build up of condensation. Multiple owner forums confirmed this. Conditions: ----------- * Engine is warm and has typically being driven for ~15min * Starting in cold weather ~0-4 degrees c. * Used for short journeys (~6 miles each way) Notes ----- * When I start the engine, it goes to about 2K RPM, sounds rough for about half a second then it's fine. This has been diagnosed as normal though for this car. * When I move off when the engine is cold, I get slight revving for the first couple of seconds, again this looks fairly normal for this engine looking on owner forums. Thoughts? --------- My first though would be that it could be the oil, as it gets warmer the vicosity changes and it's not as effective? I thought it could be the timing chain, but it doesn't happen from cold. My third thought would be tappets. I'm not brilliant with mechanics so not a clue. I recently put some Wynns Hydraulic Lifter fluid into the oil with no success. Sounds the same. The car *did* have some gasket work done and I'd be suprised if they did a full flush of fluids. Tried to include as much info as I thought was relevant, but if theres anything else let me know EDIT: Conclusion? ----------------- It got a bit worse when the engine got to 85-86ish and the ticking was getting louder, it was also happening on *some* cold starts for 30seconds. It went in for a full check hoping it was the Ex. Man. gasket, and they found that the **timing chain** had a small amount of slack on it, and on an unrelated note the oil pressure switch needed replacing, the old oil in the system probably didn't help the longevity of the chain. **Update** Months on and the car still does the same thing. I have checked the oil, changed it, had the chain done and still after a 15-20 min drive it will tick away to itself. I think its the tappets, and occasionally the sound will go away again before returning later in my journey.
2015/02/06
[ "https://mechanics.stackexchange.com/questions/15337", "https://mechanics.stackexchange.com", "https://mechanics.stackexchange.com/users/9353/" ]
Corsa's (actually Vauxhalls/Opels in general) sometimes have noisy hydraulic lifters. I drove mine for 60 thousand kilometers with this noise before I upgraded to a Turbo Coupe and gave the car to my mom. No problems so far. The Coupe had the same stupid tick. Again, I drove it for 30 thousand kilometers before trading it in for a Subaru Forester XT. Only problem I had with it was the turbo. Nothing wrong with the lifters or valves. If you click on my profile and check out my questions, you'll actually see one [where I posted a video of a loud ticking coming from my engine bay in the Coupe](https://mechanics.stackexchange.com/questions/7539/astra-turbo-sounding-like-a-diesel). I assume this is the same sound you hear. (The video makes it out to be a bit harsher than it actually is). These noises are usually a valve that's stuck for whatever reason. It's something you can have looked at when the car is in for a major service or something, but it's my experience, and there is considerable consensus, that it's not a serious problem that you need to immediately spend your Valentine's Day money on.
62,698,801
I have .csv files (abc.csv, def.csv, etc...) in the directory and I would like to count of rows in every file and save the single file having name column and count column. My expected output as below : ``` df = name count abc .... def .... ghi .... ``` I am doing something like below to get count but not able to covert in dataframe. Please suggest. ``` import os path = '/some/path/to/file' for filename in os.listdir(path): with open(filename, 'r', encoding="latin-1") as fileObj: # -1 to exclude the header print("Rows Counted {} in the csv {}:".format(len(fileObj.readlines()) - 1, filename)) ```
2020/07/02
[ "https://Stackoverflow.com/questions/62698801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13838014/" ]
Put the name/line count of each file into lists, and then create your DataFrame once the loop is over: ``` import os import pandas as pd path = '/some/path/to/file' names, counts = [], [] for filename in os.listdir(path): with open(filename, 'r', encoding="latin-1") as fileObj: names.append(filename) # -1 to exclude the header counts.append(len(fileObj.readlines()) - 1) df = pd.DataFrame({'name': names, 'count': counts}) ```
150,243
I have to redesign an existing M2-Shop with a given style guide. That guide defines structures for headlines, sub-lines, product etc. like a style guide does. My problem is that there is no given structure in the less structure to change that easily. Is that even possible to have a let's say boilerplate for CSS? The styles are spread all over the less files. To say a headline H1 has to have a font size with 24px and a red text color and maybe a given line height that modifications I have also to change in every less file e.g. `cms.less`, `product.less`, `product-list.less` and so on. Is there a way to simplify that?
2016/12/14
[ "https://magento.stackexchange.com/questions/150243", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/20318/" ]
I would never recommend writing a module to hide an attribute, in most cases this can be done via the admin panel. Here is how to disable fax via the admin panel. **This is for Magento EE 2.1.1** 1. Goto `Stores - Attributes - Customer Address` 2. Click on the attribute fax and set `use in customer segment` to no **This is for Magento CE 2.0.7** 1. Goto Stores - Configuration - Customers - Customer Configuration 2. Expand Address Templates group and remove `{{depend fax}}<br/>F: {{var fax}}{{/depend}}` from all the text boxes. > > I've only specified these versions because thats the ones I tested on. > > >
3,283,693
If $S=\left\{ A=\begin{bmatrix}A\_1&0 \\ 0&A\_2 \end{bmatrix} \in \mathbb{M}\_4(\mathbb{C}): det A\_1=detA\_2 \right\}$. Then is this set open in $\mathbb{M}\_{4}(\mathbb{C})$ with usual topology. If not then what are the interior points. I would like some hints towards this. Also if someone could suggest a book to study topology of space of complex matrices, it will be helpfull to me. Thank you. I have an analytic map from open unit disc to the norm unit ball of space of matrices having image contained in $S$. That is why i am wondering about the interior of this set.
2019/07/05
[ "https://math.stackexchange.com/questions/3283693", "https://math.stackexchange.com", "https://math.stackexchange.com/users/303760/" ]
The area of a circular sector is given by: $$A\_{\text{circular sector}} = \frac{r^2}{2} (\theta - \sin(\theta))$$ The intersection of two circles is just twice this: $$A\_{\text{intersection}} = r^2 (\theta - \sin(\theta))$$ The height of the rectangle can be found using simple trigonometry: $$h = 2r \sin\left(\frac{\theta}{2}\right)$$ And the width of the rectangle is twice the height of the circle segment. $$w = 2 r \left(1 - \cos\left(\frac{\theta}{2}\right)\right)$$ $\theta$ itself can be found also using trigonometry. $$\theta = 2 \arccos\left(\frac{d}{2r}\right)$$ So the ratio between the area of the intersection and its bounding rectangle is: $$\begin{split} R &= \frac{4r^2\left(1 - \cos\left(\frac{\theta}{2}\right)\right)\sin\left(\frac{\theta}{2}\right)}{r^2 \left(\theta - \sin\left(\theta\right)\right)} \\ &= \frac{4 \left(1 - \cos\left(\arccos\left(\frac{d}{2r}\right)\right)\right) \sin\left(\arccos\left(\frac{d}{2r}\right)\right)}{2\arccos\left(\frac{d}{2r}\right) - \sin\left(2\arccos\left(\frac{d}{2r}\right)\right)} \\ \end{split}$$ It is true that $\sin( \arccos(x)) = \sqrt{1 - x^2}$ and $\sin(2 \arccos(x)) = 2x \sqrt{1-x^2}$ so: $$\begin{split} R &= \frac{4 \left(1 - \frac{d}{2r}\right)\sqrt{1 - {\left(\frac{d}{2r}\right)}^2}}{2 \left(\arccos\left(\frac{d}{2r}\right) - \frac{d}{2r} \sqrt{1-{\left(\frac{d}{2r}\right)}^2} \right)} \\ &= \frac{2\left(1 - \frac{d}{2r}\right)\sqrt{1 - {\left(\frac{d}{2r}\right)}^2}}{\arccos\left(\frac{d}{2r}\right) - \frac{d}{2r} \sqrt{1-{\left(\frac{d}{2r}\right)}^2}} \\ \end{split}$$ We can take $\frac{d}{2r}$ to be $u$, a dimensionless parameter that describes the relationship between the size of the circles and the distance between them. $$R = \frac{2 \left(1 - u\right)\sqrt{1 - u^2}}{\arccos(u) - u \sqrt{1-u^2}}$$ This function is monotonically increasing on the interval $u \in [0, 1)$ so $R$ has a maximum in the limit when $u = 1$ (and in particular, the complete overlap case of $u = 0$ where $R = \frac{4}{\pi}$ is actually the minimum). This value can be found via L'Hopital's rule: $$\begin{split} \lim\_{u \rightarrow 1} \, &\frac{2 \left(1 - u\right)\sqrt{1 - u^2}}{\arccos(u) - u \sqrt{1-u^2}} \\ &=\lim\_{u \rightarrow 1} \, \frac{2\frac{2u^2 - u - 1}{\sqrt{1 - u^2}}}{-2 \sqrt{1 - u^2}} \\ &=\lim\_{u \rightarrow 1} \, -\frac{2u^2 - u - 1}{1 - u^2} \\ &=\lim\_{u \rightarrow 1} \, \frac{(2u + 1)(1-u)}{(1 + u)(1-u)} \\ &=\lim\_{u \rightarrow 1} \, \frac{(2u + 1)}{(1 + u)} \\ &= \frac{3}{2} \end{split}$$
36,669,599
My sql database does not include fault code owners, those details are stored within an xml file Is it possible to Groupby FaultCodeOwner when that data is coming from an external source? I get the following error: cannot assign void to anonymous type property ``` var query = referenceDt.AsEnumerable() .Where(results => declarations.CaapcityIssues.Contains((results.Field<string>("FabricName")))) .GroupBy(results => new { **FaultCodeOwner = faultCodeDetails.getFacultCodeOwner(results.Field<int>("FaultCode"), out owner)** }) .OrderBy(newFaultCodes => newFaultCodes.Key.FaultCodeOnwer) .Select(newFaultCodes => new { FaultCodeOwner = newFaultCodes.Key.FaultCodeOwner, Count = newFaultCodes.Count() }); ```
2016/04/16
[ "https://Stackoverflow.com/questions/36669599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6153531/" ]
You cannot group by anything that is not in the database without bringing your query results in memory first. Inserting ToEnumerable or ToList after the Where method will do that. Unfortunately, you may bring more data in memory than you otherwise would.
53,556,409
I'm using Chrome 70 and Chrome does add methods `.flatMap`, `.flatten`, `.flat`. So my code does run as expected. Unfortunately, TypeScript doesn't like it. ``` // data.flatMap lint error export const transformData = (data: any[]) => data.flatMap(abc => [ parentObj(abc), ...generateTasks(abc) ]); ``` The warning I got is `TS2339: Property 'flatMap' does not exist on type 'any[]'.` I'm using Angular 6, which uses Typescript ~2.9.2, and I already include `import 'core-js/es7/array';` in `polyfills.ts`. My guess is that there is no typing for these methods, and I did try to `npm run -dev @types/array.prototype.flatmap` but still not solve.
2018/11/30
[ "https://Stackoverflow.com/questions/53556409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3648961/" ]
You should add `es2019` or `es2019.array` to your `--lib` setting for TypeScript to recognize `array.flat()` and `flatMap()`. Example: ``` { "compilerOptions": { "target": "es5", "lib": [ "es2019" ] } } ``` Previously this was available as part of `esnext` or `esnext.array`, but it's now officially part of ES2019.
17,824,212
I want to write a sql query wherein the fourth letter should be `'x'` and there should be `'m'` anywhere in the whole word. I am having a list of over 5000 words. I tried the command ``` where name like '___x%m%' ``` but that would only give me those where `x` is the fourth letter and there is m after x, but how to find those names which have `x` as fourth letter and have `m` coming before `x`?
2013/07/24
[ "https://Stackoverflow.com/questions/17824212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/569014/" ]
You can do this: ``` where name like '____x%' and name like '%m%' ```
23,767,868
I am well versed in C++, but fairly new to openGL and the OpenGL SuperBible. I would like to take a projection matrix that the prior developer used in a shader and apply the matrix without a shader. For example, I would like to take the following (only the relevant code is posted): ``` GLShaderManager shaderManager; // Zoom and shade shaderManager.UseStockShader(GLT_SHADER_FLAT, viewFrustum.GetProjectionMatrix(), vGreen); ``` and use it to adjust the zoom without applying the shader (where ???? is the function I am looking for): ``` // Adjust the zoom without applying a shader ????(viewFrustum.GetProjectionMatrix()); ``` My question is, what function(s) could I use to do this? Note that the matrix in viewFrustum.GetProjectionMatrix() is already set up, and I am trying to avoid having to recode this whole functionality. I am looking for a function that will just apply the matrix and not interfere with color. Clarification: The object I am drawing can have over 1 million polygons, and changes color. I am simply looking for a function that goes in place of ????.
2014/05/20
[ "https://Stackoverflow.com/questions/23767868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1298656/" ]
You need to know the configuration of the matrices in OpenGL, such as how many rows and columns they have and whether they are row or column major. This can be gleaned from many places, including: 1. The [official OpenGL specs](http://www.khronos.org/files/opengl42-quick-reference-card.pdf). 2. Some [tutorial on the subject](http://www.sjbaker.org/steve/omniv/matrices_can_be_your_friends.html) 3. From the sources of some of the many OpenGL compatible matrix math libraries out there. In fact most 3D engines based on OpenGL will have some rudimentary form of matrix support that is compatible. It might actually be better to just use one of those libraries. @genpfault suggested [GLM](http://glm.g-truc.net) which looks promising.
70,478,973
I have list which contains a map List<Map<String, Object>> map has two keys which is a id and the amount. I want to sort the list descending order base on the amount key, if the amount is same for two elements in the list then sort it based on the id. How can I do this ? ``` List<Map<String, Object>> list = new ArrayList<>(); Map<String, Object> hm = new HashMap<>(); hm.put(id, 1); hm.put(amount, 25000); list.add(hm); ``` index of list element = 1, 2, 3 ,4 ,5 ,6 values for id = 1, 2, 3 ,4 ,5, 4 values for amount = 10000, 450000, 25000, 45000, 35000, 75000 list should sorted as follows(index of list) = 6, 4 (id is large), 2, 5, 3, 1
2021/12/25
[ "https://Stackoverflow.com/questions/70478973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11383967/" ]
Your model is not wrong as suggested in comments - your NetworkP2P might be missing only one column (Reciever), which could work as optional foreign key (to satisfy your sentence "Not all Phone numbers match the ones that Subscribers have."), but it looks more log than relational table. Query for your desired output: ``` select caller.SubscriberID as Caller, reciever.SubscriberID as Reciever, caller.PhoneNumber as CallerPhone, nt.AddresseeNumber as RecieverPhone, -- better than reciever.PhoneNumber because you can use left join recievers to get missing substribers nt.CallStart, nt.CallEnd from Subscriber as caller inner join NetworkP2P as nt on nt.SubscriberID = caller.SubscriberID inner join Subscriber as reciever on nt.AddresseeNumber = reciever.PhoneNumber -- where '2021-02-03' between nt.CallStart and nt.CallEnd -- calls in 2021-02-03 -- where nt.CallStart between '2021-02-01' and '2021-02-28' -- calls in specific interval -- where eomonth(nt.CallStart) = eomonth('2021-02-01') -- calls in specific month ``` You should always use database schema for all your tables (for example dbo.Subscriber).
49,161,709
My data looks something like this: ``` dat <- data.frame(Model = rep(c("OM", "EM-1", "EM-2", "EM-3"), each = 3), Run = rep(c(1,2,3), time=4), Value = c(2,10,5,20,26,7,8,15,33,11,31,7)) ``` Where I have values from multiple models across several runs, in this case 4 models with 3 runs each. The "OM" model is the base case and I would like to compare everything back to it. I would like to, using tidyverse, calculate a new value which would be the difference between each model run and its corresponding "OM" model run. I think I am getting close with: ``` library(tidyverse) x <- dat %>% group_by(Run) %>% filter(!is.na(Value)) %>% mutate(Diff = c(NA, diff(Value))) ``` Which calculates the difference between Runs of subsequent models but I cant figure out how to get all of these calculations to be in relation to the "OM" model, instead of just whatever the previous model was. I know I can do this by subsetting my data and doing the calculations that way but I am trying to do it cleanly in tidyverse since I will have lots of different models over time and don't want to have to subset all of them to run calculations. Thanks in advance for the help.
2018/03/07
[ "https://Stackoverflow.com/questions/49161709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2666272/" ]
Yes, your coding technique is good (or at least acceptable). Using `break` is perfectly fine in `for` loops. In fact, it suggest you may have advanced knowledge about `Java` as you already demonstrate that you know that `break` will end the loop. The same goes for using `return` multiple times as it demonstrates that you know that a function will stop running once it `return`s something, meaning that you know using multiple `return`s can improve efficiency. Also, your frequent use of `for` loops demonstrates that you're comfortable using them, which is good. Your use of `i` and `j` as counter variables strengthens this impression. Note: I would just like to point out that using lengthy variable names isn't the best practice as you're more prone to making a typo (that said, it's good that you're using camelCase for your variables).
20,032
I've just started implementing bullet into my Ogre project. I followed the install instructions here: <http://www.ogre3d.org/tikiwiki/OgreBullet+Tutorial+1> And the rest if the tutorial here: <http://www.ogre3d.org/tikiwiki/OgreBullet+Tutorial+2> I got that to work fine however now I wanted to extend it to a handle a first person camera. I created a CapsuleShape and a Rigid Body (like the tutorial did for the boxes) however when I run the game the capsule falls over and rolls around on the floor, causing the camera swing wildly around. I need a way to fix the capsule to always stay upright, but I have no idea how Below is the code I'm using. (part of) Header File ``` OgreBulletDynamics::DynamicsWorld *mWorld; // OgreBullet World OgreBulletCollisions::DebugDrawer *debugDrawer; std::deque<OgreBulletDynamics::RigidBody *> mBodies; std::deque<OgreBulletCollisions::CollisionShape *> mShapes; OgreBulletCollisions::CollisionShape *character; OgreBulletDynamics::RigidBody *characterBody; Ogre::SceneNode *charNode; Ogre::Camera* mCamera; Ogre::SceneManager* mSceneMgr; Ogre::RenderWindow* mWindow; ``` main file ``` bool MinimalOgre::go(void) { ... mCamera = mSceneMgr->createCamera("PlayerCam"); mCamera->setPosition(Vector3(0,0,0)); mCamera->lookAt(Vector3(0,0,300)); mCamera->setNearClipDistance(5); mCameraMan = new OgreBites::SdkCameraMan(mCamera); OgreBulletCollisions::CollisionShape *Shape; Shape = new OgreBulletCollisions::StaticPlaneCollisionShape(Vector3(0,1,0), 0); // (normal vector, distance) OgreBulletDynamics::RigidBody *defaultPlaneBody = new OgreBulletDynamics::RigidBody( "BasePlane", mWorld); defaultPlaneBody->setStaticShape(Shape, 0.1, 0.8); // (shape, restitution, friction) // push the created objects to the deques mShapes.push_back(Shape); mBodies.push_back(defaultPlaneBody); character = new OgreBulletCollisions::CapsuleCollisionShape(1.0f, 1.0f, Vector3(0, 1, 0)); charNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); charNode->attachObject(mCamera); charNode->setPosition(mCamera->getPosition()); characterBody = new OgreBulletDynamics::RigidBody("character", mWorld); characterBody->setShape( charNode, character, 0.0f, // dynamic body restitution 10.0f, // dynamic body friction 10.0f, // dynamic bodymass Vector3(0,0,0), Quaternion(0, 0, 1, 0)); mShapes.push_back(character); mBodies.push_back(characterBody); ... } ```
2011/11/21
[ "https://gamedev.stackexchange.com/questions/20032", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/11299/" ]
I actually just finished writing this for my capsule object yesterday. You just need to call btRigidBody::setAngularFactor(btVector3(Yaw, Pitch, Roll)); Calling it with all 0s will prevent your object from rotating on any angle. Here is where I originally found the answer: <http://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?p=&f=9&t=2956> (In reply to that thread I have had no issues using Bullet 2.79 and setAngularFactor)
5,388,194
Is there a Java Web Framework, with mvc, thrid-party integration APIs, libraries and tools? Something like Zend Framework for PHP?
2011/03/22
[ "https://Stackoverflow.com/questions/5388194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/268912/" ]
Using Zend for a while, I found the transition to Spring fairly easy. Spring does come with more bells and whistles (Dependancy injection, AOP etc)
21,707,120
I'm trying to rename an XCode5 project that has an attached CocoaPods (Pods project). (I've attached the CocoaPods using the following tutorial: <http://www.raywenderlich.com/12139/introduction-to-cocoapods>) I've tried the standard renaming technique: <https://stackoverflow.com/a/19442868/173623> But it breaks the build, since the rename only takes place for App project. How can I accomplish this task? Thank you.
2014/02/11
[ "https://Stackoverflow.com/questions/21707120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/173623/" ]
After viewing your provided tutorial, I would like to suggest you the following: * First follow the standard renaming technique that you got in another post * Now if you have enough time and patience, then it'd be best to start over from the section `Installing Your First Dependency` If you don't do that, then you may follow the next steps, but I can't guarantee for success. * `Replace` all the occurrence of `CocoaPodsExample.xcworkspace` with `<NEW_PROJ_NAME>.xcworkspace` in the `Pods` folder and possible places * Close the Xcode project (if you had it open) and open `<NEW_PROJ_NAME>.xcworkspace` to continue and test if it worked * Now, switch to `ViewController.m` and replace `CocoaPodsExample` with `<NEW_PROJ_NAME>` if exists Thats it! The project should now build successfully.
21,916,516
I'm working on an AngularJS app that uses a custom directive. I'm also trying to use unit testing in my app. So, I'm trying to leverage Jasmine for that. Currently, My unit test is the problem. Currently, it looks like the following: **myDirective.spec.js** ``` describe('Directive: myDirective', function () { describe('Function: myProcedure', function () { it('should word', function ($rootScope, $compile) { var e = angular.element('<div><br /></div>'); console.log($compile); $compile(e)($rootScope); expect(true).toBe(true); }); }); }); ``` This test is throwing an exception. When the console.log line is ran, it prints: 'undefined'. The next line throws an error to Jasmine that says: 'TypeError: undefined is not a function'. Its like I'm not injecting the $compile service. However, I believe I'm doing so. My test runner looks like the following: ``` <html ng-app="testApp"> <head> <title></title> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine-html.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/boot.js"></script> <script type="text/javascript" src="index.html.js"></script> <script type="text/javascript" src="directives/myDirective.js"></script> <script type="text/javascript" src="tests/unit/myDirective.spec.js"></script> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jasmine/2.0.0/jasmine.css" /> </head> <body> <a href="#" onclick="env.execute()">run tests</a> </body> </html> ``` Why cannot I not run this basic test? What am I doing wrong?
2014/02/20
[ "https://Stackoverflow.com/questions/21916516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3284007/" ]
First you must add angular mocks: ``` <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular-mocks.js"> </script> ``` then load the modules and inject $compile/$rootScope in `beforeEach` blocks: ``` describe('Directive: myDirective', function () { var $compile; var $rootScope; beforeEach(module('testApp')); beforeEach(inject(function(_$compile_, _$rootScope_){ $compile = _$compile_; $rootScope = _$rootScope_; })); describe('Function: myProcedure', function () { it('should word', function () { var e = angular.element('<div><br /></div>'); $compile(e)($rootScope); expect(true).toBe(true); }); }); }); ``` Check unit testing docs: <http://docs.angularjs.org/guide/dev_guide.unit-testing#directives>
2,852,182
Let $f(x,y)$ be a real-valued function in two variables. Let $x\_n \to x\_0$ and $y\_n \to y\_0$ as $n \to \infty$. We assume $f(x,y)$ is differentiable in $x$ at $(x\_0, y\_0)$ with derivative $f'\_x(x\_0,y\_0)$. Further suppose $f'\_x(x,y)$ is continuous at $(x\_0,y\_0)$. > > **Question:** Consider the following Taylor expansion about $(x\_0,y\_n)$: > $$f(x\_n,y\_n) = f(x\_0,y\_n) + f'\_x(x\_0,y\_n)(x\_n - x\_0) + R\_n(x\_n,y\_n)$$ > > > Is it neccesary true that $R\_n(x\_n,y\_n) = o(|x\_n - x\_0|)$? > > > Clearly if all instances of $y\_n$ are replaced by $y\_0$, the Taylor expansion is correct based on the definition of differentiability. And if $f(x,y)$ is differentiable in both $x$ and $y$ at $(x\_0,y\_0)$, we have $$f(x\_n,y\_n) = f(x\_0,y\_0) + f'\_x(x\_0,y\_0)(x\_n - x\_0) + f'\_y(x\_0,y\_0)(y\_n - y\_0) + R\_n^\*(x\_n,y\_n)$$ with $R^\*\_n(x\_n,y\_n) = o(|x\_n - x\_0| + |y\_n - y\_0|)$. However, if we don't have differentiability in the two variables, I wonder if the Taylor expansion in the question is correct.
2018/07/15
[ "https://math.stackexchange.com/questions/2852182", "https://math.stackexchange.com", "https://math.stackexchange.com/users/556297/" ]
**Yes**. continuity of $f\_x'(x,y)$ at $(x\_0,y\_0)$ is enough. Proof: Because $f\_x'(x,y)$ is continuous at $(x\_0,y\_0)$, there exists a closed ball $\mathcal{B}$ centered at $(x\_0,y\_0)$ such as $f'\_x(x,y)$ exists. For $n$ high enough, both $x\_n$ and $y\_n$ are in the ball, and we can thus write $$f(x\_n,y\_n) = f(x\_0,y\_n) + f'\_x(x\_0,y\_n)(x\_n - x\_0) + R\_n(x\_n,y\_n)$$ with $$\frac{R\_n(x\_n,y\_n)}{x\_n - x\_0} = \frac{f(x\_n,y\_n) - f(x\_0,y\_n)}{x\_n - x\_0} - f'\_x(x\_0,y\_n) $$ We need to find a sufficient condition for > > $$ \frac{R\_n(x\_n,y\_n)}{x\_n - x\_0} = o(1)$$ > > > For $n$ high enough so that $x\_n$ and $y\_n$ are in the ball $\mathcal{B}$, we have, from the Mean Value Theorem, > > $$\frac{ f(x\_n,y\_n) - f(x\_0,y\_n)}{x\_n - x\_0} = f'\_x(\tilde{x}\_n,y\_n)$$ > > > where $\tilde{x}\_n$ is between $x\_n$ and $x\_0$. Hence, together with the triangle inequality, > > $$\begin{align} > \left|\frac{R\_n(x\_n,y\_n)}{x\_n - x\_0}\right| > &= \left| f'\_x(\tilde{x}\_n,y\_n) - f'\_x(x\_0,y\_n) \right| \\ > &\le \left| f'\_x(\tilde{x}\_n,y\_n) - f'\_x(x\_0,y\_0) \right| + \left| f'\_x(x\_0,y\_n) - f'\_x(x\_0,y\_0) \right|\\ > &= o(1) > \end{align} $$ > > > with the last true because of the continuity of the derivative at $(x\_0,y\_0)$. This proves the result. **Note 1**: Essentially the same proof can be used when $x$ and $y$ are vectors. However, if $x$ is a vector, we need that $f$ be differentiable in $x$ in a neighborhood of $(x\_0,y\_0)$ to justify the use of the mean value theorem. **Note 2**: Instead of the continuity of $f\_x'(x,y)$ at $(x\_0,y\_0)$, we can assume that at $x\_0$ and $y$ on a closed ball $\mathcal{B}$ centered at $y\_0$ , we have $f\_x'(x,y)$ continuous in $x$ uniformly in $y$, so that, for any $x\_n \to 0$, $$\sup\_{y \in \mathcal{B}}\left| f'\_x({x}\_n,y) - f'\_x(x\_0,y) \right| = o(1)$$ In which case, for $n$ large enough so that $y\_n$ is in the ball, $$\left| f'\_x(\tilde{x}\_n,y\_n) - f'\_x(x\_0,y\_n) \right| \le \sup\_{y \in \mathcal{B}}\left| f'\_x(\tilde{x}\_n,y) - f'\_x(x\_0,y) \right| = o(1)$$
6,275,246
I have two tables, Subject and Content, where Content references Subject with foreign key. I want to display how many times each subject appears in Content table (0, if it does not appear). But the query below only gives me the rows with count > 0 and ignores the others: ``` SELECT Subject.id, Subject.name, COUNT(Content.subject_id) AS `count` FROM Subject LEFT JOIN Content ON Subject.id = Content.subject_id WHERE type = @type GROUP BY Subject.id; ``` I checked and tried to follow [this](https://stackoverflow.com/questions/3855678/mysql-include-zero-rows-when-using-count-with-group-by), [this](https://stackoverflow.com/questions/1478384/mysql-select-count-group-by-not-returning-rows-where-the-count-is-zero) and [this](https://stackoverflow.com/questions/743456/displaying-rows-with-count-0-with-mysql-group-by) post but for some reason the code above does not work. Any ideas? Edit: the type field is in the Content table and that was causing the the problem as "Will A" pointed out
2011/06/08
[ "https://Stackoverflow.com/questions/6275246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/705972/" ]
Which table is `type` a column in? I'm supposing that it's Content - and by including the field in the WHERE clause, you're forcing the Content table on the right-hand side of the LEFT JOIN to have data in it (which means the LEFT JOIN is actually then just an INNER JOIN). Try: ``` SELECT Subject.id, Subject.name, COUNT(Content.subject_id) AS `count` FROM Subject LEFT JOIN Content ON Subject.id = Content.subject_id AND type = @type GROUP BY Subject.id; ```
54,403,960
I am trying to update room database want to add two columns with an existing database and don't want to lose the data. My existing table name WordTable ``` @Entity data class WordTable( @PrimaryKey(autoGenerate = true) var id: Int = 0, var word: String = "", var des: String = "", var bookmark: Boolean = false, var addByUser: Boolean = false, var uploaded: Boolean = false) ``` I want to add this two column, so my code is now ``` @Entity data class WordTable( @PrimaryKey(autoGenerate = true) var id: Int = 0, var word: String = "", var des: String = "", var ref: String = "Added by user", var recent: Date = Date(), var bookmark: Boolean = false, var addByUser: Boolean = false, var uploaded: Boolean = false) ``` Note: I provide date conveter Create a new table ``` database.execSQL("CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT," + " word TEXT," + " des TEXT," + " ref TEXT," + " recent INTEGER," + " bookmark INTEGER," + " addByUser INTEGER," + " uploaded INTEGER)") ``` Copy previous data ``` database.execSQL("Insert Into USER (id, word, des, bookmark, addByUser, uploaded) Select * From WordTable") ``` Drop word table ``` database.execSQL("Drop Table WordTable") ``` Rename user table to WordTable ``` database.execSQL("Alter Table USER RENAME TO WordTable") ``` And I get this error; ``` Expected: TableInfo{name='WordTable', columns={addByUser=Column{name='addByUser', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}, word=Column{name='word', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0}, bookmark=Column{name='bookmark', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}, uploaded=Column{name='uploaded', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}, id=Column{name='id', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=1}, ref=Column{name='ref', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0}, des=Column{name='des', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0}, recent=Column{name='recent', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}}, foreignKeys=[], indices=[]} Found: TableInfo{name='WordTable', columns={addByUser=Column{name='addByUser', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0}, word=Column{name='word', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0}, bookmark=Column{name='bookmark', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0}, uploaded=Column{name='uploaded', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0}, id=Column{name='id', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=1}, ref=Column{name='ref', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0}, des=Column{name='des', type='TEXT', affinity='2', notNull=false, primaryKeyPosition=0}, recent=Column{name='recent', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0}}, foreignKeys=[], indices=[]} ``` The difference between Expected and Found is ``` Expected: notNull=true Found: notNull=false ``` so I try to modify the create table code ``` database.execSQL("CREATE TABLE `USER` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `word` TEXT NOT NULL, `des` TEXT NOT NULL, `ref` TEXT NOT NULL, `recent` INTEGER NOT NULL, `bookmark` INTEGER NOT NULL, `addByUser` INTEGER NOT NULL, `uploaded` INTEGER NOT NULL)") ``` But this time I get this error: ``` android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: USER.ref (Sqlite code 1299), (OS error - 2:No such file or directory) at android.database.sqlite.SQLiteConnection.nativeExecuteForChangedRowCount(Native Method) at android.database.sqlite.SQLiteConnection.executeForChangedRowCount(SQLiteConnection.java:742) ``` I also try alter table and column but get same error. How can I fix this?
2019/01/28
[ "https://Stackoverflow.com/questions/54403960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5935559/" ]
You can copy queries to create tables or modify tables from the generated room database file. Just double tap shift and look for \_Impl. Your problem is related to `NON NULL` data types in your tables you need to specify these fields as `NON NULL` and handle `DEFAULT` values that need to be assigned during your Room Migration.
3,472
I am working on [this code](https://github.com/nfmcclure/tensorflow_cookbook/blob/master/09_Recurrent_Neural_Networks/02_Implementing_RNN_for_Spam_Prediction/02_implementing_rnn.py) for spam detection using recurrent neural networks. Question 1. I am wondering whether this field (using RNNs for email spam detection) worths more researches or it is a closed research field. Question 2. What is the oldest published paper in this field? Quesiton 3. What are the pros and cons of using RNNs for email spam detection over other classification methods?
2017/06/10
[ "https://ai.stackexchange.com/questions/3472", "https://ai.stackexchange.com", "https://ai.stackexchange.com/users/6050/" ]
There's a strong sentiment towards the idea that medical diagnosis is largely [Abductive Reasoning](https://en.wikipedia.org/wiki/Abductive_reasoning). See [this presentation](https://blogs.kent.ac.uk/jonw/files/2015/04/Aliseda2012.pdf) for additional details. One approach to automated abductive reasoning is [parsimonious covering theory](https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2244953/). If you want a relatively in-depth look at all of this, check out the book [Abductive Inference Models for Diagnostic Problem-Solving](http://rads.stackoverflow.com/amzn/click/0387973435) . Expert systems have also been shown to work very well for medical diagnosis. As far back as the 1970's, systems like [MYCIN](https://en.wikipedia.org/wiki/Mycin) could beat human experts in terms of diagnosis and treatment plans. From what I can tell, there doesn't seem to be any reason in principle to think that AI/ML can't be used across the board for medical diagnosis, mental health or otherwise.
33,170,820
I have x86 C++ application which using ImageMagic++ library. I also have machine with CentOS 7 x86\_64. I need to build my application on this machine. I have installed i686 ImageMagick library: ``` [dvoryankin@testsuitel]$ yum list installed | grep Magick ImageMagick.i686 6.7.8.9-10.el7 @base ImageMagick-c++.i686 6.7.8.9-10.el7 @base ImageMagick-c++-devel.i686 6.7.8.9-10.el7 @base ImageMagick-devel.i686 6.7.8.9-10.el7 @base ``` When I try to build my application I have an error: ``` /usr/include/ImageMagick/magick/magick-config.h:9:31: fatal error: magick-config-64.h: No such file or directory #include "magick-config-64.h" ``` It's happened becuase file */usr/include/ImageMagick/magick/magick-config.h* use macro definition `__WORDSIZE` to determine which file must be included *magick-config-64.h* or *magick-config-32.h*. On my machine with CentOS 7 x86\_64 this macro is equal 64 and ImageMagick try to include *magick-config-64.h* but i686 library doesn't have this, only *magick-config-32.h*. How I can build x86 application with x86 ImageMagick library on CentOS 7 x86\_64 machine without change any library files?
2015/10/16
[ "https://Stackoverflow.com/questions/33170820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3844730/" ]
I added this : ``` // Add timeZone Date.prototype.addTimeZone = function () { if(this.getTimezoneOffset() > 0){ this.setMinutes(this.getTimezoneOffset()); } return this; }; ``` And this on my controller/model : ``` new Date(myDate).addTimeZone(); ``` **To resume :** **extend-date-prototype.js** ``` // Add timeZone Date.prototype.addTimeZone = function () { if(this.getTimezoneOffset() > 0){ this.setMinutes(this.getTimezoneOffset()); } return this; }; // Remove TimeZone Date.prototype.toJSON = function(){ return moment(this).format('YYYY-MM-DD') + 'T00:00:00.000Z'; }; ``` **view.html** ``` <p ng-bind="(myDate | date:'dd/MM/yyyy')"></p> ``` **controller.js** ``` new Date(myDate).addTimeZone(); ``` I use [moment.js](http://momentjs.com/)
57,927,197
I have a dictionary like below. ``` d = {'key1': {'match': '45.56', 'key12': '45.56'}, 'key2': {'key21': '45.56', 'match2': '45.56'}, 'key3': {'key31': '45.56', 'key32': '45.56'}, 'key4': ["key4", "key5"]} ``` I want to grab key names (where the value of the key is either match or match2) under heading "match" and unmatch ones under "not match" heading. ``` match key1 key2 not match key3 key4 ``` I tried the below code but it doesn't return anything: ``` d = {'key1': {'match': '45.56', 'key12': '45.56'}, 'key2': {'key21': '45.56', 'match2': '45.56'}, 'key3': {'key31': '45.56', 'key32': '45.56'}, 'key4': ["key4", "key5"]} print(*[k for k in d if 'match' in d[k] or 'match2' in d[k]], sep='\n') ---only prints the matched values ```
2019/09/13
[ "https://Stackoverflow.com/questions/57927197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8340881/" ]
You can do a list comprehension to get the match using `any` and membership check and non-match using set difference: ``` d = {'key1': {'match': '45.56', 'key12': '45.56'}, 'key2': {'key21': '45.56', 'match2': '45.56'}, 'key3': {'key31': '45.56', 'key32': '45.56'}, 'key4': ["key4", "key5"]} to_look = {'match', 'match2'} match = [k for k, v in d.items() if any(x in to_look for x in v)] not_match = set(d).difference(match) print('match') print(*match, sep='\n') print('\nnot match') print(*not_match, sep='\n') ``` **Output**: ``` match key1 key2 not match key3 key4 ```
22,184
Assuming that there are no known complete graph invariants in the spirit of [Harrsion's question](https://mathoverflow.net/questions/11631/complete-graph-invariants) that do not depend on any labelling (see [graph property](http://en.wikipedia.org/wiki/Graph_invariant) at Wikipedia), I wonder if there are graph invariants that are * almost complete, i.e. discriminating almost all finite graphs up to isomorphism * almost complete in a weaker sense, i.e. discriminating all finite graphs except for a small, but finite fraction (the smaller the fraction the greater the invariant's discriminating power) * probably complete, i.e. not proven to be incomplete yet (e.g. by counterexamples) Can anyone provide examples or references?
2010/04/22
[ "https://mathoverflow.net/questions/22184", "https://mathoverflow.net", "https://mathoverflow.net/users/2672/" ]
I'm not sure I understand the question well enough to know whether this is a reasonable answer. But a standard observation concerning the graph isomorphism problem is that there is an approach that feels as though it almost works: work out the eigenvalues and eigenvectors of the adjacency matrix. There is a small technical problem that you can't do this exactly, and a more fundamental problem that if you have eigenvalues of multiplicity greater than 1 then you don't distinguish all graphs. But I would guess that almost all graphs have adjacency matrices with distinct eigenvalues. Can anyone confirm this? And if that is the case, does it answer your question?
16,454,723
How to Make a Game Like Cut the Rope using vrope class ??? my game is on cocos2d for iphone >> cut the rope
2013/05/09
[ "https://Stackoverflow.com/questions/16454723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2372875/" ]
Using **NSURLConnection** ,Try this ``` // Create the request. NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://cdn.cultofmac.com/wp-content/uploads/2013/03/colorware-iphone-5-xl.jpg"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; // create the connection with the request // and start loading the data NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; if (theConnection) { // Create the NSMutableData to hold the received data. // receivedData is an instance variable declared elsewhere. receivedData = [[NSMutableData data] retain]; } else { // Inform the user that the connection failed. } ``` For more info on NSURLConnection Refer this :[URL Loading System Programming Guide](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html) **EDIT** Here `recievedData` is the instance variable of type `NSMutableData` ``` -(void)downloadWithNsurlconnection { NSURL *url = [NSURL URLWithString:currentURL]; NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60]; receivedData = [[NSMutableData alloc] initWithLength:0]; NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES]; } - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; [receivedData setLength:0]; } - (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [receivedData appendData:data]; } - (void) connectionDidFinishLoading:(NSURLConnection *)connection { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:[currentURL stringByAppendingString:@".jpg"]]; NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]); [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; [receivedData writeToFile:pdfPath atomically:YES]; } ```
74,556,541
i am not experienced working with docker and docker-compose, but atleast i know how to get a container running, below is my compose file of a simple react app boiler plate. my intention was to assign an IP to it so that i can ping it from the external network, and also to access it without any port mapping to the host ``` version: "3.9" services: front-web: build: context: . dockerfile: Dockerfile args: buildno: 1.0.0 container_name: web-front domainname: fontend dns: 8.8.8.8 network_mode: "host" hostname: alpha restart: unless-stopped stop_grace_period: 1m expose: - 4000 tty: true pid: host stdin_open: true ports: - target: 4000 published: 4000 protocol: tcp mode: host networks: web-net: ipv4_address: 192.168.1.195 volumes: - web-front:/app/data networks: web-net: name: web-net driver: bridge driver_opts: enable_ipv4: 1 enable_ipv6: 1 ipam: driver: default config: - subnet: 192.168.1.1/24 ip_range: 192.168.1.195/24 gateway: 192.168.1.195/24 volumes: web-front: ``` the docker file of the app is below ``` FROM node:alpine3.16 # RUN addgroup app && adduser -SG app app # USER app WORKDIR /app RUN mkdir data EXPOSE 4000 COPY package* . RUN npm install COPY . . CMD [ "npm", "start" ] ``` ignore the "adduser" although it also failed to workout. whenever i run docker-compose up, i get an error saying: ``` Attaching to web-front Error response from daemon: failed to add interface vethcf21a7d to sandbox: error setting interface "vethcf21a7d" IP to 192.168.1.195/24: cannot program address 192.168.1.195/24 in sandbox interface because it conflicts with existing route {Ifindex: 31 Dst: 192.168.1.0/24 Src: 192.168.1.1 Gw: <nil> Flags: [] Table: 254} ``` i am not sure how to go about this, kindly assist I tried changing the driver part in the Networks section from brigde to macvlan, the build would pass but again i could not ping the the container with its ip. adding external:true, makes the whole thing fail
2022/11/24
[ "https://Stackoverflow.com/questions/74556541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20569584/" ]
Here is a one liner that will do the trick using `gsub()` ``` gsub(".*def.*(\\d+)\\)%ile.*%ile", "\\1", x, perl = TRUE) ``` Here's an approach that will work with any number of "%ile"s. Based on `str_split()` ``` x <- "abc(0)(1)%ile, def(2)(3)(4)%ile(5)%ile(9)%ile" x %>% str_split("def", simplify = TRUE) %>% subset(TRUE, 2) %>% str_split("%ile", simplify = TRUE) %>% subset(TRUE, 1) %>% str_replace(".*(\\d+)\\)$", "\\1") ```
473,455
Just wondering if there is any way to put emacs and shell in the same window. Like split the shell in to two parts, one for shell it self, the other one for emacs. Or is there any way to switch the shell window and emacs window quickly? The reason I am asking this is: sometimes I need to run my program with shell command, that I have to close the emacs and go back to the shell window. It is a little waste of time to switch back and forth. Thank you
2012/09/11
[ "https://superuser.com/questions/473455", "https://superuser.com", "https://superuser.com/users/100570/" ]
Try enabling the `discard` mount option for an Ext4 filesystem and running a recent Linux kernel. This option is being used for SSDs mainly. At the same time it is being currently supported by [`zram`](https://www.kernel.org/doc/Documentation/blockdev/zram.txt) too.
145,215
Which is the real one? What is the other one? How did I get it? ![screenshot](https://i.stack.imgur.com/rG0D8.jpg)
2014/09/14
[ "https://apple.stackexchange.com/questions/145215", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/3044/" ]
TL;DR: keep the one that looks like a bag, it is now a universal app. The cart one was the iPad specific one. Looks like the one of the left (with the shopping cart icon) is the old one. Launching it now directs me to the new one, but it didn't when I was trying to figure this out before. Here's what I get when launching the old one now.![enter image description here](https://i.stack.imgur.com/VLuRy.jpg) EDIT-20140917: It appears that Apple may have had a separate iPad app that they have since deprecated and made their iPhone/iPod Touch app a universal app and that's why this app is now defunct.
130,607
The issue has crept up on me slowly over the last several years. I am increasingly aware of the massive debt that many of my students are taking on, debt which is far beyond the sort of debt that I incurred as an undergraduate in the 1980s. Because of this, in recent semesters I have found it somewhat difficult to fail students. Instead of simply asking myself "does this student deserve to fail this class?", I find myself asking "does this student deserve to have their life ruined?" In many cases (e.g. students who are already on academic probation) this is not much of an exaggeration. It is a very bad situation to find yourself in your early 20s with no college degree but $30,000 in debt. In some cases, I am aware that a decision of mine might be a contributing cause of a student ending up in just such a situation. I can no longer regard a failing grade as a relatively minor matter (like a speeding ticket). How do professors reconcile their de jure role as guardians of academic integrity with their de facto role of being (at least in part) responsible for their students' economic future?
2019/05/15
[ "https://academia.stackexchange.com/questions/130607", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/72815/" ]
**You are responsible for teaching the students to the best of your ability, and to judge their capacities to use what they have learned**. That judgment is made based on their grades. So you have several things to think about here. 1. **Are you teaching the best you can?** Teaching does not mean "downloading facts", as I'm sure you're aware. It means "transferring knowledge, skills, and attitudes". That "transfer" part is the important bit — transfer means that the student is able to reproduce and use what they've learned. Is your teaching enhancing this transfer? This is a tough nut to crack — how do you know? Are you planning your assessments so that you can really tease out the nuances and to see which students really understand, or are they just assessments because you need to assign a grade somehow? Your institution might have a center for teaching how to teach, and if you feel that you aren't teaching your best class then start there. Otherwise, lots of books and resources exist, which I'm sure we can all provide. 2. **Are you assessing fairly?** Fairly doesn't mean easily. It means that you are creating assessments that actually test understanding and that a student with reasonable ability will be able to succeed at. It also means to understand their context. It's easy to make a "really good" assessment that everyone fails because they also have three projects and two midterms in their other courses. Are your expectations clearly communicated, and are you ensuring that you only assess what you've asked for? (that doesn't mean that you can't expect students to go above and beyond, just that you need to tell them you expect them to) 3. **Are you assessing accurately?** I'm distinguishing this from "fair", but you can treat "fair" and "accurate" as two sides of the same coin. Accurate means that your assessments are set up so that appropriate weight is given to appropriate topics, and that your tests actually enable students to display their understanding and capacities, rather than whether they memorized the example or found the answer on stack exchange. Creating fair assessments is challenging, but there is a lot of research and resources available. 4. **Are you giving every student the chance to seek help?** I often find that if students are slipping through the cracks, setting up a regular meeting with them to keep them on track can do wonders. However, I am in a job in which I'm required to work with students like this, so it's easy for me to do. If you are a busy research professor who is teaching two courses per semester while juggling other things, it's a lot harder. Ultimately, the final exam is not when a student should find out they failed the course. They should know that they are on a bad path long before then, and should have opportunities to get on track. If you are doing these things, then **you** are not causing them financial ruin. It's similarly not fair to say that the students are causing this — you don't know their context and can't make the judgment. Perhaps they went to a bad high school that just didn't prepare them, or perhaps they are always on the train to another city because their parents are sick and they can't attend classes. It is not your responsibility to help them in this way unless you are capable of providing everyone the same help. Which brings me to the most unfortunate reality of post-secondary education: **Not everyone can make it**. For whatever reason, some students simply will not demonstrate that their abilities are up to the standard that has been set. Notice the wording I used there — I didn't say that they don't have those abilities, but that they will not **demonstrate** that they have those abilities. Provided you are assessing them fairly/accurately, teaching the best you can, and giving the help they pay for, then you are providing them with every opportunity to demonstrate those abilities. If they are unable to do so, then it would be unethical to let them pass regardless of the reason.
8,411,466
I am using a way to insert some javascript code in the page which works with all browsers but not with IE. Here is a sample: <http://boxfly.free.fr/tmp/innerjs.html> The line which does not work properly with IE is: ``` ele.text = document.getElementById('DIV_js').innerHTML ; ``` If I change this line to: ``` ele.text = 'alert("Hello")' ; ``` It works. But I need to be able to insert code which is on a lot of lines, not only one line for displaying an alert, that's why I am using a DIV to contain the Javascript code... ;) Does anyone know how to make this script work with IE: ``` <body> <div id="DIV_js" style="display:none;"> var i = 'here' ; function hello() { alert('toto says ' + i) ; } </div> <script> var ele = document.createElement("script") ; ele.type = 'text/javascript' ; ele.text = document.getElementById('DIV_js').innerHTML ; document.body.insertBefore(ele, (document.getElementsByTagName("div"))[0]); </script> <span onClick="hello();">Click to display alert</span> </body> ```
2011/12/07
[ "https://Stackoverflow.com/questions/8411466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1073500/" ]
The problem was that the example constructor needs this line at the top ``` parent::__construct ``` That should fix the issues you were having. So your constructor should look like: ``` public function __construct() { parent::__construct(); $this->load->library('session'); } ``` There is no need to store CodeIgniter in a private variable. Just use the constructor as outline in the CodeIgniter documentation. I have updated the GIT repo to fix this issue.
39,149,713
I'm writing a UI where the user can type in a search term and a list get continuously updated offering suggestions. My first though was that the Rx primitive Throttle was a perfect match but it gets me half there. The suggestions take a while to fetch so I get them asynchronously on not on the UI thread. The problem is that I want to discard/skip/throw away a result if the user types af the throttle time span again. For example: * Time starts and the user presses a key : 0ms * The throttle is set to 100ms. * The fetch takes 200ms. * At 150ms the user pressed another key Now with Throttle the first fetch will still go ahead an populate the gui suggestion list. What I like to learn is how can I cancel that first fetch as it is not relevant anymore? Only the second keypress should trigger an update to the gui. Here is what I tried (I use ReactiveUI but the Q is about Rx) ``` public IEnumerable<usp_getOpdrachtgevers_Result> Results { get; set; } // [Reactive] pu public SearchOpdrachtgeverVM() { this.WhenAnyValue(x => x.FirstName, x => x.LastName ) .Throttle(TimeSpan.FromMilliseconds(200)) .Subscribe(async vm => Results = await PopulateGrid()); } private async Task<IEnumerable<usp_getOpdrachtgevers_Result>> PopulateGrid() { return await Task.Run( () => _opdrachtgeversCache .Where(x => x.vNaam.Contains(FirstName) && x.vLastName.Contains(LastName) ) ); } ```
2016/08/25
[ "https://Stackoverflow.com/questions/39149713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/381995/" ]
If you turn your async Task into an Observable, this looks like a classic use for `Switch`: ``` this.WhenAnyValue(x => x.FirstName, x => x.LastName ) .Throttle(TimeSpan.FromMilliseconds(100)) .Select(l => PopulateGrid().ToObservable()) .Switch() .Subscribe(vm => Results = vm); ``` `Throttle` should be used to suppress calls while the user is typing. So adjust that TimeSpan as you like.
58,206,823
In my `ClientController@index`, I have a form with a select input to list every client in the database. After submitting the form to list detailed client information, the `URL` is like `/clients?client_id=id`. The routes are the defult with `route::resource()`. ``` <form name="show_client" id="show_client"> <div class="form-group"> <label for="branch"><b>Selectione o Cliente</b></label> <select class="form-control select2" name="client_id" id="client_id" required> <option value="">Selecione o Cliente</option> @foreach ($list as $client) <option value="{{ $client->client_id }}">{{ $client->name }} </option> @endforeach </select> </div> <hr /> <div class="form-group"> <button type="submit" class="btn btn-primary btn-rounded">Listar Cliente</button> </div> </form> ``` ``` <script> $(function() { $('#show_client').submit(function(){ var client_id = $('#client_id').val(); $(this).attr('action', "/clients/" + client_id); }); }); </script> ``` Is there any way to work the url to be /clients/id? I accomplish that by using an js function but it's clearly not the solution.
2019/10/02
[ "https://Stackoverflow.com/questions/58206823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1742421/" ]
Assuming `search` is in your `methods` it should not be using an arrow function as that will give you the wrong `this` binding. Instead use: ```js methods: { search: throttle(function (live) { // ... }, 500) } ``` Here I'm also assuming that `throttle` will preserve the `this` value, which would be typical for implementations of throttling.
401,773
Let $a\_1,\dots,a\_n$ be real numbers, and set $a\_{ij} = a\_ia\_j$. Consider the $n \times n$ matrix $A=(a\_{ij})$. Then 1. It is possible to choose $a\_1.\dots,a\_n$ such that $A$ is non-singular 2. matrix $A$ is positive definite if $(a\_1,\dots,a\_n)$ is nonzero vector 3. matrix $A$ is positive semi definite for all $(a\_1,\dots,a\_n)$ 4. for all $(a\_1,\dots,a\_n)$, $0$ is an eigen value of $A$ I have calculated upto $3\times 3$ that determimant is $0$ but I have no idea how to conclude rigoriously. please help?
2013/05/25
[ "https://math.stackexchange.com/questions/401773", "https://math.stackexchange.com", "https://math.stackexchange.com/users/24690/" ]
It depends. With $a=(a\_1,\ldots,a\_n)$, we can more conveniently write $v\mapsto \langle a,v\rangle a$ instead of $v\mapsto Av$, which simplifies computations. 1. If $n=1$, then $a\_1=1$ is a valid choice and makes $A$ regular (the identity). For $n>1$, there exists nonzero $v$ with $\langle a,v\rangle = 0$, hence $A$ is singular. (To be explicit, either some $a\_i$ is $=0$ and then the $i$th standard base vector $e\_i$ is in the kernel; or $a\_1,a\_2$ are nonzero and $a\_1e\_2-a\_2e\_1$ is in the kernel. That is: Such a choice is possible if and only if $n=1$. 2. $\langle Av,v\rangle = \langle \langle a,v\rangle a,v\rangle = \langle a,v\rangle^2\ge 0$, so we see that $A$ is positive *semi*-definite. But if $n>1$ or $a=0$, it is defnitely not positive definite, as follows from 1. Hence the claim is true only for $n=1$ 3. As shown in 2, this is correct 4. As shown in 1, this is correct only if $n>1$. So the only claim that is unrestrictedly correct, is 3.
5,371,869
**Please note:** While the bounty is no longer available, I'm still keen for anyone with an answer to this question to contribute; I'm still watching it, and I'm waiting to see if there is a better answer. Thanks, and please read on... --- I am looking for a way to convert an arbitrary set of [RCC](http://en.wikipedia.org/wiki/Region_connection_calculus)-like spatial relations (or similar) describing a constraint network into Venn-diagram-like images. For example, the constraint network as expressed in RCC8: `W {EC} Y`, `X {TPP} Y`, `Z {NTPP} Y`, `Z {PO} X`. ..could be represented by the following diagram with circular or square regions: ![Example 1: Venn diagram representing constraint network using circular regions.](https://i.stack.imgur.com/QYE9H.png) ..alternatively:   ![Venn diagram representing constraint network using square regions.](https://i.stack.imgur.com/pjAMA.png) Is anyone aware of software that can at least generate such diagrams programmatically (via an API) from a specification of RCC-like constraints? I am aware that such a constraint network could be underspecified, precluding a match to any single such diagram (many solutions may exist). Ideally, I would like to deal with this by being able to generate possible alternatives, but can resort to none (and raising an error) for now. Just to be clear, in this question I am specifically asking for software which can calculate a ***diagram layout*** based on RCC-like constraints in a ***declarative manner***. I am not concerned with tools to turn a DSL for RCC into some other syntax, nor am I interested in particular image serialization formats or methods. I am hoping to find an algorithm to do this for dealing with an arbitrary number of constraints for up to six unique sets. ***Notes:*** [Graphviz](http://www.graphviz.org/) (as @vickirk mentioned below) is an example of a **diagram layout software package**, which is akin to what I'm after. Unfortunately, it seems that Graphviz itself cannot help with this problem (but I'd be very happy to be proven wrong!). It seems this is a very hard problem.
2011/03/20
[ "https://Stackoverflow.com/questions/5371869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Who need's a backend? Here's a **working prototype** using HTML/CSS/JS: <http://jsfiddle.net/RuvE6/6/> Just enter the RCC8 code syntax in the field and hit the button! ![HTML/CSS/JS RCC8 Diagram Builder](https://i.stack.imgur.com/owghs.png) Some current limitations: * Doesn't handle ambiguity * There's no error handling if syntax is off * Probably breaks in some valid cases (I haven't tested very much) * Didn't implement any inverse cases (yet?) **Edit: How it works** Basically, there are two *families* of relationships shown with these diagrams: * **A *contains* B** * **A *is adjacent to* B**. There are then sub-types or variations, like: * **A *contains* B** and **B *is tangential to* A** * **A *is adjacent to* B** and **A *overlaps with* to B** Both of the basic concepts are *kind of* baked into the HTML rendering world: * containment --> nested HTML elements: `<div class="region"><div class="region"></div></div>` * adjacency --> sibling HTML elements: `<div class="region"></div><div class="region"></div>` I handle the variations with special classes that (rather crudely) wiggle margins around to accomplish the desired layout: * **containment, with tangent:** `<div class="region"><div class="region touches-parent"></div></div>` (child has negative top margin to touch parent) * **adjacency, with overlap:** `<div class="ven"><div class="region"></div><div class="region touches-parent"></div></div>` (a wrapper is added to trigger CSS on the children - the second element has negative left margin to overlap the first.) There is some static markup commented out in the jsfiddle showing the structure I started with. To complete the functional loop, there is a bit of code that parses the RCC8 statement into A {XX} B parts, and attempts to render the necessary markup for each part. It checks as it goes to not duplicate regions. I also go through afterwards and set the heights of all sibling the same, which ensures they will overlap and/or abut properly. This code is really just a start, and it has it's conceits. It's basically a *linear* diagram, which means it doesn't, for instance, handle cases where there are complicated adjacencies, like this: `A {EC} B, C {EC} B, D {EC} B` These might be handled be smarted JS parsing and more complicated CSS, but probably quickly venture into the realm of more force-directed layouts (a *smarter* [bubble chart](http://vis.stanford.edu/protovis/ex/bubble.html), for instance).
74,412,503
I don't know why when `a` is located in `def test()` it can not be found and gives the error > > UnboundLocalError: cannot access local variable 'a' where it is not associated with a value > > > ```py import keyboard import time a = 0 def test(): a+= 1 print("The number is now ", a) time.sleep(1) while keyboard.is_pressed('i') == False: test() ``` I tried setting `a` as `global a` or using a `nonlocal` modifier on it inside the `def` but it doesn't seem to work. Is there a way I can get it to recognize `a` and run properly?
2022/11/12
[ "https://Stackoverflow.com/questions/74412503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20485120/" ]
To access a global variable within a function you must specify it with global. Otherwise, the variable inside the function is a local variable that only has utility inside that function. That's why you get the error: "UnboundLocalError: local variable 'a' referenced before assignment". Inside the function you haven't defined the variable 'a' yet, either local or global. ``` import keyboard import time a = 0 def test(): global a a+= 1 print("The number is now ", a) time.sleep(1) while keyboard.is_pressed('i') == False: test() ```
33,504,770
I have a `UIView` that contains buttons and labels. When these buttons are pressed, this `UIView` will become blur using the code below. ``` @IBOutlet weak var blurView: UIView! var blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark) var blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = blurView.bounds blurView.addSubview(blurEffectView) ``` However, I want to remove the blur effect later on. What is the code for removing the blurred `UIView`?
2015/11/03
[ "https://Stackoverflow.com/questions/33504770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/794575/" ]
It's hard to know exactly what is going on in your code, as you've clearly posted a cut up version (the last 4 lines are part of a method somewhere, presumably). You could do something like this to remove all `UIVisualEffectView` subviews from your `blurView`: ``` for subview in blurView.subviews { if subview is UIVisualEffectView { subview.removeFromSuperview() } } ```
74,195,322
i have a quick question i'm trying to make an application but i've faced a problem, i want to assign data to a button then pass that data to datagridview when the button is clicked ex. [![enter image description here](https://i.stack.imgur.com/5T3di.png)](https://i.stack.imgur.com/5T3di.png) ``` private void TeaButton_Click(object sender, EventArgs e) { sales.OrderDataGridView.Rows.Add(1, "Tea", 5.0); } ``` i expected it to pass the values inside the parentheses to the data grid view, but it returned a null reference error, the reason was "sales." it was returning null value, but i don't know any other way beside this .
2022/10/25
[ "https://Stackoverflow.com/questions/74195322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20330704/" ]
Add the `max-width` property with the value of `{n}ch`. For example: `max-width: 100ch`. Then, apply `white-space: nowrap`, and `overflow: hidden` to remove the overflow characters. In order to add some dots at the end, add the `text-overflow: ellipsis` property. Any character after the value you defined will be removed. ```css p { max-width: 30ch; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } ``` ```html <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore</p> ``` --- If you want to limit the number of lines, you can use the `line-clamp` properties instead of setting the number of characters (`max-width: {n}ch`): ```css display: -webkit-box; -webkit-line-clamp: 3; /* Set the number of lines here */ -webkit-box-orient: vertical; ``` Example: ```css div { max-width: 100px; } p { display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; text-overflow: ellipsis; } ``` ```html <div> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore</p> </div> ```
160,224
I have a custom menu using `add_menu_page`: ``` add_menu_page('My menu' , 'Some text', 'read', 'nwcm'); ``` Under it, I show a custom post type menu item; ``` // Create the news custom post type register_post_type('nwcm_news', array( 'labels' => array( 'name' => __('News for clients', NWCM_TEXT_DOMAIN) , 'singular_name' => __('News', NWCM_TEXT_DOMAIN) ) , 'public' => true, 'has_archive' => true, 'public' => true, 'show_ui' => true, 'show_in_menu' => 'nwcm', 'taxonomies' => array( 'nwcm_news_category' ) , )); ``` Then I add a custom taxonomy hooked to that "nwcm\_news" post type: ``` // register news taxonomy register_taxonomy('nwcm_news_category', 'nwcm_news', array( 'label' => __('News categories') , 'menu_name' => __('News categories') , 'rewrite' => array( 'slug' => 'nwcm_news_category' ) , 'hierarchical' => true )); ``` The parent menu and the custom post type both show correctly... but, the taxonomy menu isn't showing :( How can I solve this? I had checked [this solution](https://stackoverflow.com/a/20034946/232082) but the answer lacks the full code example..
2014/09/04
[ "https://wordpress.stackexchange.com/questions/160224", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/7515/" ]
You have some messed up code. I have reformatted your code to code which actually works. The following solution allows you to give your Custom Post Type menu a menu name of what ever you want. Just change the label "menu\_name". **POST TYPE** ``` // Create the news custom post type register_post_type('nwcm_news', array( 'labels' => array( 'name' => __('News for clients', 'NWCM'), 'singular_name' => __('News', 'NWCM'), 'menu_name' => __('NWCM', 'NWCM'), 'all_items' => __('View Articles', 'NWCM'), ), 'public' => true, 'has_archive' => true, 'show_ui' => true, 'show_in_menu' => true, 'taxonomies' => array( 'nwcm_news_category' ) )); ``` **TAXONOMY** ``` // register news taxonomy register_taxonomy('nwcm_news_category', 'nwcm_news', array( 'label' => 'News Categories', 'labels' => array( 'menu_name' => __('News Categories', 'NWCM') ), 'rewrite' => array( 'slug' => 'nwcm-news-category' ), 'hierarchical' => true )); ``` I'm not 100% sure if you are wanting your own custom admin menu to add your stuff under, or if you just want to change the menu name of the custom post type. I have added in the `menu_name` of "NWCM" to the `labels` of your custom post type. I would highly recommend you read through and fully understand the parameters and arguments for registering custom post types and taxonomies. * [`register_post_type();`](http://codex.wordpress.org/Function_Reference/register_post_type#Parameters) * [`register_taxonomy();`](http://codex.wordpress.org/Function_Reference/register_taxonomy#Parameters) --- **EDIT: 09/05/2014** If you wanted to completely add your own custom admin menu, and mix in your Custom Post Types, Custom Taxonomies, and any other custom admin pages of your own... The following solution works. Please note, it's just a starting point and you don't have to do it this way 100% to a "T". It's just an example... I recommend you modify it, so that it's understandable and maintainable by you or your developer. **Hook into `init` and register Custom Post Types and Custom Taxonomies.** ``` if ( ! function_exists( 'mbe_init' ) ) { function mbe_init() { # Create the news custom post type register_post_type( 'nwcm_news', array( 'labels' => array( 'name' => __( 'News for clients', 'NWCM' ), 'singular_name' => __( 'News', 'NWCM' ), ), 'public' => true, 'has_archive' => true, 'show_ui' => true, 'show_in_menu' => false,// adding to custom menu manually 'taxonomies' => array( 'nwcm_news_category' ) ) ); # Create the news categories custom taxonomy register_taxonomy( 'nwcm_news_category', 'nwcm_news', array( 'label' => 'News Categories', 'labels' => array( 'menu_name' => __( 'News Categories', 'NWCM' ) ), 'rewrite' => array( 'slug' => 'nwcm-news-category' ), 'hierarchical' => true ) ); } add_action( 'init', 'mbe_init' ); } ``` **Hook into `admin_menu` to create a custom parent admin menu, and add Custom Submenu Admin Pages, Custom Post Type pages, and Custom Taxonomy Pages all to the custom parent admin menu.** ``` if ( ! function_exists( 'mbe_add_admin_menu' ) && ! function_exists( 'mbe_display_admin_page' ) ) { function mbe_add_admin_menus() { # Settings for custom admin menu $page_title = 'News for clients'; $menu_title = 'NWCM'; $capability = 'post'; $menu_slug = 'nwcm'; $function = 'mbe_display_admin_page';// Callback function which displays the page content. $icon_url = 'dashicons-admin-page'; $position = 0; # Add custom admin menu add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position ); $submenu_pages = array( # Avoid duplicate pages. Add submenu page with same slug as parent slug. array( 'parent_slug' => 'nwcm', 'page_title' => 'Summary of News', 'menu_title' => 'Summary', 'capability' => 'read', 'menu_slug' => 'nwcm', 'function' => 'mbe_display_admin_page',// Uses the same callback function as parent menu. ), # Post Type :: View All Posts array( 'parent_slug' => 'nwcm', 'page_title' => '', 'menu_title' => 'View News', 'capability' => '', 'menu_slug' => 'edit.php?post_type=nwcm_news', 'function' => null,// Doesn't need a callback function. ), # Post Type :: Add New Post array( 'parent_slug' => 'nwcm', 'page_title' => '', 'menu_title' => 'Add News', 'capability' => '', 'menu_slug' => 'post-new.php?post_type=nwcm_news', 'function' => null,// Doesn't need a callback function. ), # Taxonomy :: Manage News Categories array( 'parent_slug' => 'nwcm', 'page_title' => '', 'menu_title' => 'News Categories', 'capability' => '', 'menu_slug' => 'edit-tags.php?taxonomy=nwcm_news_category&post_type=nwcm_news', 'function' => null,// Doesn't need a callback function. ), ); # Add each submenu item to custom admin menu. foreach ( $submenu_pages as $submenu ) { add_submenu_page( $submenu['parent_slug'], $submenu['page_title'], $submenu['menu_title'], $submenu['capability'], $submenu['menu_slug'], $submenu['function'] ); } } add_action( 'admin_menu', 'mbe_add_admin_menus', 1 ); /* If you add any extra custom sub menu pages which are not a Custom Post Type or a Custom Taxonomy, you will need * to create a callback function for each of your custom submenu items you create above. */ # Default Admin Page for Custom Admin Menu function mbe_display_admin_page() { # Display custom admin page content from newly added custom admin menu. echo '<div class="wrap">' . PHP_EOL; echo '<h2>My Custom Admin Page Title</h2>' . PHP_EOL; echo '<p>This is the custom admin page created from the custom admin menu.</p>' . PHP_EOL; echo '</div><!-- end .wrap -->' . PHP_EOL; echo '<div class="clear"></div>' . PHP_EOL; } } ``` **Hook into `parent_file` to correctly highlight your Custom Post Type and Custom Taxonomy submenu items with your custom parent menu/page.** ``` if ( ! function_exists( 'mbe_set_current_menu' ) ) { function mbe_set_current_menu( $parent_file ) { global $submenu_file, $current_screen, $pagenow; # Set the submenu as active/current while anywhere in your Custom Post Type (nwcm_news) if ( $current_screen->post_type == 'nwcm_news' ) { if ( $pagenow == 'post.php' ) { $submenu_file = 'edit.php?post_type=' . $current_screen->post_type; } if ( $pagenow == 'edit-tags.php' ) { $submenu_file = 'edit-tags.php?taxonomy=nwcm_news_category&post_type=' . $current_screen->post_type; } $parent_file = 'nwcm'; } return $parent_file; } add_filter( 'parent_file', 'mbe_set_current_menu' ); } ``` If you need any clarification about how any of this works, read the following pages from top to bottom. 1. [Adding Custom Parent Admin Menus](http://codex.wordpress.org/Function_Reference/add_menu_page) 2. [Adding Custom Child Admin Menus](http://codex.wordpress.org/Function_Reference/add_submenu_page) 3. [Roles and Capabilities in WordPress](http://codex.wordpress.org/Roles_and_Capabilities) 4. [Registering Custom Post Types](http://codex.wordpress.org/Function_Reference/register_post_type) 5. [Registering Custom Taxonomies](http://codex.wordpress.org/Function_Reference/register_taxonomy) 6. [WordPress Plugin API :: Action Reference](http://codex.wordpress.org/Plugin_API/Action_Reference) 7. [WordPress Plugin API :: Action Reference :: `init`](http://codex.wordpress.org/Plugin_API/Action_Reference/init) 8. [WordPress Plugin API :: Action Reference :: `admin_menu`](http://codex.wordpress.org/Plugin_API/Action_Reference/admin_menu) 9. [WordPress Plugin API :: Filter Reference](http://codex.wordpress.org/Plugin_API/Filter_Reference) 10. [List of All WordPress Hooks (including actions and filters)](http://adambrown.info/p/wp_hooks/hook)
64,127,599
So I've started learning vectors for the first time and wrote a simple program which goes like this: ``` #include <iostream> #include <vector> using namespace std; int main() { vector<int> g1; int n; cout<<"enter values"<<endl; do { cin>>n; g1.push_back(n); } while (n); cout<<"Vector values are: "<<endl; for(auto i=g1.begin(); i<g1.size();i++) cout<<*i<<endl; } ``` When I try executing it, an error shows up saying "type mismatch" at the g1.size() part. Why exactly does this happen? I used the auto keyword for the iterator involved and assumed there wouldn't be any problem?
2020/09/29
[ "https://Stackoverflow.com/questions/64127599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12987935/" ]
That is the bad side of using `auto`. If you have no idea what the result of `auto` is, you get no idea why it is something totally different you expect! `std::vector::begin` delivers a `std::vector::iterator` and you can't compare it against an `size_type` value which is a result of `std::vector::size`. This type is typically `std::size_t` You have to compare against another iterator which is the representation of the end of the vector like: ``` for(auto i = g1.begin(); i != g1.end(); i++) ```
58,479,855
``` dfs=[] for i in range(387): print(i) dfs.append(pd.DataFrame(0, index=range(121211), columns=range(31))) pd.concat(dfs,axis=1) #can only change this ``` In the code above, `pd.concat` is pretty slow, is there a way to make column join faster? assume I can only change the `pd.concat` part.
2019/10/21
[ "https://Stackoverflow.com/questions/58479855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1497720/" ]
You are instantiating a very large dataframe all containing zero values. Rather than concatenate, just use the dataframe constructor with your desired index and columns. ``` dfs = pd.DataFrame( 0, index=range(121211), columns=list(range(31)) * 387 ) ``` For example (using a much smaller size dataframe): ``` >>> pd.DataFrame(0, index=range(3), columns=list(range(2)) * 3) 0 1 0 1 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 2 0 0 0 0 0 0 ``` **EDIT** Assuming that each dataframe has the same index, different columns and different values, try concatenating the numpy values directly (avoiding the overhead of index and column checking for `concat`). ``` pd.DataFrame( np.concatenate([df.values for df in dfs], axis=1), index=dfs[0].index, columns=[col for df in dfs for col in df] ) ``` After checking the timings of this approach vs. concat, they are very similar when using random data. For dataframes this large, you may want to consider alternative solutions such as [Dask](https://dask.org/).
42,430,928
I did a lot of research before I post this question, but still cant figure out why I can't print a simple php value. My issue is that I'm trying to assign a value to an id, basically I want to assign the id that comes back from DataBase to button id. I'm able to print the values of id, name, email, but I can't assign the id as a value. Can anyone tell me what is wrong with this line of code please? ``` $table .= '<td><button id = "<?php echo $row[\'id\']; ?>" onclick = "editUser()">Edit</button></td>'; ``` Here's my PHP code which simply pulls data from database and display them on the page using Ajax. ``` <?php require "conexion.php"; $name =$_GET["nombre"]; if($name === "showPeople"){ $client = mysqli_real_escape_string($con, $name); $result = mysqli_query($con,"SELECT * FROM people"); $table .= '<table>'; while($row = mysqli_fetch_assoc($result)) { $table .= '<tr>'; $table .= '<td>' .$row['id'] . '</td>'; $table .= '<td>' .$row['name'] . '</td>'; $table .= '<td>' .$row['email'] . '</td>'; $table .= '<td><button id = "<?php echo $row[\'id\']; ?>" onclick = "editUser()">Edit</button></td>'; $table .= '</tr>'; } $table .= '</table>'; echo $table; } ?> ```
2017/02/24
[ "https://Stackoverflow.com/questions/42430928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5245070/" ]
You can't put `<?php` and `?>` inside of strings and then print them to execute their contents. Try this instead: ``` $table .= '<td><button id="' .$row['id'] . '" onclick="editUser()">Edit</button></td>'; ```
46,622,473
i use [multer](/questions/tagged/multer "show questions tagged 'multer'") according to it's readme file in github it's readme said call multer in [middleware](/questions/tagged/middleware "show questions tagged 'middleware'") like this: **app.js** ``` var multer = require('multer') app.post('/upload', upload.single('image'), function(req, res){}) ``` but i defined my **function(req, res)** in another file - post.js - and my code in **app.js** looks like this: ``` app.post('/upload', upload.single('image'), post.new) ``` how can i **require** multer only on post.js, almost like this: **post.js** ``` var multer = require('multer') module.exports.new = function(req, res){ //access to req.file } ``` **app.js** ``` app.post('/upload', post.new) ```
2017/10/07
[ "https://Stackoverflow.com/questions/46622473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8455506/" ]
Since rails expects your module naming to follow your file structure, your concern should be named: ``` module Api::Concerns::ErrorSerializer ``` Since you're including it in `Api::TemplatesController`, I would do: ``` class Api::TemplatesController < ApiController include Api::Concerns::ErrorSerializer ... end ``` To help rails out with the constant lookup.
23,726,044
After being a MATLAB user for many years, I am now migrating to python. I try to find a concise manner to simply rewrite the following MATLAB code in python: ``` s = sum(Mtx); newMtx = Mtx(:, s>0); ``` where Mtx is a 2D sparse matrix My python solution is: ``` s = Mtx.sum(0) newMtx = Mtx[:, np.where((s>0).flat)[0]] # taking the columns with nonzero indices ``` where Mtx is a 2D CSC sparse matrix The python code is not as readable / elegant as in matlab.. any idea how to write it more elegantly? Thanks!
2014/05/18
[ "https://Stackoverflow.com/questions/23726044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2476373/" ]
There are no strong typedefs in C++11. There is support for units with `<chrono>` but that is a totally different thing. Nobody can agree on what behaviour strong typedefs should have, exactly, so there has never been a proposal for them that got anywhere, so not only are they in neither C++11 nor C++14, there is no realistic prospect at this time that they will get into any future Standard.
12,243,560
I have tried the below program. It is working in eclipse -> if u give lattitude and longitude value through ddms means it displayed in emulator as current position.... but its not detecting current position in android phone. ``` private class mylocationlistener implements LocationListener { public void onLocationChanged(Location location) { Date today = new Date(); Timestamp currentTimeStamp = new Timestamp(today.getTime()); LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); LocationListener ll = new mylocationlistener(); boolean isGPS = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); if (isGPS){ lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll); if (location != null) { Log.d("LOCATION CHANGED", location.getLatitude() + ""); Log.d("LOCATION CHANGED", location.getLongitude() + ""); String str = "\n CurrentLocation: "+ "\n Latitude: "+ location.getLatitude() + "\n Longitude: " + location.getLongitude() + "\n Accuracy: " + location.getAccuracy() + "\n CurrentTimeStamp "+ currentTimeStamp; Toast.makeText(MainActivity.this,str,Toast.LENGTH_SHORT).show(); tv.append(str); } else { String s1="GPS activation in process"; Toast.makeText(MainActivity.this,s1,Toast.LENGTH_SHORT).show(); /*alert.setTitle("gps"); alert.setMessage("GPS activation in progress,\n Please click after few second."); alert.setPositiveButton("OK", null); alert.show();*/ } } else { String s2="Enable Gps"; Toast.makeText(MainActivity.this,s2,Toast.LENGTH_SHORT).show(); } } public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } ``` }
2012/09/03
[ "https://Stackoverflow.com/questions/12243560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1642978/" ]
I made one service for that. It is easy for get Longitude / Latitude using it. Copy/paste this class in your project. ``` package com.sample; import com.sample.globalconstant; import android.app.Service; import android.content.Context; import android.content.Intent; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.widget.Toast; public class MyServiceGPS extends Service { private static final String TAG = "BOOMBOOMTESTGPS"; private LocationManager mLocationManager = null; private static final int LOCATION_INTERVAL = 1000; private static final float LOCATION_DISTANCE = 10f; private class LocationListener implements android.location.LocationListener{ Location mLastLocation; public LocationListener(String provider) { Log.e(TAG, "LocationListener " + provider); mLastLocation = new Location(provider); } public void onLocationChanged(Location location) { Log.e(TAG, "onLocationChanged: " + location.getLatitude() +"....."+ location.getLongitude()); globalconstant.lat = location.getLatitude(); globalconstant.lon = location.getLongitude(); Toast.makeText(getApplicationContext(), location.getLatitude() +"....."+ location.getLongitude(), 1000).show(); mLastLocation.set(location); } public void onProviderDisabled(String provider) { Log.e(TAG, "onProviderDisabled: " + provider); } public void onProviderEnabled(String provider) { Log.e(TAG, "onProviderEnabled: " + provider); } public void onStatusChanged(String provider, int status, Bundle extras) { Log.e(TAG, "onStatusChanged: " + provider); } } LocationListener[] mLocationListeners = new LocationListener[] { new LocationListener(LocationManager.GPS_PROVIDER), new LocationListener(LocationManager.NETWORK_PROVIDER) }; @Override public IBinder onBind(Intent arg0) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.e(TAG, "onStartCommand"); super.onStartCommand(intent, flags, startId); return START_STICKY; } @Override public void onCreate() { Log.e(TAG, "onCreate"); initializeLocationManager(); try { mLocationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, mLocationListeners[1]); } catch (java.lang.SecurityException ex) { Log.i(TAG, "fail to request location update, ignore", ex); } catch (IllegalArgumentException ex) { Log.d(TAG, "network provider does not exist, " + ex.getMessage()); } try { mLocationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, mLocationListeners[0]); } catch (java.lang.SecurityException ex) { Log.i(TAG, "fail to request location update, ignore", ex); } catch (IllegalArgumentException ex) { Log.d(TAG, "gps provider does not exist " + ex.getMessage()); } } @Override public void onDestroy() { Log.e(TAG, "onDestroy"); super.onDestroy(); if (mLocationManager != null) { for (int i = 0; i < mLocationListeners.length; i++) { try { mLocationManager.removeUpdates(mLocationListeners[i]); } catch (Exception ex) { Log.i(TAG, "fail to remove location listners, ignore", ex); } } } } private void initializeLocationManager() { Log.e(TAG, "initializeLocationManager"); if (mLocationManager == null) { mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE); } } } ``` Copy this code in your Activity when you want to start: ``` startService(new Intent(this,MyServiceGPS.class)); ``` Create one class globalconstant: ``` public class globalconstant { public static double lat, lon; } ``` when you want to current latitude and longitude in your project only write this `globalconstant.lat ,globalconstant.lon` Add `uses-permission in Manifest`
588,732
I am using OSX 10.7.5 and my OSX is becoming a bit unresponsive, comparing to what it was like before. Sometimes just opening new window of browser or terminal takes few seconds or the Dock hovering effect is not fluent. At these moments I watch system resources and I still have 3G of memory free and the processor is not used at all. Can it be caused by hard drive or other IO? How can I found out which application is causing this?
2013/04/28
[ "https://superuser.com/questions/588732", "https://superuser.com", "https://superuser.com/users/128678/" ]
Use `top` to monitor system resources. As you mention issues with opening the browser possibly there is malware active or some other agent which is causing unwarranted network activity. To monitor this use-: ``` ifconfig -a # for the network interface name to monitor ``` then ``` tcpdump -i <interface> ``` An alternative for network monitoring is `nettop` - a command line tool which I believe is available from Lion version. It's available from Apple store.
6,989,102
I am running a parfor loop in Matlab that takes a lot of time and I would like to know how many iterations are left. How can I get that info?
2011/08/08
[ "https://Stackoverflow.com/questions/6989102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27943/" ]
I don't believe you *can* get that information directly from MATLAB, short of printing something with each iteration and counting these lines by hand. To see why, recall that each `parfor` iteration executes in its own workspace: while incrementing a counter within the loop is legal, accessing its "current" value is not (because this value does not really exist until completion of the loop). Furthermore, the `parfor` construct does not guarantee any particular execution order, so printing the iterator value isn't helpful. ``` cnt = 0; parfor i=1:n cnt = cnt + 1; % legal disp(cnt); % illegal disp(i); % legal ofc. but out of order end ``` Maybe someone does have a clever workaround, but I think that the independent nature of the `parfor` iterations belies taking a reliable count. The restrictions mentioned above, plus those on using `evalin`, etc. support this conclusion. As @Jonas suggested, you could obtain the iteration count via side effects occurring outside of MATLAB, e.g. creating empty files in a certain directory and counting them. This you can do in MATLAB of course: ``` fid = fopen(['countingDir/f' num2str(i)],'w'); fclose(fid); length(dir('countingDir')); ```
54,112,731
I very new to programming and I can't find the solution of my issue, can you give me the solution please? I have this JSON file: ``` { "groups": "[{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }]" } ``` And I need something like this in my js (but i want import my JSON to get array like this) : ``` const groups = [{ id: 1, title: 'group 1' }, { id: 2, title: 'group 2' }] ``` I don't know how to do without using jQuery. I already tried with this: ``` const json = require('./test.json'); ``` This code returns an object: ![screen of what is returned](https://i.stack.imgur.com/ZBgT3.png) It's almost what I want but it didn't work when I use it in my code because I don't want an object but and array like I said above. How can achieve this?
2019/01/09
[ "https://Stackoverflow.com/questions/54112731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10890347/" ]
The value of `groups` is not valid JSON: string values should be surrounded by double-quote marks, and so should keys. The file with valid JSON in that string would look like this: ``` { "groups": "[{ \"id\": 1, \"title\": \"group 1\" }, { \"id\": 2, \"title\": \"group 2\" }]" } ``` Of course if you have control over the creation of this file, it would be better to have this value as part of the native JSON content, rather than JSON-in-a-string-inside-JSON. If that's not possible, you will need to correct the quoting in the string yourself, which can be done with a couple of Regular Expression replacements. ``` /* obj is the object in the JSON file */ var json_str = obj.groups.replace(/'/g,"\"").replace(/([a-z]+)\:/g,"\"$1\":"); var groups = JSON.parse(json_str); ``` Alternatively, although the string is not valid JSON it is a valid Javascript expression, so **if the contents of the file are trustworthy,** you can also do it with `eval:` ``` var groups = eval(obj.groups); ```