qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
21,161,430
Is any convinient way to dynamically render some page inside application and then retrieve its contents as `InputStream` or `String`? For example, the simplest way is: ``` // generate url Link link = linkSource.createPageRenderLink("SomePageLink"); String urlAsString = link.toAbsoluteURI() + "/customParam/" + customParamValue; // get info stream from url HttpGet httpGet = new HttpGet(urlAsString); httpGet.addHeader("cookie", request.getHeader("cookie")); HttpResponse response = new DefaultHttpClient().execute(httpGet); InputStream is = response.getEntity().getContent(); ... ``` But it seems it must be some more easy method how to archive the same result. Any ideas?
2014/01/16
[ "https://Stackoverflow.com/questions/21161430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1479414/" ]
From your implementation it seems that you are using naive A\* algorithm. Use following way:- > > 1. A\* is algorithm which is implemented using priority queue similar to BFS. > 2. Heuristic function is evaluated at each node to define its fitness to be selected as next node to be visited. > 3. As new node is visited its neighboring unvisited nodes are added into queue with its heuristic values as keys. > 4. Do this till every heuristic value in the queue is less than(or greater) calculated value of goal state. > > >
1. Find bottlenecks of your implementation using profiler . [ex. jprofiler is easy to use](http://java.dzone.com/articles/jprofiler-your-java-code-could) 2. Use threads in areas where algorithm can run simultaneously. 3. Profile your JavaVM to run faster. [Allocate more RAM](http://www.wikihow.com/Allocate-More-RAM-to-Minecraft)
21,161,430
Is any convinient way to dynamically render some page inside application and then retrieve its contents as `InputStream` or `String`? For example, the simplest way is: ``` // generate url Link link = linkSource.createPageRenderLink("SomePageLink"); String urlAsString = link.toAbsoluteURI() + "/customParam/" + customParamValue; // get info stream from url HttpGet httpGet = new HttpGet(urlAsString); httpGet.addHeader("cookie", request.getHeader("cookie")); HttpResponse response = new DefaultHttpClient().execute(httpGet); InputStream is = response.getEntity().getContent(); ... ``` But it seems it must be some more easy method how to archive the same result. Any ideas?
2014/01/16
[ "https://Stackoverflow.com/questions/21161430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1479414/" ]
A linked list is not a good data structure for the open set. You have to find the node with the smallest F from it, you can either search through the list in O(n) or insert in sorted position in O(n), either way it's O(n). With a heap it's only O(log n). Updating the G score would remain O(n) (since you have to find the node first), unless you also added a HashTable from nodes to indexes in the heap. A linked list is also not a good data structure for the closed set, where you need fast "Contains", which is O(n) in a linked list. You should use a HashSet for that.
From your implementation it seems that you are using naive A\* algorithm. Use following way:- > > 1. A\* is algorithm which is implemented using priority queue similar to BFS. > 2. Heuristic function is evaluated at each node to define its fitness to be selected as next node to be visited. > 3. As new node is visited its neighboring unvisited nodes are added into queue with its heuristic values as keys. > 4. Do this till every heuristic value in the queue is less than(or greater) calculated value of goal state. > > >
7,242,568
How can I chceck on iPhone with regularexpressions NSStrring contain only this chars: `a-zA-Z` numbers `0-9` or specialchars: `!@#$%^&*()_+-={}[]:"|;'\<>?,./`
2011/08/30
[ "https://Stackoverflow.com/questions/7242568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/919602/" ]
``` NSCharacterSet *charactersToRemove = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 "] invertedSet]; NSString *stringValueOfTextField = [[searchBar.text componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@""]; ``` try this::::
For this purposes you can use standard class [NSRegularExpression](http://developer.apple.com/library/mac/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html)
7,242,568
How can I chceck on iPhone with regularexpressions NSStrring contain only this chars: `a-zA-Z` numbers `0-9` or specialchars: `!@#$%^&*()_+-={}[]:"|;'\<>?,./`
2011/08/30
[ "https://Stackoverflow.com/questions/7242568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/919602/" ]
``` NSCharacterSet *charactersToRemove = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 "] invertedSet]; NSString *stringValueOfTextField = [[searchBar.text componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@""]; ``` try this::::
``` NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\w[!@#$%^&*()_+-={}\[\]:\"|;'\<>?,./]" options:NSRegularExpressionCaseInsensitive error:&error]; NSUInteger numberOfMatches = [regex numberOfMatchesInString:string options:0 range:NSMakeRange(0, [string length])]; ``` Note that `NSRegularExpression` is only available on iOS 4 and above.
41,503,110
What I need is to enable android location service and to set the current location as a destination, then when I close the application and going to another location and coming back to the original location (or when I will be close to the original location) I want the location service to identify that I am now in the original location and to turn on the application again (and to perform something). How I can Do this on Android studio?
2017/01/06
[ "https://Stackoverflow.com/questions/41503110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7383294/" ]
You need to add encoding. Try this, ``` src = $('#googlemap').attr('src'); src = encodeURI(src); $('#googlemap').attr('src', src); ```
``` str.replace(/[ø]/g,'%C3%B8'); ``` use regular expression to solve it. The above code will replace the special character.
41,503,110
What I need is to enable android location service and to set the current location as a destination, then when I close the application and going to another location and coming back to the original location (or when I will be close to the original location) I want the location service to identify that I am now in the original location and to turn on the application again (and to perform something). How I can Do this on Android studio?
2017/01/06
[ "https://Stackoverflow.com/questions/41503110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7383294/" ]
You need to add encoding. Try this, ``` src = $('#googlemap').attr('src'); src = encodeURI(src); $('#googlemap').attr('src', src); ```
It does actually. The `replace` function return a new string. Store new string into variable and change the src back. ``` var src; var newStr; src = $('#googlemap').attr('src'); newStr = src.replace('ø', '%C3%B8'); console.log(src); console.log(newStr); $('#googlemap').attr('src', newStr); ```
12,791,129
I call an activity called Activity1 from an Activity called MainActivity using the following: ``` Intent intent = new Intent(Intent.ACTION_VIEW, uri); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); ``` So, when the control comes to Activity1. The normal activity lifecycle is started. i.e onCreate() is called and so on. when i click the back button when the control is in Activity1. The finish method is called, which in turn calls the onDestroy() and now the control is back with the MainActivity screen. ``` @Override public void onBackPressed() { Log.d(TAG, "onBackPressed()"); finish(); } ``` The next time i call Activity1. The onCreate is called again as i called the onDestroy (when i pressed the back button) from the previous call. Question: 1. is there a way to pass control back to the MainActivity when the back button is pressed without having to call the "finish()" method? 2. problem with calling finish, every time i call Activity1 from MainActivity, A new instance of Activity1 is created. that is the lifecycle again starts from onCreate().. i do not want this to happen as this is has become a major performance issue. The main point i'm looking for is whether i can start the activity1 from the resume state rather than oncreate, when i call it after the first time.
2012/10/09
[ "https://Stackoverflow.com/questions/12791129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/992706/" ]
I don't believe you need to call the "finish()" method on onBackPressed. Android does that for you when you press the back button. The onBackPressed is used to last minuet tidy up (save stuff to sharepreferences, etc). Android default behaviour is to call onCreate whenever a new activity is place on the screen. You cannot call a new Intent without this to happen. I'm not sure why this is performance issue for you. Can you go in a little more detail what activity1 is doing? Are you doing heavy network communication? Is it possible you can cache the store results?
in Actitity1 you define your WebView as: ``` private static WebView webView = null; ``` in `onCreate()` you only create it if it's null: ``` if(webView == null){ //create webview and load from network } ``` Use this approach wisely as it may easly lead to memory leaks if you point to objects in other activities, or objects that may be kept alive (runnables, messages, etc.)
26,361,849
I've designed a program that can encrypt 26 English letters. Here's how I'm handling the input. I'm reading it from a text file and stores it in a string. ``` ifstream L; string str1; char ch; L.open("ToBeCoded.txt"); while(iL.get(ch)) str1.push_back(ch); ``` However, it's inefficient, if I want to read a different file, I have to change the name in codes to make it work. So is there any dynamic way to do so? Like drag the file or type the address of the file during run time? By the way, do you have a better way to read txt to string? This one 'seems' slow.
2014/10/14
[ "https://Stackoverflow.com/questions/26361849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3839908/" ]
you can use istream getline instead <http://www.cplusplus.com/reference/istream/istream/getline/>
If you are on Windows you can use DragAcceptFiles and WM\_DROPFILES messages. More details here: <http://msdn.microsoft.com/en-us/library/bb776406(VS.85).aspx> <http://msdn.microsoft.com/en-us/library/bb774303(VS.85).aspx>
26,361,849
I've designed a program that can encrypt 26 English letters. Here's how I'm handling the input. I'm reading it from a text file and stores it in a string. ``` ifstream L; string str1; char ch; L.open("ToBeCoded.txt"); while(iL.get(ch)) str1.push_back(ch); ``` However, it's inefficient, if I want to read a different file, I have to change the name in codes to make it work. So is there any dynamic way to do so? Like drag the file or type the address of the file during run time? By the way, do you have a better way to read txt to string? This one 'seems' slow.
2014/10/14
[ "https://Stackoverflow.com/questions/26361849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3839908/" ]
I would suggest you use the `getline` for this kind of problem. <http://www.cplusplus.com/reference/string/string/getline/?kw=getline> getline is an ifstream function that will get the string user efficiently. If you wanted to get the whole string file, just go to the link that Neil Kirk posted: [Read whole ASCII file into C++ std::string](https://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring) it explains exactly how to do that.
If you are on Windows you can use DragAcceptFiles and WM\_DROPFILES messages. More details here: <http://msdn.microsoft.com/en-us/library/bb776406(VS.85).aspx> <http://msdn.microsoft.com/en-us/library/bb774303(VS.85).aspx>
1,043,246
does nhibernate parse xml files everytime someone makes a request or just once when the application starts ? well here is what i m doing : ``` public class SessionManager { private readonly ISessionFactory _sessionFactory; public SessionManager() { _sessionFactory = GetSessionFactory(); } public ISession GetSession() { return _sessionFactory.OpenSession(); } private static ISessionFactory GetSessionFactory() { return Fluently.Configure() .Database(MsSqlConfiguration.MsSql2005 .ConnectionString(c => c.Is( @"Data Source=Pc-De-Yassir;Initial Catalog=MyDatabase;User Id=sa;Password=password;Integrated Security=True") )) .Mappings(m => m.AutoMappings.Add ( AutoPersistenceModel.MapEntitiesFromAssemblyOf<Model.Category>() )) .BuildSessionFactory(); } } ``` and here is how i get data from the database ``` public IList<Category> GetCategories() { var session = new SessionManager().GetSession(); return session.CreateCriteria(typeof(Category)) .List<Category>();} ``` So my question is will nhibernate configure itself the first time this method run or each time a request is made ?
2009/06/25
[ "https://Stackoverflow.com/questions/1043246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72443/" ]
Once each time you instantiate an ISessionFactory off the top of my head...
It does it only once. If you would like to improve the performance of the application, use ngen.exe tool. nHibernate is usually slow for the first time, because of the amount of code that need to be compiled when the application starts for the first time. I had similiar probles with performance at application startup, and ngen.exe solved my problems.
94,809
I have one requirement to update the customer first name and last name in address information section. I tried through csv file import/export method but it only update in account information section not in address information such as billing and shipping address in admin panel(customer->manage customer section). Currently few records in customer information section are present with lastname combine in firstname section (e.g firstname:- testtest1 and lastname:- blank instead of firstname:-test and lastname: test1) and I want to split the firstname and lastname separately in address information section too. So how should I proceed to solve this query to my bulk of customer.
2015/12/23
[ "https://magento.stackexchange.com/questions/94809", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/28881/" ]
Go admin side `System -> Import/Export -> Export` and Export all customer with all data After your exported csv file updates bellow header fields data ``` _address_firstname _address_lastname ``` Go admin side `System -> Import/Export -> Import` and upload your updated csv file **Make bellow settings :** 1. Entity Type \* : Customer 2. Import Behavior \*: Replace Existing Complex Data 3. Select File to Import \*: upload updated file After click `Check Data` button if no error then click `import` button **Note :** first backup your database
**Select File to Import \*: upload updated file.** Its not uploading only processing.
66,760,581
Have to show one textbox only at a time, if click on toggle need to hide first textbox and need to show second textbox. If I click again need to show first textbox and hide second textbox. Tried below, but unable to display one textbox onload itself... HTML: ``` <div><input *ngIf="text1" id="test1" type="text" placeholder="Textbox1" /> </div> <div> <input *ngIf="text2" id="test2" type="text" placeholder="Textbox2" /> </div> <button (click)="toggle()">Toggle</button> ``` .ts ``` toggle() { this.text1 = !this.text1; if (this.text1) { this.text2 = false; this.text1 = true; } else { this.text2 = true; this.text1 = false; } } ``` [Demo](https://stackblitz.com/edit/hide-and-show-textboxes?file=src%2Fapp%2Ftypeahead-template.ts)
2021/03/23
[ "https://Stackoverflow.com/questions/66760581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1989472/" ]
You can use 1booleanItem ```typescript toggle() { this.text1 = !this.text1; } ``` ```html <div><input *ngIf="text1" id="test1" type="text" placeholder="Textbox1" /> </div> <div> <input *ngIf="!text1" id="test2" type="text" placeholder="Textbox2" /> </div> <button (click)="toggle()">Toggle</button> ``` [Demo](https://stackblitz.com/edit/hide-and-show-textboxes-dzomii?file=src%2Fapp%2Ftypeahead-template.html)
> > Tried below, but unable to display one textbox onload itself > > > you can set the boolean of one of the text boxes to true: ``` public text1: boolean = true; ``` Using a single variable to track the visibility: ``` export class NgbdTypeaheadTemplate { public showText1: boolean = true; toggle() { this.showText1 = !this.showText1; } } ``` and ``` <div><input *ngIf="showText1" id="test1" type="text" placeholder="Textbox1" /> </div> <div> <input *ngIf="!showText1" id="test2" type="text" placeholder="Textbox2" /> </div> ```
29,847
An often repeated phrase I hear is that "The enemies of the Christian are world, the flesh, and the devil." But I wonder, does God's word reveal to us that there are more enemies than those 3 that we should be wary of? The phrase above is not a phrase in the bible but it's no doubt passed around because it's easy to remember and poignantly true. I just wonder if there's explicitly more than that. Below are some verses identifying the hurdles of the world, the flesh, and the devil--but I wonder if there is anything *else* that we must fight against. World: > > * **James 4:4 NIV** You adulterous people, don’t you know that friendship with the **world** means enmity against God? Therefore, anyone who chooses to be a friend of the world becomes an enemy of God. > * **Romans 12:2 NIV** Do not conform to the pattern of this **world**, but be transformed by the renewing of your mind. Then you will be able to test and approve what God’s will is—his good, pleasing and perfect will. > > > Flesh: > > * **Galatians 5:13 NIV** You, my brothers and sisters, were called to be free. But do not use your freedom to indulge the **flesh**; rather, serve one another humbly in love. > * **Galatians 6:7-8 NIV** Do not be deceived: God cannot be mocked. A man reaps what he sows. Whoever sows to please their **flesh**, from the flesh will reap destruction; whoever sows to please the Spirit, from the Spirit will reap eternal life. > * **Romans 7:25 ESV** Thanks be to God through Jesus Christ our Lord! So then, I myself serve the law of God with my mind, but with my **flesh** I serve the law of sin. > > > Devil: > > * **1 Peter 5:8 NIV** Be alert and of sober mind. Your enemy the **devil** prowls around like a roaring lion looking for someone to devour. > * **Ephesians 6:11 ESV** Put on the whole armor of God, that you may be able to stand against the schemes of the **devil**. > > >
2014/06/10
[ "https://christianity.stackexchange.com/questions/29847", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/11471/" ]
The phrase in question comes from the [Book of Common Prayer](http://en.wikipedia.org/wiki/Book_of_Common_Prayer), from [the Litany](http://justus.anglican.org/resources/bcp/1928/Litany.htm). > > FROM all evil and mischief; from sin; from the crafts and assaults of the devil; from thy wrath, and from everlasting damnation, Good Lord, deliver us. > > > From all blindness of heart; from pride, vainglory, and hypocrisy; from envy, hatred, and malice, and all uncharitableness, Good Lord, deliver us. > > > **From all inordinate and sinful affections; and from all the deceits of the world, the flesh, and the devil, Good Lord, deliver us.** > > > From lightning and tempest; from earthquake, fire, and flood; from plague, pestilence, and famine; from battle and murder, and from sudden death, Good Lord, deliver us. > > > The first edition of the Book of Common Prayer was published in 1549, and being the first church service in English, it had a profound impact on English religious phraseology. Its also where "till death do us part" comes from. It might be an interesting exercise, I suppose, to go through the list of things there and cross-reference with a Bible concordance.
The apostle John uses the word *world* (Greek transliteration, *cosmos*) 26 times in 1 John, 2 John, and Revelation (NIV). Here's how he unpacks the word in 1 John 2:16,17: > > "For all that is in the world, the lust of the flesh and the lust of the eyes and the boastful pride of life, is not from the Father, but is from the world. The world is passing away, and also its lusts; but the one who does the will of God lives forever." > > > Since your triumvirate includes the *world*, the *flesh*, and the *devil*, there is some obvious overlap with John's unpacking of the word *cosmos*. It seems to me that your word *flesh* subsumes the two lusts mentioned by John (viz., the lusts of the flesh and eyes). The word *flesh* (Greek transliteration *sarx*) in the NT denotes what I call the **anti-God principle (or tendency)** which resides in the hearts of all of us. Since the fall of the human race, which occurred when our first parents sinned by disobeying God, every child of Adam's seed has this bent toward sin. Parents need not teach their children how to sin; it comes natural to them. Our physical appetites (e.g., hunger, thirst, sleep, and sensual-and sexual pleasure), though God-given and God sanctioned, constitute one instrument of the flesh, but only when we attempt to satisfy those appetites in ways which God forbids. Whatever God forbids, He does so for good reason. Simply put, God says "Thou shalt not" because He loves us, He wants what is best for us, and He wants to protect us from unpleasant and often unanticipated consequences. In that way, God is very much like a good parent. It is no accident, of course, that one of the many names of God is *Father*. Elsewhere in his first letter, John tells us, > > "We know that we are of God, and that the whole world lies in the power of the evil one" (1 John 5:19 NAS). > > > In this verse we learn that the devil (i.e., satan, the evil one, Beelzebub--see 2 Kings 1:2-3, 6, 16) exercises his power in and through the world and its system. The world in that sense denotes the fiendishly organized effort of satan and his minions (also known as "rulers, powers, world forces of darkness, and spiritual forces of wickedness in the heavenlies," 6:12) to "kill, steal, and destroy" (John 10:10) two things in particular: > > * everything God declared to be "good" from the very beginning, particularly man and woman whom He created in His own image > * the plans and purposes of God, particularly as they relate to the unfolding drama of salvation which will ultimately triumph over satan, when > > > "'The kingdom of the world has become the kingdom of our Lord and of His Christ; and He will reign forever and ever" (Revelation 11:15 NAS). > > > Until that glorious day, Christians must confront the same enemies our first parents, particularly Eve, confronted: > > * The lust of the flesh: "the woman saw that the tree was good for food" (Genesis 3:6) > * The lust of the eyes: "the woman saw that the tree was . . . a delight to the eyes" (ibid.) > * The pride of life: "the woman saw that the tree . . . was desirable to make one wise, [so] she took from its fruit and ate; and she gave also to her husband with her, and he ate" (ibid.). > > > Jesus came to this sin-cursed world, John tells us, to defeat Satan once and for all. > > "for the devil has sinned from the beginning. The Son of God appeared for this purpose, to destroy the works of the devil" (1 John 3:8 NAS). > > > Our Lord's death on the cross dealt Satan a death blow, as it were (see Genesis 3:15), and Paul tells us that in the wake of Christ's victorious cross death, our Lord bound Satan and paraded him throughout the universe, giving him a taste of the shame, punishment, and torment that will be his to bear when one day he will be cast into the lake of fire forever and ever (Revelation 20:10): > > "Therefore it says, "WHEN HE ASCENDED ON HIGH, HE LED CAPTIVE A HOST OF CAPTIVES, AND HE GAVE GIFTS TO MEN." (Now this expression, "He ascended," what does it mean except that He also had descended into the lower parts of the earth? He who descended is Himself also He who ascended far above all the heavens, so that He might fill all things)" (Ephesians 4:8 NAS). > > > In conclusion, the Christian's enemies are certainly the world, the flesh, and the devil, though as I've pointed out above, we can, without doing violence to the text of Scripture, expand them to include the notion of lust, which goes hand in hand with the flesh. Are there other enemies of which Christians should be aware? Yes, and I think that Paul's description of the armor of God in Ephesians, chapter 6, would have to include doubt, discouragement, and defeat, particularly when we fail to put on "the full armor of God" (6:11).
51,554
I use a site on a regular basis so I wanted to make sure it was secure. One of the things I checked was that when I changed my first name to `<img src="http://blah.blah/blah/blah.notanextension" onerror=alert(document.cookie);>Henry` that it didn't give me the alert with all of my cookies (I had already determined that they stripped `<script>` tags). Well it did, however, after going to the home page and then re-visiting my profile, the XSS had been removed from my name. I verified that the filter that did this is applied recursively and works pretty well as far as I could tell. The site uses CSRF tokens, so someone could not insert XSS via CSRF. Is this a security problem even though the input is sanitized whenever I re-visit the page?
2014/02/14
[ "https://security.stackexchange.com/questions/51554", "https://security.stackexchange.com", "https://security.stackexchange.com/users/36184/" ]
Yes it could be a problem. It depends on the point that the first name field is sanitized. My first impressions that it was a DOM update that caused the alert to be shown (see [DOM based XSS](https://www.owasp.org/index.php/DOM_Based_XSS)). However, as you said you could refresh the page this is unlikely unless a hash is added to the address bar (e.g. `www.example.com/page.aspx#name=foo`). Maybe a script runs to sanitize the value when the home page is displayed (which would be odd). There is also the possibility that certain values can bypass the sanitization and exploit the vulnerability. Either of these things mean that the XSS payload may be executed when an admin user views the list of users. There is also the possibility that [Broken Access Controls](https://www.owasp.org/index.php/Broken_Access_Control) could allow another user to update the first name of another user to exploit this XSS flaw when they log in. It all depends on when the sanitisation executes, so more investigation would be needed on the site to determine this.
So from what you're saying it sounds like the update isn't persisted to the database, it shows on the page when you save it, but not if you navigate away and then back. If that's the case then this is likely to be a limited risk (not to say I wouldn't recommend fixing it though), as it would be hard to construct a valid attack scenario where this could have an impact. In order for an attacker to exploit it, it sounds like they'd need access to your session to enter the data, at which point stealing your session token is a bit pointless. As it doesn't persist then there's no risk of another user viewing your name and executing the JavaScript. If the data you've entered shows up elsewhere in the application (for example in an administration page), then obviously then it would be a nasty 2nd order XSS which could have quite a large impact.
53,084,564
I am trying to find the maximum value in two array of zeros which I have populated using a loop as follows: ``` dydx = zeros(n+1) error = zeros(n+1) for i in range(n): dydx[i]=(y[i+1]-y[i])/h error[i]= cos(i)-dydx[i] ``` If I try to find `i = np.argmax(dydx)` I get a non callable error?
2018/10/31
[ "https://Stackoverflow.com/questions/53084564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10031292/" ]
Try using `np.max(dxdy)`. It should give you the max value.
Are you trying to solve a Euler's value. I.e. something like this? ``` import numpy as np x0=0 y0=1 xf=10 n=101 deltax=(xf-x0)/(n-1) x=np.linspace(x0,xf,n) y = np.zeros( [n] ) y[0]=y0 for i in range(1,n): y[i] = deltax*(-y[i-1] + np.sin(x[i-1]))+y[i-1] #for i in range ( n ) : # print ( x[i] , y[i] ) print(max(y)) ``` [REF](https://faculty.washington.edu/heathml/2018spring307/euler_method.pdf)
53,084,564
I am trying to find the maximum value in two array of zeros which I have populated using a loop as follows: ``` dydx = zeros(n+1) error = zeros(n+1) for i in range(n): dydx[i]=(y[i+1]-y[i])/h error[i]= cos(i)-dydx[i] ``` If I try to find `i = np.argmax(dydx)` I get a non callable error?
2018/10/31
[ "https://Stackoverflow.com/questions/53084564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10031292/" ]
Try using `np.max(dxdy)`. It should give you the max value.
Is the above your full code, and are you using `zeros()` as a function or a list, `zeros=[]`? If it is a list, it cannot be called. When I tried the following, no error is returned: ``` def zeros(): n=0 dydx = zeros(n+1) error = zeros(n+1) for i in range(n): dydx[i]=(y[i+1]-y[i])/h error[i]= cos(i)-dydx[i] print (i = np.argmax(dydx)) ```
40,008,286
I want to bring up an EC2 instance at a particular time, run a java batch job and shut the instance down once done, using Java. I figured out how to bring up the instance and run my job. Need to know how can i shut it down once the job is done. Found out that it is possible by changing the "setDesiredCapacity" of the auto scaling group value to 0. this method takes the auto scaling group name as input. But since the ASG name is dynamically created, not sure how can i get it to my Java job. Any suggestions?
2016/10/12
[ "https://Stackoverflow.com/questions/40008286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5118784/" ]
It appears that your requirements are: * On a regular schedule, start an Amazon EC2 instance that will run a batch job * At the conclusion of the job, terminate the EC2 instance Instead of using Auto Scaling (which is designed to dynamically scale capacity based upon demand), I would recommend: * **Use a schedule to launch a new EC2 instance**. The schedule could be a `cron` job on a machine somewhere (on EC2 or anywhere on the Internet), or you could use [Amazon CloudWatch Events](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/WhatIsCloudWatchEvents.html) to run a Lambda function, which launches the instance. * When the batch job is complete, **terminate the instance**, which can be done via a couple of methods: + Send a command to the operating system to **shutdown**. If the EC2 instance is launched with a **shutdown behavior** of `terminate`, then the instance will automatically be terminated. See: [Changing the Instance Initiated Shutdown Behavior](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#Using_ChangingInstanceInitiatedShutdownBehavior) + Alternatively, have your application make a [`TerminateInstances`](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/ec2/model/TerminateInstancesRequest.html) API call to AWS to directly terminate the instance. Or, you could be nice and modern and **not use an Amazon EC2 instance!** Since your batch job is in Java, **you could use a [Lambda function](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)** together with a CloudWatch Events schedule. The schedule would trigger the Lambda function, which could run your Java code. When it is finished, Lambda will automatically terminate. You are only billed per 100ms of usage. Please note that Lambda functions can execute for a maximum of **5 minutes**, so if your operation takes longer than this, Lambda is not a suitable solution.
You can use the following- * Cloudwatch Event Rule as Scheduler. Target would be Lambda in point 2. * Lambda to change the desired capacity of auto scaling group by calling "setDesiredCapacity" of the auto scaling group. * In order to shut down the instances after the batch job is complete, please use the AWS Java SDK in the EC2 instance to change the "setDesiredCapacity" to zero again. Points to be noted * Your minimum capacity should be zero for instances to be terminated. * Cloudwatch Event Rule Cron Expression should take the time taken by EC2 to spin up into consideration. * If you don't want your requests to over public internet, use vpc endpoints to configure traffic internally within your VPC.
94,648
The below Python 3 program scans 4 files `a.txt`, `b.txt`, `c.txt`, `d.txt` and then outputs the read data into a file `output.txt` in a formatted way. The first line of each file is guaranteed to have a header and the second line of each file will be blank. I'm required to scan those four files. Program: ``` def main(): with open('a.txt', 'r') as file_a, open('b.txt', 'r') as file_b, open('c.txt', 'r') as file_c, open('d.txt', 'r') as file_d: lines1, lines2, lines3, lines4 = file_a.readlines(), file_b.readlines(), file_c.readlines(), file_d.readlines() lines = [lines1, lines2, lines3, lines4] number_of_spaces = 5 assert len(lines1) == len(lines2) == len(lines3) == len(lines4), "Error. Different number of lines found in the files" row, column = 0, 1 with open('output.txt', 'w') as output: while row < len(lines): output.write(lines[row][0].strip() + ' ' * number_of_spaces) row += 1 output.write('\n') row = 0 while column < len(lines1): while row < len(lines): output.write(lines[row][column].strip() + ' ' * (number_of_spaces + len(lines[row][0].strip()) - len(lines[row][column].strip()))) row += 1 output.write('\n') column += 1 row = 0 if __name__ == "__main__": main() ``` When executed gives `output.txt`: ``` Sl.No Elements Abbreviation Mass 1 Hydrogen H 1 2 Helium He 4 3 Lithium Li 7 4 Beryllium Be 9 ... 98 Californium Cf 251 99 Einsteinium Es 252 100 Fermium Fm 257 ``` Is there any room for improvement? --- **Additional information** (if necessary): Note that `...` in the files mean that there are a lot of similar data and not that the file contains those dots. `a.txt`: ``` Sl.No 1 2 3 ... 99 100 ``` `b.txt`: ``` Elements Hydrogen Helium Lithium Beryllium ... Californium Einsteinium Fermium ``` `c.txt`: ``` Abbreviation H He Li Be ... Cf Es Fm ``` `d.txt`: ``` Mass 1 4 7 9 ... 251 252 257 ```
2015/06/25
[ "https://codereview.stackexchange.com/questions/94648", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/70403/" ]
If possible, use the new Java 8 datetime API (and there does not seem to be a constraint to use any older version). It is less cumbersome to do such operations there. You can get the difference in weeks easier and it is probably more readable. With `TemporalAdjusters` you can start from the first day of a month and go the the first monday. ``` LocalDate firstMondayOfMonth = LocalDate.of(2015, 6, 1).with(TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY)); LocalDate lastDayOfMonth = LocalDate.of(2015,6,1).with(TemporalAdjusters.lastDayOfMonth()); LocalDate lastSundayOfMonth = lastDayOfMonth.with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY)); long weeksBetweenDates = ChronoUnit.WEEKS.between(firstMondayOfMonth, lastSundayOfMonth.plusDays(1)); ``` Apart from that, the class `Solution` does not do very much. You could simply use a method where you do your calculation. Your variables are not speaking. Don't use `A`,`B` etc. but `startDate` or something like that EDIT: In Java 8, you can get the first day of the Week with `WeekFields.of(Locale.getDefault()).getFirstDayOfWeek()` also, one method / class should only do one thing. For example, parsing your dates and calculating the difference between two dates are two different things and should be in two methods / classes. see <https://en.wikipedia.org/wiki/Single_responsibility_principle>
The week does not start with a Monday in all regions (e.g. in the U.S., Sunday is the first day of the week). Therefore, instead of `Calendar.MONDAY`, you should use the `Calendar` method `getFirstDayOfWeek()` to determine the first day of the week (and compute the last day of the week from this value).
94,648
The below Python 3 program scans 4 files `a.txt`, `b.txt`, `c.txt`, `d.txt` and then outputs the read data into a file `output.txt` in a formatted way. The first line of each file is guaranteed to have a header and the second line of each file will be blank. I'm required to scan those four files. Program: ``` def main(): with open('a.txt', 'r') as file_a, open('b.txt', 'r') as file_b, open('c.txt', 'r') as file_c, open('d.txt', 'r') as file_d: lines1, lines2, lines3, lines4 = file_a.readlines(), file_b.readlines(), file_c.readlines(), file_d.readlines() lines = [lines1, lines2, lines3, lines4] number_of_spaces = 5 assert len(lines1) == len(lines2) == len(lines3) == len(lines4), "Error. Different number of lines found in the files" row, column = 0, 1 with open('output.txt', 'w') as output: while row < len(lines): output.write(lines[row][0].strip() + ' ' * number_of_spaces) row += 1 output.write('\n') row = 0 while column < len(lines1): while row < len(lines): output.write(lines[row][column].strip() + ' ' * (number_of_spaces + len(lines[row][0].strip()) - len(lines[row][column].strip()))) row += 1 output.write('\n') column += 1 row = 0 if __name__ == "__main__": main() ``` When executed gives `output.txt`: ``` Sl.No Elements Abbreviation Mass 1 Hydrogen H 1 2 Helium He 4 3 Lithium Li 7 4 Beryllium Be 9 ... 98 Californium Cf 251 99 Einsteinium Es 252 100 Fermium Fm 257 ``` Is there any room for improvement? --- **Additional information** (if necessary): Note that `...` in the files mean that there are a lot of similar data and not that the file contains those dots. `a.txt`: ``` Sl.No 1 2 3 ... 99 100 ``` `b.txt`: ``` Elements Hydrogen Helium Lithium Beryllium ... Californium Einsteinium Fermium ``` `c.txt`: ``` Abbreviation H He Li Be ... Cf Es Fm ``` `d.txt`: ``` Mass 1 4 7 9 ... 251 252 257 ```
2015/06/25
[ "https://codereview.stackexchange.com/questions/94648", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/70403/" ]
> > > ``` > public int year; > public String m1; > public String m2; > > > public Solution(int Y, String A, String B) throws ParseException { > this.year = Y; > this.m1 = A; > this.m2 = B; > > ``` > > These fields shouldn't be public. By making them public you've exposed them to the outside world. These are internal details that should be properly encapsulated. Truthfully though, you don't need them at all. I would just work directly with the arguments that you passed in. Rename them though. Your current names don't tell the client what kind of values to expect. What's an "A"? How would another dev know what to pass into this method without looking at the internals? They wouldn't. ``` public Solution(int year, String startMonth, String endMonth) throws ParseException ```
The week does not start with a Monday in all regions (e.g. in the U.S., Sunday is the first day of the week). Therefore, instead of `Calendar.MONDAY`, you should use the `Calendar` method `getFirstDayOfWeek()` to determine the first day of the week (and compute the last day of the week from this value).
1,469,187
I have two computers on the same Wifi router. I want to ping the other one, it does not happen, I get a "destination host unreachable". Things I've already tried: I disabled the Firewall on both computers I tried to ping myself on both computers, I get a reply I capture the traffic in Wireshark, I can capture the ICMP packets that pinging some outside address like 8.8.8.8, when I ping the other computer or myself, Wireshark does not capture this. Any ideas? **EDIT:** Some additional information. ``` Internet Protocol Version 4, Src: 192.168.0.1, Dst: 192.168.0.131 Internet Control Message Protocol Type: 3 (Destination unreachable) Code: 3 (Port unreachable) Checksum: 0x7f07 [correct] [Checksum Status: Good] Unused: 00000000 Internet Protocol Version 4, Src: 192.168.0.131, Dst: 192.168.0.1 0100 .... = Version: 4 .... 0101 = Header Length: 20 bytes (5) Differentiated Services Field: 0x00 (DSCP: CS0, ECN: Not-ECT) Total Length: 56 Identification: 0x2c37 (11319) Flags: 0x0000 Time to live: 128 Protocol: UDP (17) Header checksum: 0x8ca9 [validation disabled] [Header checksum status: Unverified] Source: 192.168.0.131 Destination: 192.168.0.1 User Datagram Protocol, Src Port: 63998, Dst Port: 2054 Data (28 bytes) ``` Like I said before I do not capture the ICMP messages when I send the ping request. I did capture some ICMP communication between router and PC, I added the message above if it is of any help to anyone.
2019/08/08
[ "https://superuser.com/questions/1469187", "https://superuser.com", "https://superuser.com/users/169917/" ]
The question is identical to [Why does my remote process still run after killing an ssh session?](https://superuser.com/questions/20679/why-does-my-remote-process-still-run-after-killing-an-ssh-session). Also the answer is. By simply forcing the pseudo-TTY with `-t` on kill of PuTTY, the command on server end will end. PuTTY pseudo-terminal is discussed in [PuTTY: how to properly emulate -t option](https://superuser.com/questions/670494/putty-how-to-properly-emulate-t-option). However, this discussion fails to recognize the `-m` option you're using. That makes PuTTY behave differently.
just add -t option can solve this problem
9,935,259
I have `Car` (table `cars`) method that `has_many` owners (table `owners`). How can I choose all cars, that has no owners (== in the table `owners` is no one row with respective car's ID)?
2012/03/29
[ "https://Stackoverflow.com/questions/9935259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/984621/" ]
I would do it as per below in the model.... ``` @cars_without_owners = Car.where("owner_id = ?", nil) ``` or to be safe.... ``` @cars_without_owners = Car.where("owner_id = ? OR owner_id = ?", nil, "") ```
You could use this, although it would be very slow if your tables have many records: ``` Car.where("not exists (select o.id from owners as o where o.car_id = cars.id)") ```
264,311
**I have 4 reserved instances with a few months left:** c1.medium (active) m1.small (active) m1.small (active) t1.micro (active) **In "My Instances" i see 5 stopped instances, and 4 running:** m1.small m1.small m1.large c1.medium **In the billing section, it's clear that i am billed for the running instances:** *Amazon EC2 running Windows Reserved Instances:* c1.medium (17 hrs) m1.small (1270 hrs) *Amazon EC2 running Windows:* m1.large (640 hrs) c1.medium (665 hrs) Problem is, i can't seem to move the working machines to the reserved instances (it suggests only "on demand" and "spot" instances...) **what is the best approach for utilizing the already paid for (and cheaper) reserved instances? How do i do that?**
2011/04/28
[ "https://serverfault.com/questions/264311", "https://serverfault.com", "https://serverfault.com/users/79776/" ]
Your instances should automatically take advantage of reserve if there are reserves available. However, you have to remember that reserve [comes with a number of limitations](http://theagileadmin.com/2011/03/31/why-amazon-reserve-instances-torment-me/) - when you buy reserve they are locked to 1. Instance type 2. Availability zone and region 3. Operating system If your instances are in a different AZ, for example, from what you bought, they won't take advantage of reserve pricing.
Reserved instances are still on-demand instances, they have an hourly charge. That hourly charge is just cheaper than for a non-reserved on-demand instance.
64,422
On The New York Times I read the following sentence: > > The bad news here begins with the economy, which stinks. This is the > epicenter of the *dot-bomb*, the edge of the ailing Pacific Rim and > now a major casualty of tourist malaise. > > > What does *dot-bomb* mean?
2012/04/16
[ "https://english.stackexchange.com/questions/64422", "https://english.stackexchange.com", "https://english.stackexchange.com/users/24531/" ]
It's referring to the economic collapse of the "dot-com" boom, which occurred in the late 1990s. [This Wikipedia article](http://en.wikipedia.org/wiki/Dot-com_bubble) explains it rather well.
I don't have too many authoritative references, but I'd say that in this case it's probably a synecdoche, putting *dot-bomb*, a failed dot-com, for the *dot-com bust*, when a bunch of dot-coms failed. > > * NOAD and Oxford Dictionaries Online: `informal` an unsuccessful dot-com [ODO dot-com company]: : *many promising Internet start-ups ended up as dot-bombs.* > * Wikipedia: With the stock market crash around the year 2000 that ended the dot-com bubble, many failed and failing dot-com companies were referred to punningly as **dot-bombs**, **dot-cons** or **dot-gones**. > * Wiktionary: A failed dot-com company or venture > * Urban Dictionary: What happens after thousands of investors in internet companies all forget the hard-learned lessons in software development process and basic business plans: built it well and be profitable. *I lost my job in the dot bomb.* > > >
64,422
On The New York Times I read the following sentence: > > The bad news here begins with the economy, which stinks. This is the > epicenter of the *dot-bomb*, the edge of the ailing Pacific Rim and > now a major casualty of tourist malaise. > > > What does *dot-bomb* mean?
2012/04/16
[ "https://english.stackexchange.com/questions/64422", "https://english.stackexchange.com", "https://english.stackexchange.com/users/24531/" ]
It generally means that the new dot-com economy will collapse. ie "bomb" in AE=to fail spectacularly. dot-com + bomb -> dot-bomb
I don't have too many authoritative references, but I'd say that in this case it's probably a synecdoche, putting *dot-bomb*, a failed dot-com, for the *dot-com bust*, when a bunch of dot-coms failed. > > * NOAD and Oxford Dictionaries Online: `informal` an unsuccessful dot-com [ODO dot-com company]: : *many promising Internet start-ups ended up as dot-bombs.* > * Wikipedia: With the stock market crash around the year 2000 that ended the dot-com bubble, many failed and failing dot-com companies were referred to punningly as **dot-bombs**, **dot-cons** or **dot-gones**. > * Wiktionary: A failed dot-com company or venture > * Urban Dictionary: What happens after thousands of investors in internet companies all forget the hard-learned lessons in software development process and basic business plans: built it well and be profitable. *I lost my job in the dot bomb.* > > >
64,101,764
I want to change the background image of a project component when you hover over it. The img is in the array object. I already pull 'naam' and 'wat' from it, but the 'hover over and change the background to the img image' part I don't get. What do I need to do to make this work? I can't wrap my head around it. This is the code I'm using: ``` import React from 'react'; import './projectenoverzicht.scss'; import { Link } from 'react-router-dom'; import { ProjectenLijst } from './../../../data'; import { Grid } from '@material-ui/core'; import Sectiekopje from '../Sectiekopje/Sectiekopje'; const Projectenoverzicht = () => { const Project = ({ naam, wat }) => { const ProjectNaam = () => ( <div className='project_kader_banner'> <p className='project-kader-banner__titel'>{naam}</p> <p className='project-kader-banner__wat'>{wat}</p> </div> ); return ( <div className='project-kader'> <ProjectNaam /> </div> ) } return ( <> <Sectiekopje kop='Projecten' /> <Grid container spacing={2} className='home-projecten-overzicht'> <Grid item xs={12} md={3}> <Link to='/projecten#project1' className='link'> <Project naam={ProjectenLijst[0].naam} img={ProjectenLijst[0].img} wat={ProjectenLijst[0].wat} /> </Link> </Grid> <Grid item xs={12} md={3}> <Link to='/projecten#project2' className='link'> <Project naam={ProjectenLijst[1].naam} img={ProjectenLijst[1].img} wat={ProjectenLijst[1].wat} /> </Link> </Grid> <Grid item xs={12} md={3}> <Link to='/projecten#project3' className='link'> <Project naam={ProjectenLijst[2].naam} img={ProjectenLijst[2].img} wat={ProjectenLijst[2].wat} /> </Link> </Grid> <Grid item xs={12} md={3}> <Link to='/projecten#music-player' className='link'> <Project naam={ProjectenLijst[3].naam} img={ProjectenLijst[3].img} wat={ProjectenLijst[3].wat} /> </Link> </Grid> </Grid> </> ) } export default Projectenoverzicht; ```
2020/09/28
[ "https://Stackoverflow.com/questions/64101764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12051775/" ]
I don't understand, for which component you want to change your background, but generally: ``` const imgs = ['imgOffHover.png', 'imgOnHover.png'] ImageDiv = () => { [bcgImg, setBcgImg] = useState(imgs[0]) return ( <div onMouseEnter={() => setBcgImg(imgs[1])} onMouseLeave={() => setBcgImg(imgs[0])} > <img src={bcgImg} alt="bcgImage" /> </div> } ```
You can use css instead of JSX events like this [answer](https://stackoverflow.com/questions/41503150/adding-style-attributes-to-a-css-class-dynamically-in-react-app/55998158#55998158) You could state your backgrounds in your class like so: ``` .my-image-class { background-image: var(--my-image); background-repeat: no-repeat; background-position: center; &:hover { background-image: var(--hover-image); transform: scale(1.5); } } ``` And your JSX code should be like so: ``` <div key={index} className="my-image-class" style={{ '--my-image': `url(path)`; '--hover-image': `url(other-path)` }} > ```
64,101,764
I want to change the background image of a project component when you hover over it. The img is in the array object. I already pull 'naam' and 'wat' from it, but the 'hover over and change the background to the img image' part I don't get. What do I need to do to make this work? I can't wrap my head around it. This is the code I'm using: ``` import React from 'react'; import './projectenoverzicht.scss'; import { Link } from 'react-router-dom'; import { ProjectenLijst } from './../../../data'; import { Grid } from '@material-ui/core'; import Sectiekopje from '../Sectiekopje/Sectiekopje'; const Projectenoverzicht = () => { const Project = ({ naam, wat }) => { const ProjectNaam = () => ( <div className='project_kader_banner'> <p className='project-kader-banner__titel'>{naam}</p> <p className='project-kader-banner__wat'>{wat}</p> </div> ); return ( <div className='project-kader'> <ProjectNaam /> </div> ) } return ( <> <Sectiekopje kop='Projecten' /> <Grid container spacing={2} className='home-projecten-overzicht'> <Grid item xs={12} md={3}> <Link to='/projecten#project1' className='link'> <Project naam={ProjectenLijst[0].naam} img={ProjectenLijst[0].img} wat={ProjectenLijst[0].wat} /> </Link> </Grid> <Grid item xs={12} md={3}> <Link to='/projecten#project2' className='link'> <Project naam={ProjectenLijst[1].naam} img={ProjectenLijst[1].img} wat={ProjectenLijst[1].wat} /> </Link> </Grid> <Grid item xs={12} md={3}> <Link to='/projecten#project3' className='link'> <Project naam={ProjectenLijst[2].naam} img={ProjectenLijst[2].img} wat={ProjectenLijst[2].wat} /> </Link> </Grid> <Grid item xs={12} md={3}> <Link to='/projecten#music-player' className='link'> <Project naam={ProjectenLijst[3].naam} img={ProjectenLijst[3].img} wat={ProjectenLijst[3].wat} /> </Link> </Grid> </Grid> </> ) } export default Projectenoverzicht; ```
2020/09/28
[ "https://Stackoverflow.com/questions/64101764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12051775/" ]
I don't understand, for which component you want to change your background, but generally: ``` const imgs = ['imgOffHover.png', 'imgOnHover.png'] ImageDiv = () => { [bcgImg, setBcgImg] = useState(imgs[0]) return ( <div onMouseEnter={() => setBcgImg(imgs[1])} onMouseLeave={() => setBcgImg(imgs[0])} > <img src={bcgImg} alt="bcgImage" /> </div> } ```
So as far as i get it you want to change your components background.I made a solution which works as follows: * First make a state in functional component which will save your background image value ``` const [BgImg, setBgImg] = useState("") ``` * Second step make a mouse enter and mouse leave events that will be called once someone hovers over your component.So that is when we will pass the backgrounds value. ``` <div className='project-kader' onMouseEnter={() => setBgImg("Back ground Image 1 Url")} onMouseLeave={()=>setBgImg("Back ground Image 2 Url")} // Your background image value is save // Now pass it to inline styles to change background style={{backgroundImage: "url(" + BgImg + ")",height:'500px'}} > <ProjectNaam /> </div> ```
64,101,764
I want to change the background image of a project component when you hover over it. The img is in the array object. I already pull 'naam' and 'wat' from it, but the 'hover over and change the background to the img image' part I don't get. What do I need to do to make this work? I can't wrap my head around it. This is the code I'm using: ``` import React from 'react'; import './projectenoverzicht.scss'; import { Link } from 'react-router-dom'; import { ProjectenLijst } from './../../../data'; import { Grid } from '@material-ui/core'; import Sectiekopje from '../Sectiekopje/Sectiekopje'; const Projectenoverzicht = () => { const Project = ({ naam, wat }) => { const ProjectNaam = () => ( <div className='project_kader_banner'> <p className='project-kader-banner__titel'>{naam}</p> <p className='project-kader-banner__wat'>{wat}</p> </div> ); return ( <div className='project-kader'> <ProjectNaam /> </div> ) } return ( <> <Sectiekopje kop='Projecten' /> <Grid container spacing={2} className='home-projecten-overzicht'> <Grid item xs={12} md={3}> <Link to='/projecten#project1' className='link'> <Project naam={ProjectenLijst[0].naam} img={ProjectenLijst[0].img} wat={ProjectenLijst[0].wat} /> </Link> </Grid> <Grid item xs={12} md={3}> <Link to='/projecten#project2' className='link'> <Project naam={ProjectenLijst[1].naam} img={ProjectenLijst[1].img} wat={ProjectenLijst[1].wat} /> </Link> </Grid> <Grid item xs={12} md={3}> <Link to='/projecten#project3' className='link'> <Project naam={ProjectenLijst[2].naam} img={ProjectenLijst[2].img} wat={ProjectenLijst[2].wat} /> </Link> </Grid> <Grid item xs={12} md={3}> <Link to='/projecten#music-player' className='link'> <Project naam={ProjectenLijst[3].naam} img={ProjectenLijst[3].img} wat={ProjectenLijst[3].wat} /> </Link> </Grid> </Grid> </> ) } export default Projectenoverzicht; ```
2020/09/28
[ "https://Stackoverflow.com/questions/64101764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12051775/" ]
So as far as i get it you want to change your components background.I made a solution which works as follows: * First make a state in functional component which will save your background image value ``` const [BgImg, setBgImg] = useState("") ``` * Second step make a mouse enter and mouse leave events that will be called once someone hovers over your component.So that is when we will pass the backgrounds value. ``` <div className='project-kader' onMouseEnter={() => setBgImg("Back ground Image 1 Url")} onMouseLeave={()=>setBgImg("Back ground Image 2 Url")} // Your background image value is save // Now pass it to inline styles to change background style={{backgroundImage: "url(" + BgImg + ")",height:'500px'}} > <ProjectNaam /> </div> ```
You can use css instead of JSX events like this [answer](https://stackoverflow.com/questions/41503150/adding-style-attributes-to-a-css-class-dynamically-in-react-app/55998158#55998158) You could state your backgrounds in your class like so: ``` .my-image-class { background-image: var(--my-image); background-repeat: no-repeat; background-position: center; &:hover { background-image: var(--hover-image); transform: scale(1.5); } } ``` And your JSX code should be like so: ``` <div key={index} className="my-image-class" style={{ '--my-image': `url(path)`; '--hover-image': `url(other-path)` }} > ```
2,892,685
I'm the sole author of a paper and in my introduction I've written: > > We are able to talk about... Doing so we manage to capture ... We accomplish this by embedding... > > > and I'm wondering whether it's correct to talk about myself in the plural like that, similar to the way that mathematicians tend to write when talking about some mathematical fact or proof. If not do I just write things like "I am able to talk about"? Because that just sounds odd.
2018/08/24
[ "https://math.stackexchange.com/questions/2892685", "https://math.stackexchange.com", "https://math.stackexchange.com/users/90380/" ]
Top-to-bottom, then left-to-right: * Pythagorean Theorem * Area under a Gaussian (Normal distribution) * Fourier synthesis * Solution to a quadratic equation * Volume of a sphere * Differential cross section to the scattering amplitude in scattering theory (thanks to @SamFisher) * Raising operator for the quantum harmonic oscillator * Raising and lowering operators for quantum angular momentum * Time evolution of a Heisenberg operator in quantum mechanics * Legendre transformation between Lagrangian and Hamiltonian in theoretical mechanics * Coordinate transformation in special relativity * Energy of a relativistic particle * Relation between electric field and electric potentials in electrodynamics * Volume of a pyramid --- As a personal aside, I was responsible for something closely related to this list. I was a consultant on the movie [Raising Genius](https://www.imdb.com/title/tt0328875/?ref_=fn_al_tt_1) about a high-school science genius who locks himself in a bathroom and covers the walls with equations. ([Here is the trailer](https://www.imdb.com/title/tt0328875/videoplayer/vi2206335257?ref_=tt_pv_vi_aiv_1).) . I spent nearly 20 hours covering every square inch of the bathroom shower walls with genuine equations and graphs actually related to the solid-state physics discussed by the main character. I don't think anyone has tried to identify these equations from the film, so I'm pleased that the OP here actually cares what was written over the Byonce photograph!
I'm a bit late to the party. However, here is a partial transcription, equation by equation: > > $$c^2 = a^2 + b^2$$ > > > This is the Pythagorean theorem, and corresponds to the right triangle labeled above. > > $$ > \int\_{-\infty}^\infty e^{-x^2}\,dx = \sqrt{\pi} > $$ > > > The [Gaussian integral](https://en.wikipedia.org/wiki/Gaussian_integral) > > $$ > f(x) = a\_0 + \sum\_{n=1}^\infty \left(a\_n \cos\frac {n \pi x}{L} + b\_n \sin\frac{n \pi x}{L} \right) > $$ > > > This is $f(x)$ equated to its [Fourier series](http://mathworld.wolfram.com/FourierSeries.html). $f(x)$ here is a function of period $2L$. > > $$ > x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} > $$ > > > The quadratic formula > > $$ > V = \frac 43 \pi r^3 > $$ > > > Volume of a sphere (labeled above) > > $$ > \frac{d \sigma}{d \Omega} = |f(\theta, \phi)|^2 > $$ > > > Not sure what's going on here, but David's answer above claims it has to do with spherical coordinates > > $$ > a^\dagger = |n\rangle = \sqrt{n+1} |n+1\rangle\\ > $$ > > > The "creation operator"; related to the [quantum harmonic oscillator](https://en.wikipedia.org/wiki/Quantum_harmonic_oscillator) > > $$ > J\_{\pm}|j,m \rangle = \sqrt{j(j+1) - m(m \pm 1)} |j, m \pm 1 \rangle > $$ > > > Solution to quantum wave equation Will continue this if I find the motivation/attention span
2,892,685
I'm the sole author of a paper and in my introduction I've written: > > We are able to talk about... Doing so we manage to capture ... We accomplish this by embedding... > > > and I'm wondering whether it's correct to talk about myself in the plural like that, similar to the way that mathematicians tend to write when talking about some mathematical fact or proof. If not do I just write things like "I am able to talk about"? Because that just sounds odd.
2018/08/24
[ "https://math.stackexchange.com/questions/2892685", "https://math.stackexchange.com", "https://math.stackexchange.com/users/90380/" ]
Top-to-bottom, then left-to-right: * Pythagorean Theorem * Area under a Gaussian (Normal distribution) * Fourier synthesis * Solution to a quadratic equation * Volume of a sphere * Differential cross section to the scattering amplitude in scattering theory (thanks to @SamFisher) * Raising operator for the quantum harmonic oscillator * Raising and lowering operators for quantum angular momentum * Time evolution of a Heisenberg operator in quantum mechanics * Legendre transformation between Lagrangian and Hamiltonian in theoretical mechanics * Coordinate transformation in special relativity * Energy of a relativistic particle * Relation between electric field and electric potentials in electrodynamics * Volume of a pyramid --- As a personal aside, I was responsible for something closely related to this list. I was a consultant on the movie [Raising Genius](https://www.imdb.com/title/tt0328875/?ref_=fn_al_tt_1) about a high-school science genius who locks himself in a bathroom and covers the walls with equations. ([Here is the trailer](https://www.imdb.com/title/tt0328875/videoplayer/vi2206335257?ref_=tt_pv_vi_aiv_1).) . I spent nearly 20 hours covering every square inch of the bathroom shower walls with genuine equations and graphs actually related to the solid-state physics discussed by the main character. I don't think anyone has tried to identify these equations from the film, so I'm pleased that the OP here actually cares what was written over the Byonce photograph!
To add a correction to David's answer, $\frac{d\sigma}{d\Omega} = |f(\theta, \phi)|^2$ relates the differential cross section to the scattering amplitude in scattering theory. The equation involving $J\_\pm$ shows the action of the raising ($+$) and lowering ($-$) operators on angular momentum eigenstates in quantum mechanics. Finally, $H = p\dot{q} - L$ relates the Hamiltonian to the Lagrangian in classical mechanics. This is not Lagrange's equation, but simply the definition of the Hamiltonian function. Edit: Also to specify, the equation involving $a^\dagger$ shows the action of the creation operator on an eigenstate of the quantum harmonic oscillator. Another edit: I just noticed no one mentioned this equation, but $A(t) = e^{iHt/\hbar} A e^{-iHt/\hbar}$ is the time evolution of an operator in quantum mechanics in the case where the Hamiltonian does not depend on time.
2,892,685
I'm the sole author of a paper and in my introduction I've written: > > We are able to talk about... Doing so we manage to capture ... We accomplish this by embedding... > > > and I'm wondering whether it's correct to talk about myself in the plural like that, similar to the way that mathematicians tend to write when talking about some mathematical fact or proof. If not do I just write things like "I am able to talk about"? Because that just sounds odd.
2018/08/24
[ "https://math.stackexchange.com/questions/2892685", "https://math.stackexchange.com", "https://math.stackexchange.com/users/90380/" ]
Top-to-bottom, then left-to-right: * Pythagorean Theorem * Area under a Gaussian (Normal distribution) * Fourier synthesis * Solution to a quadratic equation * Volume of a sphere * Differential cross section to the scattering amplitude in scattering theory (thanks to @SamFisher) * Raising operator for the quantum harmonic oscillator * Raising and lowering operators for quantum angular momentum * Time evolution of a Heisenberg operator in quantum mechanics * Legendre transformation between Lagrangian and Hamiltonian in theoretical mechanics * Coordinate transformation in special relativity * Energy of a relativistic particle * Relation between electric field and electric potentials in electrodynamics * Volume of a pyramid --- As a personal aside, I was responsible for something closely related to this list. I was a consultant on the movie [Raising Genius](https://www.imdb.com/title/tt0328875/?ref_=fn_al_tt_1) about a high-school science genius who locks himself in a bathroom and covers the walls with equations. ([Here is the trailer](https://www.imdb.com/title/tt0328875/videoplayer/vi2206335257?ref_=tt_pv_vi_aiv_1).) . I spent nearly 20 hours covering every square inch of the bathroom shower walls with genuine equations and graphs actually related to the solid-state physics discussed by the main character. I don't think anyone has tried to identify these equations from the film, so I'm pleased that the OP here actually cares what was written over the Byonce photograph!
The right-hand-side is taken from the preface to Srednicki's textbook *Quantum Field Theory* (page 8), available online on [his webpage](https://web.physics.ucsb.edu/~mark/qft.html): [![enter image description here](https://i.stack.imgur.com/nyein.png)](https://i.stack.imgur.com/nyein.png) These are mostly equations from physics. The first one is the [quantum-mechanical differential cross-section](https://en.wikipedia.org/wiki/Cross_section_(physics)#Quantum_scattering). The second one corresponds to the one-dimensional [quantum harmonic oscillator](https://en.wikipedia.org/wiki/Quantum_harmonic_oscillator#Ladder_operator_method). The third one corresponds to the [quantum angular momentum operator](https://en.wikipedia.org/wiki/Angular_momentum_operator#Quantization). The fourth one is the time evolution of an operator in the [Heisenberg picture](https://en.wikipedia.org/wiki/Heisenberg_picture). The fifth one is the Legendre transform of the Lagrangian, that is, [the Hamiltonian](https://en.wikipedia.org/wiki/Hamiltonian_mechanics#As_a_reformulation_of_Lagrangian_mechanics). The sixth one is a [Lorentz transformation](https://en.wikipedia.org/wiki/Lorentz_transformation). The seventh one is the (relativistic) [energy-momentum relation](https://en.wikipedia.org/wiki/Energy%E2%80%93momentum_relation). The eight and last one is the electric field in terms of the [electromagnetic potentials](https://en.wikipedia.org/wiki/Electric_potential#Generalization_to_electrodynamics).
2,892,685
I'm the sole author of a paper and in my introduction I've written: > > We are able to talk about... Doing so we manage to capture ... We accomplish this by embedding... > > > and I'm wondering whether it's correct to talk about myself in the plural like that, similar to the way that mathematicians tend to write when talking about some mathematical fact or proof. If not do I just write things like "I am able to talk about"? Because that just sounds odd.
2018/08/24
[ "https://math.stackexchange.com/questions/2892685", "https://math.stackexchange.com", "https://math.stackexchange.com/users/90380/" ]
Top-to-bottom, then left-to-right: * Pythagorean Theorem * Area under a Gaussian (Normal distribution) * Fourier synthesis * Solution to a quadratic equation * Volume of a sphere * Differential cross section to the scattering amplitude in scattering theory (thanks to @SamFisher) * Raising operator for the quantum harmonic oscillator * Raising and lowering operators for quantum angular momentum * Time evolution of a Heisenberg operator in quantum mechanics * Legendre transformation between Lagrangian and Hamiltonian in theoretical mechanics * Coordinate transformation in special relativity * Energy of a relativistic particle * Relation between electric field and electric potentials in electrodynamics * Volume of a pyramid --- As a personal aside, I was responsible for something closely related to this list. I was a consultant on the movie [Raising Genius](https://www.imdb.com/title/tt0328875/?ref_=fn_al_tt_1) about a high-school science genius who locks himself in a bathroom and covers the walls with equations. ([Here is the trailer](https://www.imdb.com/title/tt0328875/videoplayer/vi2206335257?ref_=tt_pv_vi_aiv_1).) . I spent nearly 20 hours covering every square inch of the bathroom shower walls with genuine equations and graphs actually related to the solid-state physics discussed by the main character. I don't think anyone has tried to identify these equations from the film, so I'm pleased that the OP here actually cares what was written over the Byonce photograph!
Welp, here is my Latex practice for today. I will be going down the left side then move on to the right side, going down. 1. Pythagoras' Theorem: First off, we see a triangle with sides labeled $a$, $b$, and $c$, with below it, the equation $$a^2+b^2=c^2$$ This is, of course, Pythagoras' famous theorem and applies to a right triangle, and helps one find, by square rooting both sides, the 'hypotenuse' of the triangle. 2. Gaussian Integral: $$\int^{\infty}\_{-\infty} e^{{-x}^2} dx=\sqrt{\pi}$$ The 'gaussian function' is the function used in the normal distribution curve in probability and statistics. This is an exceedingly simple form evaluated, that of $e^{{-x}^2}$. The little curly $\int$, is called the *integral* and represents the area under the curve, when we write $\int^\infty\_{-\infty}$ are calculating the area under the curve from x to negative infinity and positive infinity. Were we to graph the Gaussian distribution function and find the area under the curve, would get $\sqrt{\pi}$. 3. Function in terms of Fourier Series: $$f(x)=a\_0+\sum\_{-\infty}^\infty {\left( a\_n \cos{\frac{n \pi x}{L}} ^{\infty}\_{-\infty} - b\_n \sin{\frac{n \pi x}{L}} \right)}$$ This describes a function in terms of a constant plus an infinite number of sine and cosine waves. These can describe many many functions, and is used in signal processing. 4. Quadratic Equation: $$x=\frac{-b \pm \sqrt{b^2-4ac}}{2a}$$ This gives the values of $x$ for which $ax^2+bx+c=0$. It is commonly learned in Algebra. 5. Sphere: This is an image of a mathematical geometric object known as the 'sphere'. It is defined as all points of a distance $r$ relative to a 'center point'. 6. Volume of Sphere: $$V=\frac{4}{3}\pi r^3$$ This is the equation, given radius $r$, to calculate the volume the sphere encloses. This is commonly learned in Geometry class in high school. 7. Differential Cross Section of Scattering Amplitude: $$\frac{d \sigma}{d \Omega}=|f(\theta, \phi)|^2$$ 8. Creation Operator: $$a^{\dagger} | n \rangle = \sqrt{n+1} |n+1 \rangle$$ This relates the 'operation' of applying the 'operator' to the state of the quantum system, to raise to the next highest energy level of the state, or put another way, to raise the state to its next state by the Principle Quantum Number. This is known to be used to solve the simple harmonic equation of a Quantum System. 9. Quantum Total Angular Moment Ladder Operator: $$J\_{\pm}|j,m\rangle = \sqrt{j(j+1)-m(m \pm 1)} |j, m \pm 1 \rangle $$ There is, basically, the 'normal' angular moment relative to an origin, which is what one expects in classical physics, but due to the discovery of 'quantum spin', or 'intrinsic angular moment', we add it to the normal angular moment. Now, one represents this as $j$. This particular operator, similar to the other ladder operator, finds the quantum state of higher magnetic quantum number. 10. Time Evolution of Operator in Quantum Mechanics: $$A(t)=e^{+iHt/\hbar}Ae^{-iHt/\hbar}$$ In the *Heisenberg picture* of Quantum Mechanics, operators evolve with time and quantum states are the same. Here, $H$ is the Hamiltonian of a Quantum System, $t$ time, $i$ the imaginary number, $\hbar$ Planck's constant. $A$ is our Quantum Operator. This describes, the operator over time. It should be noted that this only works in this form if $H$, the Hamiltonian operator, is constant over time. 11. Hamiltonian of a Particle: $$H=p \dot{q} - L$$ This represents, in a way, the 'total energy' of a particle with respect to any parameters used to describe the system. $L$ here is the 'Lagrangian' of the system and is that which is minimized over time in the system, and is described as $L=T-V$, where $T$ here is kinetic, $p$ momentum, and $\dot{q}$ the change in the parameter(that describes space in some fashion) with respect to time, or the 'generalized velocity'. 12. Time Dilation/Time Component of Lorentz Transformation: $$ct'=\gamma \left( {ct-\beta x} \right)$$ This describes, with respect to another inertial frame traveling at a velocity $v$ ($\beta=v/c$), where $c$ is the transmission velocity of light in a local inertial frame, in a vacuum, the time relative to you of the observer moving. This is known as 'time dilation'. 13. Energy-Mass Equivalence: $$E=\sqrt{pc^2+m^2c^4}$$ This formula describes the total energy of a system with *rest mass*, or the mass of the object at rest, $m$, and momentum $p$, where $c$ is the speed of light. This is basically the $E=mc^2$ which describes the energy of the system being in a manner 'equivalent to energy'. This gives rise to the energy released via fusion. 14. Electric Field: $$E=-\dot{A}/c-\nabla{\varphi}$$ With respect to given 'potentials' (a 'vector potential' $A$ and scalar potential $\varphi$), the electric field, or basically, the value at each point in space of the force of the particle divided by charge, or, sticking a charge in space, allows one via the equation $F=qE$ (q is the charge of the particle) to calculate the force on the particle.
2,892,685
I'm the sole author of a paper and in my introduction I've written: > > We are able to talk about... Doing so we manage to capture ... We accomplish this by embedding... > > > and I'm wondering whether it's correct to talk about myself in the plural like that, similar to the way that mathematicians tend to write when talking about some mathematical fact or proof. If not do I just write things like "I am able to talk about"? Because that just sounds odd.
2018/08/24
[ "https://math.stackexchange.com/questions/2892685", "https://math.stackexchange.com", "https://math.stackexchange.com/users/90380/" ]
The right-hand-side is taken from the preface to Srednicki's textbook *Quantum Field Theory* (page 8), available online on [his webpage](https://web.physics.ucsb.edu/~mark/qft.html): [![enter image description here](https://i.stack.imgur.com/nyein.png)](https://i.stack.imgur.com/nyein.png) These are mostly equations from physics. The first one is the [quantum-mechanical differential cross-section](https://en.wikipedia.org/wiki/Cross_section_(physics)#Quantum_scattering). The second one corresponds to the one-dimensional [quantum harmonic oscillator](https://en.wikipedia.org/wiki/Quantum_harmonic_oscillator#Ladder_operator_method). The third one corresponds to the [quantum angular momentum operator](https://en.wikipedia.org/wiki/Angular_momentum_operator#Quantization). The fourth one is the time evolution of an operator in the [Heisenberg picture](https://en.wikipedia.org/wiki/Heisenberg_picture). The fifth one is the Legendre transform of the Lagrangian, that is, [the Hamiltonian](https://en.wikipedia.org/wiki/Hamiltonian_mechanics#As_a_reformulation_of_Lagrangian_mechanics). The sixth one is a [Lorentz transformation](https://en.wikipedia.org/wiki/Lorentz_transformation). The seventh one is the (relativistic) [energy-momentum relation](https://en.wikipedia.org/wiki/Energy%E2%80%93momentum_relation). The eight and last one is the electric field in terms of the [electromagnetic potentials](https://en.wikipedia.org/wiki/Electric_potential#Generalization_to_electrodynamics).
I'm a bit late to the party. However, here is a partial transcription, equation by equation: > > $$c^2 = a^2 + b^2$$ > > > This is the Pythagorean theorem, and corresponds to the right triangle labeled above. > > $$ > \int\_{-\infty}^\infty e^{-x^2}\,dx = \sqrt{\pi} > $$ > > > The [Gaussian integral](https://en.wikipedia.org/wiki/Gaussian_integral) > > $$ > f(x) = a\_0 + \sum\_{n=1}^\infty \left(a\_n \cos\frac {n \pi x}{L} + b\_n \sin\frac{n \pi x}{L} \right) > $$ > > > This is $f(x)$ equated to its [Fourier series](http://mathworld.wolfram.com/FourierSeries.html). $f(x)$ here is a function of period $2L$. > > $$ > x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} > $$ > > > The quadratic formula > > $$ > V = \frac 43 \pi r^3 > $$ > > > Volume of a sphere (labeled above) > > $$ > \frac{d \sigma}{d \Omega} = |f(\theta, \phi)|^2 > $$ > > > Not sure what's going on here, but David's answer above claims it has to do with spherical coordinates > > $$ > a^\dagger = |n\rangle = \sqrt{n+1} |n+1\rangle\\ > $$ > > > The "creation operator"; related to the [quantum harmonic oscillator](https://en.wikipedia.org/wiki/Quantum_harmonic_oscillator) > > $$ > J\_{\pm}|j,m \rangle = \sqrt{j(j+1) - m(m \pm 1)} |j, m \pm 1 \rangle > $$ > > > Solution to quantum wave equation Will continue this if I find the motivation/attention span
2,892,685
I'm the sole author of a paper and in my introduction I've written: > > We are able to talk about... Doing so we manage to capture ... We accomplish this by embedding... > > > and I'm wondering whether it's correct to talk about myself in the plural like that, similar to the way that mathematicians tend to write when talking about some mathematical fact or proof. If not do I just write things like "I am able to talk about"? Because that just sounds odd.
2018/08/24
[ "https://math.stackexchange.com/questions/2892685", "https://math.stackexchange.com", "https://math.stackexchange.com/users/90380/" ]
The right-hand-side is taken from the preface to Srednicki's textbook *Quantum Field Theory* (page 8), available online on [his webpage](https://web.physics.ucsb.edu/~mark/qft.html): [![enter image description here](https://i.stack.imgur.com/nyein.png)](https://i.stack.imgur.com/nyein.png) These are mostly equations from physics. The first one is the [quantum-mechanical differential cross-section](https://en.wikipedia.org/wiki/Cross_section_(physics)#Quantum_scattering). The second one corresponds to the one-dimensional [quantum harmonic oscillator](https://en.wikipedia.org/wiki/Quantum_harmonic_oscillator#Ladder_operator_method). The third one corresponds to the [quantum angular momentum operator](https://en.wikipedia.org/wiki/Angular_momentum_operator#Quantization). The fourth one is the time evolution of an operator in the [Heisenberg picture](https://en.wikipedia.org/wiki/Heisenberg_picture). The fifth one is the Legendre transform of the Lagrangian, that is, [the Hamiltonian](https://en.wikipedia.org/wiki/Hamiltonian_mechanics#As_a_reformulation_of_Lagrangian_mechanics). The sixth one is a [Lorentz transformation](https://en.wikipedia.org/wiki/Lorentz_transformation). The seventh one is the (relativistic) [energy-momentum relation](https://en.wikipedia.org/wiki/Energy%E2%80%93momentum_relation). The eight and last one is the electric field in terms of the [electromagnetic potentials](https://en.wikipedia.org/wiki/Electric_potential#Generalization_to_electrodynamics).
To add a correction to David's answer, $\frac{d\sigma}{d\Omega} = |f(\theta, \phi)|^2$ relates the differential cross section to the scattering amplitude in scattering theory. The equation involving $J\_\pm$ shows the action of the raising ($+$) and lowering ($-$) operators on angular momentum eigenstates in quantum mechanics. Finally, $H = p\dot{q} - L$ relates the Hamiltonian to the Lagrangian in classical mechanics. This is not Lagrange's equation, but simply the definition of the Hamiltonian function. Edit: Also to specify, the equation involving $a^\dagger$ shows the action of the creation operator on an eigenstate of the quantum harmonic oscillator. Another edit: I just noticed no one mentioned this equation, but $A(t) = e^{iHt/\hbar} A e^{-iHt/\hbar}$ is the time evolution of an operator in quantum mechanics in the case where the Hamiltonian does not depend on time.
2,892,685
I'm the sole author of a paper and in my introduction I've written: > > We are able to talk about... Doing so we manage to capture ... We accomplish this by embedding... > > > and I'm wondering whether it's correct to talk about myself in the plural like that, similar to the way that mathematicians tend to write when talking about some mathematical fact or proof. If not do I just write things like "I am able to talk about"? Because that just sounds odd.
2018/08/24
[ "https://math.stackexchange.com/questions/2892685", "https://math.stackexchange.com", "https://math.stackexchange.com/users/90380/" ]
The right-hand-side is taken from the preface to Srednicki's textbook *Quantum Field Theory* (page 8), available online on [his webpage](https://web.physics.ucsb.edu/~mark/qft.html): [![enter image description here](https://i.stack.imgur.com/nyein.png)](https://i.stack.imgur.com/nyein.png) These are mostly equations from physics. The first one is the [quantum-mechanical differential cross-section](https://en.wikipedia.org/wiki/Cross_section_(physics)#Quantum_scattering). The second one corresponds to the one-dimensional [quantum harmonic oscillator](https://en.wikipedia.org/wiki/Quantum_harmonic_oscillator#Ladder_operator_method). The third one corresponds to the [quantum angular momentum operator](https://en.wikipedia.org/wiki/Angular_momentum_operator#Quantization). The fourth one is the time evolution of an operator in the [Heisenberg picture](https://en.wikipedia.org/wiki/Heisenberg_picture). The fifth one is the Legendre transform of the Lagrangian, that is, [the Hamiltonian](https://en.wikipedia.org/wiki/Hamiltonian_mechanics#As_a_reformulation_of_Lagrangian_mechanics). The sixth one is a [Lorentz transformation](https://en.wikipedia.org/wiki/Lorentz_transformation). The seventh one is the (relativistic) [energy-momentum relation](https://en.wikipedia.org/wiki/Energy%E2%80%93momentum_relation). The eight and last one is the electric field in terms of the [electromagnetic potentials](https://en.wikipedia.org/wiki/Electric_potential#Generalization_to_electrodynamics).
Welp, here is my Latex practice for today. I will be going down the left side then move on to the right side, going down. 1. Pythagoras' Theorem: First off, we see a triangle with sides labeled $a$, $b$, and $c$, with below it, the equation $$a^2+b^2=c^2$$ This is, of course, Pythagoras' famous theorem and applies to a right triangle, and helps one find, by square rooting both sides, the 'hypotenuse' of the triangle. 2. Gaussian Integral: $$\int^{\infty}\_{-\infty} e^{{-x}^2} dx=\sqrt{\pi}$$ The 'gaussian function' is the function used in the normal distribution curve in probability and statistics. This is an exceedingly simple form evaluated, that of $e^{{-x}^2}$. The little curly $\int$, is called the *integral* and represents the area under the curve, when we write $\int^\infty\_{-\infty}$ are calculating the area under the curve from x to negative infinity and positive infinity. Were we to graph the Gaussian distribution function and find the area under the curve, would get $\sqrt{\pi}$. 3. Function in terms of Fourier Series: $$f(x)=a\_0+\sum\_{-\infty}^\infty {\left( a\_n \cos{\frac{n \pi x}{L}} ^{\infty}\_{-\infty} - b\_n \sin{\frac{n \pi x}{L}} \right)}$$ This describes a function in terms of a constant plus an infinite number of sine and cosine waves. These can describe many many functions, and is used in signal processing. 4. Quadratic Equation: $$x=\frac{-b \pm \sqrt{b^2-4ac}}{2a}$$ This gives the values of $x$ for which $ax^2+bx+c=0$. It is commonly learned in Algebra. 5. Sphere: This is an image of a mathematical geometric object known as the 'sphere'. It is defined as all points of a distance $r$ relative to a 'center point'. 6. Volume of Sphere: $$V=\frac{4}{3}\pi r^3$$ This is the equation, given radius $r$, to calculate the volume the sphere encloses. This is commonly learned in Geometry class in high school. 7. Differential Cross Section of Scattering Amplitude: $$\frac{d \sigma}{d \Omega}=|f(\theta, \phi)|^2$$ 8. Creation Operator: $$a^{\dagger} | n \rangle = \sqrt{n+1} |n+1 \rangle$$ This relates the 'operation' of applying the 'operator' to the state of the quantum system, to raise to the next highest energy level of the state, or put another way, to raise the state to its next state by the Principle Quantum Number. This is known to be used to solve the simple harmonic equation of a Quantum System. 9. Quantum Total Angular Moment Ladder Operator: $$J\_{\pm}|j,m\rangle = \sqrt{j(j+1)-m(m \pm 1)} |j, m \pm 1 \rangle $$ There is, basically, the 'normal' angular moment relative to an origin, which is what one expects in classical physics, but due to the discovery of 'quantum spin', or 'intrinsic angular moment', we add it to the normal angular moment. Now, one represents this as $j$. This particular operator, similar to the other ladder operator, finds the quantum state of higher magnetic quantum number. 10. Time Evolution of Operator in Quantum Mechanics: $$A(t)=e^{+iHt/\hbar}Ae^{-iHt/\hbar}$$ In the *Heisenberg picture* of Quantum Mechanics, operators evolve with time and quantum states are the same. Here, $H$ is the Hamiltonian of a Quantum System, $t$ time, $i$ the imaginary number, $\hbar$ Planck's constant. $A$ is our Quantum Operator. This describes, the operator over time. It should be noted that this only works in this form if $H$, the Hamiltonian operator, is constant over time. 11. Hamiltonian of a Particle: $$H=p \dot{q} - L$$ This represents, in a way, the 'total energy' of a particle with respect to any parameters used to describe the system. $L$ here is the 'Lagrangian' of the system and is that which is minimized over time in the system, and is described as $L=T-V$, where $T$ here is kinetic, $p$ momentum, and $\dot{q}$ the change in the parameter(that describes space in some fashion) with respect to time, or the 'generalized velocity'. 12. Time Dilation/Time Component of Lorentz Transformation: $$ct'=\gamma \left( {ct-\beta x} \right)$$ This describes, with respect to another inertial frame traveling at a velocity $v$ ($\beta=v/c$), where $c$ is the transmission velocity of light in a local inertial frame, in a vacuum, the time relative to you of the observer moving. This is known as 'time dilation'. 13. Energy-Mass Equivalence: $$E=\sqrt{pc^2+m^2c^4}$$ This formula describes the total energy of a system with *rest mass*, or the mass of the object at rest, $m$, and momentum $p$, where $c$ is the speed of light. This is basically the $E=mc^2$ which describes the energy of the system being in a manner 'equivalent to energy'. This gives rise to the energy released via fusion. 14. Electric Field: $$E=-\dot{A}/c-\nabla{\varphi}$$ With respect to given 'potentials' (a 'vector potential' $A$ and scalar potential $\varphi$), the electric field, or basically, the value at each point in space of the force of the particle divided by charge, or, sticking a charge in space, allows one via the equation $F=qE$ (q is the charge of the particle) to calculate the force on the particle.
8,174,556
Here's an [example on JSFiddle](http://jsfiddle.net/haGWe/3/). Excerpt of code: ``` <table style="height:100%"> <tr height="20"><td></td></tr> <tr> <td>This gray cell fits all available height of table</td> </tr> <tr height="20"><td></td></tr> </table> ``` There is a table with three rows. Row in the middle fits all available height of table. I took this solution from [here](https://stackoverflow.com/questions/1118566/fit-td-height-to-page). Problem is that impossible to make overflow-y for middle cell. It seems that the middle cell has a min-height property equals height of it's content. So does it possible to turn on scrolling (overflow-y:auto) somehow and if it doesn't how to implement this layout in divs? UPD. Thanks. Seems like this is working example: <http://jsfiddle.net/haGWe/6/> But it's still interesting how to implement this with divs.
2011/11/17
[ "https://Stackoverflow.com/questions/8174556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1052640/" ]
It sounds a bit like [mod\_security](https://modsecurity.org/), switched on and in its most aggressive mode, and it thinks you're trying to hack the site. The reason I say it only sounds a *bit* like that is because no-one should normally configure it to check POST data because that causes far too many false positives. But check the error log(s) as it will probably be listed there if it's that. If so you'll need to turn it off in the hosting settings or nag your host to do it. Also try a bare minimum script: `<?php var_dump($GLOBALS); ?>` to see if the data reaches PHP at all.
if you wish to use the following `base64encode()` and insert ,after read `base64decode()`
8,174,556
Here's an [example on JSFiddle](http://jsfiddle.net/haGWe/3/). Excerpt of code: ``` <table style="height:100%"> <tr height="20"><td></td></tr> <tr> <td>This gray cell fits all available height of table</td> </tr> <tr height="20"><td></td></tr> </table> ``` There is a table with three rows. Row in the middle fits all available height of table. I took this solution from [here](https://stackoverflow.com/questions/1118566/fit-td-height-to-page). Problem is that impossible to make overflow-y for middle cell. It seems that the middle cell has a min-height property equals height of it's content. So does it possible to turn on scrolling (overflow-y:auto) somehow and if it doesn't how to implement this layout in divs? UPD. Thanks. Seems like this is working example: <http://jsfiddle.net/haGWe/6/> But it's still interesting how to implement this with divs.
2011/11/17
[ "https://Stackoverflow.com/questions/8174556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1052640/" ]
It sounds a bit like [mod\_security](https://modsecurity.org/), switched on and in its most aggressive mode, and it thinks you're trying to hack the site. The reason I say it only sounds a *bit* like that is because no-one should normally configure it to check POST data because that causes far too many false positives. But check the error log(s) as it will probably be listed there if it's that. If so you'll need to turn it off in the hosting settings or nag your host to do it. Also try a bare minimum script: `<?php var_dump($GLOBALS); ?>` to see if the data reaches PHP at all.
Send this into your db ``` <a href=www.google.com>Google</a> ``` or When called from db ``` echo "http://".$row_TabelName['RowName']; ``` It should solve your issue.
8,174,556
Here's an [example on JSFiddle](http://jsfiddle.net/haGWe/3/). Excerpt of code: ``` <table style="height:100%"> <tr height="20"><td></td></tr> <tr> <td>This gray cell fits all available height of table</td> </tr> <tr height="20"><td></td></tr> </table> ``` There is a table with three rows. Row in the middle fits all available height of table. I took this solution from [here](https://stackoverflow.com/questions/1118566/fit-td-height-to-page). Problem is that impossible to make overflow-y for middle cell. It seems that the middle cell has a min-height property equals height of it's content. So does it possible to turn on scrolling (overflow-y:auto) somehow and if it doesn't how to implement this layout in divs? UPD. Thanks. Seems like this is working example: <http://jsfiddle.net/haGWe/6/> But it's still interesting how to implement this with divs.
2011/11/17
[ "https://Stackoverflow.com/questions/8174556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1052640/" ]
It sounds a bit like [mod\_security](https://modsecurity.org/), switched on and in its most aggressive mode, and it thinks you're trying to hack the site. The reason I say it only sounds a *bit* like that is because no-one should normally configure it to check POST data because that causes far too many false positives. But check the error log(s) as it will probably be listed there if it's that. If so you'll need to turn it off in the hosting settings or nag your host to do it. Also try a bare minimum script: `<?php var_dump($GLOBALS); ?>` to see if the data reaches PHP at all.
try: ``` if($_POST && !empty($_POST['save'])){ $text = mysql_real_escape_string(htmlentities($_POST['textarea'])); $title = mysql_real_escape_string(htmlentities($_POST['title'])); ```
8,174,556
Here's an [example on JSFiddle](http://jsfiddle.net/haGWe/3/). Excerpt of code: ``` <table style="height:100%"> <tr height="20"><td></td></tr> <tr> <td>This gray cell fits all available height of table</td> </tr> <tr height="20"><td></td></tr> </table> ``` There is a table with three rows. Row in the middle fits all available height of table. I took this solution from [here](https://stackoverflow.com/questions/1118566/fit-td-height-to-page). Problem is that impossible to make overflow-y for middle cell. It seems that the middle cell has a min-height property equals height of it's content. So does it possible to turn on scrolling (overflow-y:auto) somehow and if it doesn't how to implement this layout in divs? UPD. Thanks. Seems like this is working example: <http://jsfiddle.net/haGWe/6/> But it's still interesting how to implement this with divs.
2011/11/17
[ "https://Stackoverflow.com/questions/8174556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1052640/" ]
try: ``` if($_POST && !empty($_POST['save'])){ $text = mysql_real_escape_string(htmlentities($_POST['textarea'])); $title = mysql_real_escape_string(htmlentities($_POST['title'])); ```
if you wish to use the following `base64encode()` and insert ,after read `base64decode()`
8,174,556
Here's an [example on JSFiddle](http://jsfiddle.net/haGWe/3/). Excerpt of code: ``` <table style="height:100%"> <tr height="20"><td></td></tr> <tr> <td>This gray cell fits all available height of table</td> </tr> <tr height="20"><td></td></tr> </table> ``` There is a table with three rows. Row in the middle fits all available height of table. I took this solution from [here](https://stackoverflow.com/questions/1118566/fit-td-height-to-page). Problem is that impossible to make overflow-y for middle cell. It seems that the middle cell has a min-height property equals height of it's content. So does it possible to turn on scrolling (overflow-y:auto) somehow and if it doesn't how to implement this layout in divs? UPD. Thanks. Seems like this is working example: <http://jsfiddle.net/haGWe/6/> But it's still interesting how to implement this with divs.
2011/11/17
[ "https://Stackoverflow.com/questions/8174556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1052640/" ]
try: ``` if($_POST && !empty($_POST['save'])){ $text = mysql_real_escape_string(htmlentities($_POST['textarea'])); $title = mysql_real_escape_string(htmlentities($_POST['title'])); ```
Send this into your db ``` <a href=www.google.com>Google</a> ``` or When called from db ``` echo "http://".$row_TabelName['RowName']; ``` It should solve your issue.
1,564,981
I am trying to figure out how to prove $17^{200} - 1$ is a multiple of $10$. I am talking simple algebra stuff once everything is set in place. I have to use mathematical induction. I figure I need to split $17^{200}$ into something like $(17^{40})^5 - 1$ and have it as $n = 17^{40}$ and $n^5 - 1$. I just don't know if that's a good way to start.
2015/12/07
[ "https://math.stackexchange.com/questions/1564981", "https://math.stackexchange.com", "https://math.stackexchange.com/users/296815/" ]
Since it seems a bit strange to use induction to solve for particular case ($17^{200} - 1$), and it seems from your question that you want to see this solved via an inductive proof, let's use induction to solve a somewhat more general problem, and recover this particular example as a special case. So, let's make the conjecture that $$4 \mid n \implies 10 \mid (17^n - 1).$$ This means we want to show 10 divides $17^{4k} - 1$ for all integers $k$. Now, the base case is $k = 1$ and we have $$ 17^{4k} - 1 = 17^4 - 1 = 83520 = 10 \* 8352.$$ Indeed, the hypothesis holds in the base case. Now, assume the statement is true for some integer $m$. We then have \begin{align\*} &&17^{4m} - 1 &= 10 \cdot a &\text{for some } a \in \mathbb{Z} \\ \implies && 17^4 (17^{4m} - 1) &= 10 \cdot a \\ \implies && 17^{4m+1} - 83521 &= 10 \cdot a \\ \implies && 17^{4m+1} - 1 &= 10\cdot a + 83520 \\ \implies && 17^{4m+1} - 1 &= 10\cdot (a + 8352) \end{align\*} Thus, 10 divides $17^{4m+1}$ if it divides $17^{4m}$; hence, we have shown that 10 divides $17^{4k}$ for every integer $k$. Since 200 is a multiple of 4, the problem at hand is then solved as a special case of this theorem.
$17^{200} - 1$ is clearly even and so it remains to prove that it is a multiple of $5$. Now, $17^{200}= (15+2)^{200}=15a+2^{200}$. So it suffices to prove that $2^{200}-1$ is a multiple of $5$. Indeed, $2^{200}=(2^{4})^{50}=16^{50}=(5b+1)^{50}=5c+1$.
1,564,981
I am trying to figure out how to prove $17^{200} - 1$ is a multiple of $10$. I am talking simple algebra stuff once everything is set in place. I have to use mathematical induction. I figure I need to split $17^{200}$ into something like $(17^{40})^5 - 1$ and have it as $n = 17^{40}$ and $n^5 - 1$. I just don't know if that's a good way to start.
2015/12/07
[ "https://math.stackexchange.com/questions/1564981", "https://math.stackexchange.com", "https://math.stackexchange.com/users/296815/" ]
Since it seems a bit strange to use induction to solve for particular case ($17^{200} - 1$), and it seems from your question that you want to see this solved via an inductive proof, let's use induction to solve a somewhat more general problem, and recover this particular example as a special case. So, let's make the conjecture that $$4 \mid n \implies 10 \mid (17^n - 1).$$ This means we want to show 10 divides $17^{4k} - 1$ for all integers $k$. Now, the base case is $k = 1$ and we have $$ 17^{4k} - 1 = 17^4 - 1 = 83520 = 10 \* 8352.$$ Indeed, the hypothesis holds in the base case. Now, assume the statement is true for some integer $m$. We then have \begin{align\*} &&17^{4m} - 1 &= 10 \cdot a &\text{for some } a \in \mathbb{Z} \\ \implies && 17^4 (17^{4m} - 1) &= 10 \cdot a \\ \implies && 17^{4m+1} - 83521 &= 10 \cdot a \\ \implies && 17^{4m+1} - 1 &= 10\cdot a + 83520 \\ \implies && 17^{4m+1} - 1 &= 10\cdot (a + 8352) \end{align\*} Thus, 10 divides $17^{4m+1}$ if it divides $17^{4m}$; hence, we have shown that 10 divides $17^{4k}$ for every integer $k$. Since 200 is a multiple of 4, the problem at hand is then solved as a special case of this theorem.
We need to prove that for all $n$, $17^{4n} -1$ is divisible by 10. Consider when n=1: $17^{4} - 1 = (17^{2} - 1)(17^{2} +1)=(288)(290)$ this is obviously divisible by 10. Assume for some integer k that $17^{4k} -1$ is divisible by 10. Then $17^{4(k+1)} -1 =17^{4k+4} -1=(17^{4})(17^{4k}) -1 = (17^{4k} -1) + (17^{4} -1)(17^{4k}) = (17^{4k} -1) + (288)(290)(17^{4k}) $ And both parts of the last sum are divisible by 10 as required.
1,564,981
I am trying to figure out how to prove $17^{200} - 1$ is a multiple of $10$. I am talking simple algebra stuff once everything is set in place. I have to use mathematical induction. I figure I need to split $17^{200}$ into something like $(17^{40})^5 - 1$ and have it as $n = 17^{40}$ and $n^5 - 1$. I just don't know if that's a good way to start.
2015/12/07
[ "https://math.stackexchange.com/questions/1564981", "https://math.stackexchange.com", "https://math.stackexchange.com/users/296815/" ]
Since it seems a bit strange to use induction to solve for particular case ($17^{200} - 1$), and it seems from your question that you want to see this solved via an inductive proof, let's use induction to solve a somewhat more general problem, and recover this particular example as a special case. So, let's make the conjecture that $$4 \mid n \implies 10 \mid (17^n - 1).$$ This means we want to show 10 divides $17^{4k} - 1$ for all integers $k$. Now, the base case is $k = 1$ and we have $$ 17^{4k} - 1 = 17^4 - 1 = 83520 = 10 \* 8352.$$ Indeed, the hypothesis holds in the base case. Now, assume the statement is true for some integer $m$. We then have \begin{align\*} &&17^{4m} - 1 &= 10 \cdot a &\text{for some } a \in \mathbb{Z} \\ \implies && 17^4 (17^{4m} - 1) &= 10 \cdot a \\ \implies && 17^{4m+1} - 83521 &= 10 \cdot a \\ \implies && 17^{4m+1} - 1 &= 10\cdot a + 83520 \\ \implies && 17^{4m+1} - 1 &= 10\cdot (a + 8352) \end{align\*} Thus, 10 divides $17^{4m+1}$ if it divides $17^{4m}$; hence, we have shown that 10 divides $17^{4k}$ for every integer $k$. Since 200 is a multiple of 4, the problem at hand is then solved as a special case of this theorem.
Here is another proof that $k(k^4-1)$ is divisible by $10$, using some "fun" observations ;) The base case is $2(2^4-1) = 30$, which is easily seen to be $3\cdot10$ Assume $k^5-k = 10 a$ for some $a \in \mathbb{Z}$ $$(k+1)^5-(k+1)$$ $$=\left(k^5+5k^4+10k^3+10k^2+5k+1\right)-(k+1)$$ $$=k^5+5k^4+10k^3+10k^2+5k-k$$ $$=(k^5-k)+5k^4+10k^3+10k^2+5k$$ $$10a+5(k^4+2k^3+2k^2+k)$$ Since an odd times and odd is odd and an even times and even is even, so $k^4+k$ is either $(2k+1)+(2r+1) = 2(r+k+1)$ or $2n+2r=2(n+r)$ and thus must be even, so we rewrite the above as $$10a+5(2(k^3+k^2+p)) = 10(a+k^3+k^2+p)$$ Examining $17^{200}-1$, we realize that $17^{200}-1$ must be divisible by $10$ if $17^{50}$ is not. $17^{50}$ *has* no factors of $10$ though (as it is prime), so $17^{200}-1$ must be divisible by $10$.
1,564,981
I am trying to figure out how to prove $17^{200} - 1$ is a multiple of $10$. I am talking simple algebra stuff once everything is set in place. I have to use mathematical induction. I figure I need to split $17^{200}$ into something like $(17^{40})^5 - 1$ and have it as $n = 17^{40}$ and $n^5 - 1$. I just don't know if that's a good way to start.
2015/12/07
[ "https://math.stackexchange.com/questions/1564981", "https://math.stackexchange.com", "https://math.stackexchange.com/users/296815/" ]
Since it seems a bit strange to use induction to solve for particular case ($17^{200} - 1$), and it seems from your question that you want to see this solved via an inductive proof, let's use induction to solve a somewhat more general problem, and recover this particular example as a special case. So, let's make the conjecture that $$4 \mid n \implies 10 \mid (17^n - 1).$$ This means we want to show 10 divides $17^{4k} - 1$ for all integers $k$. Now, the base case is $k = 1$ and we have $$ 17^{4k} - 1 = 17^4 - 1 = 83520 = 10 \* 8352.$$ Indeed, the hypothesis holds in the base case. Now, assume the statement is true for some integer $m$. We then have \begin{align\*} &&17^{4m} - 1 &= 10 \cdot a &\text{for some } a \in \mathbb{Z} \\ \implies && 17^4 (17^{4m} - 1) &= 10 \cdot a \\ \implies && 17^{4m+1} - 83521 &= 10 \cdot a \\ \implies && 17^{4m+1} - 1 &= 10\cdot a + 83520 \\ \implies && 17^{4m+1} - 1 &= 10\cdot (a + 8352) \end{align\*} Thus, 10 divides $17^{4m+1}$ if it divides $17^{4m}$; hence, we have shown that 10 divides $17^{4k}$ for every integer $k$. Since 200 is a multiple of 4, the problem at hand is then solved as a special case of this theorem.
Consider a number with a $7$ in its units place. As we take powers of it, the units digit proceeds: $$7, 9, 3, 1, 7, 9, 3, 1, \ldots$$ Notice that when raised to a power that is a multiple of $4$, such a number ends up with a $1$ in its units place. Since $17$ has a $7$ in its units place, and since $200$ is a multiple of $4$, we reason that the number $17^{200}$ must have a $1$ in its units place. Thus, $17^{200} - 1$ has a $0$ in its units place, i.e., is a multiple of $10$ as desired. **QED**.
1,564,981
I am trying to figure out how to prove $17^{200} - 1$ is a multiple of $10$. I am talking simple algebra stuff once everything is set in place. I have to use mathematical induction. I figure I need to split $17^{200}$ into something like $(17^{40})^5 - 1$ and have it as $n = 17^{40}$ and $n^5 - 1$. I just don't know if that's a good way to start.
2015/12/07
[ "https://math.stackexchange.com/questions/1564981", "https://math.stackexchange.com", "https://math.stackexchange.com/users/296815/" ]
$17^{200} - 1$ is clearly even and so it remains to prove that it is a multiple of $5$. Now, $17^{200}= (15+2)^{200}=15a+2^{200}$. So it suffices to prove that $2^{200}-1$ is a multiple of $5$. Indeed, $2^{200}=(2^{4})^{50}=16^{50}=(5b+1)^{50}=5c+1$.
Here is another proof that $k(k^4-1)$ is divisible by $10$, using some "fun" observations ;) The base case is $2(2^4-1) = 30$, which is easily seen to be $3\cdot10$ Assume $k^5-k = 10 a$ for some $a \in \mathbb{Z}$ $$(k+1)^5-(k+1)$$ $$=\left(k^5+5k^4+10k^3+10k^2+5k+1\right)-(k+1)$$ $$=k^5+5k^4+10k^3+10k^2+5k-k$$ $$=(k^5-k)+5k^4+10k^3+10k^2+5k$$ $$10a+5(k^4+2k^3+2k^2+k)$$ Since an odd times and odd is odd and an even times and even is even, so $k^4+k$ is either $(2k+1)+(2r+1) = 2(r+k+1)$ or $2n+2r=2(n+r)$ and thus must be even, so we rewrite the above as $$10a+5(2(k^3+k^2+p)) = 10(a+k^3+k^2+p)$$ Examining $17^{200}-1$, we realize that $17^{200}-1$ must be divisible by $10$ if $17^{50}$ is not. $17^{50}$ *has* no factors of $10$ though (as it is prime), so $17^{200}-1$ must be divisible by $10$.
1,564,981
I am trying to figure out how to prove $17^{200} - 1$ is a multiple of $10$. I am talking simple algebra stuff once everything is set in place. I have to use mathematical induction. I figure I need to split $17^{200}$ into something like $(17^{40})^5 - 1$ and have it as $n = 17^{40}$ and $n^5 - 1$. I just don't know if that's a good way to start.
2015/12/07
[ "https://math.stackexchange.com/questions/1564981", "https://math.stackexchange.com", "https://math.stackexchange.com/users/296815/" ]
We need to prove that for all $n$, $17^{4n} -1$ is divisible by 10. Consider when n=1: $17^{4} - 1 = (17^{2} - 1)(17^{2} +1)=(288)(290)$ this is obviously divisible by 10. Assume for some integer k that $17^{4k} -1$ is divisible by 10. Then $17^{4(k+1)} -1 =17^{4k+4} -1=(17^{4})(17^{4k}) -1 = (17^{4k} -1) + (17^{4} -1)(17^{4k}) = (17^{4k} -1) + (288)(290)(17^{4k}) $ And both parts of the last sum are divisible by 10 as required.
Here is another proof that $k(k^4-1)$ is divisible by $10$, using some "fun" observations ;) The base case is $2(2^4-1) = 30$, which is easily seen to be $3\cdot10$ Assume $k^5-k = 10 a$ for some $a \in \mathbb{Z}$ $$(k+1)^5-(k+1)$$ $$=\left(k^5+5k^4+10k^3+10k^2+5k+1\right)-(k+1)$$ $$=k^5+5k^4+10k^3+10k^2+5k-k$$ $$=(k^5-k)+5k^4+10k^3+10k^2+5k$$ $$10a+5(k^4+2k^3+2k^2+k)$$ Since an odd times and odd is odd and an even times and even is even, so $k^4+k$ is either $(2k+1)+(2r+1) = 2(r+k+1)$ or $2n+2r=2(n+r)$ and thus must be even, so we rewrite the above as $$10a+5(2(k^3+k^2+p)) = 10(a+k^3+k^2+p)$$ Examining $17^{200}-1$, we realize that $17^{200}-1$ must be divisible by $10$ if $17^{50}$ is not. $17^{50}$ *has* no factors of $10$ though (as it is prime), so $17^{200}-1$ must be divisible by $10$.
1,564,981
I am trying to figure out how to prove $17^{200} - 1$ is a multiple of $10$. I am talking simple algebra stuff once everything is set in place. I have to use mathematical induction. I figure I need to split $17^{200}$ into something like $(17^{40})^5 - 1$ and have it as $n = 17^{40}$ and $n^5 - 1$. I just don't know if that's a good way to start.
2015/12/07
[ "https://math.stackexchange.com/questions/1564981", "https://math.stackexchange.com", "https://math.stackexchange.com/users/296815/" ]
Consider a number with a $7$ in its units place. As we take powers of it, the units digit proceeds: $$7, 9, 3, 1, 7, 9, 3, 1, \ldots$$ Notice that when raised to a power that is a multiple of $4$, such a number ends up with a $1$ in its units place. Since $17$ has a $7$ in its units place, and since $200$ is a multiple of $4$, we reason that the number $17^{200}$ must have a $1$ in its units place. Thus, $17^{200} - 1$ has a $0$ in its units place, i.e., is a multiple of $10$ as desired. **QED**.
Here is another proof that $k(k^4-1)$ is divisible by $10$, using some "fun" observations ;) The base case is $2(2^4-1) = 30$, which is easily seen to be $3\cdot10$ Assume $k^5-k = 10 a$ for some $a \in \mathbb{Z}$ $$(k+1)^5-(k+1)$$ $$=\left(k^5+5k^4+10k^3+10k^2+5k+1\right)-(k+1)$$ $$=k^5+5k^4+10k^3+10k^2+5k-k$$ $$=(k^5-k)+5k^4+10k^3+10k^2+5k$$ $$10a+5(k^4+2k^3+2k^2+k)$$ Since an odd times and odd is odd and an even times and even is even, so $k^4+k$ is either $(2k+1)+(2r+1) = 2(r+k+1)$ or $2n+2r=2(n+r)$ and thus must be even, so we rewrite the above as $$10a+5(2(k^3+k^2+p)) = 10(a+k^3+k^2+p)$$ Examining $17^{200}-1$, we realize that $17^{200}-1$ must be divisible by $10$ if $17^{50}$ is not. $17^{50}$ *has* no factors of $10$ though (as it is prime), so $17^{200}-1$ must be divisible by $10$.
22,422,845
Is it possible to declare some type of base class with template methods which i can override in derived classes? Following example: ``` #include <iostream> #include <stdexcept> #include <string> class Base { public: template<typename T> std::string method() { return "Base"; } }; class Derived : public Base { public: template<typename T> std::string method() override { return "Derived"; } }; int main() { Base *b = new Derived(); std::cout << b->method<bool>() << std::endl; return 0; } ``` I would expect `Derived` as the output but it is `Base`. I assume it is necessary to make a templated wrapper class which receives the implementing class as the template parameter. But i want to make sure.
2014/03/15
[ "https://Stackoverflow.com/questions/22422845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1931663/" ]
1) Your functions, in order to be polymorphic, should be marked with **virtual** 2) Templated functions are instantiated at the POI and can't be virtual (what is the signature??How many vtable entries do you reserve?). **Templated functions are a compile-time mechanism, virtual functions a runtime one**. Some possible solutions involve: * Change design (recommended) * Follow another approach e.g. multimethod by Andrei Alexandrescu (<http://www.icodeguru.com/CPP/ModernCppDesign/0201704315_ch11.html>)
Template methods cannot be virtual. One solution is to use static polymorphism to simulate the behavior of "template virtual" methods: ``` #include <iostream> #include <stdexcept> #include <string> template<typename D> class Base { template<typename T> std::string _method() { return "Base"; } public: template<typename T> std::string method() { return static_cast<D&>(*this).template _method<T>(); } }; class Derived : public Base<Derived> { friend class Base<Derived>; template<typename T> std::string _method() { return "Derived"; } public: //... }; int main() { Base<Derived> *b = new Derived(); std::cout << b->method<bool>() << std::endl; return 0; } ``` where `method` is the interface and `_method` is the implementation. To simulate a pure virtual method, `_method` would absent from `Base`. Unfortunately, this way `Base` changes to `Base<Derived>` so you can no longer e.g. have a container of `Base*`. Also note that for a `const` method, `static_cast<D&>` changes to `static_cast<const D&>`. Similarly, for an rvalue-reference (`&&`) method, it changes to `static_cast<D&&>`.
22,422,845
Is it possible to declare some type of base class with template methods which i can override in derived classes? Following example: ``` #include <iostream> #include <stdexcept> #include <string> class Base { public: template<typename T> std::string method() { return "Base"; } }; class Derived : public Base { public: template<typename T> std::string method() override { return "Derived"; } }; int main() { Base *b = new Derived(); std::cout << b->method<bool>() << std::endl; return 0; } ``` I would expect `Derived` as the output but it is `Base`. I assume it is necessary to make a templated wrapper class which receives the implementing class as the template parameter. But i want to make sure.
2014/03/15
[ "https://Stackoverflow.com/questions/22422845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1931663/" ]
1) Your functions, in order to be polymorphic, should be marked with **virtual** 2) Templated functions are instantiated at the POI and can't be virtual (what is the signature??How many vtable entries do you reserve?). **Templated functions are a compile-time mechanism, virtual functions a runtime one**. Some possible solutions involve: * Change design (recommended) * Follow another approach e.g. multimethod by Andrei Alexandrescu (<http://www.icodeguru.com/CPP/ModernCppDesign/0201704315_ch11.html>)
Another possible aproach to make your example work as you expect is to use `std::function`: ``` class Base { public: Base() { virtualFunction = [] () -> string { return {"Base"}; }; } template <class T> string do_smth() { return virtualFunction(); } function<string()> virtualFunction; }; class Derived : public Base { public: Derived() { virtualFunction = [] () -> string { return {"Derived"}; }; } }; int main() { auto ptr = unique_ptr<Base>(new Derived); cout << ptr->do_smth<bool>() << endl; } ``` This outputs "Derived". I'm not sure that this is what you realy want, but I hope it will help you..
22,422,845
Is it possible to declare some type of base class with template methods which i can override in derived classes? Following example: ``` #include <iostream> #include <stdexcept> #include <string> class Base { public: template<typename T> std::string method() { return "Base"; } }; class Derived : public Base { public: template<typename T> std::string method() override { return "Derived"; } }; int main() { Base *b = new Derived(); std::cout << b->method<bool>() << std::endl; return 0; } ``` I would expect `Derived` as the output but it is `Base`. I assume it is necessary to make a templated wrapper class which receives the implementing class as the template parameter. But i want to make sure.
2014/03/15
[ "https://Stackoverflow.com/questions/22422845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1931663/" ]
1) Your functions, in order to be polymorphic, should be marked with **virtual** 2) Templated functions are instantiated at the POI and can't be virtual (what is the signature??How many vtable entries do you reserve?). **Templated functions are a compile-time mechanism, virtual functions a runtime one**. Some possible solutions involve: * Change design (recommended) * Follow another approach e.g. multimethod by Andrei Alexandrescu (<http://www.icodeguru.com/CPP/ModernCppDesign/0201704315_ch11.html>)
I had the same problem, but I actually came up with a working solution. The best way to show the solution is by an example: **What we want**(doesn't work, since you can't have virtual templates): ``` class Base { template <class T> virtual T func(T a, T b) {}; } class Derived { template <class T> T func(T a, T b) { return a + b; }; } int main() { Base* obj = new Derived(); std::cout << obj->func(1, 2) << obj->func(std::string("Hello"), std::string("World")) << obj->func(0.2, 0.1); return 0; } ``` **The solution**(prints `3HelloWorld0.3`): ``` class BaseType { public: virtual BaseType* add(BaseType* b) { return {}; }; }; template <class T> class Type : public BaseType { public: Type(T t) : value(t) {}; BaseType* add(BaseType* b) { Type<T>* a = new Type<T>(value + ((Type<T>*)b)->value); return a; }; T getValue() { return value; }; private: T value; }; class Base { public: virtual BaseType* function(BaseType* a, BaseType* b) { return {}; }; template <class T> T func(T a, T b) { BaseType* argA = new Type<T>(a); BaseType* argB = new Type<T>(b); BaseType* value = this->function(argA, argB); T result = ((Type<T>*)value)->getValue(); delete argA; delete argB; delete value; return result; }; }; class Derived : public Base { public: BaseType* function(BaseType* a, BaseType* b) { return a->add(b); }; }; int main() { Base* obj = new Derived(); std::cout << obj->func(1, 2) << obj->func(std::string("Hello"), std::string("World")) << obj->func(0.2, 0.1); return 0; } ``` We use the `BaseType` class to represent any datatype or class you would usually use in a template. The members(and possibly operators) you would use in a template are described here with the virtual tag. Note that the pointers are necessary in order to get the polymorphism to work. `Type` is a template class that extends `Derived`. This actually represents a specific type, for example `Type<int>`. This class is very important, since it allows us to convert any type into the `BaseType`. The definition of the members we described described in `BaseType` are implemented here. `function` is the function we want to override. Instead of using a real template we use pointers to `BaseType` to represent a typename. The actual template function is in the `Base` class defined as `func`. It basically just calls `function` and converts `T` to `Type<T>`. If we now extend from `Base` and override `function`, the new overridden function gets called for the derived class.
22,422,845
Is it possible to declare some type of base class with template methods which i can override in derived classes? Following example: ``` #include <iostream> #include <stdexcept> #include <string> class Base { public: template<typename T> std::string method() { return "Base"; } }; class Derived : public Base { public: template<typename T> std::string method() override { return "Derived"; } }; int main() { Base *b = new Derived(); std::cout << b->method<bool>() << std::endl; return 0; } ``` I would expect `Derived` as the output but it is `Base`. I assume it is necessary to make a templated wrapper class which receives the implementing class as the template parameter. But i want to make sure.
2014/03/15
[ "https://Stackoverflow.com/questions/22422845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1931663/" ]
Template methods cannot be virtual. One solution is to use static polymorphism to simulate the behavior of "template virtual" methods: ``` #include <iostream> #include <stdexcept> #include <string> template<typename D> class Base { template<typename T> std::string _method() { return "Base"; } public: template<typename T> std::string method() { return static_cast<D&>(*this).template _method<T>(); } }; class Derived : public Base<Derived> { friend class Base<Derived>; template<typename T> std::string _method() { return "Derived"; } public: //... }; int main() { Base<Derived> *b = new Derived(); std::cout << b->method<bool>() << std::endl; return 0; } ``` where `method` is the interface and `_method` is the implementation. To simulate a pure virtual method, `_method` would absent from `Base`. Unfortunately, this way `Base` changes to `Base<Derived>` so you can no longer e.g. have a container of `Base*`. Also note that for a `const` method, `static_cast<D&>` changes to `static_cast<const D&>`. Similarly, for an rvalue-reference (`&&`) method, it changes to `static_cast<D&&>`.
Another possible aproach to make your example work as you expect is to use `std::function`: ``` class Base { public: Base() { virtualFunction = [] () -> string { return {"Base"}; }; } template <class T> string do_smth() { return virtualFunction(); } function<string()> virtualFunction; }; class Derived : public Base { public: Derived() { virtualFunction = [] () -> string { return {"Derived"}; }; } }; int main() { auto ptr = unique_ptr<Base>(new Derived); cout << ptr->do_smth<bool>() << endl; } ``` This outputs "Derived". I'm not sure that this is what you realy want, but I hope it will help you..
22,422,845
Is it possible to declare some type of base class with template methods which i can override in derived classes? Following example: ``` #include <iostream> #include <stdexcept> #include <string> class Base { public: template<typename T> std::string method() { return "Base"; } }; class Derived : public Base { public: template<typename T> std::string method() override { return "Derived"; } }; int main() { Base *b = new Derived(); std::cout << b->method<bool>() << std::endl; return 0; } ``` I would expect `Derived` as the output but it is `Base`. I assume it is necessary to make a templated wrapper class which receives the implementing class as the template parameter. But i want to make sure.
2014/03/15
[ "https://Stackoverflow.com/questions/22422845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1931663/" ]
Template methods cannot be virtual. One solution is to use static polymorphism to simulate the behavior of "template virtual" methods: ``` #include <iostream> #include <stdexcept> #include <string> template<typename D> class Base { template<typename T> std::string _method() { return "Base"; } public: template<typename T> std::string method() { return static_cast<D&>(*this).template _method<T>(); } }; class Derived : public Base<Derived> { friend class Base<Derived>; template<typename T> std::string _method() { return "Derived"; } public: //... }; int main() { Base<Derived> *b = new Derived(); std::cout << b->method<bool>() << std::endl; return 0; } ``` where `method` is the interface and `_method` is the implementation. To simulate a pure virtual method, `_method` would absent from `Base`. Unfortunately, this way `Base` changes to `Base<Derived>` so you can no longer e.g. have a container of `Base*`. Also note that for a `const` method, `static_cast<D&>` changes to `static_cast<const D&>`. Similarly, for an rvalue-reference (`&&`) method, it changes to `static_cast<D&&>`.
I had the same problem, but I actually came up with a working solution. The best way to show the solution is by an example: **What we want**(doesn't work, since you can't have virtual templates): ``` class Base { template <class T> virtual T func(T a, T b) {}; } class Derived { template <class T> T func(T a, T b) { return a + b; }; } int main() { Base* obj = new Derived(); std::cout << obj->func(1, 2) << obj->func(std::string("Hello"), std::string("World")) << obj->func(0.2, 0.1); return 0; } ``` **The solution**(prints `3HelloWorld0.3`): ``` class BaseType { public: virtual BaseType* add(BaseType* b) { return {}; }; }; template <class T> class Type : public BaseType { public: Type(T t) : value(t) {}; BaseType* add(BaseType* b) { Type<T>* a = new Type<T>(value + ((Type<T>*)b)->value); return a; }; T getValue() { return value; }; private: T value; }; class Base { public: virtual BaseType* function(BaseType* a, BaseType* b) { return {}; }; template <class T> T func(T a, T b) { BaseType* argA = new Type<T>(a); BaseType* argB = new Type<T>(b); BaseType* value = this->function(argA, argB); T result = ((Type<T>*)value)->getValue(); delete argA; delete argB; delete value; return result; }; }; class Derived : public Base { public: BaseType* function(BaseType* a, BaseType* b) { return a->add(b); }; }; int main() { Base* obj = new Derived(); std::cout << obj->func(1, 2) << obj->func(std::string("Hello"), std::string("World")) << obj->func(0.2, 0.1); return 0; } ``` We use the `BaseType` class to represent any datatype or class you would usually use in a template. The members(and possibly operators) you would use in a template are described here with the virtual tag. Note that the pointers are necessary in order to get the polymorphism to work. `Type` is a template class that extends `Derived`. This actually represents a specific type, for example `Type<int>`. This class is very important, since it allows us to convert any type into the `BaseType`. The definition of the members we described described in `BaseType` are implemented here. `function` is the function we want to override. Instead of using a real template we use pointers to `BaseType` to represent a typename. The actual template function is in the `Base` class defined as `func`. It basically just calls `function` and converts `T` to `Type<T>`. If we now extend from `Base` and override `function`, the new overridden function gets called for the derived class.
22,422,845
Is it possible to declare some type of base class with template methods which i can override in derived classes? Following example: ``` #include <iostream> #include <stdexcept> #include <string> class Base { public: template<typename T> std::string method() { return "Base"; } }; class Derived : public Base { public: template<typename T> std::string method() override { return "Derived"; } }; int main() { Base *b = new Derived(); std::cout << b->method<bool>() << std::endl; return 0; } ``` I would expect `Derived` as the output but it is `Base`. I assume it is necessary to make a templated wrapper class which receives the implementing class as the template parameter. But i want to make sure.
2014/03/15
[ "https://Stackoverflow.com/questions/22422845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1931663/" ]
Another possible aproach to make your example work as you expect is to use `std::function`: ``` class Base { public: Base() { virtualFunction = [] () -> string { return {"Base"}; }; } template <class T> string do_smth() { return virtualFunction(); } function<string()> virtualFunction; }; class Derived : public Base { public: Derived() { virtualFunction = [] () -> string { return {"Derived"}; }; } }; int main() { auto ptr = unique_ptr<Base>(new Derived); cout << ptr->do_smth<bool>() << endl; } ``` This outputs "Derived". I'm not sure that this is what you realy want, but I hope it will help you..
I had the same problem, but I actually came up with a working solution. The best way to show the solution is by an example: **What we want**(doesn't work, since you can't have virtual templates): ``` class Base { template <class T> virtual T func(T a, T b) {}; } class Derived { template <class T> T func(T a, T b) { return a + b; }; } int main() { Base* obj = new Derived(); std::cout << obj->func(1, 2) << obj->func(std::string("Hello"), std::string("World")) << obj->func(0.2, 0.1); return 0; } ``` **The solution**(prints `3HelloWorld0.3`): ``` class BaseType { public: virtual BaseType* add(BaseType* b) { return {}; }; }; template <class T> class Type : public BaseType { public: Type(T t) : value(t) {}; BaseType* add(BaseType* b) { Type<T>* a = new Type<T>(value + ((Type<T>*)b)->value); return a; }; T getValue() { return value; }; private: T value; }; class Base { public: virtual BaseType* function(BaseType* a, BaseType* b) { return {}; }; template <class T> T func(T a, T b) { BaseType* argA = new Type<T>(a); BaseType* argB = new Type<T>(b); BaseType* value = this->function(argA, argB); T result = ((Type<T>*)value)->getValue(); delete argA; delete argB; delete value; return result; }; }; class Derived : public Base { public: BaseType* function(BaseType* a, BaseType* b) { return a->add(b); }; }; int main() { Base* obj = new Derived(); std::cout << obj->func(1, 2) << obj->func(std::string("Hello"), std::string("World")) << obj->func(0.2, 0.1); return 0; } ``` We use the `BaseType` class to represent any datatype or class you would usually use in a template. The members(and possibly operators) you would use in a template are described here with the virtual tag. Note that the pointers are necessary in order to get the polymorphism to work. `Type` is a template class that extends `Derived`. This actually represents a specific type, for example `Type<int>`. This class is very important, since it allows us to convert any type into the `BaseType`. The definition of the members we described described in `BaseType` are implemented here. `function` is the function we want to override. Instead of using a real template we use pointers to `BaseType` to represent a typename. The actual template function is in the `Base` class defined as `func`. It basically just calls `function` and converts `T` to `Type<T>`. If we now extend from `Base` and override `function`, the new overridden function gets called for the derived class.
163,042
> > **Possible Duplicate:** > > [Proving an interpolation inequality](https://math.stackexchange.com/questions/28589/proving-an-interpolation-inequality) > > > Let $f \in L^p$ and $f \in L^r$ where $1 \leqslant p \leqslant r$ . Then can we say that $f \in L^q$ if $p \leqslant q \leqslant r$? ($f : \mathbb R^n \to \mathbb R$)
2012/06/25
[ "https://math.stackexchange.com/questions/163042", "https://math.stackexchange.com", "https://math.stackexchange.com/users/34329/" ]
Yes: we write $q=ap+(1-a)r$ where $0<a<1$ (if $a\in \{0,1\}$ it's clear). We apply Hölder's inequality to the exponent $\frac 1a>1$ (it's conjugate is $\frac 1{1-a}$). We get $$\int\_{\Bbb R^n}|f|^qdx=\int\_{\Bbb R^n}(|f|^p)^a(|f|^r)^{1-a}dx\leq \left(\int\_{\Bbb R^n}|f|^p\right)^a\left(\int\_{\Bbb R^n}|f|^r\right)^{1-a},$$ which is finite. We also have the inequality $$\lVert f\rVert\_{L^q}\leq \lVert f\rVert\_{L^p}^{\frac aq}\cdot \lVert f\rVert\_{L^r}^{\frac{1-a}q}.$$
**HINT** Split the $L^q$ integral over the sets $A$ and $A^C$, where $A = \{x \in \mathbb{R}^n: f(x) \leq 1\}$ argue out why both are finite making use of the fact that $f \in L^p, L^r$.
58,419,410
I am working on a .js web development file and with a radio selection of 0,1,2 I want to check the following >0 of the returned value: I have tried this for the first line: if (!$("input[name=bbClassification]:checked").val() > 0) { ``` if (!$("input[name=bbClassification]:checked").val()) { $("input[name=bbClassification]").closest('.form-group').addClass("has-error"); validationError = true; } else { $("input[name=bbClassification]").closest('.form-group').removeClass("has-error"); } ``` I only want the code to run if the returned val > 0
2019/10/16
[ "https://Stackoverflow.com/questions/58419410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11301190/" ]
If you send out links from your site that have an email address it might be related to this. <https://github.com/surbo/knockknock/blob/master/README.md>
basically, the phishing list you sent is not like suspicious emails or sender. The phishing list that includes that email, like this "http://amadermanikganj.com/Cpanelreport/equos/index.php?email=nobody@mycraftmail.com" indicates that in the param someone tried it with that email. not related to phish and suspicious activity
43,817,297
I've been experimenting with new [native ECMAScript module support](https://jakearchibald.com/2017/es-modules-in-browsers/) that has recently been added to browsers. It's pleasant to finally be able import scripts directly and cleanly from JavaScript. [**`/example.html`**](https://795258201.glitch.me/example.html) ```html <script type="module"> import {example} from '/example.js'; example(); </script> ``` [**`/example.js`**](https://795258201.glitch.me/example.js) ```js export function example() { document.body.appendChild(document.createTextNode("hello")); }; ``` However, this only allows me to import modules that are defined by separate **external** JavaScript files. I usually prefer to inline some scripts used for the initial rendering, so their requests don't block the rest of the page. With a traditional informally-structured library, that might look like this: [**`/inline-traditional.html`**](https://795258201.glitch.me/inline-traditional.html) ```html <body> <script> var example = {}; example.example = function() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script> example.example(); </script> ``` However, naively inlining modules files obviously won't work, since it would remove the filename used to identify the module to other modules. HTTP/2 server push may be the canonical way to handle this situation, but it's still not an option in all environments. Is it possible to perform an equivalent transformation with ECMAScript modules? Is there any way for a `<script type="module">` to import a module exported by another in the same document? --- I imagine this could work by allowing the script to specify a file path, and behave as though it had already been downloaded or pushed from the path. [**`/inline-name.html`**](https://795258201.glitch.me/inline-name.html) ```html <script type="module" name="/example.js"> export function example() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script type="module"> import {example} from '/example.js'; example(); </script> ``` Or maybe by an entirely different reference scheme, such as is used for local SVG references: [**`/inline-id.html`**](https://795258201.glitch.me/inline-id.html) ```html <script type="module" id="example"> export function example() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script type="module"> import {example} from '#example'; example(); </script> ``` But neither of these hypotheticals actually work, and I haven't seen an alternative which does.
2017/05/06
[ "https://Stackoverflow.com/questions/43817297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1114/" ]
Hacking Together Our Own `import from '#id'` ============================================ Exports/imports between inline scripts aren't natively supported, but it was a fun exercise to hack together an implementation for my documents. Code-golfed down to a small block, I use it like this: ```html <script type="module" data-info="https://stackoverflow.com/a/43834063">let l,e,t ='script',p=/(from\s+|import\s+)['"](#[\w\-]+)['"]/g,x='textContent',d=document, s,o;for(o of d.querySelectorAll(t+'[type=inline-module]'))l=d.createElement(t),o .id?l.id=o.id:0,l.type='module',l[x]=o[x].replace(p,(u,a,z)=>(e=d.querySelector( t+z+'[type=module][src]'))?a+`/* ${z} */'${e.src}'`:u),l.src=URL.createObjectURL (new Blob([l[x]],{type:'application/java'+t})),o.replaceWith(l)//inline</script> <script type="inline-module" id="utils"> let n = 1; export const log = message => { const output = document.createElement('pre'); output.textContent = `[${n++}] ${message}`; document.body.appendChild(output); }; </script> <script type="inline-module" id="dogs"> import {log} from '#utils'; log("Exporting dog names."); export const names = ["Kayla", "Bentley", "Gilligan"]; </script> <script type="inline-module"> import {log} from '#utils'; import {names as dogNames} from '#dogs'; log(`Imported dog names: ${dogNames.join(", ")}.`); </script> ``` Instead of `<script type="module">`, we need to define our script elements using a custom type like `<script type="inline-module">`. This prevents the browser from trying to execute their contents itself, leaving them for us to handle. The script (full version below) finds all `inline-module` script elements in the document, and transforms them into regular script module elements with the behaviour we want. Inline scripts can't be directly imported from each other, so we need to give the scripts importable URLs. We generate a `blob:` URL for each of them, containing their code, and set the `src` attribute to run from that URL instead of running inline. The `blob:` URLs acts like normal URLs from the server, so they can be imported from other modules. Each time we see a subsequent `inline-module` trying to import from `'#example'`, where `example` is the ID of a `inline-module` we've transformed, we modify that import to import from the `blob:` URL instead. This maintains the one-time execution and reference deduplication that modules are supposed to have. ```html <script type="module" id="dogs" src="blob:https://example.com/9dc17f20-04ab-44cd-906e"> import {log} from /* #utils */ 'blob:https://example.com/88fd6f1e-fdf4-4920-9a3b'; log("Exporting dog names."); export const names = ["Kayla", "Bentley", "Gilligan"]; </script> ``` The execution of module script elements is always deferred until after the document is parsed, so we don't need to worry about trying to support the way that traditional script elements can modify the document while it's still being parsed. ```js export {}; for (const original of document.querySelectorAll('script[type=inline-module]')) { const replacement = document.createElement('script'); // Preserve the ID so the element can be selected for import. if (original.id) { replacement.id = original.id; } replacement.type = 'module'; const transformedSource = original.textContent.replace( // Find anything that looks like an import from '#some-id'. /(from\s+|import\s+)['"](#[\w\-]+)['"]/g, (unmodified, action, selector) => { // If we can find a suitable script with that id... const refEl = document.querySelector('script[type=module][src]' + selector); return refEl ? // ..then update the import to use that script's src URL instead. `${action}/* ${selector} */ '${refEl.src}'` : unmodified; }); // Include the updated code in the src attribute as a blob URL that can be re-imported. replacement.src = URL.createObjectURL( new Blob([transformedSource], {type: 'application/javascript'})); // Insert the updated code inline, for debugging (it will be ignored). replacement.textContent = transformedSource; original.replaceWith(replacement); } ``` *Warnings:* this simple implementation doesn't handle script elements added after the initial document has been parsed, or allow script elements to import from other script elements that occur after them in the document. If you have both `module` and `inline-module` script elements in a document, their relative execution order may not be correct. The source code transformation is performed using a crude regex that won't handle some edge cases such as periods in IDs.
I don't believe that's possible. For inline scripts you're stuck with one of the more traditional ways of modularizing code, like the namespacing you demonstrated using object literals. With [webpack](https://en.wikipedia.org/wiki/Webpack) you can do [code splitting](https://webpack.js.org/guides/code-splitting/) which you could use to grab a very minimal chunk of code on page load and then incrementally grab the rest as needed. Webpack also has the advantage of allowing you to use the module syntax (plus a ton of other ES201X improvements) in way more environments than just Chrome Canary.
43,817,297
I've been experimenting with new [native ECMAScript module support](https://jakearchibald.com/2017/es-modules-in-browsers/) that has recently been added to browsers. It's pleasant to finally be able import scripts directly and cleanly from JavaScript. [**`/example.html`**](https://795258201.glitch.me/example.html) ```html <script type="module"> import {example} from '/example.js'; example(); </script> ``` [**`/example.js`**](https://795258201.glitch.me/example.js) ```js export function example() { document.body.appendChild(document.createTextNode("hello")); }; ``` However, this only allows me to import modules that are defined by separate **external** JavaScript files. I usually prefer to inline some scripts used for the initial rendering, so their requests don't block the rest of the page. With a traditional informally-structured library, that might look like this: [**`/inline-traditional.html`**](https://795258201.glitch.me/inline-traditional.html) ```html <body> <script> var example = {}; example.example = function() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script> example.example(); </script> ``` However, naively inlining modules files obviously won't work, since it would remove the filename used to identify the module to other modules. HTTP/2 server push may be the canonical way to handle this situation, but it's still not an option in all environments. Is it possible to perform an equivalent transformation with ECMAScript modules? Is there any way for a `<script type="module">` to import a module exported by another in the same document? --- I imagine this could work by allowing the script to specify a file path, and behave as though it had already been downloaded or pushed from the path. [**`/inline-name.html`**](https://795258201.glitch.me/inline-name.html) ```html <script type="module" name="/example.js"> export function example() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script type="module"> import {example} from '/example.js'; example(); </script> ``` Or maybe by an entirely different reference scheme, such as is used for local SVG references: [**`/inline-id.html`**](https://795258201.glitch.me/inline-id.html) ```html <script type="module" id="example"> export function example() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script type="module"> import {example} from '#example'; example(); </script> ``` But neither of these hypotheticals actually work, and I haven't seen an alternative which does.
2017/05/06
[ "https://Stackoverflow.com/questions/43817297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1114/" ]
This is possible with service workers. Since a service worker should be installed before it will be able to process a page, this requires to have a separate page to initialize a worker to avoid chicken/egg problem - or a page can reloaded when a worker is ready. Example ======= Here's a [demo](https://plnkr.co/edit/sun2hq3D5CLWrNflh6ek?p=info) that is supposed to be workable in modern browsers that support native ES modules and `async..await` (namely Chrome): *index.html* ``` <html> <head> <script> (async () => { try { const swInstalled = await navigator.serviceWorker.getRegistration('./'); await navigator.serviceWorker.register('sw.js', { scope: './' }) if (!swInstalled) { location.reload(); } } catch (err) { console.error('Worker not registered', err); } })(); </script> </head> <body> World, <script type="module" data-name="./example.js"> export function example() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script type="module"> import {example} from './example.js'; example(); </script> </body> </html> ``` *sw.js* ``` self.addEventListener('fetch', e => { // parsed pages if (/^https:\/\/run.plnkr.co\/\w+\/$/.test(e.request.url)) { e.respondWith(parseResponse(e.request)); // module files } else if (cachedModules.has(e.request.url)) { const moduleBody = cachedModules.get(e.request.url); const response = new Response(moduleBody, { headers: new Headers({ 'Content-Type' : 'text/javascript' }) } ); e.respondWith(response); } else { e.respondWith(fetch(e.request)); } }); const cachedModules = new Map(); async function parseResponse(request) { const response = await fetch(request); if (!response.body) return response; const html = await response.text(); // HTML response can be modified further const moduleRegex = /<script type="module" data-name="([\w./]+)">([\s\S]*?)<\/script>/; const moduleScripts = html.match(new RegExp(moduleRegex.source, 'g')) .map(moduleScript => moduleScript.match(moduleRegex)); for (const [, moduleName, moduleBody] of moduleScripts) { const moduleUrl = new URL(moduleName, request.url).href; cachedModules.set(moduleUrl, moduleBody); } const parsedResponse = new Response(html, response); return parsedResponse; } ``` Script bodies are being cached (native `Cache` can be used as well) and returned for respective module requests. Concerns -------- * The approach is inferior to the application built and chunked with bundling tool like Webpack or Rollup in terms of performance, flexibility, solidity and browser support - especially if blocking concurrent requests are the primary concern. * Inline scripts increase bandwidth usage. This is naturally avoided when scripts are loaded once and cached by the browser. * Inline scripts aren't modular and contradict the concept of ECMAScript modules (unless they are generated from real modules by server-side template). * Service worker initialization should be performed on a separate page to avoid unnecessary requests. * The solution is limited to a single page and doesn't take `<base>` into account. * A regular expression is used for demonstration purposes only. When used like in the example above **it enables the execution of arbitrary JavaScript code** that is available on the page. A proven library like `parse5` should be used instead (it will result in performance overhead, and still, there may be security concerns). **Never use regular expressions to parse the DOM**.
I don't believe that's possible. For inline scripts you're stuck with one of the more traditional ways of modularizing code, like the namespacing you demonstrated using object literals. With [webpack](https://en.wikipedia.org/wiki/Webpack) you can do [code splitting](https://webpack.js.org/guides/code-splitting/) which you could use to grab a very minimal chunk of code on page load and then incrementally grab the rest as needed. Webpack also has the advantage of allowing you to use the module syntax (plus a ton of other ES201X improvements) in way more environments than just Chrome Canary.
43,817,297
I've been experimenting with new [native ECMAScript module support](https://jakearchibald.com/2017/es-modules-in-browsers/) that has recently been added to browsers. It's pleasant to finally be able import scripts directly and cleanly from JavaScript. [**`/example.html`**](https://795258201.glitch.me/example.html) ```html <script type="module"> import {example} from '/example.js'; example(); </script> ``` [**`/example.js`**](https://795258201.glitch.me/example.js) ```js export function example() { document.body.appendChild(document.createTextNode("hello")); }; ``` However, this only allows me to import modules that are defined by separate **external** JavaScript files. I usually prefer to inline some scripts used for the initial rendering, so their requests don't block the rest of the page. With a traditional informally-structured library, that might look like this: [**`/inline-traditional.html`**](https://795258201.glitch.me/inline-traditional.html) ```html <body> <script> var example = {}; example.example = function() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script> example.example(); </script> ``` However, naively inlining modules files obviously won't work, since it would remove the filename used to identify the module to other modules. HTTP/2 server push may be the canonical way to handle this situation, but it's still not an option in all environments. Is it possible to perform an equivalent transformation with ECMAScript modules? Is there any way for a `<script type="module">` to import a module exported by another in the same document? --- I imagine this could work by allowing the script to specify a file path, and behave as though it had already been downloaded or pushed from the path. [**`/inline-name.html`**](https://795258201.glitch.me/inline-name.html) ```html <script type="module" name="/example.js"> export function example() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script type="module"> import {example} from '/example.js'; example(); </script> ``` Or maybe by an entirely different reference scheme, such as is used for local SVG references: [**`/inline-id.html`**](https://795258201.glitch.me/inline-id.html) ```html <script type="module" id="example"> export function example() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script type="module"> import {example} from '#example'; example(); </script> ``` But neither of these hypotheticals actually work, and I haven't seen an alternative which does.
2017/05/06
[ "https://Stackoverflow.com/questions/43817297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1114/" ]
I don't believe that's possible. For inline scripts you're stuck with one of the more traditional ways of modularizing code, like the namespacing you demonstrated using object literals. With [webpack](https://en.wikipedia.org/wiki/Webpack) you can do [code splitting](https://webpack.js.org/guides/code-splitting/) which you could use to grab a very minimal chunk of code on page load and then incrementally grab the rest as needed. Webpack also has the advantage of allowing you to use the module syntax (plus a ton of other ES201X improvements) in way more environments than just Chrome Canary.
We can use blob and importmap to import inline scripts. <https://github.com/xitu/inline-module> ```html <div id="app"></div> <script type="inline-module" id="foo"> const foo = 'bar'; export {foo}; </script> <script src="https://unpkg.com/inline-module/index.js" setup></script> <script type="module"> import {foo} from '#foo'; app.textContent = foo; </script> ```
43,817,297
I've been experimenting with new [native ECMAScript module support](https://jakearchibald.com/2017/es-modules-in-browsers/) that has recently been added to browsers. It's pleasant to finally be able import scripts directly and cleanly from JavaScript. [**`/example.html`**](https://795258201.glitch.me/example.html) ```html <script type="module"> import {example} from '/example.js'; example(); </script> ``` [**`/example.js`**](https://795258201.glitch.me/example.js) ```js export function example() { document.body.appendChild(document.createTextNode("hello")); }; ``` However, this only allows me to import modules that are defined by separate **external** JavaScript files. I usually prefer to inline some scripts used for the initial rendering, so their requests don't block the rest of the page. With a traditional informally-structured library, that might look like this: [**`/inline-traditional.html`**](https://795258201.glitch.me/inline-traditional.html) ```html <body> <script> var example = {}; example.example = function() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script> example.example(); </script> ``` However, naively inlining modules files obviously won't work, since it would remove the filename used to identify the module to other modules. HTTP/2 server push may be the canonical way to handle this situation, but it's still not an option in all environments. Is it possible to perform an equivalent transformation with ECMAScript modules? Is there any way for a `<script type="module">` to import a module exported by another in the same document? --- I imagine this could work by allowing the script to specify a file path, and behave as though it had already been downloaded or pushed from the path. [**`/inline-name.html`**](https://795258201.glitch.me/inline-name.html) ```html <script type="module" name="/example.js"> export function example() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script type="module"> import {example} from '/example.js'; example(); </script> ``` Or maybe by an entirely different reference scheme, such as is used for local SVG references: [**`/inline-id.html`**](https://795258201.glitch.me/inline-id.html) ```html <script type="module" id="example"> export function example() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script type="module"> import {example} from '#example'; example(); </script> ``` But neither of these hypotheticals actually work, and I haven't seen an alternative which does.
2017/05/06
[ "https://Stackoverflow.com/questions/43817297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1114/" ]
Hacking Together Our Own `import from '#id'` ============================================ Exports/imports between inline scripts aren't natively supported, but it was a fun exercise to hack together an implementation for my documents. Code-golfed down to a small block, I use it like this: ```html <script type="module" data-info="https://stackoverflow.com/a/43834063">let l,e,t ='script',p=/(from\s+|import\s+)['"](#[\w\-]+)['"]/g,x='textContent',d=document, s,o;for(o of d.querySelectorAll(t+'[type=inline-module]'))l=d.createElement(t),o .id?l.id=o.id:0,l.type='module',l[x]=o[x].replace(p,(u,a,z)=>(e=d.querySelector( t+z+'[type=module][src]'))?a+`/* ${z} */'${e.src}'`:u),l.src=URL.createObjectURL (new Blob([l[x]],{type:'application/java'+t})),o.replaceWith(l)//inline</script> <script type="inline-module" id="utils"> let n = 1; export const log = message => { const output = document.createElement('pre'); output.textContent = `[${n++}] ${message}`; document.body.appendChild(output); }; </script> <script type="inline-module" id="dogs"> import {log} from '#utils'; log("Exporting dog names."); export const names = ["Kayla", "Bentley", "Gilligan"]; </script> <script type="inline-module"> import {log} from '#utils'; import {names as dogNames} from '#dogs'; log(`Imported dog names: ${dogNames.join(", ")}.`); </script> ``` Instead of `<script type="module">`, we need to define our script elements using a custom type like `<script type="inline-module">`. This prevents the browser from trying to execute their contents itself, leaving them for us to handle. The script (full version below) finds all `inline-module` script elements in the document, and transforms them into regular script module elements with the behaviour we want. Inline scripts can't be directly imported from each other, so we need to give the scripts importable URLs. We generate a `blob:` URL for each of them, containing their code, and set the `src` attribute to run from that URL instead of running inline. The `blob:` URLs acts like normal URLs from the server, so they can be imported from other modules. Each time we see a subsequent `inline-module` trying to import from `'#example'`, where `example` is the ID of a `inline-module` we've transformed, we modify that import to import from the `blob:` URL instead. This maintains the one-time execution and reference deduplication that modules are supposed to have. ```html <script type="module" id="dogs" src="blob:https://example.com/9dc17f20-04ab-44cd-906e"> import {log} from /* #utils */ 'blob:https://example.com/88fd6f1e-fdf4-4920-9a3b'; log("Exporting dog names."); export const names = ["Kayla", "Bentley", "Gilligan"]; </script> ``` The execution of module script elements is always deferred until after the document is parsed, so we don't need to worry about trying to support the way that traditional script elements can modify the document while it's still being parsed. ```js export {}; for (const original of document.querySelectorAll('script[type=inline-module]')) { const replacement = document.createElement('script'); // Preserve the ID so the element can be selected for import. if (original.id) { replacement.id = original.id; } replacement.type = 'module'; const transformedSource = original.textContent.replace( // Find anything that looks like an import from '#some-id'. /(from\s+|import\s+)['"](#[\w\-]+)['"]/g, (unmodified, action, selector) => { // If we can find a suitable script with that id... const refEl = document.querySelector('script[type=module][src]' + selector); return refEl ? // ..then update the import to use that script's src URL instead. `${action}/* ${selector} */ '${refEl.src}'` : unmodified; }); // Include the updated code in the src attribute as a blob URL that can be re-imported. replacement.src = URL.createObjectURL( new Blob([transformedSource], {type: 'application/javascript'})); // Insert the updated code inline, for debugging (it will be ignored). replacement.textContent = transformedSource; original.replaceWith(replacement); } ``` *Warnings:* this simple implementation doesn't handle script elements added after the initial document has been parsed, or allow script elements to import from other script elements that occur after them in the document. If you have both `module` and `inline-module` script elements in a document, their relative execution order may not be correct. The source code transformation is performed using a crude regex that won't handle some edge cases such as periods in IDs.
This is possible with service workers. Since a service worker should be installed before it will be able to process a page, this requires to have a separate page to initialize a worker to avoid chicken/egg problem - or a page can reloaded when a worker is ready. Example ======= Here's a [demo](https://plnkr.co/edit/sun2hq3D5CLWrNflh6ek?p=info) that is supposed to be workable in modern browsers that support native ES modules and `async..await` (namely Chrome): *index.html* ``` <html> <head> <script> (async () => { try { const swInstalled = await navigator.serviceWorker.getRegistration('./'); await navigator.serviceWorker.register('sw.js', { scope: './' }) if (!swInstalled) { location.reload(); } } catch (err) { console.error('Worker not registered', err); } })(); </script> </head> <body> World, <script type="module" data-name="./example.js"> export function example() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script type="module"> import {example} from './example.js'; example(); </script> </body> </html> ``` *sw.js* ``` self.addEventListener('fetch', e => { // parsed pages if (/^https:\/\/run.plnkr.co\/\w+\/$/.test(e.request.url)) { e.respondWith(parseResponse(e.request)); // module files } else if (cachedModules.has(e.request.url)) { const moduleBody = cachedModules.get(e.request.url); const response = new Response(moduleBody, { headers: new Headers({ 'Content-Type' : 'text/javascript' }) } ); e.respondWith(response); } else { e.respondWith(fetch(e.request)); } }); const cachedModules = new Map(); async function parseResponse(request) { const response = await fetch(request); if (!response.body) return response; const html = await response.text(); // HTML response can be modified further const moduleRegex = /<script type="module" data-name="([\w./]+)">([\s\S]*?)<\/script>/; const moduleScripts = html.match(new RegExp(moduleRegex.source, 'g')) .map(moduleScript => moduleScript.match(moduleRegex)); for (const [, moduleName, moduleBody] of moduleScripts) { const moduleUrl = new URL(moduleName, request.url).href; cachedModules.set(moduleUrl, moduleBody); } const parsedResponse = new Response(html, response); return parsedResponse; } ``` Script bodies are being cached (native `Cache` can be used as well) and returned for respective module requests. Concerns -------- * The approach is inferior to the application built and chunked with bundling tool like Webpack or Rollup in terms of performance, flexibility, solidity and browser support - especially if blocking concurrent requests are the primary concern. * Inline scripts increase bandwidth usage. This is naturally avoided when scripts are loaded once and cached by the browser. * Inline scripts aren't modular and contradict the concept of ECMAScript modules (unless they are generated from real modules by server-side template). * Service worker initialization should be performed on a separate page to avoid unnecessary requests. * The solution is limited to a single page and doesn't take `<base>` into account. * A regular expression is used for demonstration purposes only. When used like in the example above **it enables the execution of arbitrary JavaScript code** that is available on the page. A proven library like `parse5` should be used instead (it will result in performance overhead, and still, there may be security concerns). **Never use regular expressions to parse the DOM**.
43,817,297
I've been experimenting with new [native ECMAScript module support](https://jakearchibald.com/2017/es-modules-in-browsers/) that has recently been added to browsers. It's pleasant to finally be able import scripts directly and cleanly from JavaScript. [**`/example.html`**](https://795258201.glitch.me/example.html) ```html <script type="module"> import {example} from '/example.js'; example(); </script> ``` [**`/example.js`**](https://795258201.glitch.me/example.js) ```js export function example() { document.body.appendChild(document.createTextNode("hello")); }; ``` However, this only allows me to import modules that are defined by separate **external** JavaScript files. I usually prefer to inline some scripts used for the initial rendering, so their requests don't block the rest of the page. With a traditional informally-structured library, that might look like this: [**`/inline-traditional.html`**](https://795258201.glitch.me/inline-traditional.html) ```html <body> <script> var example = {}; example.example = function() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script> example.example(); </script> ``` However, naively inlining modules files obviously won't work, since it would remove the filename used to identify the module to other modules. HTTP/2 server push may be the canonical way to handle this situation, but it's still not an option in all environments. Is it possible to perform an equivalent transformation with ECMAScript modules? Is there any way for a `<script type="module">` to import a module exported by another in the same document? --- I imagine this could work by allowing the script to specify a file path, and behave as though it had already been downloaded or pushed from the path. [**`/inline-name.html`**](https://795258201.glitch.me/inline-name.html) ```html <script type="module" name="/example.js"> export function example() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script type="module"> import {example} from '/example.js'; example(); </script> ``` Or maybe by an entirely different reference scheme, such as is used for local SVG references: [**`/inline-id.html`**](https://795258201.glitch.me/inline-id.html) ```html <script type="module" id="example"> export function example() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script type="module"> import {example} from '#example'; example(); </script> ``` But neither of these hypotheticals actually work, and I haven't seen an alternative which does.
2017/05/06
[ "https://Stackoverflow.com/questions/43817297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1114/" ]
Hacking Together Our Own `import from '#id'` ============================================ Exports/imports between inline scripts aren't natively supported, but it was a fun exercise to hack together an implementation for my documents. Code-golfed down to a small block, I use it like this: ```html <script type="module" data-info="https://stackoverflow.com/a/43834063">let l,e,t ='script',p=/(from\s+|import\s+)['"](#[\w\-]+)['"]/g,x='textContent',d=document, s,o;for(o of d.querySelectorAll(t+'[type=inline-module]'))l=d.createElement(t),o .id?l.id=o.id:0,l.type='module',l[x]=o[x].replace(p,(u,a,z)=>(e=d.querySelector( t+z+'[type=module][src]'))?a+`/* ${z} */'${e.src}'`:u),l.src=URL.createObjectURL (new Blob([l[x]],{type:'application/java'+t})),o.replaceWith(l)//inline</script> <script type="inline-module" id="utils"> let n = 1; export const log = message => { const output = document.createElement('pre'); output.textContent = `[${n++}] ${message}`; document.body.appendChild(output); }; </script> <script type="inline-module" id="dogs"> import {log} from '#utils'; log("Exporting dog names."); export const names = ["Kayla", "Bentley", "Gilligan"]; </script> <script type="inline-module"> import {log} from '#utils'; import {names as dogNames} from '#dogs'; log(`Imported dog names: ${dogNames.join(", ")}.`); </script> ``` Instead of `<script type="module">`, we need to define our script elements using a custom type like `<script type="inline-module">`. This prevents the browser from trying to execute their contents itself, leaving them for us to handle. The script (full version below) finds all `inline-module` script elements in the document, and transforms them into regular script module elements with the behaviour we want. Inline scripts can't be directly imported from each other, so we need to give the scripts importable URLs. We generate a `blob:` URL for each of them, containing their code, and set the `src` attribute to run from that URL instead of running inline. The `blob:` URLs acts like normal URLs from the server, so they can be imported from other modules. Each time we see a subsequent `inline-module` trying to import from `'#example'`, where `example` is the ID of a `inline-module` we've transformed, we modify that import to import from the `blob:` URL instead. This maintains the one-time execution and reference deduplication that modules are supposed to have. ```html <script type="module" id="dogs" src="blob:https://example.com/9dc17f20-04ab-44cd-906e"> import {log} from /* #utils */ 'blob:https://example.com/88fd6f1e-fdf4-4920-9a3b'; log("Exporting dog names."); export const names = ["Kayla", "Bentley", "Gilligan"]; </script> ``` The execution of module script elements is always deferred until after the document is parsed, so we don't need to worry about trying to support the way that traditional script elements can modify the document while it's still being parsed. ```js export {}; for (const original of document.querySelectorAll('script[type=inline-module]')) { const replacement = document.createElement('script'); // Preserve the ID so the element can be selected for import. if (original.id) { replacement.id = original.id; } replacement.type = 'module'; const transformedSource = original.textContent.replace( // Find anything that looks like an import from '#some-id'. /(from\s+|import\s+)['"](#[\w\-]+)['"]/g, (unmodified, action, selector) => { // If we can find a suitable script with that id... const refEl = document.querySelector('script[type=module][src]' + selector); return refEl ? // ..then update the import to use that script's src URL instead. `${action}/* ${selector} */ '${refEl.src}'` : unmodified; }); // Include the updated code in the src attribute as a blob URL that can be re-imported. replacement.src = URL.createObjectURL( new Blob([transformedSource], {type: 'application/javascript'})); // Insert the updated code inline, for debugging (it will be ignored). replacement.textContent = transformedSource; original.replaceWith(replacement); } ``` *Warnings:* this simple implementation doesn't handle script elements added after the initial document has been parsed, or allow script elements to import from other script elements that occur after them in the document. If you have both `module` and `inline-module` script elements in a document, their relative execution order may not be correct. The source code transformation is performed using a crude regex that won't handle some edge cases such as periods in IDs.
I tweaked [Jeremy's](https://stackoverflow.com/a/43834063/13052533) answer with the use of [this article to prevent scripts from executing](https://medium.com/snips-ai/how-to-block-third-party-scripts-with-a-few-lines-of-javascript-f0b08b9c4c0) ``` <script data-info="https://stackoverflow.com/a/43834063"> // awsome guy on [data-info] wrote 90% of this but I added the mutation/module-type part let l,e,t='script',p=/(from\s+|import\s+)['"](#[\w\-]+)['"]/g,x='textContent',d=document,s,o; let evls = event => ( event.target.type === 'javascript/blocked', event.preventDefault(), event.target.removeEventListener( 'beforescriptexecute', evls ) ) ;(new MutationObserver( mutations => mutations.forEach( ({ addedNodes }) => addedNodes.forEach( node => ( node.nodeType === 1 && node.matches( t+'[module-type=inline]' ) && ( node.type = 'javascript/blocked', node.addEventListener( 'beforescriptexecute', evls ), o = node, l=d.createElement(t), o.id?l.id=o.id:0, l.type='module', l[x]=o[x].replace(p,(u,a,z)=> (e=d.querySelector(t+z+'[type=module][src]')) ?a+`/* ${z} */'${e.src}'` :u), l.src=URL.createObjectURL( new Blob([l[x]], {type:'application/java'+t})), o.replaceWith(l) )//inline ) ) ))) .observe( document.documentElement, { childList: true, subtree: true } ) // for(o of d.querySelectorAll(t+'[module-type=inline]')) // l=d.createElement(t), // o.id?l.id=o.id:0, // l.type='module', // l[x]=o[x].replace(p,(u,a,z)=> // (e=d.querySelector(t+z+'[type=module][src]')) // ?a+`/* ${z} */'${e.src}'` // :u), // l.src=URL.createObjectURL( // new Blob([l[x]], // {type:'application/java'+t})), // o.replaceWith(l)//inline</script> ``` I'm hoping that this solves the dynamic-script-appending issue (using MutationObserver), vs-code not syntax-highlighting (preserving type=module) and I imagine that using the same MutationObserver one could execute scripts once the imported ids are added to the DOM. Please tell me if this has issues!
43,817,297
I've been experimenting with new [native ECMAScript module support](https://jakearchibald.com/2017/es-modules-in-browsers/) that has recently been added to browsers. It's pleasant to finally be able import scripts directly and cleanly from JavaScript. [**`/example.html`**](https://795258201.glitch.me/example.html) ```html <script type="module"> import {example} from '/example.js'; example(); </script> ``` [**`/example.js`**](https://795258201.glitch.me/example.js) ```js export function example() { document.body.appendChild(document.createTextNode("hello")); }; ``` However, this only allows me to import modules that are defined by separate **external** JavaScript files. I usually prefer to inline some scripts used for the initial rendering, so their requests don't block the rest of the page. With a traditional informally-structured library, that might look like this: [**`/inline-traditional.html`**](https://795258201.glitch.me/inline-traditional.html) ```html <body> <script> var example = {}; example.example = function() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script> example.example(); </script> ``` However, naively inlining modules files obviously won't work, since it would remove the filename used to identify the module to other modules. HTTP/2 server push may be the canonical way to handle this situation, but it's still not an option in all environments. Is it possible to perform an equivalent transformation with ECMAScript modules? Is there any way for a `<script type="module">` to import a module exported by another in the same document? --- I imagine this could work by allowing the script to specify a file path, and behave as though it had already been downloaded or pushed from the path. [**`/inline-name.html`**](https://795258201.glitch.me/inline-name.html) ```html <script type="module" name="/example.js"> export function example() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script type="module"> import {example} from '/example.js'; example(); </script> ``` Or maybe by an entirely different reference scheme, such as is used for local SVG references: [**`/inline-id.html`**](https://795258201.glitch.me/inline-id.html) ```html <script type="module" id="example"> export function example() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script type="module"> import {example} from '#example'; example(); </script> ``` But neither of these hypotheticals actually work, and I haven't seen an alternative which does.
2017/05/06
[ "https://Stackoverflow.com/questions/43817297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1114/" ]
Hacking Together Our Own `import from '#id'` ============================================ Exports/imports between inline scripts aren't natively supported, but it was a fun exercise to hack together an implementation for my documents. Code-golfed down to a small block, I use it like this: ```html <script type="module" data-info="https://stackoverflow.com/a/43834063">let l,e,t ='script',p=/(from\s+|import\s+)['"](#[\w\-]+)['"]/g,x='textContent',d=document, s,o;for(o of d.querySelectorAll(t+'[type=inline-module]'))l=d.createElement(t),o .id?l.id=o.id:0,l.type='module',l[x]=o[x].replace(p,(u,a,z)=>(e=d.querySelector( t+z+'[type=module][src]'))?a+`/* ${z} */'${e.src}'`:u),l.src=URL.createObjectURL (new Blob([l[x]],{type:'application/java'+t})),o.replaceWith(l)//inline</script> <script type="inline-module" id="utils"> let n = 1; export const log = message => { const output = document.createElement('pre'); output.textContent = `[${n++}] ${message}`; document.body.appendChild(output); }; </script> <script type="inline-module" id="dogs"> import {log} from '#utils'; log("Exporting dog names."); export const names = ["Kayla", "Bentley", "Gilligan"]; </script> <script type="inline-module"> import {log} from '#utils'; import {names as dogNames} from '#dogs'; log(`Imported dog names: ${dogNames.join(", ")}.`); </script> ``` Instead of `<script type="module">`, we need to define our script elements using a custom type like `<script type="inline-module">`. This prevents the browser from trying to execute their contents itself, leaving them for us to handle. The script (full version below) finds all `inline-module` script elements in the document, and transforms them into regular script module elements with the behaviour we want. Inline scripts can't be directly imported from each other, so we need to give the scripts importable URLs. We generate a `blob:` URL for each of them, containing their code, and set the `src` attribute to run from that URL instead of running inline. The `blob:` URLs acts like normal URLs from the server, so they can be imported from other modules. Each time we see a subsequent `inline-module` trying to import from `'#example'`, where `example` is the ID of a `inline-module` we've transformed, we modify that import to import from the `blob:` URL instead. This maintains the one-time execution and reference deduplication that modules are supposed to have. ```html <script type="module" id="dogs" src="blob:https://example.com/9dc17f20-04ab-44cd-906e"> import {log} from /* #utils */ 'blob:https://example.com/88fd6f1e-fdf4-4920-9a3b'; log("Exporting dog names."); export const names = ["Kayla", "Bentley", "Gilligan"]; </script> ``` The execution of module script elements is always deferred until after the document is parsed, so we don't need to worry about trying to support the way that traditional script elements can modify the document while it's still being parsed. ```js export {}; for (const original of document.querySelectorAll('script[type=inline-module]')) { const replacement = document.createElement('script'); // Preserve the ID so the element can be selected for import. if (original.id) { replacement.id = original.id; } replacement.type = 'module'; const transformedSource = original.textContent.replace( // Find anything that looks like an import from '#some-id'. /(from\s+|import\s+)['"](#[\w\-]+)['"]/g, (unmodified, action, selector) => { // If we can find a suitable script with that id... const refEl = document.querySelector('script[type=module][src]' + selector); return refEl ? // ..then update the import to use that script's src URL instead. `${action}/* ${selector} */ '${refEl.src}'` : unmodified; }); // Include the updated code in the src attribute as a blob URL that can be re-imported. replacement.src = URL.createObjectURL( new Blob([transformedSource], {type: 'application/javascript'})); // Insert the updated code inline, for debugging (it will be ignored). replacement.textContent = transformedSource; original.replaceWith(replacement); } ``` *Warnings:* this simple implementation doesn't handle script elements added after the initial document has been parsed, or allow script elements to import from other script elements that occur after them in the document. If you have both `module` and `inline-module` script elements in a document, their relative execution order may not be correct. The source code transformation is performed using a crude regex that won't handle some edge cases such as periods in IDs.
We can use blob and importmap to import inline scripts. <https://github.com/xitu/inline-module> ```html <div id="app"></div> <script type="inline-module" id="foo"> const foo = 'bar'; export {foo}; </script> <script src="https://unpkg.com/inline-module/index.js" setup></script> <script type="module"> import {foo} from '#foo'; app.textContent = foo; </script> ```
43,817,297
I've been experimenting with new [native ECMAScript module support](https://jakearchibald.com/2017/es-modules-in-browsers/) that has recently been added to browsers. It's pleasant to finally be able import scripts directly and cleanly from JavaScript. [**`/example.html`**](https://795258201.glitch.me/example.html) ```html <script type="module"> import {example} from '/example.js'; example(); </script> ``` [**`/example.js`**](https://795258201.glitch.me/example.js) ```js export function example() { document.body.appendChild(document.createTextNode("hello")); }; ``` However, this only allows me to import modules that are defined by separate **external** JavaScript files. I usually prefer to inline some scripts used for the initial rendering, so their requests don't block the rest of the page. With a traditional informally-structured library, that might look like this: [**`/inline-traditional.html`**](https://795258201.glitch.me/inline-traditional.html) ```html <body> <script> var example = {}; example.example = function() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script> example.example(); </script> ``` However, naively inlining modules files obviously won't work, since it would remove the filename used to identify the module to other modules. HTTP/2 server push may be the canonical way to handle this situation, but it's still not an option in all environments. Is it possible to perform an equivalent transformation with ECMAScript modules? Is there any way for a `<script type="module">` to import a module exported by another in the same document? --- I imagine this could work by allowing the script to specify a file path, and behave as though it had already been downloaded or pushed from the path. [**`/inline-name.html`**](https://795258201.glitch.me/inline-name.html) ```html <script type="module" name="/example.js"> export function example() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script type="module"> import {example} from '/example.js'; example(); </script> ``` Or maybe by an entirely different reference scheme, such as is used for local SVG references: [**`/inline-id.html`**](https://795258201.glitch.me/inline-id.html) ```html <script type="module" id="example"> export function example() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script type="module"> import {example} from '#example'; example(); </script> ``` But neither of these hypotheticals actually work, and I haven't seen an alternative which does.
2017/05/06
[ "https://Stackoverflow.com/questions/43817297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1114/" ]
This is possible with service workers. Since a service worker should be installed before it will be able to process a page, this requires to have a separate page to initialize a worker to avoid chicken/egg problem - or a page can reloaded when a worker is ready. Example ======= Here's a [demo](https://plnkr.co/edit/sun2hq3D5CLWrNflh6ek?p=info) that is supposed to be workable in modern browsers that support native ES modules and `async..await` (namely Chrome): *index.html* ``` <html> <head> <script> (async () => { try { const swInstalled = await navigator.serviceWorker.getRegistration('./'); await navigator.serviceWorker.register('sw.js', { scope: './' }) if (!swInstalled) { location.reload(); } } catch (err) { console.error('Worker not registered', err); } })(); </script> </head> <body> World, <script type="module" data-name="./example.js"> export function example() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script type="module"> import {example} from './example.js'; example(); </script> </body> </html> ``` *sw.js* ``` self.addEventListener('fetch', e => { // parsed pages if (/^https:\/\/run.plnkr.co\/\w+\/$/.test(e.request.url)) { e.respondWith(parseResponse(e.request)); // module files } else if (cachedModules.has(e.request.url)) { const moduleBody = cachedModules.get(e.request.url); const response = new Response(moduleBody, { headers: new Headers({ 'Content-Type' : 'text/javascript' }) } ); e.respondWith(response); } else { e.respondWith(fetch(e.request)); } }); const cachedModules = new Map(); async function parseResponse(request) { const response = await fetch(request); if (!response.body) return response; const html = await response.text(); // HTML response can be modified further const moduleRegex = /<script type="module" data-name="([\w./]+)">([\s\S]*?)<\/script>/; const moduleScripts = html.match(new RegExp(moduleRegex.source, 'g')) .map(moduleScript => moduleScript.match(moduleRegex)); for (const [, moduleName, moduleBody] of moduleScripts) { const moduleUrl = new URL(moduleName, request.url).href; cachedModules.set(moduleUrl, moduleBody); } const parsedResponse = new Response(html, response); return parsedResponse; } ``` Script bodies are being cached (native `Cache` can be used as well) and returned for respective module requests. Concerns -------- * The approach is inferior to the application built and chunked with bundling tool like Webpack or Rollup in terms of performance, flexibility, solidity and browser support - especially if blocking concurrent requests are the primary concern. * Inline scripts increase bandwidth usage. This is naturally avoided when scripts are loaded once and cached by the browser. * Inline scripts aren't modular and contradict the concept of ECMAScript modules (unless they are generated from real modules by server-side template). * Service worker initialization should be performed on a separate page to avoid unnecessary requests. * The solution is limited to a single page and doesn't take `<base>` into account. * A regular expression is used for demonstration purposes only. When used like in the example above **it enables the execution of arbitrary JavaScript code** that is available on the page. A proven library like `parse5` should be used instead (it will result in performance overhead, and still, there may be security concerns). **Never use regular expressions to parse the DOM**.
I tweaked [Jeremy's](https://stackoverflow.com/a/43834063/13052533) answer with the use of [this article to prevent scripts from executing](https://medium.com/snips-ai/how-to-block-third-party-scripts-with-a-few-lines-of-javascript-f0b08b9c4c0) ``` <script data-info="https://stackoverflow.com/a/43834063"> // awsome guy on [data-info] wrote 90% of this but I added the mutation/module-type part let l,e,t='script',p=/(from\s+|import\s+)['"](#[\w\-]+)['"]/g,x='textContent',d=document,s,o; let evls = event => ( event.target.type === 'javascript/blocked', event.preventDefault(), event.target.removeEventListener( 'beforescriptexecute', evls ) ) ;(new MutationObserver( mutations => mutations.forEach( ({ addedNodes }) => addedNodes.forEach( node => ( node.nodeType === 1 && node.matches( t+'[module-type=inline]' ) && ( node.type = 'javascript/blocked', node.addEventListener( 'beforescriptexecute', evls ), o = node, l=d.createElement(t), o.id?l.id=o.id:0, l.type='module', l[x]=o[x].replace(p,(u,a,z)=> (e=d.querySelector(t+z+'[type=module][src]')) ?a+`/* ${z} */'${e.src}'` :u), l.src=URL.createObjectURL( new Blob([l[x]], {type:'application/java'+t})), o.replaceWith(l) )//inline ) ) ))) .observe( document.documentElement, { childList: true, subtree: true } ) // for(o of d.querySelectorAll(t+'[module-type=inline]')) // l=d.createElement(t), // o.id?l.id=o.id:0, // l.type='module', // l[x]=o[x].replace(p,(u,a,z)=> // (e=d.querySelector(t+z+'[type=module][src]')) // ?a+`/* ${z} */'${e.src}'` // :u), // l.src=URL.createObjectURL( // new Blob([l[x]], // {type:'application/java'+t})), // o.replaceWith(l)//inline</script> ``` I'm hoping that this solves the dynamic-script-appending issue (using MutationObserver), vs-code not syntax-highlighting (preserving type=module) and I imagine that using the same MutationObserver one could execute scripts once the imported ids are added to the DOM. Please tell me if this has issues!
43,817,297
I've been experimenting with new [native ECMAScript module support](https://jakearchibald.com/2017/es-modules-in-browsers/) that has recently been added to browsers. It's pleasant to finally be able import scripts directly and cleanly from JavaScript. [**`/example.html`**](https://795258201.glitch.me/example.html) ```html <script type="module"> import {example} from '/example.js'; example(); </script> ``` [**`/example.js`**](https://795258201.glitch.me/example.js) ```js export function example() { document.body.appendChild(document.createTextNode("hello")); }; ``` However, this only allows me to import modules that are defined by separate **external** JavaScript files. I usually prefer to inline some scripts used for the initial rendering, so their requests don't block the rest of the page. With a traditional informally-structured library, that might look like this: [**`/inline-traditional.html`**](https://795258201.glitch.me/inline-traditional.html) ```html <body> <script> var example = {}; example.example = function() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script> example.example(); </script> ``` However, naively inlining modules files obviously won't work, since it would remove the filename used to identify the module to other modules. HTTP/2 server push may be the canonical way to handle this situation, but it's still not an option in all environments. Is it possible to perform an equivalent transformation with ECMAScript modules? Is there any way for a `<script type="module">` to import a module exported by another in the same document? --- I imagine this could work by allowing the script to specify a file path, and behave as though it had already been downloaded or pushed from the path. [**`/inline-name.html`**](https://795258201.glitch.me/inline-name.html) ```html <script type="module" name="/example.js"> export function example() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script type="module"> import {example} from '/example.js'; example(); </script> ``` Or maybe by an entirely different reference scheme, such as is used for local SVG references: [**`/inline-id.html`**](https://795258201.glitch.me/inline-id.html) ```html <script type="module" id="example"> export function example() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script type="module"> import {example} from '#example'; example(); </script> ``` But neither of these hypotheticals actually work, and I haven't seen an alternative which does.
2017/05/06
[ "https://Stackoverflow.com/questions/43817297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1114/" ]
This is possible with service workers. Since a service worker should be installed before it will be able to process a page, this requires to have a separate page to initialize a worker to avoid chicken/egg problem - or a page can reloaded when a worker is ready. Example ======= Here's a [demo](https://plnkr.co/edit/sun2hq3D5CLWrNflh6ek?p=info) that is supposed to be workable in modern browsers that support native ES modules and `async..await` (namely Chrome): *index.html* ``` <html> <head> <script> (async () => { try { const swInstalled = await navigator.serviceWorker.getRegistration('./'); await navigator.serviceWorker.register('sw.js', { scope: './' }) if (!swInstalled) { location.reload(); } } catch (err) { console.error('Worker not registered', err); } })(); </script> </head> <body> World, <script type="module" data-name="./example.js"> export function example() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script type="module"> import {example} from './example.js'; example(); </script> </body> </html> ``` *sw.js* ``` self.addEventListener('fetch', e => { // parsed pages if (/^https:\/\/run.plnkr.co\/\w+\/$/.test(e.request.url)) { e.respondWith(parseResponse(e.request)); // module files } else if (cachedModules.has(e.request.url)) { const moduleBody = cachedModules.get(e.request.url); const response = new Response(moduleBody, { headers: new Headers({ 'Content-Type' : 'text/javascript' }) } ); e.respondWith(response); } else { e.respondWith(fetch(e.request)); } }); const cachedModules = new Map(); async function parseResponse(request) { const response = await fetch(request); if (!response.body) return response; const html = await response.text(); // HTML response can be modified further const moduleRegex = /<script type="module" data-name="([\w./]+)">([\s\S]*?)<\/script>/; const moduleScripts = html.match(new RegExp(moduleRegex.source, 'g')) .map(moduleScript => moduleScript.match(moduleRegex)); for (const [, moduleName, moduleBody] of moduleScripts) { const moduleUrl = new URL(moduleName, request.url).href; cachedModules.set(moduleUrl, moduleBody); } const parsedResponse = new Response(html, response); return parsedResponse; } ``` Script bodies are being cached (native `Cache` can be used as well) and returned for respective module requests. Concerns -------- * The approach is inferior to the application built and chunked with bundling tool like Webpack or Rollup in terms of performance, flexibility, solidity and browser support - especially if blocking concurrent requests are the primary concern. * Inline scripts increase bandwidth usage. This is naturally avoided when scripts are loaded once and cached by the browser. * Inline scripts aren't modular and contradict the concept of ECMAScript modules (unless they are generated from real modules by server-side template). * Service worker initialization should be performed on a separate page to avoid unnecessary requests. * The solution is limited to a single page and doesn't take `<base>` into account. * A regular expression is used for demonstration purposes only. When used like in the example above **it enables the execution of arbitrary JavaScript code** that is available on the page. A proven library like `parse5` should be used instead (it will result in performance overhead, and still, there may be security concerns). **Never use regular expressions to parse the DOM**.
We can use blob and importmap to import inline scripts. <https://github.com/xitu/inline-module> ```html <div id="app"></div> <script type="inline-module" id="foo"> const foo = 'bar'; export {foo}; </script> <script src="https://unpkg.com/inline-module/index.js" setup></script> <script type="module"> import {foo} from '#foo'; app.textContent = foo; </script> ```
43,817,297
I've been experimenting with new [native ECMAScript module support](https://jakearchibald.com/2017/es-modules-in-browsers/) that has recently been added to browsers. It's pleasant to finally be able import scripts directly and cleanly from JavaScript. [**`/example.html`**](https://795258201.glitch.me/example.html) ```html <script type="module"> import {example} from '/example.js'; example(); </script> ``` [**`/example.js`**](https://795258201.glitch.me/example.js) ```js export function example() { document.body.appendChild(document.createTextNode("hello")); }; ``` However, this only allows me to import modules that are defined by separate **external** JavaScript files. I usually prefer to inline some scripts used for the initial rendering, so their requests don't block the rest of the page. With a traditional informally-structured library, that might look like this: [**`/inline-traditional.html`**](https://795258201.glitch.me/inline-traditional.html) ```html <body> <script> var example = {}; example.example = function() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script> example.example(); </script> ``` However, naively inlining modules files obviously won't work, since it would remove the filename used to identify the module to other modules. HTTP/2 server push may be the canonical way to handle this situation, but it's still not an option in all environments. Is it possible to perform an equivalent transformation with ECMAScript modules? Is there any way for a `<script type="module">` to import a module exported by another in the same document? --- I imagine this could work by allowing the script to specify a file path, and behave as though it had already been downloaded or pushed from the path. [**`/inline-name.html`**](https://795258201.glitch.me/inline-name.html) ```html <script type="module" name="/example.js"> export function example() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script type="module"> import {example} from '/example.js'; example(); </script> ``` Or maybe by an entirely different reference scheme, such as is used for local SVG references: [**`/inline-id.html`**](https://795258201.glitch.me/inline-id.html) ```html <script type="module" id="example"> export function example() { document.body.appendChild(document.createTextNode("hello")); }; </script> <script type="module"> import {example} from '#example'; example(); </script> ``` But neither of these hypotheticals actually work, and I haven't seen an alternative which does.
2017/05/06
[ "https://Stackoverflow.com/questions/43817297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1114/" ]
I tweaked [Jeremy's](https://stackoverflow.com/a/43834063/13052533) answer with the use of [this article to prevent scripts from executing](https://medium.com/snips-ai/how-to-block-third-party-scripts-with-a-few-lines-of-javascript-f0b08b9c4c0) ``` <script data-info="https://stackoverflow.com/a/43834063"> // awsome guy on [data-info] wrote 90% of this but I added the mutation/module-type part let l,e,t='script',p=/(from\s+|import\s+)['"](#[\w\-]+)['"]/g,x='textContent',d=document,s,o; let evls = event => ( event.target.type === 'javascript/blocked', event.preventDefault(), event.target.removeEventListener( 'beforescriptexecute', evls ) ) ;(new MutationObserver( mutations => mutations.forEach( ({ addedNodes }) => addedNodes.forEach( node => ( node.nodeType === 1 && node.matches( t+'[module-type=inline]' ) && ( node.type = 'javascript/blocked', node.addEventListener( 'beforescriptexecute', evls ), o = node, l=d.createElement(t), o.id?l.id=o.id:0, l.type='module', l[x]=o[x].replace(p,(u,a,z)=> (e=d.querySelector(t+z+'[type=module][src]')) ?a+`/* ${z} */'${e.src}'` :u), l.src=URL.createObjectURL( new Blob([l[x]], {type:'application/java'+t})), o.replaceWith(l) )//inline ) ) ))) .observe( document.documentElement, { childList: true, subtree: true } ) // for(o of d.querySelectorAll(t+'[module-type=inline]')) // l=d.createElement(t), // o.id?l.id=o.id:0, // l.type='module', // l[x]=o[x].replace(p,(u,a,z)=> // (e=d.querySelector(t+z+'[type=module][src]')) // ?a+`/* ${z} */'${e.src}'` // :u), // l.src=URL.createObjectURL( // new Blob([l[x]], // {type:'application/java'+t})), // o.replaceWith(l)//inline</script> ``` I'm hoping that this solves the dynamic-script-appending issue (using MutationObserver), vs-code not syntax-highlighting (preserving type=module) and I imagine that using the same MutationObserver one could execute scripts once the imported ids are added to the DOM. Please tell me if this has issues!
We can use blob and importmap to import inline scripts. <https://github.com/xitu/inline-module> ```html <div id="app"></div> <script type="inline-module" id="foo"> const foo = 'bar'; export {foo}; </script> <script src="https://unpkg.com/inline-module/index.js" setup></script> <script type="module"> import {foo} from '#foo'; app.textContent = foo; </script> ```
61,013,935
Given static 2 Given static 2-D array as follow: ``` int m[4][6]; ``` How do i access to `m[2][4]` without using operator[]?
2020/04/03
[ "https://Stackoverflow.com/questions/61013935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13212108/" ]
It turns out my python script wasn't fully closed- it was still running in task manager, so that's why the command prompt window wasn't able to close yet. For anyone who might need it: I was using python selenium in my script. At the end of the program, I had to switch my code : `browser.close() to browser.quit()` so that the `chromedriver.exe` wasn't still running in task manager.
exit command in this case won't work without arguments so I suggest you try: ``` exit /b ``` it will force the cmd window to close
61,013,935
Given static 2 Given static 2-D array as follow: ``` int m[4][6]; ``` How do i access to `m[2][4]` without using operator[]?
2020/04/03
[ "https://Stackoverflow.com/questions/61013935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13212108/" ]
It turns out my python script wasn't fully closed- it was still running in task manager, so that's why the command prompt window wasn't able to close yet. For anyone who might need it: I was using python selenium in my script. At the end of the program, I had to switch my code : `browser.close() to browser.quit()` so that the `chromedriver.exe` wasn't still running in task manager.
I think the start command is opening up your python interpreter. I simply write like this 1. `"C:\Users\abhic\AppData\Local\Programs\Python\Python36\python.exe" "C:\Users\abhic\Documents\sample.py"` 2. `exit` The first part in line 1 is the python interpreter location and the second inverted comma's contain the script location and second line is for exiting the cmd. My python version is 3.6 .
1,554,845
Is there a generally-accepted best practice for creating an event handler that unsubscribes itself? E.g., the first thing I came up with is something like: ``` // Foo.cs // ... Bar bar = new Bar(/* add'l req'd state */); EventHandler handler = new EventHandler(bar.HandlerMethod); bar.HandlerToUnsubscribe = handler; eventSource.EventName += handler; // ... ``` --- ``` // Bar.cs class Bar { /* add'l req'd state */ // .ctor public EventHandler HandlerToUnsubscribe { get; set; } public void HandlerMethod(object sender, EventArgs args) { // Do what must be done w/ add'l req'd state ((EventSourceType)sender).EventName -= this.HandlerToUnsubscribe; } } ``` --- To say that this feels hackish/bad is an understatement. It's tightly coupled with a temporal dependency (`HandlerToUnsubscribe` must be assigned the exact value at the exact right time). I feel like I must be playing the part of a complicator in this case--- is there something stupid or simple that I'm missing? Context: -------- I'm creating a binding between the UI and a proprietary commanding infrastructure in Winforms (using the useful `ICommand` in System.Windows.Input). One aspect of the binding infrastructure is that users who create a binding between a UI command component (like a toolbar button or menu item) have the option to listen to the command's `CanExecuteChanged` event and then update the UI's state based on that-- typically setting the Enabled property to `true` or `false`. The technique generally works quite well, but there are ways for the event to be fired prior to a ui component's handle having been created. I'm trying to guarantee that the provided handler isn't run unless the handle has been created. Resultantly, I'm considering providing a general helper class ("`Bar`") that will aid implementation. The goal of `Bar` is to check to see if the appropriate handle exists. If so, great! If not, it will subscribe to appropriate `IsHandleCreated` event so that the supplied handlers get run when the handle eventually is created. (This is important b/c the client may set their bindings in the UI's .ctor, before a handle exists.) I want this subscription to be completely transparent, however, and so I also want each event handler to automatically unsubscribe itself from `IsHandleCreated` once it's finished running. I'm still at a point where I'm trying to figure out if this is a good idea, so I haven't generalized the concept yet-- I've only implemented it directly against ToolStripItems in this case to verify that the idea is sound. I'm not sold on it yet, though. I understand that I also have the option of simply mandating that bindings can only be created once the UI's handle has been created, in the OnLoad event of a form (e.g.). I know that can work, I've done it in the past. I'd like to see if I can ease that particular requirement in this case though. If it's even practical.
2009/10/12
[ "https://Stackoverflow.com/questions/1554845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6932/" ]
You can use the run once method here, mentioned a few times here, but there are a couple problems with that, depending on your use case. 1) You may want to re-hook the method later again, and have it run once again. Though I suppose you can reset your bool 2) You still have that reference which could end up keeping your class in memory instead of being garbage collected. One option is to use an anonymous method and a closure when you define the event handling: ``` public class Foo { public EventHandler<EventArgs> MyEvent; public void FireEvent() { if(MyEvent != null) MyEvent(this, EventArgs.Empty); } } Foo obj = new Foo(); Action<object, EventArgs> action = new Action<object, EventArgs>((sender, args) => { // We're now running the event handler, so unsubscribe obj.MyEvent -= new EventHandler<EventArgs>(action); // Do whatever you wanted to do when the event fired. }); obj.MyEvent += new EventHandler<EventArgs>(action); ```
I usually do something like the following to implement a 1 time event handler. ``` void OnControlClickOneTime(this Control c, EventHandler e) { EventHandler e2 = null; e2 = (s,args) => { c.Click -= e2; e(s,args); }; c.Click += e2; } ```
1,554,845
Is there a generally-accepted best practice for creating an event handler that unsubscribes itself? E.g., the first thing I came up with is something like: ``` // Foo.cs // ... Bar bar = new Bar(/* add'l req'd state */); EventHandler handler = new EventHandler(bar.HandlerMethod); bar.HandlerToUnsubscribe = handler; eventSource.EventName += handler; // ... ``` --- ``` // Bar.cs class Bar { /* add'l req'd state */ // .ctor public EventHandler HandlerToUnsubscribe { get; set; } public void HandlerMethod(object sender, EventArgs args) { // Do what must be done w/ add'l req'd state ((EventSourceType)sender).EventName -= this.HandlerToUnsubscribe; } } ``` --- To say that this feels hackish/bad is an understatement. It's tightly coupled with a temporal dependency (`HandlerToUnsubscribe` must be assigned the exact value at the exact right time). I feel like I must be playing the part of a complicator in this case--- is there something stupid or simple that I'm missing? Context: -------- I'm creating a binding between the UI and a proprietary commanding infrastructure in Winforms (using the useful `ICommand` in System.Windows.Input). One aspect of the binding infrastructure is that users who create a binding between a UI command component (like a toolbar button or menu item) have the option to listen to the command's `CanExecuteChanged` event and then update the UI's state based on that-- typically setting the Enabled property to `true` or `false`. The technique generally works quite well, but there are ways for the event to be fired prior to a ui component's handle having been created. I'm trying to guarantee that the provided handler isn't run unless the handle has been created. Resultantly, I'm considering providing a general helper class ("`Bar`") that will aid implementation. The goal of `Bar` is to check to see if the appropriate handle exists. If so, great! If not, it will subscribe to appropriate `IsHandleCreated` event so that the supplied handlers get run when the handle eventually is created. (This is important b/c the client may set their bindings in the UI's .ctor, before a handle exists.) I want this subscription to be completely transparent, however, and so I also want each event handler to automatically unsubscribe itself from `IsHandleCreated` once it's finished running. I'm still at a point where I'm trying to figure out if this is a good idea, so I haven't generalized the concept yet-- I've only implemented it directly against ToolStripItems in this case to verify that the idea is sound. I'm not sold on it yet, though. I understand that I also have the option of simply mandating that bindings can only be created once the UI's handle has been created, in the OnLoad event of a form (e.g.). I know that can work, I've done it in the past. I'd like to see if I can ease that particular requirement in this case though. If it's even practical.
2009/10/12
[ "https://Stackoverflow.com/questions/1554845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6932/" ]
Greg, What you have **is not** an observer pattern, but rather a message queue. So you're just using the wrong design pattern for the problem you're trying to solve. Its easy enough to implement your own message queue from scratch using a `Queue{Action{object}}`, where objects enqueue themselves, and you simply dequeue items as you invoke them.
I usually do something like the following to implement a 1 time event handler. ``` void OnControlClickOneTime(this Control c, EventHandler e) { EventHandler e2 = null; e2 = (s,args) => { c.Click -= e2; e(s,args); }; c.Click += e2; } ```
1,554,845
Is there a generally-accepted best practice for creating an event handler that unsubscribes itself? E.g., the first thing I came up with is something like: ``` // Foo.cs // ... Bar bar = new Bar(/* add'l req'd state */); EventHandler handler = new EventHandler(bar.HandlerMethod); bar.HandlerToUnsubscribe = handler; eventSource.EventName += handler; // ... ``` --- ``` // Bar.cs class Bar { /* add'l req'd state */ // .ctor public EventHandler HandlerToUnsubscribe { get; set; } public void HandlerMethod(object sender, EventArgs args) { // Do what must be done w/ add'l req'd state ((EventSourceType)sender).EventName -= this.HandlerToUnsubscribe; } } ``` --- To say that this feels hackish/bad is an understatement. It's tightly coupled with a temporal dependency (`HandlerToUnsubscribe` must be assigned the exact value at the exact right time). I feel like I must be playing the part of a complicator in this case--- is there something stupid or simple that I'm missing? Context: -------- I'm creating a binding between the UI and a proprietary commanding infrastructure in Winforms (using the useful `ICommand` in System.Windows.Input). One aspect of the binding infrastructure is that users who create a binding between a UI command component (like a toolbar button or menu item) have the option to listen to the command's `CanExecuteChanged` event and then update the UI's state based on that-- typically setting the Enabled property to `true` or `false`. The technique generally works quite well, but there are ways for the event to be fired prior to a ui component's handle having been created. I'm trying to guarantee that the provided handler isn't run unless the handle has been created. Resultantly, I'm considering providing a general helper class ("`Bar`") that will aid implementation. The goal of `Bar` is to check to see if the appropriate handle exists. If so, great! If not, it will subscribe to appropriate `IsHandleCreated` event so that the supplied handlers get run when the handle eventually is created. (This is important b/c the client may set their bindings in the UI's .ctor, before a handle exists.) I want this subscription to be completely transparent, however, and so I also want each event handler to automatically unsubscribe itself from `IsHandleCreated` once it's finished running. I'm still at a point where I'm trying to figure out if this is a good idea, so I haven't generalized the concept yet-- I've only implemented it directly against ToolStripItems in this case to verify that the idea is sound. I'm not sold on it yet, though. I understand that I also have the option of simply mandating that bindings can only be created once the UI's handle has been created, in the OnLoad event of a form (e.g.). I know that can work, I've done it in the past. I'd like to see if I can ease that particular requirement in this case though. If it's even practical.
2009/10/12
[ "https://Stackoverflow.com/questions/1554845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6932/" ]
You can use the run once method here, mentioned a few times here, but there are a couple problems with that, depending on your use case. 1) You may want to re-hook the method later again, and have it run once again. Though I suppose you can reset your bool 2) You still have that reference which could end up keeping your class in memory instead of being garbage collected. One option is to use an anonymous method and a closure when you define the event handling: ``` public class Foo { public EventHandler<EventArgs> MyEvent; public void FireEvent() { if(MyEvent != null) MyEvent(this, EventArgs.Empty); } } Foo obj = new Foo(); Action<object, EventArgs> action = new Action<object, EventArgs>((sender, args) => { // We're now running the event handler, so unsubscribe obj.MyEvent -= new EventHandler<EventArgs>(action); // Do whatever you wanted to do when the event fired. }); obj.MyEvent += new EventHandler<EventArgs>(action); ```
You can use WeakReference objects to introduce so to say *weak subscribers*. During event firing you can check whether weak reference was already collected or not and remove this subscriber from the list of subscribers if necessary. The basic idea behind this is that when subscribers are GC collected, your handler will notice it and throw them away from the subscribers list.
1,554,845
Is there a generally-accepted best practice for creating an event handler that unsubscribes itself? E.g., the first thing I came up with is something like: ``` // Foo.cs // ... Bar bar = new Bar(/* add'l req'd state */); EventHandler handler = new EventHandler(bar.HandlerMethod); bar.HandlerToUnsubscribe = handler; eventSource.EventName += handler; // ... ``` --- ``` // Bar.cs class Bar { /* add'l req'd state */ // .ctor public EventHandler HandlerToUnsubscribe { get; set; } public void HandlerMethod(object sender, EventArgs args) { // Do what must be done w/ add'l req'd state ((EventSourceType)sender).EventName -= this.HandlerToUnsubscribe; } } ``` --- To say that this feels hackish/bad is an understatement. It's tightly coupled with a temporal dependency (`HandlerToUnsubscribe` must be assigned the exact value at the exact right time). I feel like I must be playing the part of a complicator in this case--- is there something stupid or simple that I'm missing? Context: -------- I'm creating a binding between the UI and a proprietary commanding infrastructure in Winforms (using the useful `ICommand` in System.Windows.Input). One aspect of the binding infrastructure is that users who create a binding between a UI command component (like a toolbar button or menu item) have the option to listen to the command's `CanExecuteChanged` event and then update the UI's state based on that-- typically setting the Enabled property to `true` or `false`. The technique generally works quite well, but there are ways for the event to be fired prior to a ui component's handle having been created. I'm trying to guarantee that the provided handler isn't run unless the handle has been created. Resultantly, I'm considering providing a general helper class ("`Bar`") that will aid implementation. The goal of `Bar` is to check to see if the appropriate handle exists. If so, great! If not, it will subscribe to appropriate `IsHandleCreated` event so that the supplied handlers get run when the handle eventually is created. (This is important b/c the client may set their bindings in the UI's .ctor, before a handle exists.) I want this subscription to be completely transparent, however, and so I also want each event handler to automatically unsubscribe itself from `IsHandleCreated` once it's finished running. I'm still at a point where I'm trying to figure out if this is a good idea, so I haven't generalized the concept yet-- I've only implemented it directly against ToolStripItems in this case to verify that the idea is sound. I'm not sold on it yet, though. I understand that I also have the option of simply mandating that bindings can only be created once the UI's handle has been created, in the OnLoad event of a form (e.g.). I know that can work, I've done it in the past. I'd like to see if I can ease that particular requirement in this case though. If it's even practical.
2009/10/12
[ "https://Stackoverflow.com/questions/1554845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6932/" ]
Greg, What you have **is not** an observer pattern, but rather a message queue. So you're just using the wrong design pattern for the problem you're trying to solve. Its easy enough to implement your own message queue from scratch using a `Queue{Action{object}}`, where objects enqueue themselves, and you simply dequeue items as you invoke them.
You can use the run once method here, mentioned a few times here, but there are a couple problems with that, depending on your use case. 1) You may want to re-hook the method later again, and have it run once again. Though I suppose you can reset your bool 2) You still have that reference which could end up keeping your class in memory instead of being garbage collected. One option is to use an anonymous method and a closure when you define the event handling: ``` public class Foo { public EventHandler<EventArgs> MyEvent; public void FireEvent() { if(MyEvent != null) MyEvent(this, EventArgs.Empty); } } Foo obj = new Foo(); Action<object, EventArgs> action = new Action<object, EventArgs>((sender, args) => { // We're now running the event handler, so unsubscribe obj.MyEvent -= new EventHandler<EventArgs>(action); // Do whatever you wanted to do when the event fired. }); obj.MyEvent += new EventHandler<EventArgs>(action); ```
1,554,845
Is there a generally-accepted best practice for creating an event handler that unsubscribes itself? E.g., the first thing I came up with is something like: ``` // Foo.cs // ... Bar bar = new Bar(/* add'l req'd state */); EventHandler handler = new EventHandler(bar.HandlerMethod); bar.HandlerToUnsubscribe = handler; eventSource.EventName += handler; // ... ``` --- ``` // Bar.cs class Bar { /* add'l req'd state */ // .ctor public EventHandler HandlerToUnsubscribe { get; set; } public void HandlerMethod(object sender, EventArgs args) { // Do what must be done w/ add'l req'd state ((EventSourceType)sender).EventName -= this.HandlerToUnsubscribe; } } ``` --- To say that this feels hackish/bad is an understatement. It's tightly coupled with a temporal dependency (`HandlerToUnsubscribe` must be assigned the exact value at the exact right time). I feel like I must be playing the part of a complicator in this case--- is there something stupid or simple that I'm missing? Context: -------- I'm creating a binding between the UI and a proprietary commanding infrastructure in Winforms (using the useful `ICommand` in System.Windows.Input). One aspect of the binding infrastructure is that users who create a binding between a UI command component (like a toolbar button or menu item) have the option to listen to the command's `CanExecuteChanged` event and then update the UI's state based on that-- typically setting the Enabled property to `true` or `false`. The technique generally works quite well, but there are ways for the event to be fired prior to a ui component's handle having been created. I'm trying to guarantee that the provided handler isn't run unless the handle has been created. Resultantly, I'm considering providing a general helper class ("`Bar`") that will aid implementation. The goal of `Bar` is to check to see if the appropriate handle exists. If so, great! If not, it will subscribe to appropriate `IsHandleCreated` event so that the supplied handlers get run when the handle eventually is created. (This is important b/c the client may set their bindings in the UI's .ctor, before a handle exists.) I want this subscription to be completely transparent, however, and so I also want each event handler to automatically unsubscribe itself from `IsHandleCreated` once it's finished running. I'm still at a point where I'm trying to figure out if this is a good idea, so I haven't generalized the concept yet-- I've only implemented it directly against ToolStripItems in this case to verify that the idea is sound. I'm not sold on it yet, though. I understand that I also have the option of simply mandating that bindings can only be created once the UI's handle has been created, in the OnLoad event of a form (e.g.). I know that can work, I've done it in the past. I'd like to see if I can ease that particular requirement in this case though. If it's even practical.
2009/10/12
[ "https://Stackoverflow.com/questions/1554845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6932/" ]
The usual way would be to store a boolean value as to whether it should run... ``` bool runMyEvent = true; void Handler(object sender, EventArgs e) { if (runMyEvent) { // handler here runMyEvent = false; } else { return; } } ```
I usually do something like the following to implement a 1 time event handler. ``` void OnControlClickOneTime(this Control c, EventHandler e) { EventHandler e2 = null; e2 = (s,args) => { c.Click -= e2; e(s,args); }; c.Click += e2; } ```
1,554,845
Is there a generally-accepted best practice for creating an event handler that unsubscribes itself? E.g., the first thing I came up with is something like: ``` // Foo.cs // ... Bar bar = new Bar(/* add'l req'd state */); EventHandler handler = new EventHandler(bar.HandlerMethod); bar.HandlerToUnsubscribe = handler; eventSource.EventName += handler; // ... ``` --- ``` // Bar.cs class Bar { /* add'l req'd state */ // .ctor public EventHandler HandlerToUnsubscribe { get; set; } public void HandlerMethod(object sender, EventArgs args) { // Do what must be done w/ add'l req'd state ((EventSourceType)sender).EventName -= this.HandlerToUnsubscribe; } } ``` --- To say that this feels hackish/bad is an understatement. It's tightly coupled with a temporal dependency (`HandlerToUnsubscribe` must be assigned the exact value at the exact right time). I feel like I must be playing the part of a complicator in this case--- is there something stupid or simple that I'm missing? Context: -------- I'm creating a binding between the UI and a proprietary commanding infrastructure in Winforms (using the useful `ICommand` in System.Windows.Input). One aspect of the binding infrastructure is that users who create a binding between a UI command component (like a toolbar button or menu item) have the option to listen to the command's `CanExecuteChanged` event and then update the UI's state based on that-- typically setting the Enabled property to `true` or `false`. The technique generally works quite well, but there are ways for the event to be fired prior to a ui component's handle having been created. I'm trying to guarantee that the provided handler isn't run unless the handle has been created. Resultantly, I'm considering providing a general helper class ("`Bar`") that will aid implementation. The goal of `Bar` is to check to see if the appropriate handle exists. If so, great! If not, it will subscribe to appropriate `IsHandleCreated` event so that the supplied handlers get run when the handle eventually is created. (This is important b/c the client may set their bindings in the UI's .ctor, before a handle exists.) I want this subscription to be completely transparent, however, and so I also want each event handler to automatically unsubscribe itself from `IsHandleCreated` once it's finished running. I'm still at a point where I'm trying to figure out if this is a good idea, so I haven't generalized the concept yet-- I've only implemented it directly against ToolStripItems in this case to verify that the idea is sound. I'm not sold on it yet, though. I understand that I also have the option of simply mandating that bindings can only be created once the UI's handle has been created, in the OnLoad event of a form (e.g.). I know that can work, I've done it in the past. I'd like to see if I can ease that particular requirement in this case though. If it's even practical.
2009/10/12
[ "https://Stackoverflow.com/questions/1554845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6932/" ]
You can use the run once method here, mentioned a few times here, but there are a couple problems with that, depending on your use case. 1) You may want to re-hook the method later again, and have it run once again. Though I suppose you can reset your bool 2) You still have that reference which could end up keeping your class in memory instead of being garbage collected. One option is to use an anonymous method and a closure when you define the event handling: ``` public class Foo { public EventHandler<EventArgs> MyEvent; public void FireEvent() { if(MyEvent != null) MyEvent(this, EventArgs.Empty); } } Foo obj = new Foo(); Action<object, EventArgs> action = new Action<object, EventArgs>((sender, args) => { // We're now running the event handler, so unsubscribe obj.MyEvent -= new EventHandler<EventArgs>(action); // Do whatever you wanted to do when the event fired. }); obj.MyEvent += new EventHandler<EventArgs>(action); ```
If it makes sense (and if you have access to the code that calls the handlers) maybe you could just remove all the events after you run the [handler](https://stackoverflow.com/questions/91778/how-to-remove-all-event-handlers-from-a-control). I don't know if this is a good idea either, just another thought.
1,554,845
Is there a generally-accepted best practice for creating an event handler that unsubscribes itself? E.g., the first thing I came up with is something like: ``` // Foo.cs // ... Bar bar = new Bar(/* add'l req'd state */); EventHandler handler = new EventHandler(bar.HandlerMethod); bar.HandlerToUnsubscribe = handler; eventSource.EventName += handler; // ... ``` --- ``` // Bar.cs class Bar { /* add'l req'd state */ // .ctor public EventHandler HandlerToUnsubscribe { get; set; } public void HandlerMethod(object sender, EventArgs args) { // Do what must be done w/ add'l req'd state ((EventSourceType)sender).EventName -= this.HandlerToUnsubscribe; } } ``` --- To say that this feels hackish/bad is an understatement. It's tightly coupled with a temporal dependency (`HandlerToUnsubscribe` must be assigned the exact value at the exact right time). I feel like I must be playing the part of a complicator in this case--- is there something stupid or simple that I'm missing? Context: -------- I'm creating a binding between the UI and a proprietary commanding infrastructure in Winforms (using the useful `ICommand` in System.Windows.Input). One aspect of the binding infrastructure is that users who create a binding between a UI command component (like a toolbar button or menu item) have the option to listen to the command's `CanExecuteChanged` event and then update the UI's state based on that-- typically setting the Enabled property to `true` or `false`. The technique generally works quite well, but there are ways for the event to be fired prior to a ui component's handle having been created. I'm trying to guarantee that the provided handler isn't run unless the handle has been created. Resultantly, I'm considering providing a general helper class ("`Bar`") that will aid implementation. The goal of `Bar` is to check to see if the appropriate handle exists. If so, great! If not, it will subscribe to appropriate `IsHandleCreated` event so that the supplied handlers get run when the handle eventually is created. (This is important b/c the client may set their bindings in the UI's .ctor, before a handle exists.) I want this subscription to be completely transparent, however, and so I also want each event handler to automatically unsubscribe itself from `IsHandleCreated` once it's finished running. I'm still at a point where I'm trying to figure out if this is a good idea, so I haven't generalized the concept yet-- I've only implemented it directly against ToolStripItems in this case to verify that the idea is sound. I'm not sold on it yet, though. I understand that I also have the option of simply mandating that bindings can only be created once the UI's handle has been created, in the OnLoad event of a form (e.g.). I know that can work, I've done it in the past. I'd like to see if I can ease that particular requirement in this case though. If it's even practical.
2009/10/12
[ "https://Stackoverflow.com/questions/1554845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6932/" ]
You can use the run once method here, mentioned a few times here, but there are a couple problems with that, depending on your use case. 1) You may want to re-hook the method later again, and have it run once again. Though I suppose you can reset your bool 2) You still have that reference which could end up keeping your class in memory instead of being garbage collected. One option is to use an anonymous method and a closure when you define the event handling: ``` public class Foo { public EventHandler<EventArgs> MyEvent; public void FireEvent() { if(MyEvent != null) MyEvent(this, EventArgs.Empty); } } Foo obj = new Foo(); Action<object, EventArgs> action = new Action<object, EventArgs>((sender, args) => { // We're now running the event handler, so unsubscribe obj.MyEvent -= new EventHandler<EventArgs>(action); // Do whatever you wanted to do when the event fired. }); obj.MyEvent += new EventHandler<EventArgs>(action); ```
There is a thorough article on CodeProject: [Weak events](http://www.codeproject.com/KB/cs/WeakEvents.aspx), which deals with several solutions to this problem.
1,554,845
Is there a generally-accepted best practice for creating an event handler that unsubscribes itself? E.g., the first thing I came up with is something like: ``` // Foo.cs // ... Bar bar = new Bar(/* add'l req'd state */); EventHandler handler = new EventHandler(bar.HandlerMethod); bar.HandlerToUnsubscribe = handler; eventSource.EventName += handler; // ... ``` --- ``` // Bar.cs class Bar { /* add'l req'd state */ // .ctor public EventHandler HandlerToUnsubscribe { get; set; } public void HandlerMethod(object sender, EventArgs args) { // Do what must be done w/ add'l req'd state ((EventSourceType)sender).EventName -= this.HandlerToUnsubscribe; } } ``` --- To say that this feels hackish/bad is an understatement. It's tightly coupled with a temporal dependency (`HandlerToUnsubscribe` must be assigned the exact value at the exact right time). I feel like I must be playing the part of a complicator in this case--- is there something stupid or simple that I'm missing? Context: -------- I'm creating a binding between the UI and a proprietary commanding infrastructure in Winforms (using the useful `ICommand` in System.Windows.Input). One aspect of the binding infrastructure is that users who create a binding between a UI command component (like a toolbar button or menu item) have the option to listen to the command's `CanExecuteChanged` event and then update the UI's state based on that-- typically setting the Enabled property to `true` or `false`. The technique generally works quite well, but there are ways for the event to be fired prior to a ui component's handle having been created. I'm trying to guarantee that the provided handler isn't run unless the handle has been created. Resultantly, I'm considering providing a general helper class ("`Bar`") that will aid implementation. The goal of `Bar` is to check to see if the appropriate handle exists. If so, great! If not, it will subscribe to appropriate `IsHandleCreated` event so that the supplied handlers get run when the handle eventually is created. (This is important b/c the client may set their bindings in the UI's .ctor, before a handle exists.) I want this subscription to be completely transparent, however, and so I also want each event handler to automatically unsubscribe itself from `IsHandleCreated` once it's finished running. I'm still at a point where I'm trying to figure out if this is a good idea, so I haven't generalized the concept yet-- I've only implemented it directly against ToolStripItems in this case to verify that the idea is sound. I'm not sold on it yet, though. I understand that I also have the option of simply mandating that bindings can only be created once the UI's handle has been created, in the OnLoad event of a form (e.g.). I know that can work, I've done it in the past. I'd like to see if I can ease that particular requirement in this case though. If it's even practical.
2009/10/12
[ "https://Stackoverflow.com/questions/1554845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6932/" ]
Greg, What you have **is not** an observer pattern, but rather a message queue. So you're just using the wrong design pattern for the problem you're trying to solve. Its easy enough to implement your own message queue from scratch using a `Queue{Action{object}}`, where objects enqueue themselves, and you simply dequeue items as you invoke them.
There is a thorough article on CodeProject: [Weak events](http://www.codeproject.com/KB/cs/WeakEvents.aspx), which deals with several solutions to this problem.
1,554,845
Is there a generally-accepted best practice for creating an event handler that unsubscribes itself? E.g., the first thing I came up with is something like: ``` // Foo.cs // ... Bar bar = new Bar(/* add'l req'd state */); EventHandler handler = new EventHandler(bar.HandlerMethod); bar.HandlerToUnsubscribe = handler; eventSource.EventName += handler; // ... ``` --- ``` // Bar.cs class Bar { /* add'l req'd state */ // .ctor public EventHandler HandlerToUnsubscribe { get; set; } public void HandlerMethod(object sender, EventArgs args) { // Do what must be done w/ add'l req'd state ((EventSourceType)sender).EventName -= this.HandlerToUnsubscribe; } } ``` --- To say that this feels hackish/bad is an understatement. It's tightly coupled with a temporal dependency (`HandlerToUnsubscribe` must be assigned the exact value at the exact right time). I feel like I must be playing the part of a complicator in this case--- is there something stupid or simple that I'm missing? Context: -------- I'm creating a binding between the UI and a proprietary commanding infrastructure in Winforms (using the useful `ICommand` in System.Windows.Input). One aspect of the binding infrastructure is that users who create a binding between a UI command component (like a toolbar button or menu item) have the option to listen to the command's `CanExecuteChanged` event and then update the UI's state based on that-- typically setting the Enabled property to `true` or `false`. The technique generally works quite well, but there are ways for the event to be fired prior to a ui component's handle having been created. I'm trying to guarantee that the provided handler isn't run unless the handle has been created. Resultantly, I'm considering providing a general helper class ("`Bar`") that will aid implementation. The goal of `Bar` is to check to see if the appropriate handle exists. If so, great! If not, it will subscribe to appropriate `IsHandleCreated` event so that the supplied handlers get run when the handle eventually is created. (This is important b/c the client may set their bindings in the UI's .ctor, before a handle exists.) I want this subscription to be completely transparent, however, and so I also want each event handler to automatically unsubscribe itself from `IsHandleCreated` once it's finished running. I'm still at a point where I'm trying to figure out if this is a good idea, so I haven't generalized the concept yet-- I've only implemented it directly against ToolStripItems in this case to verify that the idea is sound. I'm not sold on it yet, though. I understand that I also have the option of simply mandating that bindings can only be created once the UI's handle has been created, in the OnLoad event of a form (e.g.). I know that can work, I've done it in the past. I'd like to see if I can ease that particular requirement in this case though. If it's even practical.
2009/10/12
[ "https://Stackoverflow.com/questions/1554845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6932/" ]
how about a handler that runs only once? Something like this: ``` if (wasRun) return; wasRun = true; ```
I usually do something like the following to implement a 1 time event handler. ``` void OnControlClickOneTime(this Control c, EventHandler e) { EventHandler e2 = null; e2 = (s,args) => { c.Click -= e2; e(s,args); }; c.Click += e2; } ```
1,554,845
Is there a generally-accepted best practice for creating an event handler that unsubscribes itself? E.g., the first thing I came up with is something like: ``` // Foo.cs // ... Bar bar = new Bar(/* add'l req'd state */); EventHandler handler = new EventHandler(bar.HandlerMethod); bar.HandlerToUnsubscribe = handler; eventSource.EventName += handler; // ... ``` --- ``` // Bar.cs class Bar { /* add'l req'd state */ // .ctor public EventHandler HandlerToUnsubscribe { get; set; } public void HandlerMethod(object sender, EventArgs args) { // Do what must be done w/ add'l req'd state ((EventSourceType)sender).EventName -= this.HandlerToUnsubscribe; } } ``` --- To say that this feels hackish/bad is an understatement. It's tightly coupled with a temporal dependency (`HandlerToUnsubscribe` must be assigned the exact value at the exact right time). I feel like I must be playing the part of a complicator in this case--- is there something stupid or simple that I'm missing? Context: -------- I'm creating a binding between the UI and a proprietary commanding infrastructure in Winforms (using the useful `ICommand` in System.Windows.Input). One aspect of the binding infrastructure is that users who create a binding between a UI command component (like a toolbar button or menu item) have the option to listen to the command's `CanExecuteChanged` event and then update the UI's state based on that-- typically setting the Enabled property to `true` or `false`. The technique generally works quite well, but there are ways for the event to be fired prior to a ui component's handle having been created. I'm trying to guarantee that the provided handler isn't run unless the handle has been created. Resultantly, I'm considering providing a general helper class ("`Bar`") that will aid implementation. The goal of `Bar` is to check to see if the appropriate handle exists. If so, great! If not, it will subscribe to appropriate `IsHandleCreated` event so that the supplied handlers get run when the handle eventually is created. (This is important b/c the client may set their bindings in the UI's .ctor, before a handle exists.) I want this subscription to be completely transparent, however, and so I also want each event handler to automatically unsubscribe itself from `IsHandleCreated` once it's finished running. I'm still at a point where I'm trying to figure out if this is a good idea, so I haven't generalized the concept yet-- I've only implemented it directly against ToolStripItems in this case to verify that the idea is sound. I'm not sold on it yet, though. I understand that I also have the option of simply mandating that bindings can only be created once the UI's handle has been created, in the OnLoad event of a form (e.g.). I know that can work, I've done it in the past. I'd like to see if I can ease that particular requirement in this case though. If it's even practical.
2009/10/12
[ "https://Stackoverflow.com/questions/1554845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6932/" ]
Greg, What you have **is not** an observer pattern, but rather a message queue. So you're just using the wrong design pattern for the problem you're trying to solve. Its easy enough to implement your own message queue from scratch using a `Queue{Action{object}}`, where objects enqueue themselves, and you simply dequeue items as you invoke them.
If it makes sense (and if you have access to the code that calls the handlers) maybe you could just remove all the events after you run the [handler](https://stackoverflow.com/questions/91778/how-to-remove-all-event-handlers-from-a-control). I don't know if this is a good idea either, just another thought.
140,721
I work at an European company for 1,5 years now (50-100 employees) and I'm the only one in my job role. Management has a "learning by experience" mentality which means you just learn by doing, not by extended training. Because I need more challenges in my job role and because I have no one to learn from I requested if I could do a course to improve my knowledge and skills. (First course would be 1000 euros, second course 2500). Most of the study time would be outside office hours. This is the first paid education I'm asking for. They said I can't do it now because we have cash flow problems and it's not clear if the company will do well financially the coming months. If they would have, they'd pay me the course, but the cash flow problems occur quite frequently since we're having trouble finding sufficient customers. I already offered to pay a part of the course, but I don't want to pay it all myself because I think it will be of great value for my work. I also would prefer not to leave my job at the moment, but I'm not sure how long I should wait before they give me educational benefits. How can I handle this best?
2019/07/19
[ "https://workplace.stackexchange.com/questions/140721", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/57139/" ]
I think you already have the answer - the company has cash flow issues so dropping a few thousand euros on training that is essentially a "perk" is probably going to fall into the "luxury" rather than "essential" category. > > I already offered to pay a part of the course, but I don't want to pay it all myself because I think it will be of great value for my work. > > > From this I'm assuming they haven't agreed to your part-payment proposal? This might mean that it's a non-starter for now but might be worth re-proposing once the cash flow situation improves somewhat, in order for this to work though you are going to need to parlay the benefits of the course into business benefits *for the company*. And in this sort of environment these benefits need to be as specific and quantiative as possible - > > I think it will be of great value for my work > > > is a whole lot less persuasive than > > If I get qualification *A* that will mean we can take on jobs that want to do *B* - we missed out on *X* customers/projects last year because we weren't able to offer them *B* > > > Fuzzier benefits from education courses are still valuable of course, employee satisfaction (and therefore retention) and so on - but when a company is struggling for cash flow return on investment is king.
It sounds as though you have a pretty solid "no" on your employer investing in your future. Consider looking for a more challenging job in a larger, profitable company that supplements experiential learning with internal/external courses. Ask about company policy on this in your second or third interview — once you know they're interested in you. It might sound like: "I want to continue to develop my skills in X and Y. Do you provide work experience and internal/external courses that will help me do my job better and progress over time? What's your policy on employees using those benefits?"
360,612
I'm working on a toolkit (sort of a live-CD Lisp-in-a-Box) for people new to Common Lisp, and I want to make sure it is broadly satisfying. What is attractive to you about Lisp? What do/did/would you need to get you started and keep you interested? What I have so far: SBCL 10.22, Emacs 22.3, SLIME, and LTK bundled together and configured on a Linux live-CD that boots entirely to RAM. --- I've now released the result of this; it is available at the [Thnake website](http://www.jasonfruit.com/thnake).
2008/12/11
[ "https://Stackoverflow.com/questions/360612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21778/" ]
Everything in clbuild (<http://common-lisp.net/project/clbuild>) should be a good candidate to be included. Incidentally, all packages in your list except Emacs are also managed by clbuild. I think it'd be good if the collection of projects in clbuild could gather some momentum towards standard-common-lisp-library-hood.
This does: <http://www.joelonsoftware.com/articles/ThePerilsofJavaSchools.html> Of course I'd also like to learn more Python 3.0, erlang, and F#. I believe that functional languages (not to say that Python is a functional language) provide just a different perspective. The more perspective you have the better solutions you can architect. It is all about using the right tools for the job too, but if you don't at least have familiarity with something you might never think to solve a problem with a particular tool. I guess it goes back to the old saying that to a carpenter everything looks like a nail. I do not want to be hammering C# into everything when there are better solutions available. Also, times change and fads do with them.
360,612
I'm working on a toolkit (sort of a live-CD Lisp-in-a-Box) for people new to Common Lisp, and I want to make sure it is broadly satisfying. What is attractive to you about Lisp? What do/did/would you need to get you started and keep you interested? What I have so far: SBCL 10.22, Emacs 22.3, SLIME, and LTK bundled together and configured on a Linux live-CD that boots entirely to RAM. --- I've now released the result of this; it is available at the [Thnake website](http://www.jasonfruit.com/thnake).
2008/12/11
[ "https://Stackoverflow.com/questions/360612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21778/" ]
Emacs almost prevented me from learning Common Lisp. It took a lot of effort to slog through it. Emacs and SLIME are too much for a beginner and will never be broadly satisfying to beginners. If I want to learn a new programming language, I want everything else to stay out of my way while I learn it. The task of learning Lisp is hard enough without added technicalities and complications of setting up an environment. Isolate the variable. Set up SBCL with [rlwrap](http://utopia.knoware.nl/~hlub/uck/rlwrap/) or an equivalent. rlwrap supports very basic paren matching and history searching and can even do tab-completion. Not as fancy as SLIME but a beginner doesn't need SLIME. A beginner needs to be able to run `hello-world` without spending an hour fighting Emacs. Provide Emacs/SLIME as an option but don't require it.
Everything in clbuild (<http://common-lisp.net/project/clbuild>) should be a good candidate to be included. Incidentally, all packages in your list except Emacs are also managed by clbuild. I think it'd be good if the collection of projects in clbuild could gather some momentum towards standard-common-lisp-library-hood.
360,612
I'm working on a toolkit (sort of a live-CD Lisp-in-a-Box) for people new to Common Lisp, and I want to make sure it is broadly satisfying. What is attractive to you about Lisp? What do/did/would you need to get you started and keep you interested? What I have so far: SBCL 10.22, Emacs 22.3, SLIME, and LTK bundled together and configured on a Linux live-CD that boots entirely to RAM. --- I've now released the result of this; it is available at the [Thnake website](http://www.jasonfruit.com/thnake).
2008/12/11
[ "https://Stackoverflow.com/questions/360612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21778/" ]
Everything in clbuild (<http://common-lisp.net/project/clbuild>) should be a good candidate to be included. Incidentally, all packages in your list except Emacs are also managed by clbuild. I think it'd be good if the collection of projects in clbuild could gather some momentum towards standard-common-lisp-library-hood.
I think the idea of including tutorials is an excellent one. In addition to the ones already stated, there is both the easiest book for newbies on lisp (A Gentle Introduction to Symbolic Computation) and several **excellent** websites hiding out there on the web that people should know about. Here they are: * [A Gentle Introdiction to Symbolic Computation](http://www.cs.cmu.edu/~dst/LispBook/index.html) * [Learning Lisp](http://www.cs.sfu.ca/CC/310/pwfong/Lisp/) * [Casting Spels](http://lisperati.com/casting.html) * [Learning Lisp Fast](http://cs.gmu.edu/~sean/lisp/LispTutorial.html)
360,612
I'm working on a toolkit (sort of a live-CD Lisp-in-a-Box) for people new to Common Lisp, and I want to make sure it is broadly satisfying. What is attractive to you about Lisp? What do/did/would you need to get you started and keep you interested? What I have so far: SBCL 10.22, Emacs 22.3, SLIME, and LTK bundled together and configured on a Linux live-CD that boots entirely to RAM. --- I've now released the result of this; it is available at the [Thnake website](http://www.jasonfruit.com/thnake).
2008/12/11
[ "https://Stackoverflow.com/questions/360612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21778/" ]
I have some interest in learning Lisp, but I don't 'like' most of the resources available. How about extending this project to the creation of some sort of a "community" responsible for providing tutorials or something, in order to make Common Lisp more popular and easier to learn? Bad/weird/useless idea?
You should definitely add Vim too, configured with the [RainbowParenthsis](http://www.vim.org/scripts/script.php?script_id=1561) plugin. rlwrap for SBCL is a good idea, and so is (require :sb-aclrepl). Weblocks should come with cl-prevalence and maybe Elephant/BDB, too.
360,612
I'm working on a toolkit (sort of a live-CD Lisp-in-a-Box) for people new to Common Lisp, and I want to make sure it is broadly satisfying. What is attractive to you about Lisp? What do/did/would you need to get you started and keep you interested? What I have so far: SBCL 10.22, Emacs 22.3, SLIME, and LTK bundled together and configured on a Linux live-CD that boots entirely to RAM. --- I've now released the result of this; it is available at the [Thnake website](http://www.jasonfruit.com/thnake).
2008/12/11
[ "https://Stackoverflow.com/questions/360612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21778/" ]
My suggestion is to include an HTTP server like [Hunchentoot](http://www.weitz.de/hunchentoot/) and a popular web framework. I suspect that most people that want to learn Lisp these days do so because of reading Paul Graham, and wanting to mimic his success at building Viaweb, so being able to easily create and modify powerful web applications would be a strong selling point for your live CD.
This does: <http://www.joelonsoftware.com/articles/ThePerilsofJavaSchools.html> Of course I'd also like to learn more Python 3.0, erlang, and F#. I believe that functional languages (not to say that Python is a functional language) provide just a different perspective. The more perspective you have the better solutions you can architect. It is all about using the right tools for the job too, but if you don't at least have familiarity with something you might never think to solve a problem with a particular tool. I guess it goes back to the old saying that to a carpenter everything looks like a nail. I do not want to be hammering C# into everything when there are better solutions available. Also, times change and fads do with them.
360,612
I'm working on a toolkit (sort of a live-CD Lisp-in-a-Box) for people new to Common Lisp, and I want to make sure it is broadly satisfying. What is attractive to you about Lisp? What do/did/would you need to get you started and keep you interested? What I have so far: SBCL 10.22, Emacs 22.3, SLIME, and LTK bundled together and configured on a Linux live-CD that boots entirely to RAM. --- I've now released the result of this; it is available at the [Thnake website](http://www.jasonfruit.com/thnake).
2008/12/11
[ "https://Stackoverflow.com/questions/360612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21778/" ]
Everything in clbuild (<http://common-lisp.net/project/clbuild>) should be a good candidate to be included. Incidentally, all packages in your list except Emacs are also managed by clbuild. I think it'd be good if the collection of projects in clbuild could gather some momentum towards standard-common-lisp-library-hood.
Emacs does have a bit of a learning curve, but it is great for serious development -- no pesky mouse-driven gui bling in the way of the (text-based) code. Out-of-the-box CUA-mode is enabled these days (so C-x, C-c, C-v works "standard"), and there is a menu with file-operations like save, etc, so it shouldn't that hard of a slog, if it's all pre-packaged. But pre-configuring the .emacs file to ensure that CUA mode *is* enabled, SLIME doesn't have to be configured by the user etc. is a must -- plus perhpas more documentation within for the user for .emacs configs - links to EmacsWiki, etc. (hrm, if this is on a CD, it's unlikely that the user would be configuring it themselves, isn't it....)
360,612
I'm working on a toolkit (sort of a live-CD Lisp-in-a-Box) for people new to Common Lisp, and I want to make sure it is broadly satisfying. What is attractive to you about Lisp? What do/did/would you need to get you started and keep you interested? What I have so far: SBCL 10.22, Emacs 22.3, SLIME, and LTK bundled together and configured on a Linux live-CD that boots entirely to RAM. --- I've now released the result of this; it is available at the [Thnake website](http://www.jasonfruit.com/thnake).
2008/12/11
[ "https://Stackoverflow.com/questions/360612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21778/" ]
Emacs almost prevented me from learning Common Lisp. It took a lot of effort to slog through it. Emacs and SLIME are too much for a beginner and will never be broadly satisfying to beginners. If I want to learn a new programming language, I want everything else to stay out of my way while I learn it. The task of learning Lisp is hard enough without added technicalities and complications of setting up an environment. Isolate the variable. Set up SBCL with [rlwrap](http://utopia.knoware.nl/~hlub/uck/rlwrap/) or an equivalent. rlwrap supports very basic paren matching and history searching and can even do tab-completion. Not as fancy as SLIME but a beginner doesn't need SLIME. A beginner needs to be able to run `hello-world` without spending an hour fighting Emacs. Provide Emacs/SLIME as an option but don't require it.
As far as I undertand you are doing Thnake. Thank you for greate live distro! I tried it couple of days before and found it rather impressive and interesting. There are couple of things it obviously lacks, such as [LTK](http://www.peter-herth.de/ltk/) since you have already included Common Lisp and Tcl/Tk. And since there is gtk, you can include bindings and documentation for CL and Python. Also there is a need in Lisp Hyperspec, and preconfiguaration of Slime to use it. (Same for documentation for Python and Tcl) May be it would be better to add [emacs-w3m](http://www.emacswiki.org/emacs/emacs-w3m) for fast and convenient documentation browsing.
360,612
I'm working on a toolkit (sort of a live-CD Lisp-in-a-Box) for people new to Common Lisp, and I want to make sure it is broadly satisfying. What is attractive to you about Lisp? What do/did/would you need to get you started and keep you interested? What I have so far: SBCL 10.22, Emacs 22.3, SLIME, and LTK bundled together and configured on a Linux live-CD that boots entirely to RAM. --- I've now released the result of this; it is available at the [Thnake website](http://www.jasonfruit.com/thnake).
2008/12/11
[ "https://Stackoverflow.com/questions/360612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21778/" ]
Emacs does have a bit of a learning curve, but it is great for serious development -- no pesky mouse-driven gui bling in the way of the (text-based) code. Out-of-the-box CUA-mode is enabled these days (so C-x, C-c, C-v works "standard"), and there is a menu with file-operations like save, etc, so it shouldn't that hard of a slog, if it's all pre-packaged. But pre-configuring the .emacs file to ensure that CUA mode *is* enabled, SLIME doesn't have to be configured by the user etc. is a must -- plus perhpas more documentation within for the user for .emacs configs - links to EmacsWiki, etc. (hrm, if this is on a CD, it's unlikely that the user would be configuring it themselves, isn't it....)
I think the idea of including tutorials is an excellent one. In addition to the ones already stated, there is both the easiest book for newbies on lisp (A Gentle Introduction to Symbolic Computation) and several **excellent** websites hiding out there on the web that people should know about. Here they are: * [A Gentle Introdiction to Symbolic Computation](http://www.cs.cmu.edu/~dst/LispBook/index.html) * [Learning Lisp](http://www.cs.sfu.ca/CC/310/pwfong/Lisp/) * [Casting Spels](http://lisperati.com/casting.html) * [Learning Lisp Fast](http://cs.gmu.edu/~sean/lisp/LispTutorial.html)
360,612
I'm working on a toolkit (sort of a live-CD Lisp-in-a-Box) for people new to Common Lisp, and I want to make sure it is broadly satisfying. What is attractive to you about Lisp? What do/did/would you need to get you started and keep you interested? What I have so far: SBCL 10.22, Emacs 22.3, SLIME, and LTK bundled together and configured on a Linux live-CD that boots entirely to RAM. --- I've now released the result of this; it is available at the [Thnake website](http://www.jasonfruit.com/thnake).
2008/12/11
[ "https://Stackoverflow.com/questions/360612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21778/" ]
Reading [Paul Graham](http://paulgraham.com/) makes me want to learn Common Lisp. But if I actually sit down to try learning it, the urge subsides.
I think the idea of including tutorials is an excellent one. In addition to the ones already stated, there is both the easiest book for newbies on lisp (A Gentle Introduction to Symbolic Computation) and several **excellent** websites hiding out there on the web that people should know about. Here they are: * [A Gentle Introdiction to Symbolic Computation](http://www.cs.cmu.edu/~dst/LispBook/index.html) * [Learning Lisp](http://www.cs.sfu.ca/CC/310/pwfong/Lisp/) * [Casting Spels](http://lisperati.com/casting.html) * [Learning Lisp Fast](http://cs.gmu.edu/~sean/lisp/LispTutorial.html)
360,612
I'm working on a toolkit (sort of a live-CD Lisp-in-a-Box) for people new to Common Lisp, and I want to make sure it is broadly satisfying. What is attractive to you about Lisp? What do/did/would you need to get you started and keep you interested? What I have so far: SBCL 10.22, Emacs 22.3, SLIME, and LTK bundled together and configured on a Linux live-CD that boots entirely to RAM. --- I've now released the result of this; it is available at the [Thnake website](http://www.jasonfruit.com/thnake).
2008/12/11
[ "https://Stackoverflow.com/questions/360612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21778/" ]
I have some interest in learning Lisp, but I don't 'like' most of the resources available. How about extending this project to the creation of some sort of a "community" responsible for providing tutorials or something, in order to make Common Lisp more popular and easier to learn? Bad/weird/useless idea?
As far as I undertand you are doing Thnake. Thank you for greate live distro! I tried it couple of days before and found it rather impressive and interesting. There are couple of things it obviously lacks, such as [LTK](http://www.peter-herth.de/ltk/) since you have already included Common Lisp and Tcl/Tk. And since there is gtk, you can include bindings and documentation for CL and Python. Also there is a need in Lisp Hyperspec, and preconfiguaration of Slime to use it. (Same for documentation for Python and Tcl) May be it would be better to add [emacs-w3m](http://www.emacswiki.org/emacs/emacs-w3m) for fast and convenient documentation browsing.
47,065,731
pretty new to kubernetes/kops, I have followed the tutorial for kops on aws, and I have created a cluster. I'd like to run a very simple container from hub.docker on the cluster, how do I go about adding this container to the cluster? Is it in the cluster config file or will I need to add another image to the nodes.
2017/11/02
[ "https://Stackoverflow.com/questions/47065731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4118800/" ]
In Kubernetes, container could be run as Pod, which is a resource in Kubernetes. You could prepare a yaml or json file to create your pod with command `kubectl create -f $yourfile` Example could be found here <https://github.com/kubernetes/kubernetes/blob/master/examples/javaweb-tomcat-sidecar/javaweb.yaml> And for images by default, Kubernetes will pull images from Docker Hub, if not existing in your cluster, and also depends on your `ImagePullPolicy` You just need to specify your image at section `spec.containers.image` Hope this will help you.
1. For example to run the nginx web server in your cluster you can use the command line below, this will download image from docker hub and start the instance. kubectl run nginx --image=nginx --port=80 Here is command <https://kubernetes.io/docs/user-guide/kubectl/v1.8/>. To run your image change the nginx with your image name. 2. Other option is to create the deployment yaml file and run the container. > > > ``` > apiVersion: extensions/v1beta1 > kind: Deployment > metadata: > labels: > run: nginx > name: nginx > spec: > replicas: 2 > selector: > matchLabels: > run: nginx > strategy: > rollingUpdate: > maxSurge: 1 > maxUnavailable: 1 > type: RollingUpdate > template: > metadata: > labels: > run: nginx > tier: frontend > spec: > containers: > - image: nginx:1.10 > imagePullPolicy: IfNotPresent > name: nginx > lifecycle: > preStop: > exec: > command: ["/usr/sbin/nginx","-s","quit"] > restartPolicy: Always > terminationGracePeriodSeconds: 30 > > ``` > > store above file in `nginx.yaml` file then run it with kubectl command. `kubectl create -f nginx.yaml`
50,068,387
I have the problem that when I want to have an id for my database I generate a random number for this the bad thing is that it is repeated. ``` public void Iniciar() { Random r = new Random(); int prevnum = -1; for (int loop = 0; loop < 10; loop++) { do { num = r.Next(1000,9999); } while (num == prevnum); prevnum = num; } } ```
2018/04/27
[ "https://Stackoverflow.com/questions/50068387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9206372/" ]
If you are simply looking for unique IDs (and you don't require integers), you can use a UUID: ``` String id = Guid.NewGuid().ToString() ``` If you need a unique integer ID, you are better off using your database to generate them (such as mysql's `AUTO_INCREMENT`)
Simply: You cant, directly. `System.Random` can generate same number over and over again. If you still want to get 'unique random' numbers, you need to store generated numbers in a list, then check if newly generated number is in list. ``` using System; using System.Collections.Generic; class Program { public static int Main(string[] args) { var numbers = new List<int>(); Random rnd = new Random(); for (int n = 0; n < 20; n++) { int num = rnd.Next(1000, 9999); for (int i = 0; i < numbers.Count; i++) { if (num == numbers[i]) { while (num == numbers[i]) num = rnd.Next(1000, 9999); i = -1; } } numbers.Add(num); } // Uncomment if you want sorting // numbers.Sort(); // Print numbers so we can check that every entry is unique for (int i = 0; i < numbers.Count; i++) Console.WriteLine("Id: {0}", numbers[i]); return 0; } } ``` This code will try to generate random numbers if same number is generated before, then restart to check number with list. Pretty inefficient and does not works quite well with 'edge' numbers. (For example you try to generate a 20 entry list with only 19 random numbers)
1,691,607
I have a system that will allow users to send messages to thier clients. I want to limit the user to x amount of messages per day/week/month (depending on subscription). What is a good way to tally for the time period and reset the tally once the time period restarts? I would like to incorporate some sort of SQL job to reset the tally.
2009/11/07
[ "https://Stackoverflow.com/questions/1691607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77712/" ]
Perhaps your best bet is using [NHibernate](http://nhibernate.org). It's arguably the best "industry standard" when it comes to both commercial and open source ORMs. It has been around a long while to become really stable, is used in many enterprise companies, is based on the even better known Hibernate (java), but has fully been rewritten to make the best use of .NET features. ### NHibernate drawbacks This sounds like I'm an advocate of NHibernate. Perhaps I am. But NHibernate has a drawback: it has a steep learning curve and getting used to the many possibilities and choosing the right or "best" practice for your situation can be daunting, even for experienced developers. But that's the prize to pay for an enterprise-level ORM that's capable of virtually anything. ### NHibernate with FluentNHibernate rocks Many of these drawbacks and setup problems vaporize the minute you start using [Fluent Nhibernate](http://fluentnhibernate.org), personally, I hardly do without it anymore as it removes all the tediousness of NHibernate at once (almost). It makes working with NHibernate a breeze: just write your entities as POCOs and load them fully automatically to create your database, the associations etc (or don't create the schema if it's there already). Configure your database using the Fluent syntax. A very simple setup can look as basic as this: ``` // part of a default abstract setup class I use public ISessionFactory CreateSessionFactory() { return Fluently.Configure() .Database( MsSqlConfiguration.MsSql2008 .ConnectionString(c => c.Server(this.ServerName) .Database(this.DatabaseName) .Username(this.Username) .Password(this.Password) ) ) .Mappings(m => m.AutoMappings.Add(AutoMap.AssemblyOf<User>() // loads all POCOse .Where(t => t.Namespace == this.Namespace)) // here go the associations and constraints, // (or you can annotate them, or add them later) ) .ExposeConfiguration(CreateOrUpdateSchema) .BuildSessionFactory(); } // example of an entity // It _can_ be as simple as this, which generates the schema, the mappings ets // but you still have the flexibility to expand and to map using more complex // scenarios. It is not limited to just tables, you can map views, stored procedures // create triggers, associations, unique keys, constraints etc. // The Fluent docs help you step by step public class User { public virtual int Id { get; private set; } // autogens PK public virtual string Name { get; set; } // augogens Name col public virtual byte[] Picture { get; set; } // autogens Picture BLOB col public virtual List<UserSettings> Settings { get; set; } // autogens to many-to-one } public class UserSettings { public virtual int Id { get; private set: } // PK again public virtual int UserId { get; set; } // autogens FK public virtual User { get; set; } // autogens OO-mapping to User table } ``` which takes all POCO entities and automatically maps them, creates the configuration for the ORM and builds the schema in the database, provided the user has sufficient rights. One very powerful ability of Fluent (and NH to a lesser extend) is to update a database schema when you make any changes. ### Other aids to NHibernate Also on the upside: many auto generation tools exist (including the open source [MyGeneration](http://www.mygenerationsoftware.com/)) that can take your DB schema(s) from a simple ODBC or other connection and turn them into the correct entity classes, associations and HBM configuration files. Many of these tools are (partially) graphical design aids. ### Use S#arp for enforcing MVC + NH + NUnit best practices Make sure to read [NHibernate best practices](http://www.codeproject.com/KB/architecture/NHibernateBestPractices.aspx). It brings generics and DAO to the next level. You can also skip to the chase and dive deep with [S#arp](http://devlicio.us/blogs/billy_mccafferty/archive/2008/04/21/asp-net-mvc-best-practices-with-nhibernate-and-spring-net.aspx) ([download](http://www.codeplex.com/SharpArchitecture)), which is a framework that imposes all these best practices and adds NUnit to the mixture. Before I start using a new technology I usually want it well covered. NHibernate and Hibernate don't come short here. Many books explain (N)Hibernate from starter to professional, white papers are abundant and tool documentation is meanwhile rather excellent. ### About LINQ and NH LINQ and NHibernate have always gone well together through all types of `ICollection<>` which are used in the many-to-X mappings and other associations, but requires the data to be retrieved first which requires a good design (the cache helps here), otherwise it'll perform badly. This has been considered a sore point of NH ever since LINQ came about. Luckily, there's now a new kid in town: [NHibernate-LINQ](http://ayende.com/Blog/archive/2009/07/26/nhibernate-linq-1.0-released.aspx), which maps LINQ queries to `ICriteria` queries prior to submitting. ICriteria queries are well cached and this combination with LINQ is both very powerful and very performant. NH-LINQ is now part of the standard distribution. ### Disclaimer I've used NHibernate for a almost decade (first Java, later .NET). I've flirted with other ORM's both commercial and open source, but in the end always returned to NH (unless company policy demanded different, but that was rare). This story may sound a bit biased but the space here is too short to go into excruciating detail about how NHibernate compares to other technologies. It's very well possible that other ORM's better fit your need, especially if you never plan to use it in complex multi-database, multi-db-server or hard-to-map-to-OO legacy situations. For me, NH shines because it doesn't limit me in any which way and supports full roundtrip engineering, but your choice might turn out different if features of lighter ORM's that are discussed here weigh heavier for you. ***Update:** added code sample **Update:** expanded code sample, fixed typos and wording **Update:** little chapters, added LINQ part, added Disclaimer part*
Man..I'd go with the **entity framework**. It supports Linq. The entity framework 4.0 has major performance improvements over 3.5. It has everything that you require in your post. EF is more then a ORM it is a framework. I think nhibernate is a joke compared to the M$ entity framework. Nhibernate really dropped the ball for not including intellisense and making the setup easier. Many enterprise organizations have embraced entity framework as well. Entity framework can support any database that can be ran on windows because it has a feature to allow any vendor to create a provider for it. Do yourself a favor and go with EF.
1,691,607
I have a system that will allow users to send messages to thier clients. I want to limit the user to x amount of messages per day/week/month (depending on subscription). What is a good way to tally for the time period and reset the tally once the time period restarts? I would like to incorporate some sort of SQL job to reset the tally.
2009/11/07
[ "https://Stackoverflow.com/questions/1691607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77712/" ]
Just as a follow up to some of the answers here, there is NHibernate Linq spearheaded by the unbelievably prolific Oren Eini, AKA Ayende Rahien <http://ayende.com/Blog/archive/2009/07/26/nhibernate-linq-1.0-released.aspx> Haven't used it, but it looks very impressive. Seems like at some level it could even be a replacement for LINQ for SQL.
You could also look at [LLBLGen](http://LLBLGen.com) While it lacks a snappy name, it does have all the features you mentioned: It is drivers for most database version, Oracle and SQL and others It supports Linq, in that you can use Linq to query the LLBLgen generated objects It allows you to extend the generated objects, they are all partial classes
1,691,607
I have a system that will allow users to send messages to thier clients. I want to limit the user to x amount of messages per day/week/month (depending on subscription). What is a good way to tally for the time period and reset the tally once the time period restarts? I would like to incorporate some sort of SQL job to reset the tally.
2009/11/07
[ "https://Stackoverflow.com/questions/1691607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77712/" ]
Why not look at [subsonic](http://subsonicproject.com/)? I like it over the others because it's lightweight maps transparently to the database scheme (uses ActiveRecord) and fulfills all your requirements. > > It has to be very productive. > > > I think this is the job of every ORM? With subsonic you can use the Controller (for databinding) or just execute the Save method on any ORM object. > > It should allows me to extend the objects > > > Extending the generated classes is easy, they are all defined as partials. And you can even edit the templates. (They are T4 templates you include in your project, so you have complete control over how and what is generated) > > It has to be (at least allmost) > database agnostic > > > I think this is kinda basic for any ORM. Subsonic supports a lot of database of which the well knowns are: Oracle, mySql, MsSql, SqlLite, SqlCE. You can look at the database support list [here](http://subsonicproject.com/docs/Supported_Databases). > > It has to have not so much > configuration or must be based on > conventions > > > Yes, it is absolutely convention over configuraion or opinionated as they call it. For a summary of the conventions look [here](http://subsonicproject.com/docs/Conventions). > > It should allows me to work with Linq > > > Absolutely, since version 3.0 Linq is supported. For a comparisson between nhibernate, LinqToSql and subsonic read [this](http://subsonicproject.com/docs/Comparisons) It's actually a fair and up to date comparison and explicitly outlines the differences in the visions of the different ORM's. Things I miss in subsonic: * UnitOfWork support (you could solve this by using the support for transactions.) * IdentityMap support (your objects get cached in some scope (appdomain, threat, web request context, page lifetime, ...) Although you good argue if this is supposed to be part of the ORM, or of some caching layer. I heard hibernate supported both.
I know this question is almost 8 years old, but at least if there is a straggler to this question, they will get a more complete picture of the ORMs available. We've been using [Dapper](https://github.com/StackExchange/Dapper) for database access. It's very lightweight. It's extremely fast. I still get to write SQL (which is my preference). It automatically maps returned data into objects, even a dynamic object. You can add extensions that will insert, update, etc without the need for SQL. So you can build it up to more closely emulate a full ORM. Once you start using it, you'll be shocked how you lived without it. It should ship with the .NET framework. It's database agnostic, BUT the SQL you write may not be. So if you are writing your own SQL, you'd have to ensure it works on your target databases.
1,691,607
I have a system that will allow users to send messages to thier clients. I want to limit the user to x amount of messages per day/week/month (depending on subscription). What is a good way to tally for the time period and reset the tally once the time period restarts? I would like to incorporate some sort of SQL job to reset the tally.
2009/11/07
[ "https://Stackoverflow.com/questions/1691607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77712/" ]
I've used [Entity Framework](http://msdn.microsoft.com/en-us/library/aa697427(VS.80).aspx) for a couple of projects and really liked it. There admittedly were some kinks in the first version, particularly the way it dealt with foreign keys and stored procedures, but version 2, which is in beta and part of VS 2010 looks very promising.
You could also look at [LLBLGen](http://LLBLGen.com) While it lacks a snappy name, it does have all the features you mentioned: It is drivers for most database version, Oracle and SQL and others It supports Linq, in that you can use Linq to query the LLBLgen generated objects It allows you to extend the generated objects, they are all partial classes
1,691,607
I have a system that will allow users to send messages to thier clients. I want to limit the user to x amount of messages per day/week/month (depending on subscription). What is a good way to tally for the time period and reset the tally once the time period restarts? I would like to incorporate some sort of SQL job to reset the tally.
2009/11/07
[ "https://Stackoverflow.com/questions/1691607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77712/" ]
Given your requirements, I'd suggest checking out [Mindscape LightSpeed](http://www.mindscape.co.nz/products/lightspeed/default.aspx). It supports about eight or nine different databases, and is convention driven (with options for configuration), so is very easy to set up. It has a LINQ provider. It allows you to extend the classes with your own properties and methods: in particular it allows you to decouple the persistent model (the fields) from the API (the properties and methods) without breaking the convention over configuration approach.
Just as a follow up to some of the answers here, there is NHibernate Linq spearheaded by the unbelievably prolific Oren Eini, AKA Ayende Rahien <http://ayende.com/Blog/archive/2009/07/26/nhibernate-linq-1.0-released.aspx> Haven't used it, but it looks very impressive. Seems like at some level it could even be a replacement for LINQ for SQL.
1,691,607
I have a system that will allow users to send messages to thier clients. I want to limit the user to x amount of messages per day/week/month (depending on subscription). What is a good way to tally for the time period and reset the tally once the time period restarts? I would like to incorporate some sort of SQL job to reset the tally.
2009/11/07
[ "https://Stackoverflow.com/questions/1691607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77712/" ]
Just as a follow up to some of the answers here, there is NHibernate Linq spearheaded by the unbelievably prolific Oren Eini, AKA Ayende Rahien <http://ayende.com/Blog/archive/2009/07/26/nhibernate-linq-1.0-released.aspx> Haven't used it, but it looks very impressive. Seems like at some level it could even be a replacement for LINQ for SQL.
I know this question is almost 8 years old, but at least if there is a straggler to this question, they will get a more complete picture of the ORMs available. We've been using [Dapper](https://github.com/StackExchange/Dapper) for database access. It's very lightweight. It's extremely fast. I still get to write SQL (which is my preference). It automatically maps returned data into objects, even a dynamic object. You can add extensions that will insert, update, etc without the need for SQL. So you can build it up to more closely emulate a full ORM. Once you start using it, you'll be shocked how you lived without it. It should ship with the .NET framework. It's database agnostic, BUT the SQL you write may not be. So if you are writing your own SQL, you'd have to ensure it works on your target databases.
1,691,607
I have a system that will allow users to send messages to thier clients. I want to limit the user to x amount of messages per day/week/month (depending on subscription). What is a good way to tally for the time period and reset the tally once the time period restarts? I would like to incorporate some sort of SQL job to reset the tally.
2009/11/07
[ "https://Stackoverflow.com/questions/1691607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77712/" ]
Perhaps your best bet is using [NHibernate](http://nhibernate.org). It's arguably the best "industry standard" when it comes to both commercial and open source ORMs. It has been around a long while to become really stable, is used in many enterprise companies, is based on the even better known Hibernate (java), but has fully been rewritten to make the best use of .NET features. ### NHibernate drawbacks This sounds like I'm an advocate of NHibernate. Perhaps I am. But NHibernate has a drawback: it has a steep learning curve and getting used to the many possibilities and choosing the right or "best" practice for your situation can be daunting, even for experienced developers. But that's the prize to pay for an enterprise-level ORM that's capable of virtually anything. ### NHibernate with FluentNHibernate rocks Many of these drawbacks and setup problems vaporize the minute you start using [Fluent Nhibernate](http://fluentnhibernate.org), personally, I hardly do without it anymore as it removes all the tediousness of NHibernate at once (almost). It makes working with NHibernate a breeze: just write your entities as POCOs and load them fully automatically to create your database, the associations etc (or don't create the schema if it's there already). Configure your database using the Fluent syntax. A very simple setup can look as basic as this: ``` // part of a default abstract setup class I use public ISessionFactory CreateSessionFactory() { return Fluently.Configure() .Database( MsSqlConfiguration.MsSql2008 .ConnectionString(c => c.Server(this.ServerName) .Database(this.DatabaseName) .Username(this.Username) .Password(this.Password) ) ) .Mappings(m => m.AutoMappings.Add(AutoMap.AssemblyOf<User>() // loads all POCOse .Where(t => t.Namespace == this.Namespace)) // here go the associations and constraints, // (or you can annotate them, or add them later) ) .ExposeConfiguration(CreateOrUpdateSchema) .BuildSessionFactory(); } // example of an entity // It _can_ be as simple as this, which generates the schema, the mappings ets // but you still have the flexibility to expand and to map using more complex // scenarios. It is not limited to just tables, you can map views, stored procedures // create triggers, associations, unique keys, constraints etc. // The Fluent docs help you step by step public class User { public virtual int Id { get; private set; } // autogens PK public virtual string Name { get; set; } // augogens Name col public virtual byte[] Picture { get; set; } // autogens Picture BLOB col public virtual List<UserSettings> Settings { get; set; } // autogens to many-to-one } public class UserSettings { public virtual int Id { get; private set: } // PK again public virtual int UserId { get; set; } // autogens FK public virtual User { get; set; } // autogens OO-mapping to User table } ``` which takes all POCO entities and automatically maps them, creates the configuration for the ORM and builds the schema in the database, provided the user has sufficient rights. One very powerful ability of Fluent (and NH to a lesser extend) is to update a database schema when you make any changes. ### Other aids to NHibernate Also on the upside: many auto generation tools exist (including the open source [MyGeneration](http://www.mygenerationsoftware.com/)) that can take your DB schema(s) from a simple ODBC or other connection and turn them into the correct entity classes, associations and HBM configuration files. Many of these tools are (partially) graphical design aids. ### Use S#arp for enforcing MVC + NH + NUnit best practices Make sure to read [NHibernate best practices](http://www.codeproject.com/KB/architecture/NHibernateBestPractices.aspx). It brings generics and DAO to the next level. You can also skip to the chase and dive deep with [S#arp](http://devlicio.us/blogs/billy_mccafferty/archive/2008/04/21/asp-net-mvc-best-practices-with-nhibernate-and-spring-net.aspx) ([download](http://www.codeplex.com/SharpArchitecture)), which is a framework that imposes all these best practices and adds NUnit to the mixture. Before I start using a new technology I usually want it well covered. NHibernate and Hibernate don't come short here. Many books explain (N)Hibernate from starter to professional, white papers are abundant and tool documentation is meanwhile rather excellent. ### About LINQ and NH LINQ and NHibernate have always gone well together through all types of `ICollection<>` which are used in the many-to-X mappings and other associations, but requires the data to be retrieved first which requires a good design (the cache helps here), otherwise it'll perform badly. This has been considered a sore point of NH ever since LINQ came about. Luckily, there's now a new kid in town: [NHibernate-LINQ](http://ayende.com/Blog/archive/2009/07/26/nhibernate-linq-1.0-released.aspx), which maps LINQ queries to `ICriteria` queries prior to submitting. ICriteria queries are well cached and this combination with LINQ is both very powerful and very performant. NH-LINQ is now part of the standard distribution. ### Disclaimer I've used NHibernate for a almost decade (first Java, later .NET). I've flirted with other ORM's both commercial and open source, but in the end always returned to NH (unless company policy demanded different, but that was rare). This story may sound a bit biased but the space here is too short to go into excruciating detail about how NHibernate compares to other technologies. It's very well possible that other ORM's better fit your need, especially if you never plan to use it in complex multi-database, multi-db-server or hard-to-map-to-OO legacy situations. For me, NH shines because it doesn't limit me in any which way and supports full roundtrip engineering, but your choice might turn out different if features of lighter ORM's that are discussed here weigh heavier for you. ***Update:** added code sample **Update:** expanded code sample, fixed typos and wording **Update:** little chapters, added LINQ part, added Disclaimer part*
I suggest checking out NHibernate. <https://www.hibernate.org/343.html>
1,691,607
I have a system that will allow users to send messages to thier clients. I want to limit the user to x amount of messages per day/week/month (depending on subscription). What is a good way to tally for the time period and reset the tally once the time period restarts? I would like to incorporate some sort of SQL job to reset the tally.
2009/11/07
[ "https://Stackoverflow.com/questions/1691607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77712/" ]
Given your requirements, I'd suggest checking out [Mindscape LightSpeed](http://www.mindscape.co.nz/products/lightspeed/default.aspx). It supports about eight or nine different databases, and is convention driven (with options for configuration), so is very easy to set up. It has a LINQ provider. It allows you to extend the classes with your own properties and methods: in particular it allows you to decouple the persistent model (the fields) from the API (the properties and methods) without breaking the convention over configuration approach.
You could also look at [LLBLGen](http://LLBLGen.com) While it lacks a snappy name, it does have all the features you mentioned: It is drivers for most database version, Oracle and SQL and others It supports Linq, in that you can use Linq to query the LLBLgen generated objects It allows you to extend the generated objects, they are all partial classes
1,691,607
I have a system that will allow users to send messages to thier clients. I want to limit the user to x amount of messages per day/week/month (depending on subscription). What is a good way to tally for the time period and reset the tally once the time period restarts? I would like to incorporate some sort of SQL job to reset the tally.
2009/11/07
[ "https://Stackoverflow.com/questions/1691607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77712/" ]
Perhaps your best bet is using [NHibernate](http://nhibernate.org). It's arguably the best "industry standard" when it comes to both commercial and open source ORMs. It has been around a long while to become really stable, is used in many enterprise companies, is based on the even better known Hibernate (java), but has fully been rewritten to make the best use of .NET features. ### NHibernate drawbacks This sounds like I'm an advocate of NHibernate. Perhaps I am. But NHibernate has a drawback: it has a steep learning curve and getting used to the many possibilities and choosing the right or "best" practice for your situation can be daunting, even for experienced developers. But that's the prize to pay for an enterprise-level ORM that's capable of virtually anything. ### NHibernate with FluentNHibernate rocks Many of these drawbacks and setup problems vaporize the minute you start using [Fluent Nhibernate](http://fluentnhibernate.org), personally, I hardly do without it anymore as it removes all the tediousness of NHibernate at once (almost). It makes working with NHibernate a breeze: just write your entities as POCOs and load them fully automatically to create your database, the associations etc (or don't create the schema if it's there already). Configure your database using the Fluent syntax. A very simple setup can look as basic as this: ``` // part of a default abstract setup class I use public ISessionFactory CreateSessionFactory() { return Fluently.Configure() .Database( MsSqlConfiguration.MsSql2008 .ConnectionString(c => c.Server(this.ServerName) .Database(this.DatabaseName) .Username(this.Username) .Password(this.Password) ) ) .Mappings(m => m.AutoMappings.Add(AutoMap.AssemblyOf<User>() // loads all POCOse .Where(t => t.Namespace == this.Namespace)) // here go the associations and constraints, // (or you can annotate them, or add them later) ) .ExposeConfiguration(CreateOrUpdateSchema) .BuildSessionFactory(); } // example of an entity // It _can_ be as simple as this, which generates the schema, the mappings ets // but you still have the flexibility to expand and to map using more complex // scenarios. It is not limited to just tables, you can map views, stored procedures // create triggers, associations, unique keys, constraints etc. // The Fluent docs help you step by step public class User { public virtual int Id { get; private set; } // autogens PK public virtual string Name { get; set; } // augogens Name col public virtual byte[] Picture { get; set; } // autogens Picture BLOB col public virtual List<UserSettings> Settings { get; set; } // autogens to many-to-one } public class UserSettings { public virtual int Id { get; private set: } // PK again public virtual int UserId { get; set; } // autogens FK public virtual User { get; set; } // autogens OO-mapping to User table } ``` which takes all POCO entities and automatically maps them, creates the configuration for the ORM and builds the schema in the database, provided the user has sufficient rights. One very powerful ability of Fluent (and NH to a lesser extend) is to update a database schema when you make any changes. ### Other aids to NHibernate Also on the upside: many auto generation tools exist (including the open source [MyGeneration](http://www.mygenerationsoftware.com/)) that can take your DB schema(s) from a simple ODBC or other connection and turn them into the correct entity classes, associations and HBM configuration files. Many of these tools are (partially) graphical design aids. ### Use S#arp for enforcing MVC + NH + NUnit best practices Make sure to read [NHibernate best practices](http://www.codeproject.com/KB/architecture/NHibernateBestPractices.aspx). It brings generics and DAO to the next level. You can also skip to the chase and dive deep with [S#arp](http://devlicio.us/blogs/billy_mccafferty/archive/2008/04/21/asp-net-mvc-best-practices-with-nhibernate-and-spring-net.aspx) ([download](http://www.codeplex.com/SharpArchitecture)), which is a framework that imposes all these best practices and adds NUnit to the mixture. Before I start using a new technology I usually want it well covered. NHibernate and Hibernate don't come short here. Many books explain (N)Hibernate from starter to professional, white papers are abundant and tool documentation is meanwhile rather excellent. ### About LINQ and NH LINQ and NHibernate have always gone well together through all types of `ICollection<>` which are used in the many-to-X mappings and other associations, but requires the data to be retrieved first which requires a good design (the cache helps here), otherwise it'll perform badly. This has been considered a sore point of NH ever since LINQ came about. Luckily, there's now a new kid in town: [NHibernate-LINQ](http://ayende.com/Blog/archive/2009/07/26/nhibernate-linq-1.0-released.aspx), which maps LINQ queries to `ICriteria` queries prior to submitting. ICriteria queries are well cached and this combination with LINQ is both very powerful and very performant. NH-LINQ is now part of the standard distribution. ### Disclaimer I've used NHibernate for a almost decade (first Java, later .NET). I've flirted with other ORM's both commercial and open source, but in the end always returned to NH (unless company policy demanded different, but that was rare). This story may sound a bit biased but the space here is too short to go into excruciating detail about how NHibernate compares to other technologies. It's very well possible that other ORM's better fit your need, especially if you never plan to use it in complex multi-database, multi-db-server or hard-to-map-to-OO legacy situations. For me, NH shines because it doesn't limit me in any which way and supports full roundtrip engineering, but your choice might turn out different if features of lighter ORM's that are discussed here weigh heavier for you. ***Update:** added code sample **Update:** expanded code sample, fixed typos and wording **Update:** little chapters, added LINQ part, added Disclaimer part*
Why not look at [subsonic](http://subsonicproject.com/)? I like it over the others because it's lightweight maps transparently to the database scheme (uses ActiveRecord) and fulfills all your requirements. > > It has to be very productive. > > > I think this is the job of every ORM? With subsonic you can use the Controller (for databinding) or just execute the Save method on any ORM object. > > It should allows me to extend the objects > > > Extending the generated classes is easy, they are all defined as partials. And you can even edit the templates. (They are T4 templates you include in your project, so you have complete control over how and what is generated) > > It has to be (at least allmost) > database agnostic > > > I think this is kinda basic for any ORM. Subsonic supports a lot of database of which the well knowns are: Oracle, mySql, MsSql, SqlLite, SqlCE. You can look at the database support list [here](http://subsonicproject.com/docs/Supported_Databases). > > It has to have not so much > configuration or must be based on > conventions > > > Yes, it is absolutely convention over configuraion or opinionated as they call it. For a summary of the conventions look [here](http://subsonicproject.com/docs/Conventions). > > It should allows me to work with Linq > > > Absolutely, since version 3.0 Linq is supported. For a comparisson between nhibernate, LinqToSql and subsonic read [this](http://subsonicproject.com/docs/Comparisons) It's actually a fair and up to date comparison and explicitly outlines the differences in the visions of the different ORM's. Things I miss in subsonic: * UnitOfWork support (you could solve this by using the support for transactions.) * IdentityMap support (your objects get cached in some scope (appdomain, threat, web request context, page lifetime, ...) Although you good argue if this is supposed to be part of the ORM, or of some caching layer. I heard hibernate supported both.
1,691,607
I have a system that will allow users to send messages to thier clients. I want to limit the user to x amount of messages per day/week/month (depending on subscription). What is a good way to tally for the time period and reset the tally once the time period restarts? I would like to incorporate some sort of SQL job to reset the tally.
2009/11/07
[ "https://Stackoverflow.com/questions/1691607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77712/" ]
Why not look at [subsonic](http://subsonicproject.com/)? I like it over the others because it's lightweight maps transparently to the database scheme (uses ActiveRecord) and fulfills all your requirements. > > It has to be very productive. > > > I think this is the job of every ORM? With subsonic you can use the Controller (for databinding) or just execute the Save method on any ORM object. > > It should allows me to extend the objects > > > Extending the generated classes is easy, they are all defined as partials. And you can even edit the templates. (They are T4 templates you include in your project, so you have complete control over how and what is generated) > > It has to be (at least allmost) > database agnostic > > > I think this is kinda basic for any ORM. Subsonic supports a lot of database of which the well knowns are: Oracle, mySql, MsSql, SqlLite, SqlCE. You can look at the database support list [here](http://subsonicproject.com/docs/Supported_Databases). > > It has to have not so much > configuration or must be based on > conventions > > > Yes, it is absolutely convention over configuraion or opinionated as they call it. For a summary of the conventions look [here](http://subsonicproject.com/docs/Conventions). > > It should allows me to work with Linq > > > Absolutely, since version 3.0 Linq is supported. For a comparisson between nhibernate, LinqToSql and subsonic read [this](http://subsonicproject.com/docs/Comparisons) It's actually a fair and up to date comparison and explicitly outlines the differences in the visions of the different ORM's. Things I miss in subsonic: * UnitOfWork support (you could solve this by using the support for transactions.) * IdentityMap support (your objects get cached in some scope (appdomain, threat, web request context, page lifetime, ...) Although you good argue if this is supposed to be part of the ORM, or of some caching layer. I heard hibernate supported both.
You could also look at [LLBLGen](http://LLBLGen.com) While it lacks a snappy name, it does have all the features you mentioned: It is drivers for most database version, Oracle and SQL and others It supports Linq, in that you can use Linq to query the LLBLgen generated objects It allows you to extend the generated objects, they are all partial classes
11,202,485
In SQL Server, I need to design a `User` table. It should have a `UserID (int)`, a `RoleID (int)` and a `UserName (nvarchar(255))`. A user can be assigned with a name but possibly multiple roles so a `UserId` may correspond to multiple `RoleID`s. This makes it difficult to assign primary key to `UserID` as `UserID` may duplicate. Is there any better design other than breaking it up into multiple tables?
2012/06/26
[ "https://Stackoverflow.com/questions/11202485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1021306/" ]
You should have: ``` 1. a user table with UsertId(int), UserName (Varchar) 2. a role table with RoleId(int), RoleName(Varchar) 3. a user_role table with user_id(int), role_id(int) ``` And don't forget to add the proper indexing and foreign keys.
Ye, have a table Roles, then RolesUsers with UserID and RoleID, and lastly a Users table edit: where the UserID + RoleID in the RolesUsers are a composite key
48,095,096
Default `font-size` for my code is equivalent to `10px` or `0.625em`. So as per this rule, to set the font size of `<p>` as `7px` I can use `0.7em`. But in my case browser is taking the fixed font size of `9px` (checked in "computed" section of browser) even if I decrease the font size of `<p>` as `0.5em` or less. [![enter image description here](https://i.stack.imgur.com/7vqRv.png)](https://i.stack.imgur.com/7vqRv.png) ```css body { font-size: 0.625em; } h1 { font-size: 2.5em; } h2 { font-size: 1.875em; } p { font-size: 0.7em; } ``` ```html <h1>This is heading 1</h1> <h2>This is heading 2</h2> <p>This is a paragraph.</p> <p>Specifying the font-size in em allows all major browsers to resize the text. Unfortunately, there is still a problem with older versions of IE. When resizing the text, it becomes larger/smaller than it should.</p> ```
2018/01/04
[ "https://Stackoverflow.com/questions/48095096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8873934/" ]
If you want font sizes in strict relation to the root font size (which is set in a a rule for `html` , not for `body`, and should be in `px`), you have to use the `rem` unit or percent, but not `em` (which will be in relation for the default browser size of a particular element or its parent) Aditionally, most browsers have a "minimum font display" setting that prevents small sizes to become unreadable. Most likely this is set to 9px in your browser.
As you say ***font size of p as 7px I can use 0.7em***, which is not correct because here your default font size is 16px. if ``` 10px == 0.625em then 7px = (0.625/10)*7em = 0.4375em ``` And if you are using **`10px`** as your default font, you have to set the **`body`** and **`html`** font size in **`px`** i.e. **`10px`** ``` html, body { font-size: 10px; } ``` Check below snippet ```css html{ font-size: 10px; } h1 { font-size: 2.5em; } h2 { font-size: 1.875em; } p { font-size: 0.7em; } ``` ```html <h1>This is heading 1</h1> <h2>This is heading 2</h2> <p>This is a paragraph.</p> <p>Specifying the font-size in em allows all major browsers to resize the text. Unfortunately, there is still a problem with older versions of IE. When resizing the text, it becomes larger/smaller than it should.</p> ```