qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
43,349,346
Here is what I have for the date Parameter. ``` =dateadd("m",0,dateserial(year(Today),month(Today),0)) ``` I need to set the time to 11:59:59 PM
2017/04/11
[ "https://Stackoverflow.com/questions/43349346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7851460/" ]
When you defined `f`, it decided that the reference to `g` was a global name lookup. Furthermore, it retained a reference to the global environment in effect at the point of definition (that's what lets you call functions in other modules without depriving them of their original globals). When you then deleted `g`, you fundamentally broke `f` - this global lookup of `g` will now fail. The global/local environment parameters to your `exec` call do not have ANY effect whatsoever on the already-compiled function `f`. They only affect the actual text that you exec'ed: `"f(2)"`. In other words, the only name lookup that actually uses the environment you provided is that of `f` itself.
The problem is can be seen by looking at the bytecode compiled from the definition of function `f()` using `dis.dis(f)`: ```none 7 0 LOAD_GLOBAL 0 (g) 2 LOAD_FAST 0 (x) 4 CALL_FUNCTION 1 6 LOAD_CONST 1 (3) 8 BINARY_MULTIPLY 10 RETURN_VALUE ``` As you can see, the first instruction tries to load a **global** named `g`. One way to make it work would be to make `g()` a local function: ``` def f(x): def g(x): return x**2 return g(x)*3 funcs = {"f": f} del globals()['f'] # to keep it out of the global environment print(eval("f(2)", globals(), funcs)) # -> 12 ``` Here's the bytecode from the revised `f()` for comparison: ```none 8 0 LOAD_CONST 1 (<code object g at 0x00546288, file "test.py">) 2 LOAD_CONST 2 ('f.<locals>.g') 4 MAKE_FUNCTION 0 6 STORE_FAST 1 (g) 11 8 LOAD_FAST 1 (g) 10 LOAD_FAST 0 (x) 12 CALL_FUNCTION 1 14 LOAD_CONST 3 (3) 16 BINARY_MULTIPLY 18 RETURN_VALUE ```
18,744,554
For start what I am trying to do i am not even sure that is possible(looks that is) In the feature of image assets in Xcode you can select for an imageSet to be either Universal or Device Specific. When I am doing it Device Specific and select both iphone and Retina 4 and assign pics to all , it is always selected the iphone retina image and never the Retina 4 when I am using an iphone 5(device or simulator) Have searched docs but couldnt find something. Thanks
2013/09/11
[ "https://Stackoverflow.com/questions/18744554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1117453/" ]
The "R4" image will only work on 4-inch iPhone running iOS 7 or later. On older version of iOS it will use 2x image. Example. If you use images like this: ![Xcode 5 screenshot](https://i.stack.imgur.com/PGJJT.png) you will see: * iPhone 5 iOS >= 7 - number 3, * iPhone 5 iOS < 7 - number 2, * iPhone 4, 4S - number 2, * iPhone 3GS - number 1, * iPhone 5C and 5S - number 3.
In my experience, this is the case whenever you do not target specifically iOS 7.0 in your Deployment Target as part of your Project/Workspace settings. ![iOS 6.1 targeted - needs iOS 7.0!](https://i.stack.imgur.com/wLnRi.png) Targeting anything other than 7.0 seems to result in this behavior. To clarify: this value essentially specifies the minimum version of iOS that is allowed to run your app. Specifying iOS 7.0 in this field will restrict use of your app/update to ONLY users with iOS 7.0.
12,461
One of my neighbors raised the topic of toxins in the dryer effluence from our buildings' laundry rooms. That's not particularly surprising, but she claimed there was evidence that the trace toxins in the air are dangerous. It sounded just plausible enough to to possible, especially given the volume of laundry done, but, given the source, I decided to check into it before I worried. Turns out there are plenty of examples of people claiming this is a serious health hazard: 1. [Holistic Help: Chemicals Found in Dryer Exhaust and There (sic) Toxicology](https://www.holistichelp.net/blog/toxic-chemicals-in-dryer-exhaust/) 2. [Mercola: The Household Appliance that Releases 600 Potentially Dangerous Chemicals into the Air](https://articles.mercola.com/sites/articles/archive/2022/03/26/ukraine-on-fire.aspx) 3. [Natural Life Magazine: Are Soft Clothes Really Worth It?](https://web.archive.org/web/20210126193756/http://www.naturallifemagazine.com/0608/softener.htm) 4. [One Christian Ministry: Clothes Dryer Vent Exhaust Poisoning USA Neighborhoods, Families, Children](https://web.archive.org/web/20130417063347/http://www.onechristianministry.com/healthy-life-585.html) 5. [Invisible Disabilities: Why Fragrance Free?](https://invisibledisabilities.org/publications/chemicalsensitivities/whygofragrancefree/) The only basis for most of which seems to be, when they bother to cite a source, this 2011 study, [Chemical emissions from residential dryer vents during use of fragranced laundry products](https://doi.org/10.1007%2Fs11869-011-0156-1?from=SL) which did find toxins (again, not surprising). According to the [press release](https://www.washington.edu/news/2011/08/24/scented-laundry-products-emit-hazardous-chemicals-through-dryer-vents/), they went so far as to call dryer effluence a pollutant. There's also [this older EPA study](https://cfpub.epa.gov/si/si_public_record_report.cfm?Lab=NERL&dirEntryId=44765&fed_org_id=770&SIType=PR&TIMSType=&showCriteria=0&address=nerl&view=citation&personID=862&role=Author&sortBy=pubDateYear&count=100&dateBeginPublishedPresented=) cited by the Invisible Disabilities article. What I haven't seen is anything which says these emissions are actually dangerous to people in the concentrations that are actually present. Most of this seems like a lot of overreaching and overreacting, but I'd like to know more if there is more to know.
2012/11/02
[ "https://skeptics.stackexchange.com/questions/12461", "https://skeptics.stackexchange.com", "https://skeptics.stackexchange.com/users/4415/" ]
Not even close to dangerous enough to worry about ------------------------------------------------- I looked up the Material Safety data Sheet ([MSDS](https://www.seventhgeneration.com/sites/default/files/2020-01/sds-fm000013-02-1-fabric-softener-frlav-en-2018-05-18.pdf)) for the OSHA (United States) for a generic fabric softener. The following table is the LD50 (lethal does concentration for 50% lethality in a typical human) for each ingredient. [![MSDS LD50 Table for Fabric Softener](https://i.stack.imgur.com/LF6SY.png)](https://i.stack.imgur.com/LF6SY.png) As noted in the table, the LD50 for the fragrance is typically greater than 5 grams per kilo of human. While not considered *harmless*, you would need to inhale a ridiculous amount of dryer exhaust to even notice health effects. At <1% (I used 1% for calculations), a 32oz (~1L) bottle (net weight 2.64lbs or 1.2Kg) would contain less than 12mg of fragrance per bottle. You would need over 833 bottles worth per kilo of bodyweight to inhale the LD50 lower limit, and that's only if every bit of it was inhaled. Typically the MSDS becomes relevant for the workers producing the product, as the ingredients are at MUCH higher concentrations where its made.
We don't know. When deciding if fumes are dangerous, the relevant measure is the "LC-50", the airborne concentration that is lethal to 50% of test subjects. Ingestion LD-50s are of limited value here, since the lungs provide far more direct access to the bloodstream than the digestive tract does. In the absence of explicit toxicology information, occupational exposure limits are an indication of hazard levels. I searched for safety data sheets for the ingredients in the fabric softener listed in the other answer, and checked at least three for each. I was able to find inhalation LC-50s for sodium carbonate ([2300 mg/m^3/2H](https://fscimage.fishersci.com/msds/21080.htm)), vanillin ([57 mg/L/96H](https://www.pickeringlabs.com/wp-content/uploads/sds/SDS%203700-2200%20Vanillin.pdf)), and raspberry ketone ([non-toxic per EC 1272/2008](http://www.lluche.com/en/products/Pages/OpenDocuments.aspx?artNumber=100324000&type=3&template=02709QQQQS_ESP_L2_V17.docx.doc&outFileName=100324000_ESP_L2_V17.docx.pdf&productName=RASPBERRY%20KETONE%20NATURAL&reachNumber=--/--)). I also found exposure limits for d-limonene ([20 ppm per ACGIH](https://www.b2bcomposites.com/msds/nexeo/633639.pdf)), calcium chloride ([no limit per OSHA, NIOSH, or ACGIH](https://www.labchem.com/tools/msds/msds/75446.pdf)), and propylene glycol ([10 mg/m^3 per US WEEL](https://www.chemcentral.com/documents/file/view/code/sds_file/id/54594/)). For everything else (water\*, dihydrogenated palmoylethyl hydroxyethylmonium methosulfate, benzisothiazolinone, bitter orange extract, orange peel oil, eucalyptus globulus leaf oil, hexyl acetate, juniperus mexicana oil, lavandula hybrida oil, pogostemon cablin oil, and linalool), the inhalation toxicity hazard was either "no information available" or simply not included. For many of the oils, the entire toxicity section is "no information available". \*Yes, there are serious safety data sheets for water.
54,561,174
I have a string in log and I want to mask values based on regex. **For example**: ``` "email":"[email protected]", "phone":"1111111111", "text":"sample text may contain email [email protected] as well" ``` The regex should mask 1. email value - both inside the string after "email" and "text" 2. phone number **Desired output**: ``` "email":"*****", "phone":"*****", "text":"sample text may contain email ***** as well" ``` What I have been able to do is to mask email and phone individually but not the email id present inside the string after "text". **Regex developed so far**: ``` (?<=\"(?:email|phone)\"[:])(\")([^\"]*)(\") ``` <https://regex101.com/r/UvDIjI/2/>
2019/02/06
[ "https://Stackoverflow.com/questions/54561174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/988206/" ]
As you are not matching an email address in the first part by matching not a double quote, you could match the email address in the text by also not matching a double quote. One way to do this could be to get the matches using lookarounds and an [alternation](https://www.regular-expressions.info/alternation.html). Then replace the matches with `*****` Note that you don't have to escape the double quote and the colon could be written without using the character class. ``` (?<="(?:phone|email)":")[^"]+(?=")|[^@"\s]+@[^@"\s]+ ``` Explanation * `(?<="(?:phone|email)":")` Assert what is on the left is either "phone":" or "email":" * `[^"]+(?=")` Match not a double quote and make sure that there is one at the end * `|` Or * `[^@"\s]+@[^@"\s]+` Match an `email like` pattern by making use of a negated character class matching not a double quote or @ See the [regex demo](https://regex101.com/r/PyPzzz/1)
[Meta Sequence Word Boundary `\b`](https://www.rexegg.com/regex-boundaries.html) & [Alternation `|`](https://www.regular-expressions.info/alternation.html) =========================================================================================================================================================== The input string pattern has either quotes or spaces wrapped around the targets which both are considered non-words. So this: "`\b`*emailPattern*`\b`" and this: *space*`\b`*emailPattern*`\b`*space* are matches. The alternation gives one line the power of two lines. Search for *emailPattern* ***OR*** *phonePattern*. > > > ``` > /(\b\w+?@\w+?\.\w+?\b|[0-9]{10})/g; > > ``` > > * `(`Word boundary (a non-word on the left) `\b` * One or more word characters `\w+?` * Literal `@` * One or more word characters `\w+?` * Escaped literal `.` * One or more word characters `\w+?` * Word boundary (a non-word on the right) `\b` * **OR** `|` * 10 consecutive numbers `[0-9]{10}` `)` * `g`lobal flag continues search after first match. Demo ---- ```js let str = `"email":"[email protected]", "phone":"1111111111", "text":"sample text may contain email [email protected] as well"`; const rgx = /(\b\w+?@\w+?\.\w+?\b|[0-9]{10})/g; let res = str.replace(rgx, '*****'); console.log(res); ```
54,561,174
I have a string in log and I want to mask values based on regex. **For example**: ``` "email":"[email protected]", "phone":"1111111111", "text":"sample text may contain email [email protected] as well" ``` The regex should mask 1. email value - both inside the string after "email" and "text" 2. phone number **Desired output**: ``` "email":"*****", "phone":"*****", "text":"sample text may contain email ***** as well" ``` What I have been able to do is to mask email and phone individually but not the email id present inside the string after "text". **Regex developed so far**: ``` (?<=\"(?:email|phone)\"[:])(\")([^\"]*)(\") ``` <https://regex101.com/r/UvDIjI/2/>
2019/02/06
[ "https://Stackoverflow.com/questions/54561174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/988206/" ]
As you are not matching an email address in the first part by matching not a double quote, you could match the email address in the text by also not matching a double quote. One way to do this could be to get the matches using lookarounds and an [alternation](https://www.regular-expressions.info/alternation.html). Then replace the matches with `*****` Note that you don't have to escape the double quote and the colon could be written without using the character class. ``` (?<="(?:phone|email)":")[^"]+(?=")|[^@"\s]+@[^@"\s]+ ``` Explanation * `(?<="(?:phone|email)":")` Assert what is on the left is either "phone":" or "email":" * `[^"]+(?=")` Match not a double quote and make sure that there is one at the end * `|` Or * `[^@"\s]+@[^@"\s]+` Match an `email like` pattern by making use of a negated character class matching not a double quote or @ See the [regex demo](https://regex101.com/r/PyPzzz/1)
Your current RegEx is trying to accomplish too much in a single take. You'd be better off splitting the conditions and dealing with them separately. I'll assume that the input will always follow the structure of your example, no edge cases: 1. Emails: * `\w+@.+?(?="|\s)` - In emails, every character preceded by `@` is always a word character, so using `\w+@` is enough to capture the first half of the email. As for the second half, I used a wildcard (`.`) with a lazy quantifier (`+?`) to stop the capture as soon as possible and combined it with a positive lookahead that checks for double quotes or whitespaces (`(?="|\s)`) so to capture both the e-mails inside `"email"` and `"text"` properties. [Lookarounds are zero-length assertions](https://www.regular-expressions.info/lookaround.html) and thus they don't get captured. 2. Phone number: * `(?<="phone":")\d+` - Here I just use the prefix `"phone":"` in a lookbehind and then capture only digits `\d+`. Combine both conditions and you have your RegEx: `\w+@.+?(?="|\s)|(?<="phone":")\d+`. **Regex101:** <https://regex101.com/r/UvDIjI/3>
70,375
I've recently been assigned a static IP by my ISP provider (Sonic.net). My previous setting was with the modem configured to connect using static IP and the Airport Extreme as a bridge. NAT and DHCP were done at the modem, but I couldn't get WOL (Wake On LAN) to work (an Apple technote specifies that this setup won't). Now I've set up my modem as a bridge and configured the Airport Extreme to handle everything. I've set it up as a static IP and activated DHCP and NAT. I can connect to the Internet perfectly and everything else (connection-wise) works. Yet to try remote access and WOL. The only problem is that I can't access the modem's admin panel. This should be at 192.168.1.1, but I can't get to it. I think the Airport Extreme is assuming .1 as its internal address. Is there any way to access the modem in that setup unless directly linked to it (by Ethernet cable)? Will giving the modem another IP (say .201, out of Airport's DHCP range) work? Can I change the Airport's internal address somehow? EDIT: I've managed to assign the modem an IP of 192.168.0.1, so it should be in another subnet, but [this traceroute](http://pastebin.com/v1Gn1NtE) shows it hopping out after hitting local router.
2012/11/02
[ "https://apple.stackexchange.com/questions/70375", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/11411/" ]
The problem isn't just that you have two devices using the same 192.168.1.1 IP address, but also that two network segments are using the same subnet (the first 3 parts of the IP, 192.168.1.x). If you're on the AirPort's LAN at 192.168.1.123 and you try to talk to the modem at 192.168.1.1, the network sees "192.168.1" and recognizes it as local traffic, meaning that it never goes out the WAN port where the modem is. It's sort of like if I try to mail a letter to "123 Fake St, London". I mean the one in England, but there's a city called London right here in Ontario, so that's where the post office is going to send it. Anyway, when you made your own subnetwork with NAT, you should have picked a new IP subnet to go with it. The AirPort utility calls this part of the IPv4 DHCP range, even though it affects more than DHCP. It's probably currently set to "192.168.1.100 to 200". Just change the third part to something else, like "192.168.0.100 to 200". This will move your entire LAN to the 192.168.0.x subnet, and the AirPort will take 192.168.0.1 for itself.
The way to do it would be to edit the firewall on the router. Assuming your modem's address is 192.168.0.1 (and your router side network is on 192.168.1.x), using the DD\_WRT firmware it would be as easy as adding: ``` ifconfig `nvram get wan_ifname`:0 192.168.0.2 netmask 255.255.255.0 ``` to the init scripts and the following to the firewall: ``` iptables -t nat -I POSTROUTING -o `nvram get wan_ifname` -j MASQUERADE ``` Unfortunately, there is no way (that I know of) to accomplish this with the Airport Extreme; from what I've been able to gather online, this can't be done.
5,389
Here's my scenario. I have a structure section: "events". Within that I have three entry types: "events", "exhibitions", "specials". I would like the events to follow the following URL structure: ``` {type}/{slug} ``` So far no problem, since the entry type handles are defined in English. But when it comes to the Norwegian page, I want to use the Norwegian translation for each type: "arrangement", "utstilinger", "spesielle". So I added in the translations to my static translation file, and tried: ``` {type|translate}/{slug} ``` But obviously, since I'm here, I didn't have any luck. Can anyone think of a way to achieve the desired result, without resorting to adding a custom field to each entry type that would need to be filled in for every entry to use in place of `{type}`?
2014/12/23
[ "https://craftcms.stackexchange.com/questions/5389", "https://craftcms.stackexchange.com", "https://craftcms.stackexchange.com/users/359/" ]
This turned out to be easier than expected. It's not documented in the [filters section of the docs](http://buildwithcraft.com/docs/templating/filters#translate-or-t), but the t() filter can take other parameters after the tokenised variables you might want to replace in the string. Paraphrased from the source code of the globally available t() function: * source: Defines which message source application component to use. Defaults to null, meaning use 'coreMessages' for messages belonging to the 'yii' category and using 'messages' for messages belonging to Craft. * language: The target language. If set to null (default), craft()->getLanguage() will be used. * category: The message category. Please use only word letters. Note, category 'craft' is reserved for Craft and 'yii' is reserved for the Yii framework. So, the solution was as simple as: `{type|t(null, null, 'nb')}/{slug}` for URL format for Norwegian and `{type|t(null, null, 'en')}/{slug}` for English.
It works for me to use `{type|t}/{slug}` as an url format. Just make sure you make the translations before you save the entry (in the translated language). Or go back and resave the entries. The url is translated and saved at the time you save the entry, it's not updated automatically if you change the translations. UPDATE: Sorry, I spoke a bit too fast. After some more testing, it seems like I was fooled by the fact that it actually translates the string to the locale you, as a user, has when editing the entry. So, I made an entry with type exhibition, created the translation to norwegian, resaved the norwegian version of the entry, and confirmed that the type had been translated. But, the next time I saved the english version, that url was translated too. It actually makes sense that this is the way the translate filter works. It translates based on the users current locale, not the locale of the versioned entry. Maybe it would be possible to make a new twig filter (as a plugin), that translates based on the locale of the entry, and use that filter in the url format. Not sure how you'd get the entry local passed to the filter though..
25,638,249
I'm using MixPanel to send push notification and on the custom payload I add the following code: {"sound":"default"} the problem Is that no sound gets played when I receive the notification. Does anyone have a solution for this?
2014/09/03
[ "https://Stackoverflow.com/questions/25638249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3789527/" ]
``` mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI); ```
``` final Notification notification = new Notification(iconResId, tickerText, System.currentTimeMillis()); final String packageName = context.getPackageName(); notification.sound = Uri.parse("android.resource://" + packageName + "/" + soundResId); ```
25,638,249
I'm using MixPanel to send push notification and on the custom payload I add the following code: {"sound":"default"} the problem Is that no sound gets played when I receive the notification. Does anyone have a solution for this?
2014/09/03
[ "https://Stackoverflow.com/questions/25638249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3789527/" ]
``` mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI); ```
The default GCMReceiver in the Mixpanel library for Android that handles incoming push notifications from Mixpanel doesn't include sounds. You'll need to write your own BroadcastReceiver to process incoming messages from Mixpanel. You can take a look at Mixpanel's documentation for using the low level API at : <https://mixpanel.com/help/reference/android-push-notifications#advanced> - then you an apply the advice from the other answers to do anything you'd like with your custom data payload.
25,638,249
I'm using MixPanel to send push notification and on the custom payload I add the following code: {"sound":"default"} the problem Is that no sound gets played when I receive the notification. Does anyone have a solution for this?
2014/09/03
[ "https://Stackoverflow.com/questions/25638249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3789527/" ]
Maybe this helps found [here](https://stackoverflow.com/questions/22408929/unable-to-set-push-notification-sound-in-android) code will look like this. ``` Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification); r.play(); ```
try following code ``` Notification notification = new Notification(R.drawable.appicon, "Notification", System.currentTimeMillis()); notification.defaults = Notification.DEFAULT_SOUND; ```
25,638,249
I'm using MixPanel to send push notification and on the custom payload I add the following code: {"sound":"default"} the problem Is that no sound gets played when I receive the notification. Does anyone have a solution for this?
2014/09/03
[ "https://Stackoverflow.com/questions/25638249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3789527/" ]
Maybe this helps found [here](https://stackoverflow.com/questions/22408929/unable-to-set-push-notification-sound-in-android) code will look like this. ``` Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification); r.play(); ```
The default GCMReceiver in the Mixpanel library for Android that handles incoming push notifications from Mixpanel doesn't include sounds. You'll need to write your own BroadcastReceiver to process incoming messages from Mixpanel. You can take a look at Mixpanel's documentation for using the low level API at : <https://mixpanel.com/help/reference/android-push-notifications#advanced> - then you an apply the advice from the other answers to do anything you'd like with your custom data payload.
25,638,249
I'm using MixPanel to send push notification and on the custom payload I add the following code: {"sound":"default"} the problem Is that no sound gets played when I receive the notification. Does anyone have a solution for this?
2014/09/03
[ "https://Stackoverflow.com/questions/25638249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3789527/" ]
In order to send notification + sound using mixpanel, you need to do the following: * add the following code to the onCreate: ``` NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this); mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI); Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification); r.play(); ``` * Send notification from mixpanel and see it received. This will send notification on create with default sound configured on the user's device.
The default GCMReceiver in the Mixpanel library for Android that handles incoming push notifications from Mixpanel doesn't include sounds. You'll need to write your own BroadcastReceiver to process incoming messages from Mixpanel. You can take a look at Mixpanel's documentation for using the low level API at : <https://mixpanel.com/help/reference/android-push-notifications#advanced> - then you an apply the advice from the other answers to do anything you'd like with your custom data payload.
25,638,249
I'm using MixPanel to send push notification and on the custom payload I add the following code: {"sound":"default"} the problem Is that no sound gets played when I receive the notification. Does anyone have a solution for this?
2014/09/03
[ "https://Stackoverflow.com/questions/25638249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3789527/" ]
In order to send notification + sound using mixpanel, you need to do the following: * add the following code to the onCreate: ``` NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this); mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI); Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification); r.play(); ``` * Send notification from mixpanel and see it received. This will send notification on create with default sound configured on the user's device.
try following code ``` Notification notification = new Notification(R.drawable.appicon, "Notification", System.currentTimeMillis()); notification.defaults = Notification.DEFAULT_SOUND; ```
25,638,249
I'm using MixPanel to send push notification and on the custom payload I add the following code: {"sound":"default"} the problem Is that no sound gets played when I receive the notification. Does anyone have a solution for this?
2014/09/03
[ "https://Stackoverflow.com/questions/25638249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3789527/" ]
``` mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI); ```
try following code ``` Notification notification = new Notification(R.drawable.appicon, "Notification", System.currentTimeMillis()); notification.defaults = Notification.DEFAULT_SOUND; ```
25,638,249
I'm using MixPanel to send push notification and on the custom payload I add the following code: {"sound":"default"} the problem Is that no sound gets played when I receive the notification. Does anyone have a solution for this?
2014/09/03
[ "https://Stackoverflow.com/questions/25638249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3789527/" ]
``` mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI); ```
Assuming you have a declaration... ``` NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setAutoCancel(true) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher)) .setTicker(title) .setWhen(ts) .setContentTitle(title) .setStyle(new NotificationCompat.BigTextStyle() .bigText(message)) .setContentText(message); ``` ... variable constructed somewhere in your code, try this: ``` final String ringTone = "default ringtone"; // or store in preferences, and fallback to this mBuilder.setSound(Uri.parse(ringTone)); ```
25,638,249
I'm using MixPanel to send push notification and on the custom payload I add the following code: {"sound":"default"} the problem Is that no sound gets played when I receive the notification. Does anyone have a solution for this?
2014/09/03
[ "https://Stackoverflow.com/questions/25638249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3789527/" ]
In order to send notification + sound using mixpanel, you need to do the following: * add the following code to the onCreate: ``` NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this); mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI); Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification); r.play(); ``` * Send notification from mixpanel and see it received. This will send notification on create with default sound configured on the user's device.
Assuming you have a declaration... ``` NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setAutoCancel(true) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher)) .setTicker(title) .setWhen(ts) .setContentTitle(title) .setStyle(new NotificationCompat.BigTextStyle() .bigText(message)) .setContentText(message); ``` ... variable constructed somewhere in your code, try this: ``` final String ringTone = "default ringtone"; // or store in preferences, and fallback to this mBuilder.setSound(Uri.parse(ringTone)); ```
25,638,249
I'm using MixPanel to send push notification and on the custom payload I add the following code: {"sound":"default"} the problem Is that no sound gets played when I receive the notification. Does anyone have a solution for this?
2014/09/03
[ "https://Stackoverflow.com/questions/25638249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3789527/" ]
Assuming you have a declaration... ``` NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setAutoCancel(true) .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher)) .setTicker(title) .setWhen(ts) .setContentTitle(title) .setStyle(new NotificationCompat.BigTextStyle() .bigText(message)) .setContentText(message); ``` ... variable constructed somewhere in your code, try this: ``` final String ringTone = "default ringtone"; // or store in preferences, and fallback to this mBuilder.setSound(Uri.parse(ringTone)); ```
The default GCMReceiver in the Mixpanel library for Android that handles incoming push notifications from Mixpanel doesn't include sounds. You'll need to write your own BroadcastReceiver to process incoming messages from Mixpanel. You can take a look at Mixpanel's documentation for using the low level API at : <https://mixpanel.com/help/reference/android-push-notifications#advanced> - then you an apply the advice from the other answers to do anything you'd like with your custom data payload.
425,840
From what I understand the electric potential at a point $P$ is the amount of work done per unit charge $q$ in bringing that charge $q$ to the point $P$. Now consider the following question: The potential at the point $P$ is $12$ V and a charge of $3C$ is placed there, then the potential energy is simply $12\times 3 = 36$J. Here is my confusion, for the point $P$ to have a potential of $12$V, it implies that the charge being moved which is $3C$ is moving from a lower to a higher potential before it got to the point $P.$ So perhaps near the point $P$ there is a higher charge involved say $10C.$ But if $P$ were really near a high positive charge $10C$, then to bring a $3C$ charge from very far away to the point $P$, then since the electric field lines from $10C$ is greater than $3C$, ultimately work has to be done in overcoming that field and hence is the reason why the work done is positive? Because we need to do work? Also consider the same situation as above but now we are moving a charge of $-2C$ from far away to the point $P$. Again near point $P$ or at point $P$ it is of positive potential of $12V$ which implies to move $-2C$ to that point, it must be moving from a lower to a high potential. But if it really is at a higher potential near $P$ say of $1C$, then the field lines are from $1C$ towards the $-2C$ which implies work has to be done to move the $-2C$ from far away to the point $P$, but then the energy required is $-2(12) = - 24$J which implies energy was lost during moving $-2C$ from far to the point $P.$ Where in my understanding am I going wrong?
2018/08/31
[ "https://physics.stackexchange.com/questions/425840", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/203766/" ]
Consider the following: The point $P$ in an electric field has an electric potential of $12\ V$. Where this point is in the field depends on the field itself. The two fields shown below have different maxima so point P is at a different point in each, but the electric potential at $P$ is still $12\ V$ in each field. [![Point P in an electric field](https://i.stack.imgur.com/xLUO8.png)](https://i.stack.imgur.com/xLUO8.png) The charge $q$ at point $P$ has a potential energy of $E=qV$ in each field. Because the electric potential at $P$ is the same in both fields, the potential energy $E$ for the charge $q$ is the same in both fields. At this point we don't need to consider whether work was done *on* $q$ or *by* $q$, we can just take this as a starting point and say that the charge $q$ is at point $P$, and if $q=-2\ C$ then $E=qV=(-2)(12)=-24\ J$. [![Charge q at point P in an electric field](https://i.stack.imgur.com/tZPUM.png)](https://i.stack.imgur.com/tZPUM.png) Whether we want to then consider how $q$ got to $P$, or what happens next with $q$ moving from $P$, we need to understand whether work is being done *on* $q$ or *by* $q$. For a positive charge $+q$, to move from a lower electric potential to a higher electric potential, work needs to be done *on* $q$ because the potential energy is increasing as the electric potential increases, so we need to add energy to $q$. Conversely, to move from a higher electric potential to a lower electric potential, work is done *by* $q$ because the potential energy of $q$ decreases as it moves to a lower electric potential. On the other hand, for a negative charge $-q$, to move from a lower electric potential to a higher electric potential, work is done *by* $q$ because the potential energy is decreasing (becoming more negative) as the electric potential increases, e.g. from $E=qV=(-2)(8)=-16\ J$ to $E=qV=(-2)(12)=-24\ J$. That is, $q$ is losing energy. And conversely, to move from a higher electric potential to a lower electric potential, work must be done *on* $q$ because the potential energy of $q$ increases (becoming more positive) as it moves to a lower electric potential, e.g. from $E=qV=(-2)(12)=-24\ J$ to $E=qV=(-2)(8)=-16\ J$. And if $q$ moves, or is moved, sideways in the field then no work is done because the electric potential does not change and so the potential energy of $q$ does not change. [![Charge q 'has work done' or 'does work' to arrive at point P in an electric field](https://i.stack.imgur.com/Z7dGc.png)](https://i.stack.imgur.com/Z7dGc.png)
> > Again near point P or at point P it is of positive potential of 12V > which implies to move −2C to that point, it must be moving from a > lower to a high potential. > > > For a negative charge, the potential at infinity will actually be higher than at point P. This should make sense, considering that a negative charge would be attracted to P and, therefore, the work, "required" to move it from infinity to P, would have to be negative.
11,365,037
we have just started using a git account of our Django website project so that the team can collaborate on the source code. I have heard different things concerning what should be done with the `/media` directory. We currently keep the `/static` directory under version control so that the whole project can be cloned and recreated. However, the website also contains a large amount (>400mb) of uploaded images for galleries which will likely grow over time. Should this be under git also? Is there a reasonable size limit to be aware of when using GIT? And is there some other method for dealing with the `/media` folder which is used by the Django community? Any guidance would be much appreciated.
2012/07/06
[ "https://Stackoverflow.com/questions/11365037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/791335/" ]
You should exclude your **media** folder in the **.gitignore**. There are some problems. * When you check in the files its possible that they are modified (Upload script) on the server. Then you cannot pull. * when you need your sources you have to download the whole media files. * You must commit new files everytime on your server. So we use it without media files. But if you have do automatic deployment and enough time you can to it.
Definitely don't put all your uploaded files from the live site in the source code. It's not where they belong. At the very least you should back up your /media directory to an external location e.g. another server, a local NAS, some backup provider etc. If your development team wants access to the files during development, you should consider putting a small subset of these files in your source tree and using [fixtures](https://docs.djangoproject.com/en/1.4/howto/initial-data/) to create a standard set of test data for the development environment.
26,132
> > **Possible Duplicate:** > > [Why is writing zeros (or random data) over a hard drive multiple times better than just doing it once?](https://security.stackexchange.com/questions/10464/why-is-writing-zeros-or-random-data-over-a-hard-drive-multiple-times-better-th) > > > Multiple overwrites have often been discussed as a secure way of erasing data. Some people say that the only way to securely erase a magnetic HDD is to physically destroy the device, grinding each platter to powder, incineration etc. If I ask the question whether a single overwrite makes data permanently irretrievable, I get different answers. Some people say that it was an issue on older hardware, others that it still is. I have not come across a case where a single overwrite of zeros has been recovered, despite many people theorising that this could be done using techniques such as magnetic force microscopy. It seems that in general people err on the side of caution under the assumption that one of the mysterious government entities has some crazy eletron-microscope equipment capable of recovering data after single, or even multiple overwrites. While this is clearly the sensible option as it doesn't take a great deal of time to shred a disk this way, the question remains; is it necessary?
2012/12/28
[ "https://security.stackexchange.com/questions/26132", "https://security.stackexchange.com", "https://security.stackexchange.com/users/9377/" ]
The best citation I can give is from *Overwriting Hard Drive Data: The Great Wiping Controversy*, which was published as part of the [4th International Conference on Information Systems Security, ICISS 2008](https://www.google.com/search?tbs=bks:1&q=isbn:9783540898610). You can view the full text of the paper by viewing the book on Google Books, and jumping to page 243. The following excerpt is from their conclusion: > > The purpose of this paper was a categorical settlement to the controversy surrounding the misconceptions involving the belief that data can be recovered following a wipe procedure. This study has demonstrated that correctly wiped data cannot reasonably retrieved even if it of a small size or found only over small parts of the hard drive. Not even with the use of a MFM or other known methods. The belief that a tool can be developed to retrieve gigabytes or terabytes of data of information from a wiped drive is in error. > > > Although there is a good chance of recovery for any individual bit from a drive, the chance of recovery of any amount of data from a drive using an electron microscope are negligible. Even speculating on the possible recovery of an old drive, there is no likelihood that any data would be recoverable from the drive. The forensic recovery of data using electron microscopy is infeasible. This was true both on old drives and has become more difficult over tine. Further, there is a need for the data to have been written and then wiped on a raw unused drive for there to be any hopy of any level of recovery even at the bit level, which does not reflect real situations. It is unlikely that a recovered drive will have not been used for a period of time and the interaction of defragmentation, file copies and general use that overwrites data areas negates any chance of data recovery. The fallacy that data can be forensically recovered using an electron microscope or related means needs to be put to rest. > > > NIST also seem to agree. In [NIST SP 800-88](http://csrc.nist.gov/publications/nistpubs/800-88/NISTSP800-88_with-errata.pdf), they state the following: > > Studies have shown that most of today’s media can be effectively cleared by one overwrite. > > > Purging information is a media sanitization process that protects the confidentiality of information against a laboratory attack. For some media, clearing media would not suffice for purging. However, for ATA disk drives manufactured after 2001 (over 15 GB) the terms clearing and purging have converged. > > > As such, I'd say that data remanence on modern hard drives is a complete myth, and it's likely to be infeasible for old drives too. So, as a quick set of bullet points: * You *might* be able to extract individual bits after a single overwrite, but not any useful amount of data. * It is entirely infeasible to recover any data, even at the bit level, from a wiped disk area outside lab conditions, due to the effects of day-to-day use (file copies, etc). * A single overwrite, for all intents and purposes, provides complete protection against useful data recovery.
As usual, the [Wikipedia page](http://en.wikipedia.org/wiki/Data_remanence) contains useful links (Wikipedia is not "The Truth" but it is a great starting point for investigating technical issues and making one's own mind). In particular, it says that: > > As of November 2007, the United States Department of Defense considers overwriting acceptable for clearing magnetic media within the same security area/zone, but not as a sanitization method. Only degaussing or physical destruction is acceptable for the latter. > > > On the other hand, according to the 2006 NIST Special Publication 800-88 (p. 7): "Studies have shown that most of today’s media can be effectively cleared by one overwrite" and "for ATA disk drives manufactured after 2001 (over 15 GB) the terms clearing and purging have converged." An analysis by Wright et al. of recovery techniques, including magnetic force microscopy, also concludes that a single wipe is all that is required for modern drives. They point out that the long time required for multiple wipes "has created a situation where many organisations ignore the issue all together – resulting in data leaks and loss. " > > > So the generic conclusion seems to be that a simple overwrite will *most probably* erase all the data, but if you need some kind of compliance with regards to some bureaucratic regulations, then old-style physical obliteration may still be required. Note that, with regards to data cleansing, you have **two** needs: * you want to wipe the data out; * you want to be *sure* that the data has been thoroughly wiped out. A sledgehammer or an acid cauldron will go a long way towards fulfilling the latter goal.
11,668
I am looking for a translation of the [Suchiloma Sutta](https://books.google.com/books?id=pMAIAAAAQAAJ&pg=PA75&lpg=PA75&dq=is%20gotama%20afraid%20of%20me%20sutta&source=bl&ots=6BoNJZrTKa&sig=HtcmUFaEf6bLk5-rvu8owXQDgKE&hl=en&sa=X&ved=0CCwQ6AEwAmoVChMIqeKrvKaGyAIVkwiSCh2wbAhh#v=onepage&q=is%20gotama%20afraid%20of%20me%20sutta&f=false) other than the one I have found through searching on Google or some insight into the Pali. In the story, the Demon Suchiloma wants to test the Buddha and 'strikes him with his body' whereupon the Buddha withdraws his own body. Here is the passage I am interested in: > > Thereupon the demon Suchiloma addressed Bhagava thus: "O Samana! Are > you afraid of me?" (Bhagava said,) "Friend! though your touching me is > sinful, (yet) I am not afraid of you." > > > I seem to recall reading a translation of this sutta in which the Buddha's words are translated as something like: Friend, I am not afraid of you, but still, contact with you is not pleasant. Can anyone point to an alternate translation or to a Pali version of the sutta (along with any insight into the meaning of the passage in question)?
2015/09/20
[ "https://buddhism.stackexchange.com/questions/11668", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/120/" ]
Here is an alternative translation up on Sutta Central: <https://suttacentral.net/en/snp2.5> However, the sentence you are looking for is translated as so: > > Friend, I am not afraid of you, but your touch is evil. > > > The word "evil" here translates Pali `pāpako` - bad, malignant, evil, wrong, sinful. I suppose the meaning is that, although Enlightened One is not afraid to come in contact with demonic influences, even for Buddha the close contact with them is not beneficial. As poisonous food may upset the stomach, so poisonous thoughts may upset the mind.
> > Can anyone point to an alternate translation or to a Pali version of > the sutta (along with any insight into the meaning of the passage in > question)? > > > We can see this type of another situation in [With the Yakkha Āḷavaka](https://suttacentral.net/en/snp1.10) > > At one time the Lord dwelt at Āḷavī in the haunt of the yakkha > Āḷavaka. Then the latter went to the Lord’s dwelling and spoke to him > as follows: “Monk, come out!” > > > “Very well, friend” said the Buddha (and came out). > > > “Monk, go in!” > > > “Very well, friend” said the Buddha and entered his dwelling. He > repeated these demands twice, but on the fourth demand the Buddha > said: > > > “I shall not come out to you, friend, do what you will.” > > > “Monk, I shall ask you a question and if you cannot answer it I shall > either overthrow your mind, split your heart, or seizing you by the > feet, throw you to the other side of the Ganges river.” > > > “I do not see, friend, anyone in the world with its devas, Māras and > Brahmās, in this generation with its monks and brahmins, princes and > men who can either overthrow my mind, or split my heart, or seize me > by the feet and throw me to the other side of the Ganges river. > However, friend, ask what you will.” > > > By considering these two occasions we can assume Load Buddha gave an example, How to handle a tough (difficult) situation when one goes to preach someone. They are not ready to accept, and in aggressive moods. So the preacher must have develop the quality '[patience](https://buddhism.stackexchange.com/a/11756/5513)' as shown in [this answer](https://buddhism.stackexchange.com/a/11756/5513).
11,668
I am looking for a translation of the [Suchiloma Sutta](https://books.google.com/books?id=pMAIAAAAQAAJ&pg=PA75&lpg=PA75&dq=is%20gotama%20afraid%20of%20me%20sutta&source=bl&ots=6BoNJZrTKa&sig=HtcmUFaEf6bLk5-rvu8owXQDgKE&hl=en&sa=X&ved=0CCwQ6AEwAmoVChMIqeKrvKaGyAIVkwiSCh2wbAhh#v=onepage&q=is%20gotama%20afraid%20of%20me%20sutta&f=false) other than the one I have found through searching on Google or some insight into the Pali. In the story, the Demon Suchiloma wants to test the Buddha and 'strikes him with his body' whereupon the Buddha withdraws his own body. Here is the passage I am interested in: > > Thereupon the demon Suchiloma addressed Bhagava thus: "O Samana! Are > you afraid of me?" (Bhagava said,) "Friend! though your touching me is > sinful, (yet) I am not afraid of you." > > > I seem to recall reading a translation of this sutta in which the Buddha's words are translated as something like: Friend, I am not afraid of you, but still, contact with you is not pleasant. Can anyone point to an alternate translation or to a Pali version of the sutta (along with any insight into the meaning of the passage in question)?
2015/09/20
[ "https://buddhism.stackexchange.com/questions/11668", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/120/" ]
You might want to download Bhikkhu Bodhi's one hour talk on this Sutta from <http://bodhimonastery.org/sutta-nipata.html> It is track 31. I was curious, so I listened to this track and Bhikkhu Bodhi explains the point that you are asking about. The Yakkha's name is "Sūciloma"; "sūci" means needle and "loma" means hair of the body (one of the 32 parts). So this particular Yakkha had body hairs that were sharp like needles. Sūciloma wanted to determine if the Buddha was a "real ascetic" or a "fake ascetic". A "real ascetic" would not be afraid of a Yakkha while a "fake ascetic" would show fear. So Sūciloma approaches the Buddha and bends over the Buddha. Your translation of "strikes him with his body" is not correct; the Pāḷi word *upanāmesi* means "to bend over to, to place against or close to, to approach, bring near". When the Buddha withdraws his body, Sūciloma asks "Are you afraid of me?" The Buddha replies, "Friend, I am not afraid of you, though your touch is painful". Bhikkhu Bodhi explains that the Pāḷi word *pāpako* literally means "evil" but in this context should be interpreted as meaning painful to the touch [because of your sharp body hairs].
> > Can anyone point to an alternate translation or to a Pali version of > the sutta (along with any insight into the meaning of the passage in > question)? > > > We can see this type of another situation in [With the Yakkha Āḷavaka](https://suttacentral.net/en/snp1.10) > > At one time the Lord dwelt at Āḷavī in the haunt of the yakkha > Āḷavaka. Then the latter went to the Lord’s dwelling and spoke to him > as follows: “Monk, come out!” > > > “Very well, friend” said the Buddha (and came out). > > > “Monk, go in!” > > > “Very well, friend” said the Buddha and entered his dwelling. He > repeated these demands twice, but on the fourth demand the Buddha > said: > > > “I shall not come out to you, friend, do what you will.” > > > “Monk, I shall ask you a question and if you cannot answer it I shall > either overthrow your mind, split your heart, or seizing you by the > feet, throw you to the other side of the Ganges river.” > > > “I do not see, friend, anyone in the world with its devas, Māras and > Brahmās, in this generation with its monks and brahmins, princes and > men who can either overthrow my mind, or split my heart, or seize me > by the feet and throw me to the other side of the Ganges river. > However, friend, ask what you will.” > > > By considering these two occasions we can assume Load Buddha gave an example, How to handle a tough (difficult) situation when one goes to preach someone. They are not ready to accept, and in aggressive moods. So the preacher must have develop the quality '[patience](https://buddhism.stackexchange.com/a/11756/5513)' as shown in [this answer](https://buddhism.stackexchange.com/a/11756/5513).
12,099,259
So I have a situation where I want to put a very long Terms of Use document onto a page on my company's web site, but it was way too long to put in the main "content" area. I would like to use a scroll area, so that user can see the terms of use as rendered originally. So you can see what I mean, I need the entire section c off of the Apple web page: <http://www.apple.com/legal/itunes/us/terms.html#APPS> I looked into putting the HTML code for that section of the Terms of Use in `<textarea>` element, but apparently `<textarea>` will not render HTML code. Is there a solution so that I do not have a web page like 4000px high? Thanks.
2012/08/23
[ "https://Stackoverflow.com/questions/12099259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/821722/" ]
Put the content into a div with a fixed height, and set the css overflow property to 'auto' this will create a scrollable div ``` <div style='height:80px; overflow:auto;'> content here </div> ``` of course you should use a separate style sheet but that's a different story
You could create another .html file and have an `<iframe>` of it embedded with a set height and width.
12,099,259
So I have a situation where I want to put a very long Terms of Use document onto a page on my company's web site, but it was way too long to put in the main "content" area. I would like to use a scroll area, so that user can see the terms of use as rendered originally. So you can see what I mean, I need the entire section c off of the Apple web page: <http://www.apple.com/legal/itunes/us/terms.html#APPS> I looked into putting the HTML code for that section of the Terms of Use in `<textarea>` element, but apparently `<textarea>` will not render HTML code. Is there a solution so that I do not have a web page like 4000px high? Thanks.
2012/08/23
[ "https://Stackoverflow.com/questions/12099259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/821722/" ]
You can create a div to contain the content and specify a height, then user overflow: auto in your CSS to make it scrollable. Like this:- <http://jsbin.com/ifolaf/2/edit>
You could create another .html file and have an `<iframe>` of it embedded with a set height and width.
12,099,259
So I have a situation where I want to put a very long Terms of Use document onto a page on my company's web site, but it was way too long to put in the main "content" area. I would like to use a scroll area, so that user can see the terms of use as rendered originally. So you can see what I mean, I need the entire section c off of the Apple web page: <http://www.apple.com/legal/itunes/us/terms.html#APPS> I looked into putting the HTML code for that section of the Terms of Use in `<textarea>` element, but apparently `<textarea>` will not render HTML code. Is there a solution so that I do not have a web page like 4000px high? Thanks.
2012/08/23
[ "https://Stackoverflow.com/questions/12099259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/821722/" ]
Put the content into a div with a fixed height, and set the css overflow property to 'auto' this will create a scrollable div ``` <div style='height:80px; overflow:auto;'> content here </div> ``` of course you should use a separate style sheet but that's a different story
You can create a div to contain the content and specify a height, then user overflow: auto in your CSS to make it scrollable. Like this:- <http://jsbin.com/ifolaf/2/edit>
33,696,944
Starting from v2.0 Elasticsearch is listening only on localhost by default, but I'd like to make request outside localhost. For example, a request like this is allowed: `http://localhost:9200/` But this is not: `http://server_name:9200/` (from outside of the server, eg: a local computer in the same LAN). Thanks for your help.
2015/11/13
[ "https://Stackoverflow.com/questions/33696944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4184594/" ]
In /etc/elasticsearch/elasticsearch.yml set the following value: `network.host: [ localhost, _site_ ]` This option allows you to access from both the localhost and from all computers on the local network (192.168.X.X), but not from outside. [Read more about this and other options read the documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-network.html#network-interface-values)
In the remote machine where elasticsearch is installed just add the below two configurations in `/etc/elasticsearch/elasticsearch.yml` ``` network.host: xx.xx.xx.xx #remote elastic machine's internal IP discovery.type: single-node ``` Tested on elasticsearch 6.8.3 and AWS EC2 Linux AMI as remote machine
33,696,944
Starting from v2.0 Elasticsearch is listening only on localhost by default, but I'd like to make request outside localhost. For example, a request like this is allowed: `http://localhost:9200/` But this is not: `http://server_name:9200/` (from outside of the server, eg: a local computer in the same LAN). Thanks for your help.
2015/11/13
[ "https://Stackoverflow.com/questions/33696944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4184594/" ]
In `/etc/elasticsearch/elasticsearch.yml`: ``` network.host: 0.0.0.0 network.bind_host: 0.0.0.0 network.publish_host: 0.0.0.0 ```
For **ElasticSearch 7.8** and up Check if you're on single node. add following line ``` cluster.initial_master_nodes: node-1 ``` To access the Elasticsearch server from another computer or application, make the following changes to the node’s `C:\ProgramData\Elastic\Elasticsearch\config\elasticsearch.yml file:` Add following lines ``` network.host: ["0.0.0.0", 127.0.0.1", "[::1]"] network.bind_host: 0.0.0.0 network.publish_host: 0.0.0.0 http.host: 0.0.0.0 ``` Some time you might need to **Enable CORS** ``` http.cors.enabled : true http.cors.allow-origin : "*" http.cors.allow-methods : OPTIONS, HEAD, GET, POST, PUT, DELETE http.cors.allow-headers : X-Requested-With,X-Auth-Token,Content-Type, Content-Length ``` **Here is my full yml file** ``` bootstrap.memory_lock: false cluster.name: elasticsearch http.port: 9200 node.data: true node.ingest: true node.master: true node.max_local_storage_nodes: 1 cluster.initial_master_nodes: node-1 node.name: ITDEV path.data: C:\ProgramData\Elastic\Elasticsearch\data path.logs: C:\ProgramData\Elastic\Elasticsearch\logs transport.tcp.port: 9300 xpack.license.self_generated.type: basic xpack.security.enabled: false network.host: ["0.0.0.0", 127.0.0.1", "[::1]"] network.bind_host: 0.0.0.0 network.publish_host: 0.0.0.0 http.host: 0.0.0.0 http.cors.enabled : true http.cors.allow-origin : "*" http.cors.allow-methods : OPTIONS, HEAD, GET, POST, PUT, DELETE http.cors.allow-headers : X-Requested-With,X-Auth-Token,Content-Type, Content-Length ```
33,696,944
Starting from v2.0 Elasticsearch is listening only on localhost by default, but I'd like to make request outside localhost. For example, a request like this is allowed: `http://localhost:9200/` But this is not: `http://server_name:9200/` (from outside of the server, eg: a local computer in the same LAN). Thanks for your help.
2015/11/13
[ "https://Stackoverflow.com/questions/33696944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4184594/" ]
In `/etc/elasticsearch/elasticsearch.yml`: ``` network.host: 0.0.0.0 network.bind_host: 0.0.0.0 network.publish_host: 0.0.0.0 ```
Apart from setting `network.host : 0.0.0.0` there might be need to set following params ``` node.name: elasticsearch-node-1 cluster.initial_master_nodes: ["elasticsearch-node-1"] ``` All setting go in `elasticsearch/elasticsearch.yml`
33,696,944
Starting from v2.0 Elasticsearch is listening only on localhost by default, but I'd like to make request outside localhost. For example, a request like this is allowed: `http://localhost:9200/` But this is not: `http://server_name:9200/` (from outside of the server, eg: a local computer in the same LAN). Thanks for your help.
2015/11/13
[ "https://Stackoverflow.com/questions/33696944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4184594/" ]
In Elastic Search 7.0 update `/etc/elasticsearch/elasticsearch.yml` ``` network.host: 0.0.0.0 network.bind_host: 0.0.0.0 network.publish_host: 0.0.0.0 ``` Additionally: ``` discovery.seed_hosts: ["0.0.0.0", "[::0]"] ``` \*\* Don't forget to restart after changing the config. If still Elastic search not restarted check log `journalctl -xe`
For **ElasticSearch 7.8** and up Check if you're on single node. add following line ``` cluster.initial_master_nodes: node-1 ``` To access the Elasticsearch server from another computer or application, make the following changes to the node’s `C:\ProgramData\Elastic\Elasticsearch\config\elasticsearch.yml file:` Add following lines ``` network.host: ["0.0.0.0", 127.0.0.1", "[::1]"] network.bind_host: 0.0.0.0 network.publish_host: 0.0.0.0 http.host: 0.0.0.0 ``` Some time you might need to **Enable CORS** ``` http.cors.enabled : true http.cors.allow-origin : "*" http.cors.allow-methods : OPTIONS, HEAD, GET, POST, PUT, DELETE http.cors.allow-headers : X-Requested-With,X-Auth-Token,Content-Type, Content-Length ``` **Here is my full yml file** ``` bootstrap.memory_lock: false cluster.name: elasticsearch http.port: 9200 node.data: true node.ingest: true node.master: true node.max_local_storage_nodes: 1 cluster.initial_master_nodes: node-1 node.name: ITDEV path.data: C:\ProgramData\Elastic\Elasticsearch\data path.logs: C:\ProgramData\Elastic\Elasticsearch\logs transport.tcp.port: 9300 xpack.license.self_generated.type: basic xpack.security.enabled: false network.host: ["0.0.0.0", 127.0.0.1", "[::1]"] network.bind_host: 0.0.0.0 network.publish_host: 0.0.0.0 http.host: 0.0.0.0 http.cors.enabled : true http.cors.allow-origin : "*" http.cors.allow-methods : OPTIONS, HEAD, GET, POST, PUT, DELETE http.cors.allow-headers : X-Requested-With,X-Auth-Token,Content-Type, Content-Length ```
33,696,944
Starting from v2.0 Elasticsearch is listening only on localhost by default, but I'd like to make request outside localhost. For example, a request like this is allowed: `http://localhost:9200/` But this is not: `http://server_name:9200/` (from outside of the server, eg: a local computer in the same LAN). Thanks for your help.
2015/11/13
[ "https://Stackoverflow.com/questions/33696944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4184594/" ]
Rename the elasticsearch.yml file to elasticsearch.json inside config folder and add: ``` { "network" : { "host" : "10.0.0.4" } } ``` Another option is to provide the settings externally either using the ES\_JAVA\_OPTS or as parameters to the elasticsearch command, for example: `$ elasticsearch -Des.network.host=10.0.0.4` Another option is to set es.default. prefix instead of es. prefix, which means the default setting will be used only if not explicitly set in the configuration file. Another option is to use the `${...}` notation within the configuration file which will resolve to an environment setting, for example: ``` { "network" : { "host" : "${ES_NET_HOST}" } } ``` The location of the configuration file can be set externally using a system property: `$ elasticsearch -Des.config=/path/to/config/file` For more info, check out <https://www.elastic.co/guide/en/elasticsearch/reference/1.4/setup-configuration.html>
In `/etc/elasticsearch/elasticsearch.yml`: ``` network.host: 0.0.0.0 network.bind_host: 0.0.0.0 network.publish_host: 0.0.0.0 ```
33,696,944
Starting from v2.0 Elasticsearch is listening only on localhost by default, but I'd like to make request outside localhost. For example, a request like this is allowed: `http://localhost:9200/` But this is not: `http://server_name:9200/` (from outside of the server, eg: a local computer in the same LAN). Thanks for your help.
2015/11/13
[ "https://Stackoverflow.com/questions/33696944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4184594/" ]
In the remote machine where elasticsearch is installed just add the below two configurations in `/etc/elasticsearch/elasticsearch.yml` ``` network.host: xx.xx.xx.xx #remote elastic machine's internal IP discovery.type: single-node ``` Tested on elasticsearch 6.8.3 and AWS EC2 Linux AMI as remote machine
in my server ubuntu 22.04, it needs like below: ``` transport.host: localhost transport.tcp.port: 9300 http.port: 9200 network.host: 0.0.0.0 ```
33,696,944
Starting from v2.0 Elasticsearch is listening only on localhost by default, but I'd like to make request outside localhost. For example, a request like this is allowed: `http://localhost:9200/` But this is not: `http://server_name:9200/` (from outside of the server, eg: a local computer in the same LAN). Thanks for your help.
2015/11/13
[ "https://Stackoverflow.com/questions/33696944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4184594/" ]
As @arsent mentioned add that ip address to the config file: ``` sudo nano /etc/elasticsearch/elasticsearch.yml ``` Jay also added an important point - if you're using a firewall, remember to add a rule allowing traffic to that port. If you want to allow a master server to access ES over http, then add a rule allowing access to only from that particular address. For example, say you are using ufw, then run this command to add your port: ``` sudo ufw allow from xxx.xxx.xxx.xxx to any port zzzz ``` Replace xxx.xxx.xxx.xxx with your master server IP address and zzzz with the port you configured in `config/elasticsearch.yml` It is recommended to use a custom port and not keep the default 9200 To test it, SSH into your master server and ping the ES ip with the correct port to see if you get a response: ``` curl -X GET 'http://xxx.xxx.xxx.xxx:zzzz' ``` You can also verify ES is inaccessible from other IPs by trying it with your browser. There's [an excellent article](https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-elasticsearch-on-ubuntu-16-04) that shows how to set up ES on Ubuntu on DigitalOcean
Apart from setting `network.host : 0.0.0.0` there might be need to set following params ``` node.name: elasticsearch-node-1 cluster.initial_master_nodes: ["elasticsearch-node-1"] ``` All setting go in `elasticsearch/elasticsearch.yml`
33,696,944
Starting from v2.0 Elasticsearch is listening only on localhost by default, but I'd like to make request outside localhost. For example, a request like this is allowed: `http://localhost:9200/` But this is not: `http://server_name:9200/` (from outside of the server, eg: a local computer in the same LAN). Thanks for your help.
2015/11/13
[ "https://Stackoverflow.com/questions/33696944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4184594/" ]
In `/etc/elasticsearch/elasticsearch.yml`: ``` network.host: 0.0.0.0 network.bind_host: 0.0.0.0 network.publish_host: 0.0.0.0 ```
Using Windows 10 and standalone Elasticsearch 7, putting this in elasticsearch.yml solve the issue: network.host: 0.0.0.0 discovery.type: single-node
33,696,944
Starting from v2.0 Elasticsearch is listening only on localhost by default, but I'd like to make request outside localhost. For example, a request like this is allowed: `http://localhost:9200/` But this is not: `http://server_name:9200/` (from outside of the server, eg: a local computer in the same LAN). Thanks for your help.
2015/11/13
[ "https://Stackoverflow.com/questions/33696944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4184594/" ]
In Elastic Search 7.0 update `/etc/elasticsearch/elasticsearch.yml` ``` network.host: 0.0.0.0 network.bind_host: 0.0.0.0 network.publish_host: 0.0.0.0 ``` Additionally: ``` discovery.seed_hosts: ["0.0.0.0", "[::0]"] ``` \*\* Don't forget to restart after changing the config. If still Elastic search not restarted check log `journalctl -xe`
As @arsent mentioned add that ip address to the config file: ``` sudo nano /etc/elasticsearch/elasticsearch.yml ``` Jay also added an important point - if you're using a firewall, remember to add a rule allowing traffic to that port. If you want to allow a master server to access ES over http, then add a rule allowing access to only from that particular address. For example, say you are using ufw, then run this command to add your port: ``` sudo ufw allow from xxx.xxx.xxx.xxx to any port zzzz ``` Replace xxx.xxx.xxx.xxx with your master server IP address and zzzz with the port you configured in `config/elasticsearch.yml` It is recommended to use a custom port and not keep the default 9200 To test it, SSH into your master server and ping the ES ip with the correct port to see if you get a response: ``` curl -X GET 'http://xxx.xxx.xxx.xxx:zzzz' ``` You can also verify ES is inaccessible from other IPs by trying it with your browser. There's [an excellent article](https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-elasticsearch-on-ubuntu-16-04) that shows how to set up ES on Ubuntu on DigitalOcean
33,696,944
Starting from v2.0 Elasticsearch is listening only on localhost by default, but I'd like to make request outside localhost. For example, a request like this is allowed: `http://localhost:9200/` But this is not: `http://server_name:9200/` (from outside of the server, eg: a local computer in the same LAN). Thanks for your help.
2015/11/13
[ "https://Stackoverflow.com/questions/33696944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4184594/" ]
By default http transport and internal elasticsearch transport only listens to localhost. If you want to access Elasticsearch from the host other than localhost then try adding following configurations in **config/elasticsearch.yml**. ``` transport.host: localhost transport.tcp.port: 9300 http.port: 9200 network.host: 0.0.0.0 ``` Here, network.host as 0.0.0.0 allow access from any host within the network.
in my server ubuntu 22.04, it needs like below: ``` transport.host: localhost transport.tcp.port: 9300 http.port: 9200 network.host: 0.0.0.0 ```
32,622,589
Here is a sample of what I have in my table (SQL Server): ``` patientID DateCreated StartOn EndOn --------------------------------------------------- 1234 2015-09-16 2015-09-01 2015-09-30 2345 2015-09-16 2015-09-01 2015-09-30 2346 2015-09-16 2015-09-01 2015-09-30 ``` Currently, it counts the "days" to be 30. So it is really looking at days elapsed between `StartOn` and `EndOn`. I want to be able to do this counting based on `StartOn` and `DateCreated`. So, in my example the "days" should be 16, that is days elapsed from `StartOn` to `DateCreated`.
2015/09/17
[ "https://Stackoverflow.com/questions/32622589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2687803/" ]
You can use `DateDiff(Day,StartOn,DateCreated)`
So you can go with: ``` Select (EndOn - DateCreated +1) As "Days" from Tablename where patientID = 1234; ```
6,959,619
i am getting the following regex from a json from server ``` regexval = ^[A-Za-z\\'\\s\\.\\-\\,]{1,50}$ ``` there is a problem with this regular expression it has a ' which is breaking my js code to test this regular expression. how do i make this a valid regex? im doing something like this to test it ``` if(!regexval.replace(/\\/g,"\\").test(inputVal)) { } ``` **EDIT** following is the JSON ``` [ { "ExtensionData": {}, "Data1": null, "DisplayName": "First Name", "IsRequired": true, "LengthValidation": 0, "Name": "ServiceFirstName", "RegexValidation": "^[A-Za-z\\'\\s\\.\\-\\,]{1,50}$", "Type": "String", "ValidationMessage": "The field 'First Name' doesn't meet the format requirements" }, { "ExtensionData": {}, "Data1": null, "DisplayName": "Last Name", "IsRequired": true, "LengthValidation": 0, "Name": "ServiceLastName", "RegexValidation": "^[A-Za-z\\'\\s\\.\\-\\,]{1,50}$", "Type": "String", "ValidationMessage": "The field 'Last Name' doesn't meet the format requirements" } ] ```
2011/08/05
[ "https://Stackoverflow.com/questions/6959619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/866542/" ]
The double backslashes are evaluated to literal backslashes in RegEx notation... or escaped backslashes in a string (which then escapes the next character when evaluated as a regex). The RegEx build solution is: ``` regexval=/^[A-Za-z\'\s\.\-\,]{1,50}$/ ``` The string-build solution is: ``` regexval = new RegExp("^[A-Za-z\\'\\s\\.\\-\\,]{1,50}$"); ``` Both of these produce a JavaScript [RegEx object](http://www.devguru.com/technologies/ecmascript/quickref/regexp.html) which you can then call `.test` etc on. ``` if (regexval.test(inputVal)) { //... do something } ``` **Your Update** Ok so per your update, if you parse that above structure into a local JS object called `jsonobj` (for example... how to parse etc I assume you know) and you want to just test the first entry in the JSON array returned... you'd need to do the following: ``` //jsonobj - JS object after parsing your example JSON above var regex=new RegEx(jsonobj[0].RegexValidation); if (regex.test(inputVal)) { //... do your work here } ```
``` regexval = /^[A-Za-z\\'\\s\\.\\-\\,]{1,50}$/ ``` you're missing the /s needed to make it a regex value and it looks like you actually need ``` regexval = /^[A-Za-z\'\s\.\-\,]{1,50}$/ ```
6,959,619
i am getting the following regex from a json from server ``` regexval = ^[A-Za-z\\'\\s\\.\\-\\,]{1,50}$ ``` there is a problem with this regular expression it has a ' which is breaking my js code to test this regular expression. how do i make this a valid regex? im doing something like this to test it ``` if(!regexval.replace(/\\/g,"\\").test(inputVal)) { } ``` **EDIT** following is the JSON ``` [ { "ExtensionData": {}, "Data1": null, "DisplayName": "First Name", "IsRequired": true, "LengthValidation": 0, "Name": "ServiceFirstName", "RegexValidation": "^[A-Za-z\\'\\s\\.\\-\\,]{1,50}$", "Type": "String", "ValidationMessage": "The field 'First Name' doesn't meet the format requirements" }, { "ExtensionData": {}, "Data1": null, "DisplayName": "Last Name", "IsRequired": true, "LengthValidation": 0, "Name": "ServiceLastName", "RegexValidation": "^[A-Za-z\\'\\s\\.\\-\\,]{1,50}$", "Type": "String", "ValidationMessage": "The field 'Last Name' doesn't meet the format requirements" } ] ```
2011/08/05
[ "https://Stackoverflow.com/questions/6959619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/866542/" ]
Can you change the single quote to a unicode character `/u0027` or use the ASCII `\x27` and have it work properly? See it in action here: <http://jsfiddle.net/TezdR/1/> SO, really you DON'T need to do the replace but can use the "string" as it is - here is an updated version where you can see I do the replace on FirstName but not on last - and they both should work the same: <http://jsfiddle.net/TezdR/2/>
``` regexval = /^[A-Za-z\\'\\s\\.\\-\\,]{1,50}$/ ``` you're missing the /s needed to make it a regex value and it looks like you actually need ``` regexval = /^[A-Za-z\'\s\.\-\,]{1,50}$/ ```
29,600,101
Is there any possibility to change marker form and size for data cursor in Matlab? I mean it is black and square by default. I would like to change it to blue and circle, for example. I've found only how to customize text of data tips. Thank you.
2015/04/13
[ "https://Stackoverflow.com/questions/29600101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4781789/" ]
Yes - marker options are included in the properties of the undocumented `graphics.datatip` object class. These objects are accessible as hidden properties of the `graphics.datacursormanager` objects accessible through the documented `[datacursormode](http://mathworks.com/help/matlab/ref/datacursormode.html)` function. The `.DataCursors` property contains an array of these objects for each Data Cursor in the figure and `.CurrentDataCursor` property contains the object for the current one. To take your example, to change the marker for the current Data Cursor of the current figure to a blue circle, you can do as follows: ```matlab dcm_obj = datacursormode(gcf); set(dcm_obj.CurrentDataCursor, 'Marker','o', 'MarkerFaceColor','b'); ``` More detailed information about the undocumented functionality can be found at <http://undocumentedmatlab.com/blog/controlling-plot-data-tips>
yes it is possible by set `Pointer` property of `figure` to `custom` and then set the value for `PointerShapeCData` as per your choice but you can't change to RGB color format. Because `PointerShapeCData` property accept value 1 and 2. value 1 means black and 2 means white. for example : ``` a = zeros(16,16); % create matrix with size of 16 X 16 with value zero a(:,:) = 1; % assign all element value of matrix a to 1. figure('Pointer','custom ','PointerShapeCData',a); % change some element value of a variable as 2 for change black to white. a(:,1) = 2; a(:,3) = 2; a(:,7) = 2; figure('Pointer','custom ','PointerShapeCData',a); ```
29,600,101
Is there any possibility to change marker form and size for data cursor in Matlab? I mean it is black and square by default. I would like to change it to blue and circle, for example. I've found only how to customize text of data tips. Thank you.
2015/04/13
[ "https://Stackoverflow.com/questions/29600101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4781789/" ]
Hope this helps..... For white background and classic look.... * alldatacursors = findall(gcf,'type','hggroup') * set(alldatacursors,'FontSize',11) * set(alldatacursors,'FontName','Times') * set(alldatacursors,'BackgroundColor','w');
yes it is possible by set `Pointer` property of `figure` to `custom` and then set the value for `PointerShapeCData` as per your choice but you can't change to RGB color format. Because `PointerShapeCData` property accept value 1 and 2. value 1 means black and 2 means white. for example : ``` a = zeros(16,16); % create matrix with size of 16 X 16 with value zero a(:,:) = 1; % assign all element value of matrix a to 1. figure('Pointer','custom ','PointerShapeCData',a); % change some element value of a variable as 2 for change black to white. a(:,1) = 2; a(:,3) = 2; a(:,7) = 2; figure('Pointer','custom ','PointerShapeCData',a); ```
8,317,397
I have two tables: One table is a "catalog" that stores a pageID, tableLocation, and a pageName. The tableLocation is where the content for that page is stored (I have multiple areas of a the site... anyway). I need to get data from the "tableLocation" so I want to do an JOIN so I can get all the data I need for the catalog and the needed table. Of course I don't know what table to look into without the "tableLocation" data. I'm trying to use the following SQL statement: ``` SELECT p.pageID,p.tableLocation,p.pageName FROM pageCatalog p INNER JOIN (SELECT tableLocation FROM pageCatalog WHERE pageName='PAGENAME') d ON (p.pageID = d.pageID) WHERE p.pageName='PAGENAME' ``` I'm getting an error, "Invalid column name 'pageID'" If I replace the second SELECT with specific tableLocation it works. So the error is with the "INNER JOIN (SELECT..." but I'm not sure what the issue is. Any ideas? ------------- EDIT ---------- More detail: for example pageCatalog has this ``` pageID tableLocation pageName 167 tableA page1 12 tableB page2 250 tableC page3 ``` in this example I have 3 tables. I need to pull data from table\* but I need the tableLocation first. tableB has pageTitle. I need to join the two tables to get that data.
2011/11/29
[ "https://Stackoverflow.com/questions/8317397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/249316/" ]
``` (SELECT tableLocation FROM pageCatalog WHERE pageName='PAGENAME') AS d ``` I don't see a column named `pageID`, but you reference `d.pageID` Did you mean to do this: ``` (SELECT pageID FROM pageCatalog WHERE pageName='PAGENAME') AS d ```
You're not SELECTing pageID from the subquery. Try this: ``` SELECT p.pageID,p.tableLocation,p.pageName FROM pageCatalog p INNER JOIN (SELECT tableLocation, pageID FROM pageCatalog WHERE pageName='PAGENAME') d ON (p.pageID = d.pageID) WHERE p.pageName='PAGENAME' ``` Or better yet, don't use a subquery at all: ``` SELECT p.pageID, p.tableLocation, p.pageName FROM pageCatalog p INNER JOIN pageCatalog d ON p.pageID = d.pageID WHERE p.pageName='PAGENAME' AND d.pageName = 'PAGENAME'; ```
8,317,397
I have two tables: One table is a "catalog" that stores a pageID, tableLocation, and a pageName. The tableLocation is where the content for that page is stored (I have multiple areas of a the site... anyway). I need to get data from the "tableLocation" so I want to do an JOIN so I can get all the data I need for the catalog and the needed table. Of course I don't know what table to look into without the "tableLocation" data. I'm trying to use the following SQL statement: ``` SELECT p.pageID,p.tableLocation,p.pageName FROM pageCatalog p INNER JOIN (SELECT tableLocation FROM pageCatalog WHERE pageName='PAGENAME') d ON (p.pageID = d.pageID) WHERE p.pageName='PAGENAME' ``` I'm getting an error, "Invalid column name 'pageID'" If I replace the second SELECT with specific tableLocation it works. So the error is with the "INNER JOIN (SELECT..." but I'm not sure what the issue is. Any ideas? ------------- EDIT ---------- More detail: for example pageCatalog has this ``` pageID tableLocation pageName 167 tableA page1 12 tableB page2 250 tableC page3 ``` in this example I have 3 tables. I need to pull data from table\* but I need the tableLocation first. tableB has pageTitle. I need to join the two tables to get that data.
2011/11/29
[ "https://Stackoverflow.com/questions/8317397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/249316/" ]
``` (SELECT tableLocation FROM pageCatalog WHERE pageName='PAGENAME') AS d ``` I don't see a column named `pageID`, but you reference `d.pageID` Did you mean to do this: ``` (SELECT pageID FROM pageCatalog WHERE pageName='PAGENAME') AS d ```
Your subselect aliased as `d` doesn't contain a `pageID`. Try changing that to: ``` INNER JOIN (SELECT tableLocation, pageID FROM pageCatalog WHERE pageName='PAGENAME') d ON (p.pageID = d.pageID) ```
8,317,397
I have two tables: One table is a "catalog" that stores a pageID, tableLocation, and a pageName. The tableLocation is where the content for that page is stored (I have multiple areas of a the site... anyway). I need to get data from the "tableLocation" so I want to do an JOIN so I can get all the data I need for the catalog and the needed table. Of course I don't know what table to look into without the "tableLocation" data. I'm trying to use the following SQL statement: ``` SELECT p.pageID,p.tableLocation,p.pageName FROM pageCatalog p INNER JOIN (SELECT tableLocation FROM pageCatalog WHERE pageName='PAGENAME') d ON (p.pageID = d.pageID) WHERE p.pageName='PAGENAME' ``` I'm getting an error, "Invalid column name 'pageID'" If I replace the second SELECT with specific tableLocation it works. So the error is with the "INNER JOIN (SELECT..." but I'm not sure what the issue is. Any ideas? ------------- EDIT ---------- More detail: for example pageCatalog has this ``` pageID tableLocation pageName 167 tableA page1 12 tableB page2 250 tableC page3 ``` in this example I have 3 tables. I need to pull data from table\* but I need the tableLocation first. tableB has pageTitle. I need to join the two tables to get that data.
2011/11/29
[ "https://Stackoverflow.com/questions/8317397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/249316/" ]
In your inner SELECT you only select the `tableLocation` column, but then you try to refer to a `pageID` column as `d.pageID`. Try adding that column to the inner SELECT: ``` SELECT p.pageID,p.tableLocation,p.pageName FROM pageCatalog p INNER JOIN (SELECT tableLocation, pageID FROM pageCatalog WHERE pageName='PAGENAME') d ON (p.pageID = d.pageID) WHERE p.pageName='PAGENAME' ```
Your subselect aliased as `d` doesn't contain a `pageID`. Try changing that to: ``` INNER JOIN (SELECT tableLocation, pageID FROM pageCatalog WHERE pageName='PAGENAME') d ON (p.pageID = d.pageID) ```
8,317,397
I have two tables: One table is a "catalog" that stores a pageID, tableLocation, and a pageName. The tableLocation is where the content for that page is stored (I have multiple areas of a the site... anyway). I need to get data from the "tableLocation" so I want to do an JOIN so I can get all the data I need for the catalog and the needed table. Of course I don't know what table to look into without the "tableLocation" data. I'm trying to use the following SQL statement: ``` SELECT p.pageID,p.tableLocation,p.pageName FROM pageCatalog p INNER JOIN (SELECT tableLocation FROM pageCatalog WHERE pageName='PAGENAME') d ON (p.pageID = d.pageID) WHERE p.pageName='PAGENAME' ``` I'm getting an error, "Invalid column name 'pageID'" If I replace the second SELECT with specific tableLocation it works. So the error is with the "INNER JOIN (SELECT..." but I'm not sure what the issue is. Any ideas? ------------- EDIT ---------- More detail: for example pageCatalog has this ``` pageID tableLocation pageName 167 tableA page1 12 tableB page2 250 tableC page3 ``` in this example I have 3 tables. I need to pull data from table\* but I need the tableLocation first. tableB has pageTitle. I need to join the two tables to get that data.
2011/11/29
[ "https://Stackoverflow.com/questions/8317397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/249316/" ]
You're not SELECTing pageID from the subquery. Try this: ``` SELECT p.pageID,p.tableLocation,p.pageName FROM pageCatalog p INNER JOIN (SELECT tableLocation, pageID FROM pageCatalog WHERE pageName='PAGENAME') d ON (p.pageID = d.pageID) WHERE p.pageName='PAGENAME' ``` Or better yet, don't use a subquery at all: ``` SELECT p.pageID, p.tableLocation, p.pageName FROM pageCatalog p INNER JOIN pageCatalog d ON p.pageID = d.pageID WHERE p.pageName='PAGENAME' AND d.pageName = 'PAGENAME'; ```
I just did two query statements. First stored the tableLocation as a variable the second query replace the second SELECT with the variable. I wanted to avoid two queries but didn't see a way.
8,317,397
I have two tables: One table is a "catalog" that stores a pageID, tableLocation, and a pageName. The tableLocation is where the content for that page is stored (I have multiple areas of a the site... anyway). I need to get data from the "tableLocation" so I want to do an JOIN so I can get all the data I need for the catalog and the needed table. Of course I don't know what table to look into without the "tableLocation" data. I'm trying to use the following SQL statement: ``` SELECT p.pageID,p.tableLocation,p.pageName FROM pageCatalog p INNER JOIN (SELECT tableLocation FROM pageCatalog WHERE pageName='PAGENAME') d ON (p.pageID = d.pageID) WHERE p.pageName='PAGENAME' ``` I'm getting an error, "Invalid column name 'pageID'" If I replace the second SELECT with specific tableLocation it works. So the error is with the "INNER JOIN (SELECT..." but I'm not sure what the issue is. Any ideas? ------------- EDIT ---------- More detail: for example pageCatalog has this ``` pageID tableLocation pageName 167 tableA page1 12 tableB page2 250 tableC page3 ``` in this example I have 3 tables. I need to pull data from table\* but I need the tableLocation first. tableB has pageTitle. I need to join the two tables to get that data.
2011/11/29
[ "https://Stackoverflow.com/questions/8317397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/249316/" ]
In your inner SELECT you only select the `tableLocation` column, but then you try to refer to a `pageID` column as `d.pageID`. Try adding that column to the inner SELECT: ``` SELECT p.pageID,p.tableLocation,p.pageName FROM pageCatalog p INNER JOIN (SELECT tableLocation, pageID FROM pageCatalog WHERE pageName='PAGENAME') d ON (p.pageID = d.pageID) WHERE p.pageName='PAGENAME' ```
There's just no `pageID` in your sub query. Change it to this: ``` SELECT p.pageID,p.tableLocation,p.pageName FROM pageCatalog p INNER JOIN (SELECT tableLocation, pageID FROM pageCatalog WHERE pageName='PAGENAME') d ON (p.pageID = d.pageID) WHERE p.pageName='PAGENAME' ```
8,317,397
I have two tables: One table is a "catalog" that stores a pageID, tableLocation, and a pageName. The tableLocation is where the content for that page is stored (I have multiple areas of a the site... anyway). I need to get data from the "tableLocation" so I want to do an JOIN so I can get all the data I need for the catalog and the needed table. Of course I don't know what table to look into without the "tableLocation" data. I'm trying to use the following SQL statement: ``` SELECT p.pageID,p.tableLocation,p.pageName FROM pageCatalog p INNER JOIN (SELECT tableLocation FROM pageCatalog WHERE pageName='PAGENAME') d ON (p.pageID = d.pageID) WHERE p.pageName='PAGENAME' ``` I'm getting an error, "Invalid column name 'pageID'" If I replace the second SELECT with specific tableLocation it works. So the error is with the "INNER JOIN (SELECT..." but I'm not sure what the issue is. Any ideas? ------------- EDIT ---------- More detail: for example pageCatalog has this ``` pageID tableLocation pageName 167 tableA page1 12 tableB page2 250 tableC page3 ``` in this example I have 3 tables. I need to pull data from table\* but I need the tableLocation first. tableB has pageTitle. I need to join the two tables to get that data.
2011/11/29
[ "https://Stackoverflow.com/questions/8317397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/249316/" ]
``` (SELECT tableLocation FROM pageCatalog WHERE pageName='PAGENAME') AS d ``` I don't see a column named `pageID`, but you reference `d.pageID` Did you mean to do this: ``` (SELECT pageID FROM pageCatalog WHERE pageName='PAGENAME') AS d ```
There's just no `pageID` in your sub query. Change it to this: ``` SELECT p.pageID,p.tableLocation,p.pageName FROM pageCatalog p INNER JOIN (SELECT tableLocation, pageID FROM pageCatalog WHERE pageName='PAGENAME') d ON (p.pageID = d.pageID) WHERE p.pageName='PAGENAME' ```
8,317,397
I have two tables: One table is a "catalog" that stores a pageID, tableLocation, and a pageName. The tableLocation is where the content for that page is stored (I have multiple areas of a the site... anyway). I need to get data from the "tableLocation" so I want to do an JOIN so I can get all the data I need for the catalog and the needed table. Of course I don't know what table to look into without the "tableLocation" data. I'm trying to use the following SQL statement: ``` SELECT p.pageID,p.tableLocation,p.pageName FROM pageCatalog p INNER JOIN (SELECT tableLocation FROM pageCatalog WHERE pageName='PAGENAME') d ON (p.pageID = d.pageID) WHERE p.pageName='PAGENAME' ``` I'm getting an error, "Invalid column name 'pageID'" If I replace the second SELECT with specific tableLocation it works. So the error is with the "INNER JOIN (SELECT..." but I'm not sure what the issue is. Any ideas? ------------- EDIT ---------- More detail: for example pageCatalog has this ``` pageID tableLocation pageName 167 tableA page1 12 tableB page2 250 tableC page3 ``` in this example I have 3 tables. I need to pull data from table\* but I need the tableLocation first. tableB has pageTitle. I need to join the two tables to get that data.
2011/11/29
[ "https://Stackoverflow.com/questions/8317397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/249316/" ]
In your inner SELECT you only select the `tableLocation` column, but then you try to refer to a `pageID` column as `d.pageID`. Try adding that column to the inner SELECT: ``` SELECT p.pageID,p.tableLocation,p.pageName FROM pageCatalog p INNER JOIN (SELECT tableLocation, pageID FROM pageCatalog WHERE pageName='PAGENAME') d ON (p.pageID = d.pageID) WHERE p.pageName='PAGENAME' ```
You're not SELECTing pageID from the subquery. Try this: ``` SELECT p.pageID,p.tableLocation,p.pageName FROM pageCatalog p INNER JOIN (SELECT tableLocation, pageID FROM pageCatalog WHERE pageName='PAGENAME') d ON (p.pageID = d.pageID) WHERE p.pageName='PAGENAME' ``` Or better yet, don't use a subquery at all: ``` SELECT p.pageID, p.tableLocation, p.pageName FROM pageCatalog p INNER JOIN pageCatalog d ON p.pageID = d.pageID WHERE p.pageName='PAGENAME' AND d.pageName = 'PAGENAME'; ```
8,317,397
I have two tables: One table is a "catalog" that stores a pageID, tableLocation, and a pageName. The tableLocation is where the content for that page is stored (I have multiple areas of a the site... anyway). I need to get data from the "tableLocation" so I want to do an JOIN so I can get all the data I need for the catalog and the needed table. Of course I don't know what table to look into without the "tableLocation" data. I'm trying to use the following SQL statement: ``` SELECT p.pageID,p.tableLocation,p.pageName FROM pageCatalog p INNER JOIN (SELECT tableLocation FROM pageCatalog WHERE pageName='PAGENAME') d ON (p.pageID = d.pageID) WHERE p.pageName='PAGENAME' ``` I'm getting an error, "Invalid column name 'pageID'" If I replace the second SELECT with specific tableLocation it works. So the error is with the "INNER JOIN (SELECT..." but I'm not sure what the issue is. Any ideas? ------------- EDIT ---------- More detail: for example pageCatalog has this ``` pageID tableLocation pageName 167 tableA page1 12 tableB page2 250 tableC page3 ``` in this example I have 3 tables. I need to pull data from table\* but I need the tableLocation first. tableB has pageTitle. I need to join the two tables to get that data.
2011/11/29
[ "https://Stackoverflow.com/questions/8317397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/249316/" ]
Your subselect aliased as `d` doesn't contain a `pageID`. Try changing that to: ``` INNER JOIN (SELECT tableLocation, pageID FROM pageCatalog WHERE pageName='PAGENAME') d ON (p.pageID = d.pageID) ```
I just did two query statements. First stored the tableLocation as a variable the second query replace the second SELECT with the variable. I wanted to avoid two queries but didn't see a way.
8,317,397
I have two tables: One table is a "catalog" that stores a pageID, tableLocation, and a pageName. The tableLocation is where the content for that page is stored (I have multiple areas of a the site... anyway). I need to get data from the "tableLocation" so I want to do an JOIN so I can get all the data I need for the catalog and the needed table. Of course I don't know what table to look into without the "tableLocation" data. I'm trying to use the following SQL statement: ``` SELECT p.pageID,p.tableLocation,p.pageName FROM pageCatalog p INNER JOIN (SELECT tableLocation FROM pageCatalog WHERE pageName='PAGENAME') d ON (p.pageID = d.pageID) WHERE p.pageName='PAGENAME' ``` I'm getting an error, "Invalid column name 'pageID'" If I replace the second SELECT with specific tableLocation it works. So the error is with the "INNER JOIN (SELECT..." but I'm not sure what the issue is. Any ideas? ------------- EDIT ---------- More detail: for example pageCatalog has this ``` pageID tableLocation pageName 167 tableA page1 12 tableB page2 250 tableC page3 ``` in this example I have 3 tables. I need to pull data from table\* but I need the tableLocation first. tableB has pageTitle. I need to join the two tables to get that data.
2011/11/29
[ "https://Stackoverflow.com/questions/8317397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/249316/" ]
In your inner SELECT you only select the `tableLocation` column, but then you try to refer to a `pageID` column as `d.pageID`. Try adding that column to the inner SELECT: ``` SELECT p.pageID,p.tableLocation,p.pageName FROM pageCatalog p INNER JOIN (SELECT tableLocation, pageID FROM pageCatalog WHERE pageName='PAGENAME') d ON (p.pageID = d.pageID) WHERE p.pageName='PAGENAME' ```
I just did two query statements. First stored the tableLocation as a variable the second query replace the second SELECT with the variable. I wanted to avoid two queries but didn't see a way.
8,317,397
I have two tables: One table is a "catalog" that stores a pageID, tableLocation, and a pageName. The tableLocation is where the content for that page is stored (I have multiple areas of a the site... anyway). I need to get data from the "tableLocation" so I want to do an JOIN so I can get all the data I need for the catalog and the needed table. Of course I don't know what table to look into without the "tableLocation" data. I'm trying to use the following SQL statement: ``` SELECT p.pageID,p.tableLocation,p.pageName FROM pageCatalog p INNER JOIN (SELECT tableLocation FROM pageCatalog WHERE pageName='PAGENAME') d ON (p.pageID = d.pageID) WHERE p.pageName='PAGENAME' ``` I'm getting an error, "Invalid column name 'pageID'" If I replace the second SELECT with specific tableLocation it works. So the error is with the "INNER JOIN (SELECT..." but I'm not sure what the issue is. Any ideas? ------------- EDIT ---------- More detail: for example pageCatalog has this ``` pageID tableLocation pageName 167 tableA page1 12 tableB page2 250 tableC page3 ``` in this example I have 3 tables. I need to pull data from table\* but I need the tableLocation first. tableB has pageTitle. I need to join the two tables to get that data.
2011/11/29
[ "https://Stackoverflow.com/questions/8317397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/249316/" ]
In your inner SELECT you only select the `tableLocation` column, but then you try to refer to a `pageID` column as `d.pageID`. Try adding that column to the inner SELECT: ``` SELECT p.pageID,p.tableLocation,p.pageName FROM pageCatalog p INNER JOIN (SELECT tableLocation, pageID FROM pageCatalog WHERE pageName='PAGENAME') d ON (p.pageID = d.pageID) WHERE p.pageName='PAGENAME' ```
You have - ``` (SELECT tableLocation FROM pageCatalog WHERE pageName='PAGENAME') d ``` then ``` ON (p.pageID = d.pageID) ``` The `d` table will only contain the column `tableLocation` at this point.
23,429,533
In order to translate windows vista thread pool API to use in my delphi application. I need to know the definition of `_TP_POOL`. I looked into `winnt.h` and found the following `typedef` declaration: ``` typedef struct _TP_POOL TP_POOL, *PTP_POOL; ``` I can't find the `_TP_POOL` on my local header files. Which is the location of it?
2014/05/02
[ "https://Stackoverflow.com/questions/23429533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2087187/" ]
The `PTP_POOL` is an opaque pointer. You never get to know, or indeed need to know, what that pointer refers to. The thread pool API serves up `PTP_POOL` values when you call `CreateThreadpool`. And you then pass those opaque pointer values back to the other thread pool API functions that you call. The thread pool API implementation knows what the pointer refers to, but you simply do not need to. In Delphi I would declare it like this: ``` type PTP_POOL = type Pointer; ``` I'm declaring this as a distinct type so that the compiler will ensure that you don't assign pointers to other types to variables of type `PTP_POOL`.
`_TP_POOL` is an incomplete type, which is never completed in the public headers. This is a common C and C++ idiom for type-safe opaque handles. In other words, they are used to completely hide the implementation. The probably best-known example is `FILE`.
23,429,533
In order to translate windows vista thread pool API to use in my delphi application. I need to know the definition of `_TP_POOL`. I looked into `winnt.h` and found the following `typedef` declaration: ``` typedef struct _TP_POOL TP_POOL, *PTP_POOL; ``` I can't find the `_TP_POOL` on my local header files. Which is the location of it?
2014/05/02
[ "https://Stackoverflow.com/questions/23429533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2087187/" ]
The `PTP_POOL` is an opaque pointer. You never get to know, or indeed need to know, what that pointer refers to. The thread pool API serves up `PTP_POOL` values when you call `CreateThreadpool`. And you then pass those opaque pointer values back to the other thread pool API functions that you call. The thread pool API implementation knows what the pointer refers to, but you simply do not need to. In Delphi I would declare it like this: ``` type PTP_POOL = type Pointer; ``` I'm declaring this as a distinct type so that the compiler will ensure that you don't assign pointers to other types to variables of type `PTP_POOL`.
It's not defined. But given that TP\_POOL is always passed around via pointer (PTP\_POOL), you don't need to know its exact internals. Just treat PTP\_POOL as if was declared as a VOID\* reference.
60,762,637
so i have this code ``` test = json.load(open('data.json')) print (test) print(test[MACadress]) ``` and i can't get the value of MACadress, i already tried test.get(MACadress) i get this error: //this is test : {'MACadress': '0x1c1bb5d3ce17', 'daate': '2020-03-19 17:33:19.715129', 'CPU': 2051.929375, 'mem': 26.0, 'disk': 57.1, 'process': 333, 'users': '1'} //error message: Traceback (most recent call last): File "recepteur\_infos\_machines.py", line 11, in print(test[MACadress]) NameError: name 'MACadress' is not defined
2020/03/19
[ "https://Stackoverflow.com/questions/60762637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10570656/" ]
`print(test["MACadress"])` the key is a string. Without quotes you are referencing a non-existent variable.
You need to surround MACadress with hyphens, for python to treat it as a string. That is, the code should be: test = json.load(open('data.json')) print (test) print(test['MACadress'])
60,762,637
so i have this code ``` test = json.load(open('data.json')) print (test) print(test[MACadress]) ``` and i can't get the value of MACadress, i already tried test.get(MACadress) i get this error: //this is test : {'MACadress': '0x1c1bb5d3ce17', 'daate': '2020-03-19 17:33:19.715129', 'CPU': 2051.929375, 'mem': 26.0, 'disk': 57.1, 'process': 333, 'users': '1'} //error message: Traceback (most recent call last): File "recepteur\_infos\_machines.py", line 11, in print(test[MACadress]) NameError: name 'MACadress' is not defined
2020/03/19
[ "https://Stackoverflow.com/questions/60762637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10570656/" ]
`print(test["MACadress"])` the key is a string. Without quotes you are referencing a non-existent variable.
The dictionary key in this case is a string. (A word without quotations is a variable in python) So if you write the following: `print(test['MACadress'])` It should print out the string: '0x1c1bb5d3ce17'
4,522,117
I'm not quite grokking a couple of things in OOP and I'm going to use a fictional understanding of SO to see if I can get help understand. So, on this page we have a question. You can comment on the question. There are also answers. You can comment on the answers. ``` Question - comment - comment - comment Answer -comment Answer -comment -comment -comment Answer -comment -comment ``` So, I'm imagining a very high level understanding of this type of system (in PHP, not .Net as I am not yet familiar with .Net) would be like: ``` $question = new Question; $question->load($this_question_id); // from the URL probably echo $question->getTitle(); ``` To load the answers, I imagine it's something like this ("A"): ``` $answers = new Answers; $answers->loadFromQuestion($question->getID()); // or $answers->loadFromQuestion($this_question_id); while($answer = $answers->getAnswer()) { echo $answer->showFormatted(); } ``` Or, would you do ("B"): ``` $answers->setQuestion($question); // inject the whole obj, so we have access to all the data and public methods in $question $answers->loadFromQuestion(); // the ID would be found via $this->question->getID() instead of from the argument passed in while($answer = $answers->getAnswer()) { echo $answer->showFormatted(); } ``` I guess my problem is, I don't know when or if I should be passing in an entire object, and when I should just be passing in a value. Passing in the entire object gives me a lot of flexibility, but it's more memory and subject to change, I'd guess (like a property or method rename). If "A" style is better, why not just use a function? OOP seems pointless here. Thanks, Hans
2010/12/23
[ "https://Stackoverflow.com/questions/4522117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/289004/" ]
Why pass either? What about: ``` <?php $question = new Question($id); $comments = $question->getComments(); $answers = $question->getAnswers(); echo $question->getTitle(); echo $question->getText(); foreach ($comments as $comment) echo $comments->getText(); foreach ($answers as $answer) { $answer_comments = $answer->getComments(); echo $answer->getText(); foreach ($answer_comments as $comment) echo $comment->getText(); } ``` Where `getComments()` and `getAnswers()` use `$this->id` to retrieve and return an array of comment or answer objects? You could build utility methods in the comment and answer objects that allow you to load by parent id. In which case, just taking an id as a parameter would be nice. ``` $question = new Question($id); $answers = Answer::forQuestion($question->id); $comments = Comment::forQuestion($question->id); $ans_comments = Comment::forAnswer($answer->id); // or some way to distinguish what the parent object is. ``` Edit: Likely the child model (Comment or Answer in this case) doesn't need anything from the parent except and id to do db queries with. Passing in the entire parent object would be overkill. (Also, PHP has a terrible time garbage collecting objects with circular references, which might be fixed in the 5.3 series.)
Both styles are acceptable. Sometimes you only need the value, sometimes you'll need the object. In this example I would personally do something along the lines of your first example, but trivial programs like this don't tend to exist in the wild very often so maybe you want the second piece. My rule of thumb is to do the thing in the least number of lines that still clearly demonstrates what you're attempting to do to anyone who comes after you. The overhead of most object creation vs value passing is something you'll likely never ever have to deal with on modern arch.
4,522,117
I'm not quite grokking a couple of things in OOP and I'm going to use a fictional understanding of SO to see if I can get help understand. So, on this page we have a question. You can comment on the question. There are also answers. You can comment on the answers. ``` Question - comment - comment - comment Answer -comment Answer -comment -comment -comment Answer -comment -comment ``` So, I'm imagining a very high level understanding of this type of system (in PHP, not .Net as I am not yet familiar with .Net) would be like: ``` $question = new Question; $question->load($this_question_id); // from the URL probably echo $question->getTitle(); ``` To load the answers, I imagine it's something like this ("A"): ``` $answers = new Answers; $answers->loadFromQuestion($question->getID()); // or $answers->loadFromQuestion($this_question_id); while($answer = $answers->getAnswer()) { echo $answer->showFormatted(); } ``` Or, would you do ("B"): ``` $answers->setQuestion($question); // inject the whole obj, so we have access to all the data and public methods in $question $answers->loadFromQuestion(); // the ID would be found via $this->question->getID() instead of from the argument passed in while($answer = $answers->getAnswer()) { echo $answer->showFormatted(); } ``` I guess my problem is, I don't know when or if I should be passing in an entire object, and when I should just be passing in a value. Passing in the entire object gives me a lot of flexibility, but it's more memory and subject to change, I'd guess (like a property or method rename). If "A" style is better, why not just use a function? OOP seems pointless here. Thanks, Hans
2010/12/23
[ "https://Stackoverflow.com/questions/4522117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/289004/" ]
Why pass either? What about: ``` <?php $question = new Question($id); $comments = $question->getComments(); $answers = $question->getAnswers(); echo $question->getTitle(); echo $question->getText(); foreach ($comments as $comment) echo $comments->getText(); foreach ($answers as $answer) { $answer_comments = $answer->getComments(); echo $answer->getText(); foreach ($answer_comments as $comment) echo $comment->getText(); } ``` Where `getComments()` and `getAnswers()` use `$this->id` to retrieve and return an array of comment or answer objects? You could build utility methods in the comment and answer objects that allow you to load by parent id. In which case, just taking an id as a parameter would be nice. ``` $question = new Question($id); $answers = Answer::forQuestion($question->id); $comments = Comment::forQuestion($question->id); $ans_comments = Comment::forAnswer($answer->id); // or some way to distinguish what the parent object is. ``` Edit: Likely the child model (Comment or Answer in this case) doesn't need anything from the parent except and id to do db queries with. Passing in the entire parent object would be overkill. (Also, PHP has a terrible time garbage collecting objects with circular references, which might be fixed in the 5.3 series.)
Adding to what @jasonbar already mentioned: > > I don't know when or if I should be passing in an entire object, and when I should just be passing in a value. > > > It depends on the [Coupling](http://en.wikipedia.org/wiki/Coupling_%28computer_science%29) you need and the [Cohesion](http://en.wikipedia.org/wiki/Cohesion_%28computer_science%29) you desire. > > Passing in the entire object gives me a lot of flexibility, but it's more memory and subject to change. > > > PHP does not copy the object when you use it as an argument to a function. Neither do most other languages (either by default, like C# and Java, or upon explicit request, like C and C++)
4,522,117
I'm not quite grokking a couple of things in OOP and I'm going to use a fictional understanding of SO to see if I can get help understand. So, on this page we have a question. You can comment on the question. There are also answers. You can comment on the answers. ``` Question - comment - comment - comment Answer -comment Answer -comment -comment -comment Answer -comment -comment ``` So, I'm imagining a very high level understanding of this type of system (in PHP, not .Net as I am not yet familiar with .Net) would be like: ``` $question = new Question; $question->load($this_question_id); // from the URL probably echo $question->getTitle(); ``` To load the answers, I imagine it's something like this ("A"): ``` $answers = new Answers; $answers->loadFromQuestion($question->getID()); // or $answers->loadFromQuestion($this_question_id); while($answer = $answers->getAnswer()) { echo $answer->showFormatted(); } ``` Or, would you do ("B"): ``` $answers->setQuestion($question); // inject the whole obj, so we have access to all the data and public methods in $question $answers->loadFromQuestion(); // the ID would be found via $this->question->getID() instead of from the argument passed in while($answer = $answers->getAnswer()) { echo $answer->showFormatted(); } ``` I guess my problem is, I don't know when or if I should be passing in an entire object, and when I should just be passing in a value. Passing in the entire object gives me a lot of flexibility, but it's more memory and subject to change, I'd guess (like a property or method rename). If "A" style is better, why not just use a function? OOP seems pointless here. Thanks, Hans
2010/12/23
[ "https://Stackoverflow.com/questions/4522117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/289004/" ]
While I like Jason's answer, it is not, strictly speaking OO. ``` $question = new Question($id); $comments = $question->getComments(); $answers = $question->getAnswers(); echo $question->getTitle(); echo $question->getText(); foreach ($comments as $comment) echo $comments->getText(); ``` The problems are: 1. There is no information hiding, a fundamental principle of OO. 2. If the format of the answers needs to change, it must be changed in a place that is not associated with the object that houses the data. 3. The solution is not extensible. (There is no behaviour to inherit.) You *must* keep behaviour (tightly coupled) with the data. Otherwise you are not writing OO. ``` $question = new Question($id); $questionView = new QuestionView( $question ); $questionView->displayComments(); $questionView->displayAnswers(); ``` How the information is displayed is now an implementation detail, and reusable. Notice how this opens up the following possibility: ``` $question = new Question( $id ); $questionView = new QuestionView( $question ); $questionView->setPrinterFriendly(); $questionView->displayComments(); $questionView->displayAnswers(); ``` The idea is that now you can change *how* the questions are formatted from a single location in the code base. You can support multiple formats for the comments and answers without the calling code (a) ever knowing; and (b) ever needing to change (to a significant degree). If you are coding text formatting details in more than one location because you are misusing accessor methods, the life of any future maintainers will be miserable. If the maintainer is a psychopath who knows where you live, you will be in trouble. ### Objects, Data, and Views Here's the problem, as I understand it: ``` Database -> Object -> Display Content ``` You want to keep the behaviour of the object centred around logic that is intrinsic to the object. In other words, you don't want the Object to have to do things that have nothing to do with its core responsibilities. Most commonly this will include load, save, and print functionality. You want to keep these separate from the object itself because if you ever have to change database, or output format, you want to make as few changes in the system as possible, and restrain the ripple effect. To simplify this, let's take a look at loading only `Comments`; everything is applicable to `Questions` and `Answers` as well. **Comment Class** The Comment class might offer the following behaviours: * Reply * Delete * Update (requires permission) * Restore (from a delete) * etc. **CommentDB Class** We can create a `CommentDB` object that knows how to manipulate the `Comment`s in the database. A `CommentDB` object has the following behaviours: * Create * Load * Save * Update * Delete * Restore Notice that these behaviours will likely be common across all objects and can therefore be subject to refactoring. This will also let you change databases quite easily as the connection information will be isolated to a single class (the grandfather of all database objects). Example usage: ``` $commentDb = new CommentDB(); $comment = $commentDb->create(); ``` Later: ``` $comment->update( "new text" ); ``` Notice that there are a number of possible ways to implement this, but you can always do so without violating encapsulation and information hiding. **CommentView Class** Lastly, the `CommentView` class will be tightly coupled to a `Comment` class. That it can obtain the attributes of `Comment` class via accessors is expected. The information is still hidden *from the rest of the system*. The `Comment` and its `CommentView` are tightly coupled. The idea is that the formatting is kept in a single place, not scattered throughout classes that need to use the data willy nilly. Any classes that need to display comments, but in a slightly different format, can inherit from `CommentView`. See also: [Allen Holub wrote "You should never use get/set functions", is he correct?](https://stackoverflow.com/questions/996179/allen-holub-wrote-you-should-never-use-get-set-functions-is-he-correct)
Why pass either? What about: ``` <?php $question = new Question($id); $comments = $question->getComments(); $answers = $question->getAnswers(); echo $question->getTitle(); echo $question->getText(); foreach ($comments as $comment) echo $comments->getText(); foreach ($answers as $answer) { $answer_comments = $answer->getComments(); echo $answer->getText(); foreach ($answer_comments as $comment) echo $comment->getText(); } ``` Where `getComments()` and `getAnswers()` use `$this->id` to retrieve and return an array of comment or answer objects? You could build utility methods in the comment and answer objects that allow you to load by parent id. In which case, just taking an id as a parameter would be nice. ``` $question = new Question($id); $answers = Answer::forQuestion($question->id); $comments = Comment::forQuestion($question->id); $ans_comments = Comment::forAnswer($answer->id); // or some way to distinguish what the parent object is. ``` Edit: Likely the child model (Comment or Answer in this case) doesn't need anything from the parent except and id to do db queries with. Passing in the entire parent object would be overkill. (Also, PHP has a terrible time garbage collecting objects with circular references, which might be fixed in the 5.3 series.)
4,522,117
I'm not quite grokking a couple of things in OOP and I'm going to use a fictional understanding of SO to see if I can get help understand. So, on this page we have a question. You can comment on the question. There are also answers. You can comment on the answers. ``` Question - comment - comment - comment Answer -comment Answer -comment -comment -comment Answer -comment -comment ``` So, I'm imagining a very high level understanding of this type of system (in PHP, not .Net as I am not yet familiar with .Net) would be like: ``` $question = new Question; $question->load($this_question_id); // from the URL probably echo $question->getTitle(); ``` To load the answers, I imagine it's something like this ("A"): ``` $answers = new Answers; $answers->loadFromQuestion($question->getID()); // or $answers->loadFromQuestion($this_question_id); while($answer = $answers->getAnswer()) { echo $answer->showFormatted(); } ``` Or, would you do ("B"): ``` $answers->setQuestion($question); // inject the whole obj, so we have access to all the data and public methods in $question $answers->loadFromQuestion(); // the ID would be found via $this->question->getID() instead of from the argument passed in while($answer = $answers->getAnswer()) { echo $answer->showFormatted(); } ``` I guess my problem is, I don't know when or if I should be passing in an entire object, and when I should just be passing in a value. Passing in the entire object gives me a lot of flexibility, but it's more memory and subject to change, I'd guess (like a property or method rename). If "A" style is better, why not just use a function? OOP seems pointless here. Thanks, Hans
2010/12/23
[ "https://Stackoverflow.com/questions/4522117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/289004/" ]
Why pass either? What about: ``` <?php $question = new Question($id); $comments = $question->getComments(); $answers = $question->getAnswers(); echo $question->getTitle(); echo $question->getText(); foreach ($comments as $comment) echo $comments->getText(); foreach ($answers as $answer) { $answer_comments = $answer->getComments(); echo $answer->getText(); foreach ($answer_comments as $comment) echo $comment->getText(); } ``` Where `getComments()` and `getAnswers()` use `$this->id` to retrieve and return an array of comment or answer objects? You could build utility methods in the comment and answer objects that allow you to load by parent id. In which case, just taking an id as a parameter would be nice. ``` $question = new Question($id); $answers = Answer::forQuestion($question->id); $comments = Comment::forQuestion($question->id); $ans_comments = Comment::forAnswer($answer->id); // or some way to distinguish what the parent object is. ``` Edit: Likely the child model (Comment or Answer in this case) doesn't need anything from the parent except and id to do db queries with. Passing in the entire parent object would be overkill. (Also, PHP has a terrible time garbage collecting objects with circular references, which might be fixed in the 5.3 series.)
To add to [Dave Jarvis](https://stackoverflow.com/questions/4522313) and [jasonbar](https://stackoverflow.com/questions/4522165) answers, I usually have [DataMappers](http://martinfowler.com/eaaCatalog/dataMapper.html) to convert between relational data and objects, instead of using an [ActiveRecord](http://martinfowler.com/eaaCatalog/activeRecord.html) approach. So, following your example, we would have these classes: * Question * Answer * Comment and their data mappers: * QuestionMapper * AnswerMapper * CommentMapper Each mapper implementing a similar interface: * save(object) // creates or updates a record in the database (or text file, for that matter) * delete(id) * get(id) Then, we would do as: ``` $q = QuestionMapper::get( $questionid ); // here we could either (a) just return a list of Answers // previously eagerly-loaded by the // QuestionMapper, or (b) lazy load the answers by // calling AnswerMapper::getByQuestionID( $this->id ) or similar. $aAnswers = $q->getAnswers(); foreach($aAnswers as $oAnswer){ echo $oAnswer->getText(); $aComments = $oAnswer->getComments(); foreach($aComments as $oComment){ echo $oComment->getText(); } } ``` Regarding the use of things like QuestionView->render( $question ), I prefer to have Views which display the data using getters from the domain objects. If you pass a Question to a HTMLView, it will render it as HTML; if you pass it to a JSONView, then you'll get JSON-formatted content. This means that the domain objects need to have getters. PS: We could also consider the QuestionMapper to load everything related to Questions, Answers, and Comments. Since Comments always belongs to Answers or Questions, and Answers always belong to Questions, it could make sense that the QuestionMapper loaded everything. Of course we would have to consider different strategies for lazy loading a Question's set of Answers and Comments, to avoid hogging the server.
4,522,117
I'm not quite grokking a couple of things in OOP and I'm going to use a fictional understanding of SO to see if I can get help understand. So, on this page we have a question. You can comment on the question. There are also answers. You can comment on the answers. ``` Question - comment - comment - comment Answer -comment Answer -comment -comment -comment Answer -comment -comment ``` So, I'm imagining a very high level understanding of this type of system (in PHP, not .Net as I am not yet familiar with .Net) would be like: ``` $question = new Question; $question->load($this_question_id); // from the URL probably echo $question->getTitle(); ``` To load the answers, I imagine it's something like this ("A"): ``` $answers = new Answers; $answers->loadFromQuestion($question->getID()); // or $answers->loadFromQuestion($this_question_id); while($answer = $answers->getAnswer()) { echo $answer->showFormatted(); } ``` Or, would you do ("B"): ``` $answers->setQuestion($question); // inject the whole obj, so we have access to all the data and public methods in $question $answers->loadFromQuestion(); // the ID would be found via $this->question->getID() instead of from the argument passed in while($answer = $answers->getAnswer()) { echo $answer->showFormatted(); } ``` I guess my problem is, I don't know when or if I should be passing in an entire object, and when I should just be passing in a value. Passing in the entire object gives me a lot of flexibility, but it's more memory and subject to change, I'd guess (like a property or method rename). If "A" style is better, why not just use a function? OOP seems pointless here. Thanks, Hans
2010/12/23
[ "https://Stackoverflow.com/questions/4522117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/289004/" ]
While I like Jason's answer, it is not, strictly speaking OO. ``` $question = new Question($id); $comments = $question->getComments(); $answers = $question->getAnswers(); echo $question->getTitle(); echo $question->getText(); foreach ($comments as $comment) echo $comments->getText(); ``` The problems are: 1. There is no information hiding, a fundamental principle of OO. 2. If the format of the answers needs to change, it must be changed in a place that is not associated with the object that houses the data. 3. The solution is not extensible. (There is no behaviour to inherit.) You *must* keep behaviour (tightly coupled) with the data. Otherwise you are not writing OO. ``` $question = new Question($id); $questionView = new QuestionView( $question ); $questionView->displayComments(); $questionView->displayAnswers(); ``` How the information is displayed is now an implementation detail, and reusable. Notice how this opens up the following possibility: ``` $question = new Question( $id ); $questionView = new QuestionView( $question ); $questionView->setPrinterFriendly(); $questionView->displayComments(); $questionView->displayAnswers(); ``` The idea is that now you can change *how* the questions are formatted from a single location in the code base. You can support multiple formats for the comments and answers without the calling code (a) ever knowing; and (b) ever needing to change (to a significant degree). If you are coding text formatting details in more than one location because you are misusing accessor methods, the life of any future maintainers will be miserable. If the maintainer is a psychopath who knows where you live, you will be in trouble. ### Objects, Data, and Views Here's the problem, as I understand it: ``` Database -> Object -> Display Content ``` You want to keep the behaviour of the object centred around logic that is intrinsic to the object. In other words, you don't want the Object to have to do things that have nothing to do with its core responsibilities. Most commonly this will include load, save, and print functionality. You want to keep these separate from the object itself because if you ever have to change database, or output format, you want to make as few changes in the system as possible, and restrain the ripple effect. To simplify this, let's take a look at loading only `Comments`; everything is applicable to `Questions` and `Answers` as well. **Comment Class** The Comment class might offer the following behaviours: * Reply * Delete * Update (requires permission) * Restore (from a delete) * etc. **CommentDB Class** We can create a `CommentDB` object that knows how to manipulate the `Comment`s in the database. A `CommentDB` object has the following behaviours: * Create * Load * Save * Update * Delete * Restore Notice that these behaviours will likely be common across all objects and can therefore be subject to refactoring. This will also let you change databases quite easily as the connection information will be isolated to a single class (the grandfather of all database objects). Example usage: ``` $commentDb = new CommentDB(); $comment = $commentDb->create(); ``` Later: ``` $comment->update( "new text" ); ``` Notice that there are a number of possible ways to implement this, but you can always do so without violating encapsulation and information hiding. **CommentView Class** Lastly, the `CommentView` class will be tightly coupled to a `Comment` class. That it can obtain the attributes of `Comment` class via accessors is expected. The information is still hidden *from the rest of the system*. The `Comment` and its `CommentView` are tightly coupled. The idea is that the formatting is kept in a single place, not scattered throughout classes that need to use the data willy nilly. Any classes that need to display comments, but in a slightly different format, can inherit from `CommentView`. See also: [Allen Holub wrote "You should never use get/set functions", is he correct?](https://stackoverflow.com/questions/996179/allen-holub-wrote-you-should-never-use-get-set-functions-is-he-correct)
Both styles are acceptable. Sometimes you only need the value, sometimes you'll need the object. In this example I would personally do something along the lines of your first example, but trivial programs like this don't tend to exist in the wild very often so maybe you want the second piece. My rule of thumb is to do the thing in the least number of lines that still clearly demonstrates what you're attempting to do to anyone who comes after you. The overhead of most object creation vs value passing is something you'll likely never ever have to deal with on modern arch.
4,522,117
I'm not quite grokking a couple of things in OOP and I'm going to use a fictional understanding of SO to see if I can get help understand. So, on this page we have a question. You can comment on the question. There are also answers. You can comment on the answers. ``` Question - comment - comment - comment Answer -comment Answer -comment -comment -comment Answer -comment -comment ``` So, I'm imagining a very high level understanding of this type of system (in PHP, not .Net as I am not yet familiar with .Net) would be like: ``` $question = new Question; $question->load($this_question_id); // from the URL probably echo $question->getTitle(); ``` To load the answers, I imagine it's something like this ("A"): ``` $answers = new Answers; $answers->loadFromQuestion($question->getID()); // or $answers->loadFromQuestion($this_question_id); while($answer = $answers->getAnswer()) { echo $answer->showFormatted(); } ``` Or, would you do ("B"): ``` $answers->setQuestion($question); // inject the whole obj, so we have access to all the data and public methods in $question $answers->loadFromQuestion(); // the ID would be found via $this->question->getID() instead of from the argument passed in while($answer = $answers->getAnswer()) { echo $answer->showFormatted(); } ``` I guess my problem is, I don't know when or if I should be passing in an entire object, and when I should just be passing in a value. Passing in the entire object gives me a lot of flexibility, but it's more memory and subject to change, I'd guess (like a property or method rename). If "A" style is better, why not just use a function? OOP seems pointless here. Thanks, Hans
2010/12/23
[ "https://Stackoverflow.com/questions/4522117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/289004/" ]
While I like Jason's answer, it is not, strictly speaking OO. ``` $question = new Question($id); $comments = $question->getComments(); $answers = $question->getAnswers(); echo $question->getTitle(); echo $question->getText(); foreach ($comments as $comment) echo $comments->getText(); ``` The problems are: 1. There is no information hiding, a fundamental principle of OO. 2. If the format of the answers needs to change, it must be changed in a place that is not associated with the object that houses the data. 3. The solution is not extensible. (There is no behaviour to inherit.) You *must* keep behaviour (tightly coupled) with the data. Otherwise you are not writing OO. ``` $question = new Question($id); $questionView = new QuestionView( $question ); $questionView->displayComments(); $questionView->displayAnswers(); ``` How the information is displayed is now an implementation detail, and reusable. Notice how this opens up the following possibility: ``` $question = new Question( $id ); $questionView = new QuestionView( $question ); $questionView->setPrinterFriendly(); $questionView->displayComments(); $questionView->displayAnswers(); ``` The idea is that now you can change *how* the questions are formatted from a single location in the code base. You can support multiple formats for the comments and answers without the calling code (a) ever knowing; and (b) ever needing to change (to a significant degree). If you are coding text formatting details in more than one location because you are misusing accessor methods, the life of any future maintainers will be miserable. If the maintainer is a psychopath who knows where you live, you will be in trouble. ### Objects, Data, and Views Here's the problem, as I understand it: ``` Database -> Object -> Display Content ``` You want to keep the behaviour of the object centred around logic that is intrinsic to the object. In other words, you don't want the Object to have to do things that have nothing to do with its core responsibilities. Most commonly this will include load, save, and print functionality. You want to keep these separate from the object itself because if you ever have to change database, or output format, you want to make as few changes in the system as possible, and restrain the ripple effect. To simplify this, let's take a look at loading only `Comments`; everything is applicable to `Questions` and `Answers` as well. **Comment Class** The Comment class might offer the following behaviours: * Reply * Delete * Update (requires permission) * Restore (from a delete) * etc. **CommentDB Class** We can create a `CommentDB` object that knows how to manipulate the `Comment`s in the database. A `CommentDB` object has the following behaviours: * Create * Load * Save * Update * Delete * Restore Notice that these behaviours will likely be common across all objects and can therefore be subject to refactoring. This will also let you change databases quite easily as the connection information will be isolated to a single class (the grandfather of all database objects). Example usage: ``` $commentDb = new CommentDB(); $comment = $commentDb->create(); ``` Later: ``` $comment->update( "new text" ); ``` Notice that there are a number of possible ways to implement this, but you can always do so without violating encapsulation and information hiding. **CommentView Class** Lastly, the `CommentView` class will be tightly coupled to a `Comment` class. That it can obtain the attributes of `Comment` class via accessors is expected. The information is still hidden *from the rest of the system*. The `Comment` and its `CommentView` are tightly coupled. The idea is that the formatting is kept in a single place, not scattered throughout classes that need to use the data willy nilly. Any classes that need to display comments, but in a slightly different format, can inherit from `CommentView`. See also: [Allen Holub wrote "You should never use get/set functions", is he correct?](https://stackoverflow.com/questions/996179/allen-holub-wrote-you-should-never-use-get-set-functions-is-he-correct)
Adding to what @jasonbar already mentioned: > > I don't know when or if I should be passing in an entire object, and when I should just be passing in a value. > > > It depends on the [Coupling](http://en.wikipedia.org/wiki/Coupling_%28computer_science%29) you need and the [Cohesion](http://en.wikipedia.org/wiki/Cohesion_%28computer_science%29) you desire. > > Passing in the entire object gives me a lot of flexibility, but it's more memory and subject to change. > > > PHP does not copy the object when you use it as an argument to a function. Neither do most other languages (either by default, like C# and Java, or upon explicit request, like C and C++)
4,522,117
I'm not quite grokking a couple of things in OOP and I'm going to use a fictional understanding of SO to see if I can get help understand. So, on this page we have a question. You can comment on the question. There are also answers. You can comment on the answers. ``` Question - comment - comment - comment Answer -comment Answer -comment -comment -comment Answer -comment -comment ``` So, I'm imagining a very high level understanding of this type of system (in PHP, not .Net as I am not yet familiar with .Net) would be like: ``` $question = new Question; $question->load($this_question_id); // from the URL probably echo $question->getTitle(); ``` To load the answers, I imagine it's something like this ("A"): ``` $answers = new Answers; $answers->loadFromQuestion($question->getID()); // or $answers->loadFromQuestion($this_question_id); while($answer = $answers->getAnswer()) { echo $answer->showFormatted(); } ``` Or, would you do ("B"): ``` $answers->setQuestion($question); // inject the whole obj, so we have access to all the data and public methods in $question $answers->loadFromQuestion(); // the ID would be found via $this->question->getID() instead of from the argument passed in while($answer = $answers->getAnswer()) { echo $answer->showFormatted(); } ``` I guess my problem is, I don't know when or if I should be passing in an entire object, and when I should just be passing in a value. Passing in the entire object gives me a lot of flexibility, but it's more memory and subject to change, I'd guess (like a property or method rename). If "A" style is better, why not just use a function? OOP seems pointless here. Thanks, Hans
2010/12/23
[ "https://Stackoverflow.com/questions/4522117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/289004/" ]
While I like Jason's answer, it is not, strictly speaking OO. ``` $question = new Question($id); $comments = $question->getComments(); $answers = $question->getAnswers(); echo $question->getTitle(); echo $question->getText(); foreach ($comments as $comment) echo $comments->getText(); ``` The problems are: 1. There is no information hiding, a fundamental principle of OO. 2. If the format of the answers needs to change, it must be changed in a place that is not associated with the object that houses the data. 3. The solution is not extensible. (There is no behaviour to inherit.) You *must* keep behaviour (tightly coupled) with the data. Otherwise you are not writing OO. ``` $question = new Question($id); $questionView = new QuestionView( $question ); $questionView->displayComments(); $questionView->displayAnswers(); ``` How the information is displayed is now an implementation detail, and reusable. Notice how this opens up the following possibility: ``` $question = new Question( $id ); $questionView = new QuestionView( $question ); $questionView->setPrinterFriendly(); $questionView->displayComments(); $questionView->displayAnswers(); ``` The idea is that now you can change *how* the questions are formatted from a single location in the code base. You can support multiple formats for the comments and answers without the calling code (a) ever knowing; and (b) ever needing to change (to a significant degree). If you are coding text formatting details in more than one location because you are misusing accessor methods, the life of any future maintainers will be miserable. If the maintainer is a psychopath who knows where you live, you will be in trouble. ### Objects, Data, and Views Here's the problem, as I understand it: ``` Database -> Object -> Display Content ``` You want to keep the behaviour of the object centred around logic that is intrinsic to the object. In other words, you don't want the Object to have to do things that have nothing to do with its core responsibilities. Most commonly this will include load, save, and print functionality. You want to keep these separate from the object itself because if you ever have to change database, or output format, you want to make as few changes in the system as possible, and restrain the ripple effect. To simplify this, let's take a look at loading only `Comments`; everything is applicable to `Questions` and `Answers` as well. **Comment Class** The Comment class might offer the following behaviours: * Reply * Delete * Update (requires permission) * Restore (from a delete) * etc. **CommentDB Class** We can create a `CommentDB` object that knows how to manipulate the `Comment`s in the database. A `CommentDB` object has the following behaviours: * Create * Load * Save * Update * Delete * Restore Notice that these behaviours will likely be common across all objects and can therefore be subject to refactoring. This will also let you change databases quite easily as the connection information will be isolated to a single class (the grandfather of all database objects). Example usage: ``` $commentDb = new CommentDB(); $comment = $commentDb->create(); ``` Later: ``` $comment->update( "new text" ); ``` Notice that there are a number of possible ways to implement this, but you can always do so without violating encapsulation and information hiding. **CommentView Class** Lastly, the `CommentView` class will be tightly coupled to a `Comment` class. That it can obtain the attributes of `Comment` class via accessors is expected. The information is still hidden *from the rest of the system*. The `Comment` and its `CommentView` are tightly coupled. The idea is that the formatting is kept in a single place, not scattered throughout classes that need to use the data willy nilly. Any classes that need to display comments, but in a slightly different format, can inherit from `CommentView`. See also: [Allen Holub wrote "You should never use get/set functions", is he correct?](https://stackoverflow.com/questions/996179/allen-holub-wrote-you-should-never-use-get-set-functions-is-he-correct)
To add to [Dave Jarvis](https://stackoverflow.com/questions/4522313) and [jasonbar](https://stackoverflow.com/questions/4522165) answers, I usually have [DataMappers](http://martinfowler.com/eaaCatalog/dataMapper.html) to convert between relational data and objects, instead of using an [ActiveRecord](http://martinfowler.com/eaaCatalog/activeRecord.html) approach. So, following your example, we would have these classes: * Question * Answer * Comment and their data mappers: * QuestionMapper * AnswerMapper * CommentMapper Each mapper implementing a similar interface: * save(object) // creates or updates a record in the database (or text file, for that matter) * delete(id) * get(id) Then, we would do as: ``` $q = QuestionMapper::get( $questionid ); // here we could either (a) just return a list of Answers // previously eagerly-loaded by the // QuestionMapper, or (b) lazy load the answers by // calling AnswerMapper::getByQuestionID( $this->id ) or similar. $aAnswers = $q->getAnswers(); foreach($aAnswers as $oAnswer){ echo $oAnswer->getText(); $aComments = $oAnswer->getComments(); foreach($aComments as $oComment){ echo $oComment->getText(); } } ``` Regarding the use of things like QuestionView->render( $question ), I prefer to have Views which display the data using getters from the domain objects. If you pass a Question to a HTMLView, it will render it as HTML; if you pass it to a JSONView, then you'll get JSON-formatted content. This means that the domain objects need to have getters. PS: We could also consider the QuestionMapper to load everything related to Questions, Answers, and Comments. Since Comments always belongs to Answers or Questions, and Answers always belong to Questions, it could make sense that the QuestionMapper loaded everything. Of course we would have to consider different strategies for lazy loading a Question's set of Answers and Comments, to avoid hogging the server.
23,817,719
Is there opportunity to make metaprogramming function but not expand all parameters in compilation? Just want to have some parameters as the runtime parameters and some compiles. Because I know that some of them will be in range of 1..10 but the other are unkown (will be known at runtime). Lets use standard metaprogramming example: ``` unsigned int factorial(unsigned int n) { return n == 0 ? 1 : n * factorial(n - 1); } template <int n> struct factorial { enum { value = n * factorial<n - 1>::value }; }; template <> struct factorial<0> { enum { value = 1 }; }; // Usage examples: // factorial<0>::value would yield 1; // factorial<4>::value would yield 24. ``` And below is my case: ``` unsigned int cutom_imagined_function(unsigned int n, unsigned int runtime_param /* this will be given at runtime */) { return n == 0 ? 1 : (n + runtime_param) * cutom_imagined_function(n - 1); } ``` how can I convert above to metaprogramming? And run this let's say as below (or something similar): ``` // int variable; // variable = get_var_from_user(); // cutom_imagined_function<4>::value(variable) ```
2014/05/22
[ "https://Stackoverflow.com/questions/23817719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/677202/" ]
You can use the same approach: Constant expressions become template parameters, everything else doesn't: ``` template <unsigned int N> struct cutom_imagined { static unsigned int function(unsigned int r) { return (N + r) * cutom_imagined<N - 1>::function(r); } }; template <> struct cutom_imagined<0> { static unsigned int function(unsigned int) { return 1; } }; ``` Usage: ``` unsigned int result = cutom_imagined<N>::function(get_input()); ```
Assuming you meant this: ``` unsigned int cutom_imagined_function( unsigned int n, unsigned int runtime_param) { return n == 0 ? 1 : (n+runtime_param)*custom_imagined_function(n-1, runtime_param); } ``` here's the general concept I think you're describing. It's actually pretty straightforward. Make the *function itself* a template. ``` template<unsigned int in> unsigned int custom_imagined_function(unsigned int runtime_param) { return (n+runtime_param)*custom_imagined_function<n-1>(runtime_param); } template<> unsigned int custom_imagined_function<0>(unsigned int runtime_param) { return 1; } int main() { int variable; std::cin >> variable; unsigned int result = custom_imagined_function<4>(variable); } ``` Alternatively, you can use the slightly more verbose `std::integral_constant`. ``` unsigned int custom_imagined_function( std::integral_constant<unsigned int,0>, unsigned int runtime_param) { return 1; } template<unsigned int in> unsigned int custom_imagined_function( std::integral_constant<unsigned int,n>, unsigned int runtime_param) { std::integral_constant<unsigned int,n-1> less; return (n+runtime_param) * custom_imagined_function(less, runtime_param); } int main() { std::integral_constant<unsigned int,4> four; int variable; std::cin >> variable; unsigned int result = custom_imagined_function(four, variable); } ``` Additionally, now that we have `constexpr` (in some compilers anyway), the `factorial` is easily simplified: ``` constexpr unsigned int factorial(unsigned int n) { return n==0?1:n*factorial(n-1); } ```
5,867,638
I've this error using Windsor Castle with log4net in WinForm application. Error: ``` Could not convert from 'Castle.Services.Logging.Log4netIntegration.Log4netFactory,Castle.Services.Logging.Log4netIntegration,Version=2.5.1.0, Culture=neutral,PublicKeyToken=407dd0808d44fbdc' to System.Type - Maybe type could not be found ``` Stack: ``` in Castle.MicroKernel.SubSystems.Conversion.TypeNameConverter.PerformConversion(String value, Type targetType) in e:\OSS.Code\Castle.Windsor\src\Castle.Windsor\MicroKernel\SubSystems\Conversion\TypeNameConverter.cs:riga 91 in Castle.MicroKernel.SubSystems.Conversion.DefaultConversionManager.PerformConversion(String value, Type targetType) in e:\OSS.Code\Castle.Windsor\src\Castle.Windsor\MicroKernel\SubSystems\Conversion\DefaultConversionManager.cs:riga 134 in Castle.MicroKernel.SubSystems.Conversion.DefaultConversionManager.PerformConversion[TTarget](String value) in e:\OSS.Code\Castle.Windsor\src\Castle.Windsor\MicroKernel\SubSystems\Conversion\DefaultConversionManager.cs:riga 162 in Castle.Facilities.Logging.LoggingFacility.GetLoggingFactoryType(LoggerImplementation loggerApi) in Castle.Facilities.Logging.LoggingFacility.CreateProperLoggerFactory(LoggerImplementation loggerApi) in Castle.Facilities.Logging.LoggingFacility.ReadConfigurationAndCreateLoggerFactory() in Castle.Facilities.Logging.LoggingFacility.Init() in Castle.MicroKernel.Facilities.AbstractFacility.Castle.MicroKernel.IFacility.Init(IKernel kernel, IConfiguration facilityConfig) in e:\OSS.Code\Castle.Windsor\src\Castle.Windsor\MicroKernel\Facilities\AbstractFacility.cs:riga 85 in Castle.MicroKernel.DefaultKernel.AddFacility(String key, IFacility facility) in e:\OSS.Code\Castle.Windsor\src\Castle.Windsor\MicroKernel\DefaultKernel.cs:riga 320 in Castle.MicroKernel.DefaultKernel.AddFacility[T](Func`2 onCreate) in e:\OSS.Code\Castle.Windsor\src\Castle.Windsor\MicroKernel\DefaultKernel.cs:riga 377 in Castle.Windsor.WindsorContainer.AddFacility[T](Func`2 onCreate) in e:\OSS.Code\Castle.Windsor\src\Castle.Windsor\Windsor\WindsorContainer.cs:riga 629 in IocWinFormTest.Installers.LoggerInstaller.Install(IWindsorContainer container, IConfigurationStore store) in C:\Sviluppo\IocWinFormTest\IocWinFormTest\IocWinFormTest\Installers\LoggerInstaller.cs:riga 18 in Castle.Windsor.WindsorContainer.Install(IWindsorInstaller[] installers, DefaultComponentInstaller scope) in e:\OSS.Code\Castle.Windsor\src\Castle.Windsor\Windsor\WindsorContainer.cs:riga 324 in Castle.Windsor.WindsorContainer.Install(IWindsorInstaller[] installers) in e:\OSS.Code\Castle.Windsor\src\Castle.Windsor\Windsor\WindsorContainer.cs:riga 674 in IocWinFormTest.Program.Main() in C:\Sviluppo\IocWinFormTest\IocWinFormTest\IocWinFormTest\Program.cs:riga 22 in System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) in System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) in Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() in System.Threading.ThreadHelper.ThreadStart_Context(Object state) in System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) in System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) in System.Threading.ThreadHelper.ThreadStart() ``` the code: ``` public class LoggerInstaller : IWindsorInstaller { #region IWindsorInstaller Members public void Install(IWindsorContainer container, IConfigurationStore store) { container.AddFacility<LoggingFacility>(f => f.LogUsing(LoggerImplementation.Log4net).WithAppConfig()); } #endregion } ``` App.config: ``` <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections> <log4net> <logger name="NHibernate"> <level value="WARN" /> </logger> <logger name="NHibernate.SQL"> <level value="ALL" /> <appender-ref ref="RollingFile" /> </logger> <root> <level value="DEBUG" /> <appender-ref ref="RollingFile" /> <appender-ref ref="trace" /> </root> <appender name="trace" type="log4net.Appender.TraceAppender"> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value=" %date %level %message%newline" /> </layout> </appender> <appender name="RollingFile" type="log4net.Appender.RollingFileAppender"> <param name="File" value="Public\Log" /> <appendToFile value="true" /> <datePattern value=".yyyyMMdd.\tx\t" /> <rollingStyle value="Date" /> <param name="StaticLogFileName" value="false" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%d %-8ndc %-5thread %-5level %logger %message %timestampms %n" /> </layout> </appender> </log4net> </configuration> ``` I used NuGet to import all packages and interesting story is that I've the same configuration in a web app and there it works! Can you help me? Daniele
2011/05/03
[ "https://Stackoverflow.com/questions/5867638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/735864/" ]
Have you copied the `Castle.Services.Logging.Log4netIntegration.dll` and all other required assemblies to your project's folder?
Change the target of the WinForm app from the Client Profile to the .Net Framework. log4net depends on System.Web as a support assembly. The answer to my question has more details if you want to stay targeting the Client Profile. [Why does log4net 1.2.10 require System.Web?](https://stackoverflow.com/questions/6281542/why-does-log4net-1-2-10-require-system-web)
49,426,267
I'm trying to re-write a python algorithm to Java for some needs. In python algorithm I have the following code : ``` row_ind, col_ind = linear_sum_assignment(cost) ``` `linear_sum_assignment` is a [scipy function](https://docs.scipy.org/doc/scipy-0.18.1/reference/generated/scipy.optimize.linear_sum_assignment.html) Do you guys know an equivalent of that function in java ? I found [this one](https://github.com/KevinStern/software-and-algorithms/blob/master/src/main/java/blogspot/software_and_algorithms/stern_library/optimization/HungarianAlgorithm.java) but I didn't get the row indice and column indice in this one.
2018/03/22
[ "https://Stackoverflow.com/questions/49426267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7802894/" ]
Your loop is returning this ``` <li class="new" ><button class="delete-widget-button" style="float: right;">-</button><img src="{% static "images/abc.jpg"%}"></li> 2 2 1 1 <li class="new" ><button class="delete-widget-button" style="float: right;">-</button><img src="{% static "images/def.jpg,"%}"></li> 2 2 4 1 <li class="new" ><button class="delete-widget-button" style="float: right;">-</button><img src="{% static "images/bac.jpg"%}"></li> 2 2 6 1 <li class="new" ><button class="delete-widget-button" style="float: right;">-</button><img src="{% static "images/xyz.jpg"%}"></li> 1 1 1 3 <li class="new" ><button class="delete-widget-button" style="float: right;">-</button><img src="{% static "images/Brand.jpg"%}"></li> 1 1 4 3 <li class="new" ><button class="delete-widget-button" style="float: right;">-</button><img src="{% static "images/Brand.jpg"%}"></li> 1 1 6 3 ``` You might have extra comma here: "images/def.jpg," at index=1
if you replace gridster.add\_widget with console.log, the output looks fine: ``` <img src="{% static "images/abc.jpg"%}"> ``` Try adding space before closing tag: ``` ..json[index].html+'" %}"></li> ^here ```
49,426,267
I'm trying to re-write a python algorithm to Java for some needs. In python algorithm I have the following code : ``` row_ind, col_ind = linear_sum_assignment(cost) ``` `linear_sum_assignment` is a [scipy function](https://docs.scipy.org/doc/scipy-0.18.1/reference/generated/scipy.optimize.linear_sum_assignment.html) Do you guys know an equivalent of that function in java ? I found [this one](https://github.com/KevinStern/software-and-algorithms/blob/master/src/main/java/blogspot/software_and_algorithms/stern_library/optimization/HungarianAlgorithm.java) but I didn't get the row indice and column indice in this one.
2018/03/22
[ "https://Stackoverflow.com/questions/49426267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7802894/" ]
You have a problem with the use of quotes. Fix it be prefixing your inner `'` characters with a slash `\'` (this is called *escaping*): ``` gridster.add_widget('<li class="new" ><button class="delete-widget-button" style="float: right;">-</button><img src="{% static \'images/'+json[index].html+'\'%}"></li>',json[index].size_x,json[index].size_y,json[index].col,json[index].row); ``` ```js var json = [{ "html": "abc.jpg", //testing this failed "col": 1, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "def.jpg", "col": 4, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "bac.jpg", "col": 6, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "xyz.jpg", "col": 1, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "Brand.jpg", "col": 4, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "Brand.jpg", "col": 6, "row": 3, "size_y": 1, "size_x": 1 } ]; for (var index = 0; index < json.length; index++) { console.log('<img src="{% static \'images/' + json[index].html + '\' %}">'); }; ```
Your loop is returning this ``` <li class="new" ><button class="delete-widget-button" style="float: right;">-</button><img src="{% static "images/abc.jpg"%}"></li> 2 2 1 1 <li class="new" ><button class="delete-widget-button" style="float: right;">-</button><img src="{% static "images/def.jpg,"%}"></li> 2 2 4 1 <li class="new" ><button class="delete-widget-button" style="float: right;">-</button><img src="{% static "images/bac.jpg"%}"></li> 2 2 6 1 <li class="new" ><button class="delete-widget-button" style="float: right;">-</button><img src="{% static "images/xyz.jpg"%}"></li> 1 1 1 3 <li class="new" ><button class="delete-widget-button" style="float: right;">-</button><img src="{% static "images/Brand.jpg"%}"></li> 1 1 4 3 <li class="new" ><button class="delete-widget-button" style="float: right;">-</button><img src="{% static "images/Brand.jpg"%}"></li> 1 1 6 3 ``` You might have extra comma here: "images/def.jpg," at index=1
49,426,267
I'm trying to re-write a python algorithm to Java for some needs. In python algorithm I have the following code : ``` row_ind, col_ind = linear_sum_assignment(cost) ``` `linear_sum_assignment` is a [scipy function](https://docs.scipy.org/doc/scipy-0.18.1/reference/generated/scipy.optimize.linear_sum_assignment.html) Do you guys know an equivalent of that function in java ? I found [this one](https://github.com/KevinStern/software-and-algorithms/blob/master/src/main/java/blogspot/software_and_algorithms/stern_library/optimization/HungarianAlgorithm.java) but I didn't get the row indice and column indice in this one.
2018/03/22
[ "https://Stackoverflow.com/questions/49426267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7802894/" ]
You have a problem with the use of quotes. Fix it be prefixing your inner `'` characters with a slash `\'` (this is called *escaping*): ``` gridster.add_widget('<li class="new" ><button class="delete-widget-button" style="float: right;">-</button><img src="{% static \'images/'+json[index].html+'\'%}"></li>',json[index].size_x,json[index].size_y,json[index].col,json[index].row); ``` ```js var json = [{ "html": "abc.jpg", //testing this failed "col": 1, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "def.jpg", "col": 4, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "bac.jpg", "col": 6, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "xyz.jpg", "col": 1, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "Brand.jpg", "col": 4, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "Brand.jpg", "col": 6, "row": 3, "size_y": 1, "size_x": 1 } ]; for (var index = 0; index < json.length; index++) { console.log('<img src="{% static \'images/' + json[index].html + '\' %}">'); }; ```
if you replace gridster.add\_widget with console.log, the output looks fine: ``` <img src="{% static "images/abc.jpg"%}"> ``` Try adding space before closing tag: ``` ..json[index].html+'" %}"></li> ^here ```
11,283,303
I'm using the following Compare Validator : ``` <asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="DropDownList1" ErrorMessage="None can't be selected!" Operator="NotEqual" ValueToCompare="None"></asp:CompareValidator> ``` over the following Dropdown List: ``` <asp:DropDownList ID="DropDownList1" runat="server" Height="17px" Width="181px"> <asp:ListItem>None</asp:ListItem> <asp:ListItem>One</asp:ListItem> <asp:ListItem>Two</asp:ListItem> <asp:ListItem>Three</asp:ListItem> </asp:DropDownList> ``` Here's what happens : Initially, nothing happens, and 'None' is selected by default. If I choose any other option and THEN choose 'None', it give me the error. What I want to do is have the validator display the error right away when the page is first loaded, and not wait for the user to change to some other option and back over to 'None' or wait for the user to submit the form before displaying the form again. How can I achieve this?
2012/07/01
[ "https://Stackoverflow.com/questions/11283303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/939182/" ]
It is frustrating that (as you say) "A lot of people say that the ApplyChanges() call is not necessary, and equally as many say that it is" -- the fact of the matter is that *it depends* on what you are doing and where you are doing it! (How do I know all this? I've [implemented it](http://andrewrussell.net/exen/). See also: [this answer](https://stackoverflow.com/a/8025319/165500).) --- When you are setting the *initial* resolution when your game starts up: ----------------------------------------------------------------------- Do this in your *constructor* (obviously if you rename `Game1`, do it in your renamed constructor!) ``` public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; public Game1() { graphics = new GraphicsDeviceManager(this); graphics.PreferredBackBufferHeight = 600; graphics.PreferredBackBufferWidth = 800; } // ... } ``` **And *do not* touch it during `Initialize()`!** And *do not* call `ApplyChanges()`. When `Game.Run()` gets called (the default template project calls it in `Program.cs`), it will call `GraphicsDeviceManager.CreateDevice` to set up the initial display ***before*** `Initialize()` is called! This is why you must create the `GraphicsDeviceManager` and set your desired settings in the constructor of your game class (which is called before `Game.Run()`). If you try to set the resolution in `Initialize`, you cause the graphics device to be set up twice. Bad. (To be honest I'm surprised that this causes such confusion. This is the code that is provided in the default project template!) --- When you are *modifying* the resolution while the game is running: ------------------------------------------------------------------ If you present a "resolution selection" menu somewhere in your game, and you want to respond to a user (for example) clicking an option in that menu - *then* (and only then) should you use `ApplyChanges`. You should only call it from within `Update`. For example: ``` public class Game1 : Microsoft.Xna.Framework.Game { protected override void Update(GameTime gameTime) { if(userClickedTheResolutionChangeButton) { graphics.IsFullScreen = userRequestedFullScreen; graphics.PreferredBackBufferHeight = userRequestedHeight; graphics.PreferredBackBufferWidth = userRequestedWidth; graphics.ApplyChanges(); } // ... } // ... } ``` Finally, note that `ToggleFullScreen()` is the same as doing: ``` graphics.IsFullScreen = !graphics.IsFullScreen; graphics.ApplyChanges(); ```
The `GraphicsDevice.Viewport` width and height by default on my computer is 800x480, try setting a size above that that will be noticeable - like 1024x768. ``` graphics.PreferredBackBufferHeight = 768; graphics.PreferredBackBufferWidth = 1024; graphics.ApplyChanges(); ``` The above code in `Initialize` was sufficient to expand the window for me.
41,337,300
Any better way to write this comparator? ``` Comparator<JSONObject> comparator = (op1,op2) -> { Integer id1 = Integer.valueOf(String.valueOf(op1.get(field))); Integer id2 = Integer.valueOf(String.valueOf(op2.get(field))); return id2.compareTo(id1); }; ``` Is it possible to avoid the two `valueOf`?
2016/12/26
[ "https://Stackoverflow.com/questions/41337300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3727540/" ]
### Using `Comparator.comparingInt` You should be able to do the following: ``` Comparator<JSONObject> comparator = Comparator.comparingInt(obj -> Integer.valueOf(String.valueOf(obj.get(field)))) .reversed(); ``` ### `getInt` Check the API of the `JSONObject` to see if there is an `getInt` method or similar on it, then you should be able to use that directly instead of wrapping in `valueOf` calls, such as: ``` Comparator<JSONObject> comparator = Comparator.<JSONObject>comparingInt(obj -> obj.getInt(field)) .reversed(); ``` ### Return type of `.get` Alternatively, you should investigate what type your `obj.get(field)` returns. If you are lucky, it can be as simply as a typecast: ``` Comparator<JSONObject> comparator = Comparator.<JSONObject>comparingInt(obj -> (Integer) obj.get(field)) .reversed(); ``` ### Return type is `String` If you are always getting `Strings` as a result from `obj.get`, then you should be able to use `Integer.valueOf` directly, instead of also calling `String.valueOf` ``` Comparator<JSONObject> comparator = Comparator.<JSONObject>comparingInt(obj -> Integer.valueOf(obj.get(field))) .reversed(); ``` Depending on the API, you still might need to typecase to `String` ``` Comparator<JSONObject> comparator = Comparator.<JSONObject>comparingInt(obj -> Integer.valueOf((String) obj.get(field))) .reversed(); ```
> > Is it possible to avoid the two valueOf? > > > This depends on whether or not know the type of `field` your are trying to get, ie: is it an `int` or a `string` or either if it is a guaranteed `int` you can simply do this ``` Comparator<JSONObject> comparator = (op1,op2) -> { return Integer.valueOf(op1.get(field)).compareTo(Integer.valueOf(op2.get(field)); }; ``` for ascending order if value is a `string` you can do this ``` Comparator<JSONObject> comparator = (op1,op2) -> { return Integer.parseInt((String)op1.get(field)) - Integer.parseInt((String)op2.get(field)); }; ```
3,650,167
HI As a daily check I have to check the SQL connection to all our servers. At the moment this is done by manually logging on through SQL server managment studio. I was just wondering if this can be coded in C# so that I can run it first thing in a morning and its checks each server and the instance for a valid SQL connection and reports back to say if the connection is live or not. Thanks Andy
2010/09/06
[ "https://Stackoverflow.com/questions/3650167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/301751/" ]
Look at the [SqlConnection](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx) Class. It includes a basic sample. Just put a loop around that sample to connect to each server, and if any server fails to connect it throws an exception. Then just set it up as a scheduled task in Windows. A nice way to report the status might be with an email, which can easily be sent out with [SmtpClient.Send](http://msdn.microsoft.com/en-us/library/swas0fwc.aspx) (the link has a nice simple sample.
You can also have a look at this method: ``` SqlDataSourceEnumerator.Instance.GetDataSources() ``` It gives you a list of SQL servers available on the network.
3,650,167
HI As a daily check I have to check the SQL connection to all our servers. At the moment this is done by manually logging on through SQL server managment studio. I was just wondering if this can be coded in C# so that I can run it first thing in a morning and its checks each server and the instance for a valid SQL connection and reports back to say if the connection is live or not. Thanks Andy
2010/09/06
[ "https://Stackoverflow.com/questions/3650167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/301751/" ]
Look at the [SqlConnection](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx) Class. It includes a basic sample. Just put a loop around that sample to connect to each server, and if any server fails to connect it throws an exception. Then just set it up as a scheduled task in Windows. A nice way to report the status might be with an email, which can easily be sent out with [SmtpClient.Send](http://msdn.microsoft.com/en-us/library/swas0fwc.aspx) (the link has a nice simple sample.
You know, they make monitoring tools that let you know if your sql server goes down . . .
3,650,167
HI As a daily check I have to check the SQL connection to all our servers. At the moment this is done by manually logging on through SQL server managment studio. I was just wondering if this can be coded in C# so that I can run it first thing in a morning and its checks each server and the instance for a valid SQL connection and reports back to say if the connection is live or not. Thanks Andy
2010/09/06
[ "https://Stackoverflow.com/questions/3650167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/301751/" ]
Here's a little console app example that will cycle through a list of connections and attempt to connect to each, reporting success or failure. Ideally you'd perhaps want to extend this to read in a list of [connection strings](http://www.connectionstrings.com) from a file, but this should hopefully get you started. ``` using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Text; namespace SQLServerChecker { class Program { static void Main(string[] args) { // Use a dictionary to associate a friendly name with each connection string. IDictionary<string, string> connectionStrings = new Dictionary<string, string>(); connectionStrings.Add("Sales Database", "< connection string >"); connectionStrings.Add("QA Database", "< connection string >"); foreach (string databaseName in connectionStrings.Keys) { try { string connectionString = connectionStrings[databaseName]; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); Console.WriteLine("Connected to {0}", databaseName); } } catch (Exception ex) { // Handle the connection failure. Console.WriteLine("FAILED to connect to {0} - {1}", databaseName, ex.Message); } } // Wait for a keypress to stop the console closing. Console.WriteLine("Press any key to finish."); Console.ReadKey(); } } } ```
You can also have a look at this method: ``` SqlDataSourceEnumerator.Instance.GetDataSources() ``` It gives you a list of SQL servers available on the network.
3,650,167
HI As a daily check I have to check the SQL connection to all our servers. At the moment this is done by manually logging on through SQL server managment studio. I was just wondering if this can be coded in C# so that I can run it first thing in a morning and its checks each server and the instance for a valid SQL connection and reports back to say if the connection is live or not. Thanks Andy
2010/09/06
[ "https://Stackoverflow.com/questions/3650167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/301751/" ]
Here's a little console app example that will cycle through a list of connections and attempt to connect to each, reporting success or failure. Ideally you'd perhaps want to extend this to read in a list of [connection strings](http://www.connectionstrings.com) from a file, but this should hopefully get you started. ``` using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Text; namespace SQLServerChecker { class Program { static void Main(string[] args) { // Use a dictionary to associate a friendly name with each connection string. IDictionary<string, string> connectionStrings = new Dictionary<string, string>(); connectionStrings.Add("Sales Database", "< connection string >"); connectionStrings.Add("QA Database", "< connection string >"); foreach (string databaseName in connectionStrings.Keys) { try { string connectionString = connectionStrings[databaseName]; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); Console.WriteLine("Connected to {0}", databaseName); } } catch (Exception ex) { // Handle the connection failure. Console.WriteLine("FAILED to connect to {0} - {1}", databaseName, ex.Message); } } // Wait for a keypress to stop the console closing. Console.WriteLine("Press any key to finish."); Console.ReadKey(); } } } ```
You know, they make monitoring tools that let you know if your sql server goes down . . .
3,650,167
HI As a daily check I have to check the SQL connection to all our servers. At the moment this is done by manually logging on through SQL server managment studio. I was just wondering if this can be coded in C# so that I can run it first thing in a morning and its checks each server and the instance for a valid SQL connection and reports back to say if the connection is live or not. Thanks Andy
2010/09/06
[ "https://Stackoverflow.com/questions/3650167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/301751/" ]
Why c#? You could make a simple batch file that does this using the osql command. ``` osql -S servername\dbname -E -Q "select 'itworks'" ```
You can also have a look at this method: ``` SqlDataSourceEnumerator.Instance.GetDataSources() ``` It gives you a list of SQL servers available on the network.
3,650,167
HI As a daily check I have to check the SQL connection to all our servers. At the moment this is done by manually logging on through SQL server managment studio. I was just wondering if this can be coded in C# so that I can run it first thing in a morning and its checks each server and the instance for a valid SQL connection and reports back to say if the connection is live or not. Thanks Andy
2010/09/06
[ "https://Stackoverflow.com/questions/3650167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/301751/" ]
You can also have a look at this method: ``` SqlDataSourceEnumerator.Instance.GetDataSources() ``` It gives you a list of SQL servers available on the network.
You know, they make monitoring tools that let you know if your sql server goes down . . .
3,650,167
HI As a daily check I have to check the SQL connection to all our servers. At the moment this is done by manually logging on through SQL server managment studio. I was just wondering if this can be coded in C# so that I can run it first thing in a morning and its checks each server and the instance for a valid SQL connection and reports back to say if the connection is live or not. Thanks Andy
2010/09/06
[ "https://Stackoverflow.com/questions/3650167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/301751/" ]
Why c#? You could make a simple batch file that does this using the osql command. ``` osql -S servername\dbname -E -Q "select 'itworks'" ```
You know, they make monitoring tools that let you know if your sql server goes down . . .
49,957,652
I am not sure if this has been answered before in S.O, but I couldn't find any answers googling to explain this behaviour in various databases. so I thought I would clarify this here from experts. When I run this query in Oracle, Postgresql, mysql and sql-server, I get varying results. **Oracle 11g** ``` select count(1/0) from dual; ``` > > ORA-01476: divisor is equal to zero > > > <http://sqlfiddle.com/#!4/e0ee9e/751> **SQL-Server 2017** ``` select count(1/0) ; 1 ``` but `select 1/0` gives error. > > Divide by zero error encountered > > > <http://sqlfiddle.com/#!18/2be41/2> <http://sqlfiddle.com/#!18/185a6/7> **PostgreSQL 9.6** > > ERROR: division by zero > > > <http://sqlfiddle.com/#!17/340e0/80> **Mysql 5.6** ``` select count(1/0) ; 0 ``` <http://sqlfiddle.com/#!9/2be41/10> Why these differences in implementations?
2018/04/21
[ "https://Stackoverflow.com/questions/49957652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7998591/" ]
`count()` counts the number of rows or the non-`NULL` values of the expression. When the expression is constant, then it returns the number of rows. What you are seeing is the question of when and whether the constant is evaluated, and the different way that the databases handle this situation. Oracle and Postgres are clearly trying to evaluate the constant. To be honest, I'm not sure if these are run-time or compile-time errors. SQL Server postpones the evaluation until needed -- and it is never needed. So, it counts the number of rows. MySQL is the strange one. It returns `NULL` for divide-by-zero. This is not standard behavior, but also not entirely unreasonable. `COUNT(NULL)` returns `0`.
In mysql there is a specific mode (enabled or disable) `ERROR_FOR_DIVISION_BY_ZERO` that manage this situation and in your case seems disable (you should check for proper mode value) so you apparently see a wrong (or unexpected result) but is simply a configuration for error handling <https://dev.mysql.com/doc/refman/5.7/en/precision-math-expressions.html>
13,825,867
I've been looking for a solution for this one all day. I have 4 NSTextFields (actually subclassed for a few custom operations), which all share the same X position. The problem is, some have different styles (light, regular, bold) and might have different sizes. What happens is that, even though the X origin is the same, the 1st letter always has a bit of (consistently different) left margins. Please see pic: <https://dl.dropbox.com/u/1977230/Screen%20Shot%202012-12-11%20at%2017.55.58.png> I want to make sure that all lines start exactly at the same point, say 100px from the left. Any idea how to override that weird padding? Cheers
2012/12/11
[ "https://Stackoverflow.com/questions/13825867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/297587/" ]
Have you looked into CoreText? I think it may provide the facilities to do what you're looking for. From the docs... > > The Core Text layout engine is designed specifically to make simple text layout operations easy to do and to avoid side effects. > > > You are able to access "font metrics," which enable you to (from the docs)... > > For every font, glyph designers provide a set of measurements, called metrics, which describe the spacing around each glyph in the font. The typesetter uses these metrics to determine glyph placement. Font metrics are parameters such as ascent, descent, leading, cap height, x-height, and so on. > > > EDIT: It just may be that `NSTextField` was not designed for what you are trying to do. `NSTextField` does custom layout apart from a `NSLayoutManager`. You may need to upgrade to a `NSTextView`, which always has a dedicated `NSLayoutManager` attached. Apple has some example projects you could search for using `NSLayoutManager` and `NSTextView`.
If you're using NSTextField to draw simple static text, take a look at [AppKit additions to NSString](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSString_AppKitAdditions/Reference/Reference.html.). Use `sizeWithAttributes:` to get size of the "text" image. Then use the size to calculate rects for drawing. Finally use one of `draw` methods to actually draw text. Don't forget to "round" result of `sizeWithAttributes`! It's not pixel aligned. But if you need to draw something more complex than simple label, use Core Text. You can find very good example of how to use it in [twui source code](https://github.com/twitter/twui/blob/master/lib/UIKit/TUITextRenderer.m).
13,825,867
I've been looking for a solution for this one all day. I have 4 NSTextFields (actually subclassed for a few custom operations), which all share the same X position. The problem is, some have different styles (light, regular, bold) and might have different sizes. What happens is that, even though the X origin is the same, the 1st letter always has a bit of (consistently different) left margins. Please see pic: <https://dl.dropbox.com/u/1977230/Screen%20Shot%202012-12-11%20at%2017.55.58.png> I want to make sure that all lines start exactly at the same point, say 100px from the left. Any idea how to override that weird padding? Cheers
2012/12/11
[ "https://Stackoverflow.com/questions/13825867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/297587/" ]
The margin you're talking about I'm pretty sure is the `lineFragmentPadding` on the `NSTextContainer` that is used by the `NSTextField`. See the NSTextContainer reference: <http://developer.apple.com/library/Mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSTextContainer_Class/Reference/Reference.html> And here's a page from the tutorial on Text Layout: <https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/TextLayout/Concepts/CalcTextLayout.html> It states in that article: > > The typesetter makes one final adjustment when it actually fits text > into the rectangle. This adjustment is a small amount fixed by the > NSTextContainer object, called the line fragment padding, which > defines the portion on each end of the line fragment rectangle left > blank. Text is inset within the line fragment rectangle by this amount > (the rectangle itself is unaffected). Padding allows for small-scale > adjustment of the text container’s region at the edges and around any > holes and keeps text from directly abutting any other graphics > displayed near the region. You can change the padding from its default > value with the setLineFragmentPadding: method. Note that line fragment > padding isn’t a suitable means for expressing margins; you should set > the NSTextView object’s position and size for document margins or the > paragraph margin attributes for text margins. > > > Unfortunately, it looks like `NSTextField`'s `NSTextContainer` and `NSLayoutManager` are private and inaccessible, but it appears they are accessible in an `NSTextView`: <https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSTextView_Class/Reference/Reference.html#//apple_ref/occ/cl/NSTextView> So that may be the class you need to subclass if you want to have minute control over this kind of functionality.
Have you looked into CoreText? I think it may provide the facilities to do what you're looking for. From the docs... > > The Core Text layout engine is designed specifically to make simple text layout operations easy to do and to avoid side effects. > > > You are able to access "font metrics," which enable you to (from the docs)... > > For every font, glyph designers provide a set of measurements, called metrics, which describe the spacing around each glyph in the font. The typesetter uses these metrics to determine glyph placement. Font metrics are parameters such as ascent, descent, leading, cap height, x-height, and so on. > > > EDIT: It just may be that `NSTextField` was not designed for what you are trying to do. `NSTextField` does custom layout apart from a `NSLayoutManager`. You may need to upgrade to a `NSTextView`, which always has a dedicated `NSLayoutManager` attached. Apple has some example projects you could search for using `NSLayoutManager` and `NSTextView`.
13,825,867
I've been looking for a solution for this one all day. I have 4 NSTextFields (actually subclassed for a few custom operations), which all share the same X position. The problem is, some have different styles (light, regular, bold) and might have different sizes. What happens is that, even though the X origin is the same, the 1st letter always has a bit of (consistently different) left margins. Please see pic: <https://dl.dropbox.com/u/1977230/Screen%20Shot%202012-12-11%20at%2017.55.58.png> I want to make sure that all lines start exactly at the same point, say 100px from the left. Any idea how to override that weird padding? Cheers
2012/12/11
[ "https://Stackoverflow.com/questions/13825867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/297587/" ]
The margin you're talking about I'm pretty sure is the `lineFragmentPadding` on the `NSTextContainer` that is used by the `NSTextField`. See the NSTextContainer reference: <http://developer.apple.com/library/Mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSTextContainer_Class/Reference/Reference.html> And here's a page from the tutorial on Text Layout: <https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/TextLayout/Concepts/CalcTextLayout.html> It states in that article: > > The typesetter makes one final adjustment when it actually fits text > into the rectangle. This adjustment is a small amount fixed by the > NSTextContainer object, called the line fragment padding, which > defines the portion on each end of the line fragment rectangle left > blank. Text is inset within the line fragment rectangle by this amount > (the rectangle itself is unaffected). Padding allows for small-scale > adjustment of the text container’s region at the edges and around any > holes and keeps text from directly abutting any other graphics > displayed near the region. You can change the padding from its default > value with the setLineFragmentPadding: method. Note that line fragment > padding isn’t a suitable means for expressing margins; you should set > the NSTextView object’s position and size for document margins or the > paragraph margin attributes for text margins. > > > Unfortunately, it looks like `NSTextField`'s `NSTextContainer` and `NSLayoutManager` are private and inaccessible, but it appears they are accessible in an `NSTextView`: <https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSTextView_Class/Reference/Reference.html#//apple_ref/occ/cl/NSTextView> So that may be the class you need to subclass if you want to have minute control over this kind of functionality.
If you're using NSTextField to draw simple static text, take a look at [AppKit additions to NSString](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSString_AppKitAdditions/Reference/Reference.html.). Use `sizeWithAttributes:` to get size of the "text" image. Then use the size to calculate rects for drawing. Finally use one of `draw` methods to actually draw text. Don't forget to "round" result of `sizeWithAttributes`! It's not pixel aligned. But if you need to draw something more complex than simple label, use Core Text. You can find very good example of how to use it in [twui source code](https://github.com/twitter/twui/blob/master/lib/UIKit/TUITextRenderer.m).
43,335,213
I have a data structure consisting of a list of `tags`and `weights` pairs, like so: ``` tags = [['male vocalists', 4], ['Lo-Fi', 2], ['pop underground', 2], ['pop', 16], ['power pop', 99], ['post rock', 2], ['alternative', 59], ['electronic', 2], ['classic rock', 2], ['alternative rock', 14], ['pop rock', 2], ['baroque pop', 2], ['powerpop', 4], ['melodic', 2], ['seen live', 62], ['Bellshill', 3], ['singer-songwriter', 2], ['Favourites', 2], ['Teenage Fanclub', 4], ['emo', 2], ['glasgow', 12], ['Scottish', 73], ['indie pop', 27], ['indie', 100], ['00s', 3], ['new wave', 3], ['rap', 2], ['ambient', 2], ['brit pop', 2], ['90s', 14], ['britpop', 26], ['indie rock', 68], ['electronica', 2], ['shoegaze', 5], ['scotland', 11], ['post-punk', 3], ['Alt-country', 2], ['80s', 3], ['jangle pop', 7], ['guitar pop', 4], ['Pop-Rock', 2], ['rock', 31], ['favorites', 2], ['creation records', 3], ['All', 2], ['punk', 3], ['scottish pop', 2], ['british', 17], ['scottish indie', 2], ['slowcore', 2], ['UK', 6], ['jangly', 2]] ``` I know I can get tag with the highest value with: ``` top = max(tags, key=lambda x:x[1])[0] ``` which yields `indie`, correctly. but how do I get N highest values, say, 5?
2017/04/11
[ "https://Stackoverflow.com/questions/43335213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Slice the first 5 elements from a descending sort. ``` sorted(tags, key=lambda x:x[1], reverse=True)[:5] ``` MSeifert's answer is technically better algorithmically. With a large list of length `n` and comparatively small number of elements to take `m`, then `heapq.largest` may be quicker since it takes `O(n * log m)` time whereas sorting then slicing takes `O(n * log n)`. (See [here](https://stackoverflow.com/questions/33069490/nlargest-and-nsmallest-heapq-python) for a rough outline of `heapq.largest`'s algorithm). And then again, logs are almost negligible, so be sure to test if performance is a concern to you!
`heapq` lets you do some really cool stuff like that: ``` In [168]: heapq.nlargest(5, tags, key=operator.itemgetter(1)) Out[168]: [['indie', 100], ['power pop', 99], ['Scottish', 73], ['indie rock', 68], ['seen live', 62]] ```
43,335,213
I have a data structure consisting of a list of `tags`and `weights` pairs, like so: ``` tags = [['male vocalists', 4], ['Lo-Fi', 2], ['pop underground', 2], ['pop', 16], ['power pop', 99], ['post rock', 2], ['alternative', 59], ['electronic', 2], ['classic rock', 2], ['alternative rock', 14], ['pop rock', 2], ['baroque pop', 2], ['powerpop', 4], ['melodic', 2], ['seen live', 62], ['Bellshill', 3], ['singer-songwriter', 2], ['Favourites', 2], ['Teenage Fanclub', 4], ['emo', 2], ['glasgow', 12], ['Scottish', 73], ['indie pop', 27], ['indie', 100], ['00s', 3], ['new wave', 3], ['rap', 2], ['ambient', 2], ['brit pop', 2], ['90s', 14], ['britpop', 26], ['indie rock', 68], ['electronica', 2], ['shoegaze', 5], ['scotland', 11], ['post-punk', 3], ['Alt-country', 2], ['80s', 3], ['jangle pop', 7], ['guitar pop', 4], ['Pop-Rock', 2], ['rock', 31], ['favorites', 2], ['creation records', 3], ['All', 2], ['punk', 3], ['scottish pop', 2], ['british', 17], ['scottish indie', 2], ['slowcore', 2], ['UK', 6], ['jangly', 2]] ``` I know I can get tag with the highest value with: ``` top = max(tags, key=lambda x:x[1])[0] ``` which yields `indie`, correctly. but how do I get N highest values, say, 5?
2017/04/11
[ "https://Stackoverflow.com/questions/43335213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Slice the first 5 elements from a descending sort. ``` sorted(tags, key=lambda x:x[1], reverse=True)[:5] ``` MSeifert's answer is technically better algorithmically. With a large list of length `n` and comparatively small number of elements to take `m`, then `heapq.largest` may be quicker since it takes `O(n * log m)` time whereas sorting then slicing takes `O(n * log n)`. (See [here](https://stackoverflow.com/questions/33069490/nlargest-and-nsmallest-heapq-python) for a rough outline of `heapq.largest`'s algorithm). And then again, logs are almost negligible, so be sure to test if performance is a concern to you!
Use the `sorted` function, or the `.sort` method on the list. Both take a `key=` parameter like `max`. Then you can take the lowest, or highest, batch. ``` top = sorted(tags, reverse=True, key=lambda x:x[1])[0:5] ```
43,335,213
I have a data structure consisting of a list of `tags`and `weights` pairs, like so: ``` tags = [['male vocalists', 4], ['Lo-Fi', 2], ['pop underground', 2], ['pop', 16], ['power pop', 99], ['post rock', 2], ['alternative', 59], ['electronic', 2], ['classic rock', 2], ['alternative rock', 14], ['pop rock', 2], ['baroque pop', 2], ['powerpop', 4], ['melodic', 2], ['seen live', 62], ['Bellshill', 3], ['singer-songwriter', 2], ['Favourites', 2], ['Teenage Fanclub', 4], ['emo', 2], ['glasgow', 12], ['Scottish', 73], ['indie pop', 27], ['indie', 100], ['00s', 3], ['new wave', 3], ['rap', 2], ['ambient', 2], ['brit pop', 2], ['90s', 14], ['britpop', 26], ['indie rock', 68], ['electronica', 2], ['shoegaze', 5], ['scotland', 11], ['post-punk', 3], ['Alt-country', 2], ['80s', 3], ['jangle pop', 7], ['guitar pop', 4], ['Pop-Rock', 2], ['rock', 31], ['favorites', 2], ['creation records', 3], ['All', 2], ['punk', 3], ['scottish pop', 2], ['british', 17], ['scottish indie', 2], ['slowcore', 2], ['UK', 6], ['jangly', 2]] ``` I know I can get tag with the highest value with: ``` top = max(tags, key=lambda x:x[1])[0] ``` which yields `indie`, correctly. but how do I get N highest values, say, 5?
2017/04/11
[ "https://Stackoverflow.com/questions/43335213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Slice the first 5 elements from a descending sort. ``` sorted(tags, key=lambda x:x[1], reverse=True)[:5] ``` MSeifert's answer is technically better algorithmically. With a large list of length `n` and comparatively small number of elements to take `m`, then `heapq.largest` may be quicker since it takes `O(n * log m)` time whereas sorting then slicing takes `O(n * log n)`. (See [here](https://stackoverflow.com/questions/33069490/nlargest-and-nsmallest-heapq-python) for a rough outline of `heapq.largest`'s algorithm). And then again, logs are almost negligible, so be sure to test if performance is a concern to you!
``` import operator def printTopX(tags, X): print( sorted(tags, reverse=True, key=operator.itemgetter(1))[0:X] ) printTopX(tags, 5) ```
43,335,213
I have a data structure consisting of a list of `tags`and `weights` pairs, like so: ``` tags = [['male vocalists', 4], ['Lo-Fi', 2], ['pop underground', 2], ['pop', 16], ['power pop', 99], ['post rock', 2], ['alternative', 59], ['electronic', 2], ['classic rock', 2], ['alternative rock', 14], ['pop rock', 2], ['baroque pop', 2], ['powerpop', 4], ['melodic', 2], ['seen live', 62], ['Bellshill', 3], ['singer-songwriter', 2], ['Favourites', 2], ['Teenage Fanclub', 4], ['emo', 2], ['glasgow', 12], ['Scottish', 73], ['indie pop', 27], ['indie', 100], ['00s', 3], ['new wave', 3], ['rap', 2], ['ambient', 2], ['brit pop', 2], ['90s', 14], ['britpop', 26], ['indie rock', 68], ['electronica', 2], ['shoegaze', 5], ['scotland', 11], ['post-punk', 3], ['Alt-country', 2], ['80s', 3], ['jangle pop', 7], ['guitar pop', 4], ['Pop-Rock', 2], ['rock', 31], ['favorites', 2], ['creation records', 3], ['All', 2], ['punk', 3], ['scottish pop', 2], ['british', 17], ['scottish indie', 2], ['slowcore', 2], ['UK', 6], ['jangly', 2]] ``` I know I can get tag with the highest value with: ``` top = max(tags, key=lambda x:x[1])[0] ``` which yields `indie`, correctly. but how do I get N highest values, say, 5?
2017/04/11
[ "https://Stackoverflow.com/questions/43335213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Use [`heapq.nlargest`](https://docs.python.org/3.6/library/heapq.html#heapq.nlargest): ``` >>> import heapq >>> heapq.nlargest(5, tags, key=lambda x:x[1]) [['indie', 100], ['power pop', 99], ['Scottish', 73], ['indie rock', 68], ['seen live', 62]] ``` or if you're only interested in the name: ``` >>> [name for name, _ in heapq.nlargest(5, tags, key=lambda x:x[1])] ['indie', 'power pop', 'Scottish', 'indie rock', 'seen live'] ```
`heapq` lets you do some really cool stuff like that: ``` In [168]: heapq.nlargest(5, tags, key=operator.itemgetter(1)) Out[168]: [['indie', 100], ['power pop', 99], ['Scottish', 73], ['indie rock', 68], ['seen live', 62]] ```
43,335,213
I have a data structure consisting of a list of `tags`and `weights` pairs, like so: ``` tags = [['male vocalists', 4], ['Lo-Fi', 2], ['pop underground', 2], ['pop', 16], ['power pop', 99], ['post rock', 2], ['alternative', 59], ['electronic', 2], ['classic rock', 2], ['alternative rock', 14], ['pop rock', 2], ['baroque pop', 2], ['powerpop', 4], ['melodic', 2], ['seen live', 62], ['Bellshill', 3], ['singer-songwriter', 2], ['Favourites', 2], ['Teenage Fanclub', 4], ['emo', 2], ['glasgow', 12], ['Scottish', 73], ['indie pop', 27], ['indie', 100], ['00s', 3], ['new wave', 3], ['rap', 2], ['ambient', 2], ['brit pop', 2], ['90s', 14], ['britpop', 26], ['indie rock', 68], ['electronica', 2], ['shoegaze', 5], ['scotland', 11], ['post-punk', 3], ['Alt-country', 2], ['80s', 3], ['jangle pop', 7], ['guitar pop', 4], ['Pop-Rock', 2], ['rock', 31], ['favorites', 2], ['creation records', 3], ['All', 2], ['punk', 3], ['scottish pop', 2], ['british', 17], ['scottish indie', 2], ['slowcore', 2], ['UK', 6], ['jangly', 2]] ``` I know I can get tag with the highest value with: ``` top = max(tags, key=lambda x:x[1])[0] ``` which yields `indie`, correctly. but how do I get N highest values, say, 5?
2017/04/11
[ "https://Stackoverflow.com/questions/43335213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Use [`heapq.nlargest`](https://docs.python.org/3.6/library/heapq.html#heapq.nlargest): ``` >>> import heapq >>> heapq.nlargest(5, tags, key=lambda x:x[1]) [['indie', 100], ['power pop', 99], ['Scottish', 73], ['indie rock', 68], ['seen live', 62]] ``` or if you're only interested in the name: ``` >>> [name for name, _ in heapq.nlargest(5, tags, key=lambda x:x[1])] ['indie', 'power pop', 'Scottish', 'indie rock', 'seen live'] ```
Use the `sorted` function, or the `.sort` method on the list. Both take a `key=` parameter like `max`. Then you can take the lowest, or highest, batch. ``` top = sorted(tags, reverse=True, key=lambda x:x[1])[0:5] ```
43,335,213
I have a data structure consisting of a list of `tags`and `weights` pairs, like so: ``` tags = [['male vocalists', 4], ['Lo-Fi', 2], ['pop underground', 2], ['pop', 16], ['power pop', 99], ['post rock', 2], ['alternative', 59], ['electronic', 2], ['classic rock', 2], ['alternative rock', 14], ['pop rock', 2], ['baroque pop', 2], ['powerpop', 4], ['melodic', 2], ['seen live', 62], ['Bellshill', 3], ['singer-songwriter', 2], ['Favourites', 2], ['Teenage Fanclub', 4], ['emo', 2], ['glasgow', 12], ['Scottish', 73], ['indie pop', 27], ['indie', 100], ['00s', 3], ['new wave', 3], ['rap', 2], ['ambient', 2], ['brit pop', 2], ['90s', 14], ['britpop', 26], ['indie rock', 68], ['electronica', 2], ['shoegaze', 5], ['scotland', 11], ['post-punk', 3], ['Alt-country', 2], ['80s', 3], ['jangle pop', 7], ['guitar pop', 4], ['Pop-Rock', 2], ['rock', 31], ['favorites', 2], ['creation records', 3], ['All', 2], ['punk', 3], ['scottish pop', 2], ['british', 17], ['scottish indie', 2], ['slowcore', 2], ['UK', 6], ['jangly', 2]] ``` I know I can get tag with the highest value with: ``` top = max(tags, key=lambda x:x[1])[0] ``` which yields `indie`, correctly. but how do I get N highest values, say, 5?
2017/04/11
[ "https://Stackoverflow.com/questions/43335213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Use [`heapq.nlargest`](https://docs.python.org/3.6/library/heapq.html#heapq.nlargest): ``` >>> import heapq >>> heapq.nlargest(5, tags, key=lambda x:x[1]) [['indie', 100], ['power pop', 99], ['Scottish', 73], ['indie rock', 68], ['seen live', 62]] ``` or if you're only interested in the name: ``` >>> [name for name, _ in heapq.nlargest(5, tags, key=lambda x:x[1])] ['indie', 'power pop', 'Scottish', 'indie rock', 'seen live'] ```
``` import operator def printTopX(tags, X): print( sorted(tags, reverse=True, key=operator.itemgetter(1))[0:X] ) printTopX(tags, 5) ```
37,953,397
how to check a field is exactly equal to a string or number I want to check a field named `course_id` is equal a field of database `id` in `course` database. now I want to check if `course_id` is equal to `id`.
2016/06/21
[ "https://Stackoverflow.com/questions/37953397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4373986/" ]
You can validate it by using the [exists](https://laravel.com/docs/5.2/validation#rule-exists) validation rule: ``` $validationRules = ['course_id' => 'exists:course,id']; ```
create rule as below and use validator on input ``` $rules = array( 'id' => 'exists:your_table_name' ); ``` for more help <https://laravel.com/docs/5.2/validation#rule-exists>
54,368,901
I am trying to match a very specific pattern for my uni project. Unfortunately I'm stuck. The pattern goes as follows: > > * A word or number of length 1 or 2 followed by `,`. > * This is repeated for four times and then followed by `;` instead of `,`. > * This whole thing repeats itself for exactly four times but without `;` at the end. > > > Examples would be: ``` SR,SR,SR,AR;0,11,22,33;SG,1,23,DG;SY,BY,CY,DY 36,AR,CR,DR;SB,10,16,22;SG,13,BG,DG;SY,0,20,BY ``` Whereas these should not match (look for the commas and semicolons): ``` SR,SR;SR,AR;0,11,22,33;SG,1,23,DG;SY,BY,CY,DY 36,AR,CR,DR,SB,10,16,22;SG,13,BG,DG;SY,0,20,BY ``` The closest I got is ``` ((([ABCDS][RBGY])|\d{1,2})[,;]){16} ``` But this does match the negative examples above. This is my current workaround: ``` public boolean matching(String arguments) { String[] strings = arguments.split(";"); if (strings.length != 4) return false; for (String s : strings) { String[] strings1 = s.split(","); if (strings1.length != 4) return false; for (String s1 : strings1) { if (!s1.matches(POSITION_PATTERN)) return false; } } return true; } ``` However, this is not an ideal solution and very inefficient.
2019/01/25
[ "https://Stackoverflow.com/questions/54368901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10968251/" ]
You may try using the following pattern: ``` (?:[ABCDS][RBGY]|\d{1,2})(?:,(?:[ABCDS][RBGY]|\d{1,2})){3}(?:;(?:[ABCDS][RBGY]|\d{1,2})(?:,(?:[ABCDS][RBGY]|\d{1,2})){3}){3} ``` Explanation: ``` (?:[ABCDS][RBGY]|\d{1,2}) match two letter or 1-2 digits (?:,(?:[ABCDS][RBGY]|\d{1,2})){3} followed by a comma and another two letters or 1-2 digits, that quantity 3 times (?:; then match semicolon (?:[ABCDS][RBGY]|\d{1,2})(?:,(?:[ABCDS][RBGY]|\d{1,2})){3}){3} followed by the previous pattern 3 more times ``` [Demo ----](https://regex101.com/r/2UuDXx/1)
Your description of the pattern doesn't match your sample data. I suspect you mean the letter groups to be repeated four times, right? A simple one could look like this: `((\w{1,2}(,|(?:\w))){4}(;|$)){4}` It just does, step by step, what you asked for. See [DEMO](https://regexr.com/474kd)
18,328,546
On [Java revisited](http://javarevisited.blogspot.tw/2011/09/generics-java-example-tutorial.html) ,a code excerpt goes below: ``` class Holder<T>{ private T[] contents; private int index = 0; public Holder(int size){ //contents = new T[size]; //compiler error - generic array creation contents = (T[]) new Object[size]; //workaround - casting Object[] to generic Type }...} ``` It is for generic array creation, but according to type erasure (I checked it on java online tutorial), `T` ends into `Object` at class compiled, so the cast `(T[])` would ends into `(Object[])`, and that seems take **no difference to without casting**. So what is the function of that casting or any special meaning for casting? any hint is thankful.
2013/08/20
[ "https://Stackoverflow.com/questions/18328546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2130573/" ]
The cast is required to tell the compiler that the assignment is Ok from our side. Else it will show you compiler error. Due to type erasure, the type parameter `T` is replaced with it's erasure at compile time. The erasure of an unbounded type parameter is `Object`, whereas the erasure of the bounded type parameter is the type denoting the upper bound. So, if your type parameter in class had an upper bound - `Holder<T extends Number>`, then the erasure of `T` will be `Number`. That means, `T` will be replaced with `Number` by the compiler. So, in this case, since `T` in unbounded, its erasure is `Object`. So, it is replaced with `Object` by the compiler. Even though the casting removes the compiler error, the compiler would still show you a warning of Unchecked Cast. Because, the cast is not type safe, and would fail at runtime with `ClassCastException` in case you instantiate the generic type using `String` type parameter. Try this: ``` Holder<String> stringHolder = new Holder<>(5); String[] contents = stringHolder.getContents(); // ClassCastException ``` --- A safer way to create generic array is using `Array.newInstance` method. You need to pass `Class<T>` parameter to your constructor, and then use the following code: ``` public Holder(int size, Class<T> clazz){ contents = (T[]) Array.newInstance(clazz, size); } ``` Here also you will see the `Unchecked Cast` warning. But that is harmless. Even safer way is not at all to create a array whose component type is a type parameter. You can rather use an `ArrayList<T>` instead. --- **Reference:** * [Java Generic FAQs - Angelika Langer](http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeParameters.html#Can%20I%20create%20an%20array%20whose%20component%20type%20is%20a%20type%20parameter?)
T is just a placeholder. You can't instantiate it which is while the compile error exists. At compile time you need to tell the compiler what the placeholder presents. In the case of the code excerpt, the placeholder is anything.
18,328,546
On [Java revisited](http://javarevisited.blogspot.tw/2011/09/generics-java-example-tutorial.html) ,a code excerpt goes below: ``` class Holder<T>{ private T[] contents; private int index = 0; public Holder(int size){ //contents = new T[size]; //compiler error - generic array creation contents = (T[]) new Object[size]; //workaround - casting Object[] to generic Type }...} ``` It is for generic array creation, but according to type erasure (I checked it on java online tutorial), `T` ends into `Object` at class compiled, so the cast `(T[])` would ends into `(Object[])`, and that seems take **no difference to without casting**. So what is the function of that casting or any special meaning for casting? any hint is thankful.
2013/08/20
[ "https://Stackoverflow.com/questions/18328546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2130573/" ]
T is just a placeholder. You can't instantiate it which is while the compile error exists. At compile time you need to tell the compiler what the placeholder presents. In the case of the code excerpt, the placeholder is anything.
If you consider that after type erasure all type parameters end up as simple `Object`s, your question is about the use of Java Generics as a whole. In my opinion, these are: 1. Documentation / inter-developer communication / legibility / maintainability. 2. Avoid logic errors as early as possible (i.e. statically). 3. Reduce testing requirements / allow to refocus testing efforts in more transcendental aspects and made the code more robust. Unfortunately, it was difficult to fit Generics in Java maintaining full backwards compatibility and other objectives at that point. The result is that `new T[size]` is invalid. The only alternative is `new Object[size]`. The cast `(T[])` is to tell the compiler and other developers that that's exactly what you intended. In particular, the compiler will not emit a warning message in this particular line (which is much safer than globally disabling this kind of checks).
18,328,546
On [Java revisited](http://javarevisited.blogspot.tw/2011/09/generics-java-example-tutorial.html) ,a code excerpt goes below: ``` class Holder<T>{ private T[] contents; private int index = 0; public Holder(int size){ //contents = new T[size]; //compiler error - generic array creation contents = (T[]) new Object[size]; //workaround - casting Object[] to generic Type }...} ``` It is for generic array creation, but according to type erasure (I checked it on java online tutorial), `T` ends into `Object` at class compiled, so the cast `(T[])` would ends into `(Object[])`, and that seems take **no difference to without casting**. So what is the function of that casting or any special meaning for casting? any hint is thankful.
2013/08/20
[ "https://Stackoverflow.com/questions/18328546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2130573/" ]
The cast is required to tell the compiler that the assignment is Ok from our side. Else it will show you compiler error. Due to type erasure, the type parameter `T` is replaced with it's erasure at compile time. The erasure of an unbounded type parameter is `Object`, whereas the erasure of the bounded type parameter is the type denoting the upper bound. So, if your type parameter in class had an upper bound - `Holder<T extends Number>`, then the erasure of `T` will be `Number`. That means, `T` will be replaced with `Number` by the compiler. So, in this case, since `T` in unbounded, its erasure is `Object`. So, it is replaced with `Object` by the compiler. Even though the casting removes the compiler error, the compiler would still show you a warning of Unchecked Cast. Because, the cast is not type safe, and would fail at runtime with `ClassCastException` in case you instantiate the generic type using `String` type parameter. Try this: ``` Holder<String> stringHolder = new Holder<>(5); String[] contents = stringHolder.getContents(); // ClassCastException ``` --- A safer way to create generic array is using `Array.newInstance` method. You need to pass `Class<T>` parameter to your constructor, and then use the following code: ``` public Holder(int size, Class<T> clazz){ contents = (T[]) Array.newInstance(clazz, size); } ``` Here also you will see the `Unchecked Cast` warning. But that is harmless. Even safer way is not at all to create a array whose component type is a type parameter. You can rather use an `ArrayList<T>` instead. --- **Reference:** * [Java Generic FAQs - Angelika Langer](http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeParameters.html#Can%20I%20create%20an%20array%20whose%20component%20type%20is%20a%20type%20parameter?)
The cast is present to *get rid of* **compilation error**. And its an **unchecked** way of creating generic array. Even the `ArrayList` follows the same method. You can have a look at [this answer](https://stackoverflow.com/questions/18328546/why-cast-to-generic-type-takes-effect#18328546) to see both checked and unchecked methods
18,328,546
On [Java revisited](http://javarevisited.blogspot.tw/2011/09/generics-java-example-tutorial.html) ,a code excerpt goes below: ``` class Holder<T>{ private T[] contents; private int index = 0; public Holder(int size){ //contents = new T[size]; //compiler error - generic array creation contents = (T[]) new Object[size]; //workaround - casting Object[] to generic Type }...} ``` It is for generic array creation, but according to type erasure (I checked it on java online tutorial), `T` ends into `Object` at class compiled, so the cast `(T[])` would ends into `(Object[])`, and that seems take **no difference to without casting**. So what is the function of that casting or any special meaning for casting? any hint is thankful.
2013/08/20
[ "https://Stackoverflow.com/questions/18328546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2130573/" ]
The cast is present to *get rid of* **compilation error**. And its an **unchecked** way of creating generic array. Even the `ArrayList` follows the same method. You can have a look at [this answer](https://stackoverflow.com/questions/18328546/why-cast-to-generic-type-takes-effect#18328546) to see both checked and unchecked methods
If you consider that after type erasure all type parameters end up as simple `Object`s, your question is about the use of Java Generics as a whole. In my opinion, these are: 1. Documentation / inter-developer communication / legibility / maintainability. 2. Avoid logic errors as early as possible (i.e. statically). 3. Reduce testing requirements / allow to refocus testing efforts in more transcendental aspects and made the code more robust. Unfortunately, it was difficult to fit Generics in Java maintaining full backwards compatibility and other objectives at that point. The result is that `new T[size]` is invalid. The only alternative is `new Object[size]`. The cast `(T[])` is to tell the compiler and other developers that that's exactly what you intended. In particular, the compiler will not emit a warning message in this particular line (which is much safer than globally disabling this kind of checks).
18,328,546
On [Java revisited](http://javarevisited.blogspot.tw/2011/09/generics-java-example-tutorial.html) ,a code excerpt goes below: ``` class Holder<T>{ private T[] contents; private int index = 0; public Holder(int size){ //contents = new T[size]; //compiler error - generic array creation contents = (T[]) new Object[size]; //workaround - casting Object[] to generic Type }...} ``` It is for generic array creation, but according to type erasure (I checked it on java online tutorial), `T` ends into `Object` at class compiled, so the cast `(T[])` would ends into `(Object[])`, and that seems take **no difference to without casting**. So what is the function of that casting or any special meaning for casting? any hint is thankful.
2013/08/20
[ "https://Stackoverflow.com/questions/18328546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2130573/" ]
The cast is required to tell the compiler that the assignment is Ok from our side. Else it will show you compiler error. Due to type erasure, the type parameter `T` is replaced with it's erasure at compile time. The erasure of an unbounded type parameter is `Object`, whereas the erasure of the bounded type parameter is the type denoting the upper bound. So, if your type parameter in class had an upper bound - `Holder<T extends Number>`, then the erasure of `T` will be `Number`. That means, `T` will be replaced with `Number` by the compiler. So, in this case, since `T` in unbounded, its erasure is `Object`. So, it is replaced with `Object` by the compiler. Even though the casting removes the compiler error, the compiler would still show you a warning of Unchecked Cast. Because, the cast is not type safe, and would fail at runtime with `ClassCastException` in case you instantiate the generic type using `String` type parameter. Try this: ``` Holder<String> stringHolder = new Holder<>(5); String[] contents = stringHolder.getContents(); // ClassCastException ``` --- A safer way to create generic array is using `Array.newInstance` method. You need to pass `Class<T>` parameter to your constructor, and then use the following code: ``` public Holder(int size, Class<T> clazz){ contents = (T[]) Array.newInstance(clazz, size); } ``` Here also you will see the `Unchecked Cast` warning. But that is harmless. Even safer way is not at all to create a array whose component type is a type parameter. You can rather use an `ArrayList<T>` instead. --- **Reference:** * [Java Generic FAQs - Angelika Langer](http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeParameters.html#Can%20I%20create%20an%20array%20whose%20component%20type%20is%20a%20type%20parameter?)
If you consider that after type erasure all type parameters end up as simple `Object`s, your question is about the use of Java Generics as a whole. In my opinion, these are: 1. Documentation / inter-developer communication / legibility / maintainability. 2. Avoid logic errors as early as possible (i.e. statically). 3. Reduce testing requirements / allow to refocus testing efforts in more transcendental aspects and made the code more robust. Unfortunately, it was difficult to fit Generics in Java maintaining full backwards compatibility and other objectives at that point. The result is that `new T[size]` is invalid. The only alternative is `new Object[size]`. The cast `(T[])` is to tell the compiler and other developers that that's exactly what you intended. In particular, the compiler will not emit a warning message in this particular line (which is much safer than globally disabling this kind of checks).
28,345,611
I am using a linq query to feed the gridview the one below: ``` var query = (from p in db.Mytable Where p.Circuit_Type.Equals(drpCircuitType.SelectedItem) && p.Voltage >= double.Parse(Voltage) && p.HP >= double.Parse(HP) select new { p.Circuit_Type, p.Device1_Part_Number, p.Device1_Description, p.Device2_Part_Number, p.Device2_Description, p.Device3_Part_Number, p.Device4_Part_Number, p.Device4_Description, p.Min_Encl_Volume, p.Conditions_of_Acceptability, p.SCCR, p.Voltage_CombinationSCCR, p.U_Reference, p.Combination_Reference }); GridTest.DataSource = query; GridTest.DataBind(); ``` This is working so far. so What I want is if a field of those is empty not to show that column in the gridview(hide it automatically)
2015/02/05
[ "https://Stackoverflow.com/questions/28345611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4503648/" ]
You can just check if there is symbol not from your set: ``` size_t pos = mail.find_first_not_of( "-_.@" ); if( pos != std::string::npos ) ++counter; ``` This code increase counter once if whole string has any symbol not from that set, ie it is based on problem description not your code, that tries to count how many symbols not from that set.
You can use regular expressions using boost. If I understood your question correctly, you want to check for strings not containing letters, digits and "-\_.@". An example implementation is shown below. Adapt the code to your needs: ``` // std #include <iostream> using namespace std; // boost #include <boost/regex.hpp> int main () { unsigned int counter = 0; // ... my code ... string myString = "foo%[email protected]"; boost::regex myRegex("[^a-zA-Z_.@-]+"); if (boost::regex_search(myString, myRegex)) { counter++; } // ... my code ... return 0; } ``` **Update** In order to compile the code, you need to install the boost library. You do not need to install it all. Just make sure to install `libboost-regex`. For compilation, you may use the following command which links with the necessary boost library: ``` g++ -o main main.cpp -lboost_regex ```
41,589,771
I'm completely new to C++. In my program there's a function which has to take a `LPCTSTR` as a parameter. I want to convert it into a `char*`. What I tried is as follows, ``` char* GetChar(LPCTSTR var){ char* id = (char*)var; ..... } ``` But while debugging I noticed that only first letter of `var` is assigned to `id`. What have I done wrong? (I tried various answers in StackOverflow about converting LPCTSTR to char\* before coming to this solution. None of them worked for me.) **UPDATE** What i want is to get full string pointed by `var` to be treated as `char*`
2017/01/11
[ "https://Stackoverflow.com/questions/41589771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4383820/" ]
**DEMO** : ***<https://plnkr.co/edit/NzVUHpT7WQWPB2mmUlJM?p=preview>*** You should use **`componentFactoryResolver`** to add **`(component)`** dynamically from **`myexamplecomponent`** ``` /*-----------comment Component start--------*/ @Component({ selector: 'comment', template: `<textarea cols="20" rows="5">Hi</textarea>` }) export class comment{} /*-----------comment Component end--------*/ /*-----------my-example-component Component start--------*/ @Component({ selector: 'my-example-component', entryComponents: [comment], template: `<div #target> Child {{n}} <button (click)="clickMe()">Add Comment</button> </div>` }) export class MyExampleComponent{ @Input() n: number; @ViewChild('target', {read: ViewContainerRef}) target: ViewContainerRef; cmpRef: ComponentRef<comment>; private isViewInitialized:boolean = false; constructor(private componentFactoryResolver: ComponentFactoryResolver, private compiler: Compiler, private cdRef:ChangeDetectorRef) {} clickMe() { let factory = this.componentFactoryResolver.resolveComponentFactory(comment, 2); this.cmpRef = this.target.createComponent(factory) //this.cmpRef.instance.n = 'foobar'; //this.cdRef.detectChanges(); } } /*-----------my-example-component Component end--------*/ ```
Here is how I would do it: *define in parent component: `showIndex = null;` and set it back to null when you want to hide it again.* *parent component view:* ``` <div template="ngFor let item of [1,2,3,4,5]; let i = index;"> <my-example-component (onShowMore)="showIndex = i"></my-example-component> <div *ngIf="showIndex === i">More stuff in here</div> </div> ``` *MyExampleComponent:* ``` @Component({ selector: 'my-example-component', template: `<div style="border: 1px solid salmon"><button (click)="onShowMore.emit(null)">Show More</button></div>` }) export class MyExampleComponent { @Output() onShowMore = new EventEmitter<any>(); } ``` Edit How to toggle stuff in child component (code not tested): ``` import {Component, Output, EventEmitter, Input} from "@angular/core" @Component({ selector: 'Parent', template: `<child *ngFor="let item of [1,2,3,4,5]; let i = index;"(onShowMore)="onShowMore($event)" [index]="i" [showIndex]="showIndex"></child>` }) export class ParentComponent { private showIndex: number | null; ngOnInit() { this.showIndex = null; } onShowMore(childIndex) { this.showIndex = childIndex } } @Component({ selector: 'child', template: ` <div> <button (click)="showIndex === index ? hide() : show()"> {{showIndex === index ? 'Hide me' : 'Show me'}} </button> </div> <div *ngIf="showIndex === index">This is more content</div> ` }) export class ChildComponent { @Input() showIndex: number | null; @Input() index: number; @Output() onShowMore = new EventEmitter<number | null>(); show() { this.onShowMore.emit(this.index); } hide() { this.onShowMore.emit(null); } } ```
36,226,047
I've successfully coded Python to open a website and then click a link. After that, I'd like to grab info from the site that is "active". But I'm getting the following error: Search = Regex.search(res.text) AttributeError: 'NoneType' object has no attribute 'text' I think the problem is that I don't know how to "define" the clicked-into webpage as a variable. Here is the code that is relevant: ``` import re, requests, csv, pyperclip, logging from selenium import webdriver browser = webdriver.Firefox() browser.get('http://espn.go.com/golf/players') find_player = browser.find_element_by_partial_link_text("Allenby, Robert") res = find_player.click() xRegex = re.compile(r'(1991)') xSearch = xRegex.search(res.text) output_player_name = xSearch.group(1) ``` This is my first Python coding experience and my first post to ask a question. Thanks in advance for any help. PS I know that 1991 appears in the webpage. It's the year Robert Allenby turned pro.
2016/03/25
[ "https://Stackoverflow.com/questions/36226047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6115179/" ]
To find out if a jar file is signed, you can unzip the jar file using any zip utility tool. If the jar is signed it will contain files like \*.RSA, \*.SF or \*.DSA under META-INF folder. To exclude these signature files in gradle build , I did the following in my build.gradle. If you are using any other plugin to create the jar than you should check that plugins documentation for more details. ``` jar { from { (configurations.runtime).collect { it.isDirectory() ? it : zipTree(it) } } { exclude 'META-INF/*.RSA', 'META-INF/*.SF', 'META-INF/*.DSA' } manifest { attributes("Main-Class": "com.nk.social.shareit.streams.AppMain") }} ``` My entire build.gradle file is as listed below:- ``` apply plugin: 'scala' dependencies { compile group: 'org.apache.kafka', name: 'kafka-streams', version: '0.11.0.1' compile 'org.scala-lang:scala-library:2.12.2' compile 'com.sksamuel.elastic4s:elastic4s-core_2.12:5.4.2' compile 'com.sksamuel.elastic4s:elastic4s-http_2.12:5.4.2' compile 'org.apache.lucene:lucene-core:6.5.1' compile 'joda-time:joda-time:2.9.9' testCompile group: 'org.scalatest', name: 'scalatest_2.12', version: '3.0.4' } jar { from { (configurations.runtime).collect { it.isDirectory() ? it : zipTree(it) } } { exclude 'META-INF/*.RSA', 'META-INF/*.SF', 'META-INF/*.DSA' } manifest { attributes("Main-Class": "com.nk.social.shareit.streams.AppMain") } } ``` Hope this helps.
With the jar, for example given in this thread I have a problem building a fat jar. The main motivation is that the build process will skip also some dependecens. A solution found is the following one, it contains only a small change ``` jar { manifest { attributes( 'Class-Path': configurations.compile.collect { it.getName() }.join(' '), 'Main-Class': 'io.vincenzopalazzo.lightning.App' ) } from(configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }) { exclude 'META-INF/*.RSA', 'META-INF/*.SF', 'META-INF/*.DSA' } } ```
22,645,151
I have a ViewController that contains a uiscrollview and I create 2 uiview as pages inside the uiscrollview with paging and scrolling enabled: ``` _scrollView.frame = CGRectMake(_scrollView.frame.origin.x, _scrollView.frame.origin.y, _scrollView.frame.size.width, _scrollView.frame.size.height); _scrollView.contentSize = CGSizeMake(_scrollView.frame.size.width, _scrollView.frame.size.height*PAGES_NUMBER); _scrollView.delegate = self; [self.view addSubview:_scrollView]; //PAGE 1 genderViewController = [[GenderViewController alloc]init]; genderViewController.view.frame = CGRectMake(0.0, _scrollView.frame.size.height*0, _scrollView.frame.size.width, _scrollView.frame.size.height); [_scrollView addSubview:genderViewController.view]; //PAGE 2 ageViewController = [[AgeViewController alloc]init]; ageViewController.view.frame =CGRectMake(0.0, _scrollView.frame.size.height*1, _scrollView.frame.size.width, _scrollView.frame.size.height); [_scrollView addSubview:ageViewController.view]; ``` The thing is that I'm wondering how can I pass data between this 2 uiview. For example, I have a UITextField in the first page "genderViewController" and I want to show this content in and UILabel in the second page "ageViewController" once I scroll to the second page. I know how to pass data between 2 different view controllers in a navigation view, but I don't know how to do this at this stage. I would appreciate if you guys could help me with that. Thanks!
2014/03/25
[ "https://Stackoverflow.com/questions/22645151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/862227/" ]
You don't really need to create "sessions" for each test. Instead, you have to capture a snapshot of the profiling data at the end of each test, and clear the profiling data before running the next test. Using the [yourkit API](http://www.yourkit.com/docs/java/api/index.html), you can do so in a manner similar to: ``` public void profile(String host, int port, List<InputData> inputDataSet) { Map<InputData, String> pathMap = new HashMap<InputData, String>(); //If you want to save the location of each file //Init profiling data collection com.yourkit.api.Controller controller = new Controller(host, port); controller.startCPUSampling(/*with your settings*/); controller.startAllocationRecording(/*With your settings*/); //controller.startXXX with whatever data you want to collect for (InputData input: inputDataSet) { //Run your test runTest(inputData); //Save profiling data String path = controller.captureSnapshot(/*With or without memory dump*/); pathMap.put(input, path); //Clear yourkit profiling data controller.clearAllocationData(); controller.clearCPUData(); //controller.clearXXX with whatever data you are collecting } } ``` I don't think you need to stop collecting, capture snapshot, clear data, restart collecting, you can just capture and clear data, but please double-check. Once the tests are run, you can open the snapshots in yourkit and analyze the profiling data.
Unfotunately it's not clear how to run your tests. Does each test run in own JVM process or you run all tests in loop inside single JVM? If you run each test in own JVM then you need 1) Run JVM with profiler agent, i.e. use -agentpath option (the details is here <http://www.yourkit.com/docs/java/help/agent.jsp> ). 2) Specify what you are profiling on JVM startup (agent option "sampling", "tracing", etc) 3) Capture snapshot file on JVM exit ("onexit" agent option). Full list of options <http://www.yourkit.com/docs/java/help/startup_options.jsp> If you run all tests inside single JVM you can use profiler API <http://www.yourkit.com/docs/java/help/api.jsp> to start profling before test starts and capture snapshot after test finishes. You need to use com.yourkit.api.Controller class.
69,015
I started reading Hartshorne. Already in the first exercises I stumble across problems. Basically excerise 1.1 ask to prove that $k[x,y]/(y-x^2)$ is isomorphic to a polynomial ring in one variable. Well ok, so I tried the following, define $k[x,y]\to k[t]$ by $x \mapsto t$ and $y \mapsto t^2$. This is obviously a homomorphism and also $y-x^2$ is in the kernel. My problem was to show that the kernel is nothing more than $(y-x^2)$ though this seems kind of clear but I had some trouble proving it rigorously. I did the following Let $\sum\_{i,j} a\_{i,j}x^iy^j$ be in the kernel. Then the image is $\sum\_{i,j} a\_{i,j}t^it^{2j}=0$. First note that $\sum\_{i,j} a\_{i,j}x^ix^{2j}$ is also in the kernel, since it has the same image as $\sum\_{i,j} a\_{i,j}x^iy^j$. But we also see that $\sum\_{i,j} a\_{i,j}x^ix^{2j}$ is actually zero, since it is the same as $\sum\_{i,j} a\_{i,j}t^it^{2j}=0$ only with variables renamed. Thus $$\sum\_{i,j} a\_{i,j}x^iy^j=\sum\_{i,j} a\_{i,j}x^iy^j-\sum\_{i,j} a\_{i,j}x^ix^{2j}= \sum\_{i,j} a\_{i,j}x^i(y^j-x^{2j})$$, and it is well known that $a-b$ divides $a^j-b^j$. Thus the sum is divisble by $y-x^2$ and we are done. Pretty complicated proof for something that seems almost obvious. So my problem comes when doing exercise 1.2 I have to show that $k[x,y,z]/(x^2-y,x^3-z)$ is isomorphic to a polynomial ring in one variable. So again I define a homomorphism $k[x,y,z]\to k[t]$ by $x \mapsto t$, $y \mapsto t^2$ and $z\mapsto t^3$. The ideal $(x^2-y,x^3-z)$ is obviously contained in the kernel. But how do I show that it is all of that. Taking the same approach as above seems to lead to an even more complicated proof of an "obvious fact". So how can I prove 1.1 in a nicer technique that also applies to 1.2
2011/10/01
[ "https://math.stackexchange.com/questions/69015", "https://math.stackexchange.com", "https://math.stackexchange.com/users/11075/" ]
Here's another approach. Let's reconsider the first exercise. Let $\phi:k[x,y] \rightarrow k[t]$ be the the map given by $g(x,y) \mapsto g(t,t^2).$ Then $\phi$ is an epimorphism which contains in it's kernel the polynomial $y -x^2.$ We wish to show $\ker \phi = (y - x^2).$ First note as the image of $\phi$ is an integral domain, the kernal of $\phi$ is prime. Furthermore, the $\dim k[t] = 1$ and $\dim k[x,y] =2.$ Therefore, it must be the case that $ht(\ker \phi) = 1.$ We show $(y -x^2)$ is also a prime of height $1.$ Observe that the polynomial $x^2 - y \in k[y][x]$ satisfies eisenstein's criterion at the prime $(y).$ Hence, $x^2 - y$ is irreducible in $k[y,x].$ As $k[y,x]$ is a UFD, it follows $x^2 - y$ is prime. Hence, $(x^2 - y)$ is a prime of height $1.$ Given the containment $(y^2 - x) \subset \ker \phi,$ it must be the case $(y^2 -x) = \ker \phi.$ For the second exercise, one can use this same argument to show $k[x,y,z]/(x^3 - z) \cong k[x,y].$ And so, $k[x,y,z]/(x^3 - z, x^2 - y) \cong k[x,y]/(x^2 - y) \cong k[x].$
Following Gooz and Dylon Moreland's comment I came up with a proof, that is not as elegant as jspecter's but more elementary. I use the following fact from Lang chapter 4 theorem 1.1.: Let $f(x),g(x) \in R[x]$ and suppose that the leading term of $g(x)$ is invertible in $R$. Then $f(x)=g(x)d(x)+r(x)$ where the degree of $r(x)$ is smaller than that of $g(x)$. I will directly consider exercise 2 and let $f(x,y,z)$ be a polynomial the kernel of $\phi$, where $\phi$ is the homomorphism $k[x,y,z]\to k[t]$ given by $x \mapsto t$, $y \mapsto t^2$ and $z\mapsto t^3$. We wish to show that $(x^2-y,x^3-z)$ is the kernel. Consider $f(x,y,z)$ as a polynomial in $k[x,y][z]$. Then the leading term in $x^3-z$ (in $z$) is invertible in $k[x,y]$, so we write $f(x,y,z) = (x^3-z)d(x,y,z)+r(x,y,z)$. Then either $r(x,y,z)=0$ and we are done, or it has degree less than $(x^3-z)$ has, so $r(x,y,z)$ is in fact a polynomial only in $y$ and $x$. We again apply the result from above and write $r(x,y)=(x^2-y)d'(x,y)+r'(x,y)$. And we are done if $r'(x,y)=0$. Otherwise with the same reason as before $r'$ is polynomial only in $x$. So now we have $$ f(x,y,z) = (x^3-z)d(x,y,z) + (x^2-y)d'(x,y) +r'(x).$$ If we now apply $\phi$ we see that $0=r'(t)$ and this is only possible if $r'=0$, so we have $$ f(x,y,z) = (x^3-z)d(x,y,z) + (x^2-y)d'(x,y) \in (x^2-y,x^3-z). $$
69,015
I started reading Hartshorne. Already in the first exercises I stumble across problems. Basically excerise 1.1 ask to prove that $k[x,y]/(y-x^2)$ is isomorphic to a polynomial ring in one variable. Well ok, so I tried the following, define $k[x,y]\to k[t]$ by $x \mapsto t$ and $y \mapsto t^2$. This is obviously a homomorphism and also $y-x^2$ is in the kernel. My problem was to show that the kernel is nothing more than $(y-x^2)$ though this seems kind of clear but I had some trouble proving it rigorously. I did the following Let $\sum\_{i,j} a\_{i,j}x^iy^j$ be in the kernel. Then the image is $\sum\_{i,j} a\_{i,j}t^it^{2j}=0$. First note that $\sum\_{i,j} a\_{i,j}x^ix^{2j}$ is also in the kernel, since it has the same image as $\sum\_{i,j} a\_{i,j}x^iy^j$. But we also see that $\sum\_{i,j} a\_{i,j}x^ix^{2j}$ is actually zero, since it is the same as $\sum\_{i,j} a\_{i,j}t^it^{2j}=0$ only with variables renamed. Thus $$\sum\_{i,j} a\_{i,j}x^iy^j=\sum\_{i,j} a\_{i,j}x^iy^j-\sum\_{i,j} a\_{i,j}x^ix^{2j}= \sum\_{i,j} a\_{i,j}x^i(y^j-x^{2j})$$, and it is well known that $a-b$ divides $a^j-b^j$. Thus the sum is divisble by $y-x^2$ and we are done. Pretty complicated proof for something that seems almost obvious. So my problem comes when doing exercise 1.2 I have to show that $k[x,y,z]/(x^2-y,x^3-z)$ is isomorphic to a polynomial ring in one variable. So again I define a homomorphism $k[x,y,z]\to k[t]$ by $x \mapsto t$, $y \mapsto t^2$ and $z\mapsto t^3$. The ideal $(x^2-y,x^3-z)$ is obviously contained in the kernel. But how do I show that it is all of that. Taking the same approach as above seems to lead to an even more complicated proof of an "obvious fact". So how can I prove 1.1 in a nicer technique that also applies to 1.2
2011/10/01
[ "https://math.stackexchange.com/questions/69015", "https://math.stackexchange.com", "https://math.stackexchange.com/users/11075/" ]
Here's another approach. Let's reconsider the first exercise. Let $\phi:k[x,y] \rightarrow k[t]$ be the the map given by $g(x,y) \mapsto g(t,t^2).$ Then $\phi$ is an epimorphism which contains in it's kernel the polynomial $y -x^2.$ We wish to show $\ker \phi = (y - x^2).$ First note as the image of $\phi$ is an integral domain, the kernal of $\phi$ is prime. Furthermore, the $\dim k[t] = 1$ and $\dim k[x,y] =2.$ Therefore, it must be the case that $ht(\ker \phi) = 1.$ We show $(y -x^2)$ is also a prime of height $1.$ Observe that the polynomial $x^2 - y \in k[y][x]$ satisfies eisenstein's criterion at the prime $(y).$ Hence, $x^2 - y$ is irreducible in $k[y,x].$ As $k[y,x]$ is a UFD, it follows $x^2 - y$ is prime. Hence, $(x^2 - y)$ is a prime of height $1.$ Given the containment $(y^2 - x) \subset \ker \phi,$ it must be the case $(y^2 -x) = \ker \phi.$ For the second exercise, one can use this same argument to show $k[x,y,z]/(x^3 - z) \cong k[x,y].$ And so, $k[x,y,z]/(x^3 - z, x^2 - y) \cong k[x,y]/(x^2 - y) \cong k[x].$
At the risk of stating the obvious, rather than computing the kernel of your homomorphism, you could just write down its inverse: $t \mapsto x$. The argument then boils down to showing that $$f(x,y,z) \equiv f(x, x^2, x^3) \mod{\left\langle y - x^2, z - x^3 \right\rangle}$$ which is true because equivalence modulo an ideal is a congruence relation. e.g. so we can use $y \equiv x^2$ to make a substitution.
69,015
I started reading Hartshorne. Already in the first exercises I stumble across problems. Basically excerise 1.1 ask to prove that $k[x,y]/(y-x^2)$ is isomorphic to a polynomial ring in one variable. Well ok, so I tried the following, define $k[x,y]\to k[t]$ by $x \mapsto t$ and $y \mapsto t^2$. This is obviously a homomorphism and also $y-x^2$ is in the kernel. My problem was to show that the kernel is nothing more than $(y-x^2)$ though this seems kind of clear but I had some trouble proving it rigorously. I did the following Let $\sum\_{i,j} a\_{i,j}x^iy^j$ be in the kernel. Then the image is $\sum\_{i,j} a\_{i,j}t^it^{2j}=0$. First note that $\sum\_{i,j} a\_{i,j}x^ix^{2j}$ is also in the kernel, since it has the same image as $\sum\_{i,j} a\_{i,j}x^iy^j$. But we also see that $\sum\_{i,j} a\_{i,j}x^ix^{2j}$ is actually zero, since it is the same as $\sum\_{i,j} a\_{i,j}t^it^{2j}=0$ only with variables renamed. Thus $$\sum\_{i,j} a\_{i,j}x^iy^j=\sum\_{i,j} a\_{i,j}x^iy^j-\sum\_{i,j} a\_{i,j}x^ix^{2j}= \sum\_{i,j} a\_{i,j}x^i(y^j-x^{2j})$$, and it is well known that $a-b$ divides $a^j-b^j$. Thus the sum is divisble by $y-x^2$ and we are done. Pretty complicated proof for something that seems almost obvious. So my problem comes when doing exercise 1.2 I have to show that $k[x,y,z]/(x^2-y,x^3-z)$ is isomorphic to a polynomial ring in one variable. So again I define a homomorphism $k[x,y,z]\to k[t]$ by $x \mapsto t$, $y \mapsto t^2$ and $z\mapsto t^3$. The ideal $(x^2-y,x^3-z)$ is obviously contained in the kernel. But how do I show that it is all of that. Taking the same approach as above seems to lead to an even more complicated proof of an "obvious fact". So how can I prove 1.1 in a nicer technique that also applies to 1.2
2011/10/01
[ "https://math.stackexchange.com/questions/69015", "https://math.stackexchange.com", "https://math.stackexchange.com/users/11075/" ]
Here's another approach. Let's reconsider the first exercise. Let $\phi:k[x,y] \rightarrow k[t]$ be the the map given by $g(x,y) \mapsto g(t,t^2).$ Then $\phi$ is an epimorphism which contains in it's kernel the polynomial $y -x^2.$ We wish to show $\ker \phi = (y - x^2).$ First note as the image of $\phi$ is an integral domain, the kernal of $\phi$ is prime. Furthermore, the $\dim k[t] = 1$ and $\dim k[x,y] =2.$ Therefore, it must be the case that $ht(\ker \phi) = 1.$ We show $(y -x^2)$ is also a prime of height $1.$ Observe that the polynomial $x^2 - y \in k[y][x]$ satisfies eisenstein's criterion at the prime $(y).$ Hence, $x^2 - y$ is irreducible in $k[y,x].$ As $k[y,x]$ is a UFD, it follows $x^2 - y$ is prime. Hence, $(x^2 - y)$ is a prime of height $1.$ Given the containment $(y^2 - x) \subset \ker \phi,$ it must be the case $(y^2 -x) = \ker \phi.$ For the second exercise, one can use this same argument to show $k[x,y,z]/(x^3 - z) \cong k[x,y].$ And so, $k[x,y,z]/(x^3 - z, x^2 - y) \cong k[x,y]/(x^2 - y) \cong k[x].$
Let me give a completely elementary argument. Let $A=k[X,Y]/(X^2-Y)$, and let $x$ and $y$ be the images of $X$ and $Y$ in $A$. There is a algebra map $k[X,Y]\to k[t]$ such that $X\mapsto t$ and $Y\mapsto t^2$; the element $X^2-Y$ is in its kernel, so the map descend to an algebra map $\alpha:A\to k[t]$ such that $\alpha(x)=t$ and $\alpha(y)=t^2$. Now obviously there is a map $\beta:k[t]\to A$ such that $\beta(t)=x$. The composition $\alpha\circ\beta$ is the identity of $k[t]$: since it is an algebra map, it is enough to compute its action on the generator $t$, and $\alpha(\beta(t))=\alpha(x)=t$. Similarly, $\beta\circ\alpha$ is the identity in $A$: $\beta(\alpha(x))=\beta(t)=x$ and $\beta(\alpha(y))=\beta(t^2)=x^2=y$. We conclude that $\alpha$ and $\beta$ are isomorphisms. The exact same argument deals with your other example.
7,505,663
Ok guys. This is a revision ``` class Node<E> { // (1) private E data; // Data (2) private Node<E> next; // Reference to next node (3) Node(E data, Node<E> next) { // (4) this.data = data; this.next = next; } public void setData(E e) {} // (5) public void xxxData(E e) {} // (6) public E getData(E e) {return null;} // (7) public static void main(String [] args) { Node<? extends Integer> n1 = new Node<Integer>(1,null); //8 Node<? super Integer> n2 = new Node<Integer>(1,null); //9 n1.setData(new Integer(1)); //10 compiler error n1.xxxData(new Integer(1)); //11 compiler error n2.setData(new Integer(1)); //12 ok } } ``` Here's a rewrite hopefully i can convey my confusion nicely. 1. n1 is upper bounded wildcard. So this wont allow adding of records. Clause 10 proves this. 2. clause 11 also proves that method names (in this case 'SET' to determine adding of records) not being used since xxxData method gives the same compiler error. 3. n2 is lower bounded wildcard. Since method names doesn't play a role here, how does compiler knows that setData method can be used on n2 (since n2 is a lower bounded wildcard and this wildcard allows for adding of records)? Basically what the difference on method setData on clause 10 and 12? Bear in mind nothing happens in those methods. It's empty or returning null.
2011/09/21
[ "https://Stackoverflow.com/questions/7505663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303250/" ]
If I understood your question properly, I guess it's because Integer is both super- and subtype to itself.
Java doesn't care about get/set in the method name; it's all based on method parameter types. Consider ``` interface G<T> T f1(); void f2(T t); void f3(); ``` Substitute T with different types, methods signatures are changed too; for example, `G<Int>` methods ``` Int f1(); void f2(Int t); void f3(); ``` So we can do the following ``` G<Int> o = ...; Int i = o.f1(); o.f2(i); o.f3(); ``` What happens with wildcards? Actually compiler can't directly reason about wildcards; they must be replaced with fixed albeit unknown types; this process is called "wildcard capture". For example, given a `G<? super Int>` type, compiler internally treats it as `G<W>`, where `W` is an unknown supertype of `Int`. `G<W>` has methods ``` W f1(); void f2(W t); void f3(); ``` So we can do ``` G<? super Int> o = ...; Object i = o.f1(); // f1() returns W, which is subtype of Object o.f2( new Int(42) ); // f2() accepts W; Int is a subtype of W, accepted. o.f3(); ``` Similarly ``` G<? extends Int> o = ...; // G<W>, where W is a subtype of Int Int i = o.f1(); // f1() returns W, which is subtype of Int o.f2( new Int(42) ); // error: f2() accepts W; Int is NOT a subtype of W o.f3(); ```