qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
28,295,013
I have a UIDate Picker embedded in a static TableViewCell and at the moment I disabled most of the code except the code responsible for the date picker. *I'm using the Date Picker as a Count Down Timer* So this is kind of all, except some usual outlets and vars: ``` override func viewDidLoad() { super.viewDidLoad() // tfName.delegate = self // tfDescription.delegate = self // datePicker.countDownDuration = 60 // pickerValueChanged(self) } @IBAction func pickerValueChanged(sender: AnyObject) { seconds = Int(datePicker.countDownDuration) hours = seconds / 3600 if hours == 0{ minutes = seconds / 60 } else{ minutes = seconds % 3600 / 60 } labelDuration.text = "\(hours) hours \(minutes) minutes" } ``` The first time I change the value of the Picker, the value changed function does not fire at all, but the spins after it does without failing. I tried to call it in `viewDidLoad`, with `pickerValueChanged(self)` and that works, but does not solve the problem. Also I commented out every line of code in the `pickerValueChanged` function and `viewDidLoad` but it still did not fire the first spin.. Thank you for your time! **Update: Added pictures** After the first spin, pickerValueChanged does not get called: ![First spin](https://i.stack.imgur.com/1Eytw.png) From the second spin and beyond, the event gets called and the label is updated: ![Second spin](https://i.stack.imgur.com/fcLYN.png) **Tried:** Executing: `datePicker.setDate(NSDate(), animated: true` in `viewDidLoad()` solves the problem that the event doesn't get called at the first spin, but this sets the initial state of the Date Picker to the current time. Since I'm using this control to set a duration to a event, I want to let it start at 0 hour and 1 minute. This can be done with `datePicker.countDownDuration = 60` but after this, the main problem gets back again. So a solution could be setting the DatePicker with a NSDate of 1 minute, but how to do this? **Solution:** ``` var dateComp : NSDateComponents = NSDateComponents() dateComp.hour = 0 dateComp.minute = 1 dateComp.timeZone = NSTimeZone.systemTimeZone() var calendar : NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)! var date : NSDate = calendar.dateFromComponents(dateComp)! datePicker.setDate(date, animated: true) ```
2015/02/03
[ "https://Stackoverflow.com/questions/28295013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4069967/" ]
Time ago I found another problem that somehow resembles this one. It was about presenting a view controller from within the `tableView:didSelectRowAtIndexPath:` and the problem was that it was taking lots of time for the new controller to actually show up. One of the workarounds turned out to be using `dispatch_async` on the main queue. The same worked for me in this case. In my `viewDidLoad`, I asynchronously dispatched the picker setup code on the main queue and, in my case, it started to respond to the `valueChanged` event even on the first pick: ``` DispatchQueue.main.async { self.pickerView.datePickerMode = .countDownTimer self.pickerView.minuteInterval = 5 self.pickerView.countDownDuration = 15 } ```
Actually, all you need is to **not** set `datePicker.countDownDuration` in `viewDidLoad` but add it to `viewDidAppear`, or later.
28,295,013
I have a UIDate Picker embedded in a static TableViewCell and at the moment I disabled most of the code except the code responsible for the date picker. *I'm using the Date Picker as a Count Down Timer* So this is kind of all, except some usual outlets and vars: ``` override func viewDidLoad() { super.viewDidLoad() // tfName.delegate = self // tfDescription.delegate = self // datePicker.countDownDuration = 60 // pickerValueChanged(self) } @IBAction func pickerValueChanged(sender: AnyObject) { seconds = Int(datePicker.countDownDuration) hours = seconds / 3600 if hours == 0{ minutes = seconds / 60 } else{ minutes = seconds % 3600 / 60 } labelDuration.text = "\(hours) hours \(minutes) minutes" } ``` The first time I change the value of the Picker, the value changed function does not fire at all, but the spins after it does without failing. I tried to call it in `viewDidLoad`, with `pickerValueChanged(self)` and that works, but does not solve the problem. Also I commented out every line of code in the `pickerValueChanged` function and `viewDidLoad` but it still did not fire the first spin.. Thank you for your time! **Update: Added pictures** After the first spin, pickerValueChanged does not get called: ![First spin](https://i.stack.imgur.com/1Eytw.png) From the second spin and beyond, the event gets called and the label is updated: ![Second spin](https://i.stack.imgur.com/fcLYN.png) **Tried:** Executing: `datePicker.setDate(NSDate(), animated: true` in `viewDidLoad()` solves the problem that the event doesn't get called at the first spin, but this sets the initial state of the Date Picker to the current time. Since I'm using this control to set a duration to a event, I want to let it start at 0 hour and 1 minute. This can be done with `datePicker.countDownDuration = 60` but after this, the main problem gets back again. So a solution could be setting the DatePicker with a NSDate of 1 minute, but how to do this? **Solution:** ``` var dateComp : NSDateComponents = NSDateComponents() dateComp.hour = 0 dateComp.minute = 1 dateComp.timeZone = NSTimeZone.systemTimeZone() var calendar : NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)! var date : NSDate = calendar.dateFromComponents(dateComp)! datePicker.setDate(date, animated: true) ```
2015/02/03
[ "https://Stackoverflow.com/questions/28295013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4069967/" ]
I think you should try implement this delegate instead ``` - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component ```
I don't know if I got your problem, but Date picker works using the target-action pattern and it triggers this mechanism when you change a value. So if the problem is the very first value shown, you should initialize your variable taking it as the "default" value.
28,295,013
I have a UIDate Picker embedded in a static TableViewCell and at the moment I disabled most of the code except the code responsible for the date picker. *I'm using the Date Picker as a Count Down Timer* So this is kind of all, except some usual outlets and vars: ``` override func viewDidLoad() { super.viewDidLoad() // tfName.delegate = self // tfDescription.delegate = self // datePicker.countDownDuration = 60 // pickerValueChanged(self) } @IBAction func pickerValueChanged(sender: AnyObject) { seconds = Int(datePicker.countDownDuration) hours = seconds / 3600 if hours == 0{ minutes = seconds / 60 } else{ minutes = seconds % 3600 / 60 } labelDuration.text = "\(hours) hours \(minutes) minutes" } ``` The first time I change the value of the Picker, the value changed function does not fire at all, but the spins after it does without failing. I tried to call it in `viewDidLoad`, with `pickerValueChanged(self)` and that works, but does not solve the problem. Also I commented out every line of code in the `pickerValueChanged` function and `viewDidLoad` but it still did not fire the first spin.. Thank you for your time! **Update: Added pictures** After the first spin, pickerValueChanged does not get called: ![First spin](https://i.stack.imgur.com/1Eytw.png) From the second spin and beyond, the event gets called and the label is updated: ![Second spin](https://i.stack.imgur.com/fcLYN.png) **Tried:** Executing: `datePicker.setDate(NSDate(), animated: true` in `viewDidLoad()` solves the problem that the event doesn't get called at the first spin, but this sets the initial state of the Date Picker to the current time. Since I'm using this control to set a duration to a event, I want to let it start at 0 hour and 1 minute. This can be done with `datePicker.countDownDuration = 60` but after this, the main problem gets back again. So a solution could be setting the DatePicker with a NSDate of 1 minute, but how to do this? **Solution:** ``` var dateComp : NSDateComponents = NSDateComponents() dateComp.hour = 0 dateComp.minute = 1 dateComp.timeZone = NSTimeZone.systemTimeZone() var calendar : NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)! var date : NSDate = calendar.dateFromComponents(dateComp)! datePicker.setDate(date, animated: true) ```
2015/02/03
[ "https://Stackoverflow.com/questions/28295013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4069967/" ]
I came up the following solution to initialize the datePicker component (in countdown timer mode) with 0 hours and 1 minute and it responds directly at the first spin. Since this appears to be a bug and is very frustrating if you want a textlabel to update its value when the datePicker is changed and it does not at the first go: ``` var dateComp : NSDateComponents = NSDateComponents() dateComp.hour = 0 dateComp.minute = 1 dateComp.timeZone = NSTimeZone.systemTimeZone() var calendar : NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)! var date : NSDate = calendar.dateFromComponents(dateComp)! datePicker.setDate(date, animated: true) ``` The timeZone component is not really needed for this to work for my implementation.
Similar problem as above, I used ``` DispatchQueue.main.asyncAfter(deadline: .now()) { self.datePicker.countDownDuration = 60 } ``` to put it on the next runloop. Seems a viable workaround.
28,295,013
I have a UIDate Picker embedded in a static TableViewCell and at the moment I disabled most of the code except the code responsible for the date picker. *I'm using the Date Picker as a Count Down Timer* So this is kind of all, except some usual outlets and vars: ``` override func viewDidLoad() { super.viewDidLoad() // tfName.delegate = self // tfDescription.delegate = self // datePicker.countDownDuration = 60 // pickerValueChanged(self) } @IBAction func pickerValueChanged(sender: AnyObject) { seconds = Int(datePicker.countDownDuration) hours = seconds / 3600 if hours == 0{ minutes = seconds / 60 } else{ minutes = seconds % 3600 / 60 } labelDuration.text = "\(hours) hours \(minutes) minutes" } ``` The first time I change the value of the Picker, the value changed function does not fire at all, but the spins after it does without failing. I tried to call it in `viewDidLoad`, with `pickerValueChanged(self)` and that works, but does not solve the problem. Also I commented out every line of code in the `pickerValueChanged` function and `viewDidLoad` but it still did not fire the first spin.. Thank you for your time! **Update: Added pictures** After the first spin, pickerValueChanged does not get called: ![First spin](https://i.stack.imgur.com/1Eytw.png) From the second spin and beyond, the event gets called and the label is updated: ![Second spin](https://i.stack.imgur.com/fcLYN.png) **Tried:** Executing: `datePicker.setDate(NSDate(), animated: true` in `viewDidLoad()` solves the problem that the event doesn't get called at the first spin, but this sets the initial state of the Date Picker to the current time. Since I'm using this control to set a duration to a event, I want to let it start at 0 hour and 1 minute. This can be done with `datePicker.countDownDuration = 60` but after this, the main problem gets back again. So a solution could be setting the DatePicker with a NSDate of 1 minute, but how to do this? **Solution:** ``` var dateComp : NSDateComponents = NSDateComponents() dateComp.hour = 0 dateComp.minute = 1 dateComp.timeZone = NSTimeZone.systemTimeZone() var calendar : NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)! var date : NSDate = calendar.dateFromComponents(dateComp)! datePicker.setDate(date, animated: true) ```
2015/02/03
[ "https://Stackoverflow.com/questions/28295013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4069967/" ]
It seems to be something to do with the animated parameter. You just need this line: ``` datePicker.setDate(date, animated: true) ```
I don't know if I got your problem, but Date picker works using the target-action pattern and it triggers this mechanism when you change a value. So if the problem is the very first value shown, you should initialize your variable taking it as the "default" value.
28,295,013
I have a UIDate Picker embedded in a static TableViewCell and at the moment I disabled most of the code except the code responsible for the date picker. *I'm using the Date Picker as a Count Down Timer* So this is kind of all, except some usual outlets and vars: ``` override func viewDidLoad() { super.viewDidLoad() // tfName.delegate = self // tfDescription.delegate = self // datePicker.countDownDuration = 60 // pickerValueChanged(self) } @IBAction func pickerValueChanged(sender: AnyObject) { seconds = Int(datePicker.countDownDuration) hours = seconds / 3600 if hours == 0{ minutes = seconds / 60 } else{ minutes = seconds % 3600 / 60 } labelDuration.text = "\(hours) hours \(minutes) minutes" } ``` The first time I change the value of the Picker, the value changed function does not fire at all, but the spins after it does without failing. I tried to call it in `viewDidLoad`, with `pickerValueChanged(self)` and that works, but does not solve the problem. Also I commented out every line of code in the `pickerValueChanged` function and `viewDidLoad` but it still did not fire the first spin.. Thank you for your time! **Update: Added pictures** After the first spin, pickerValueChanged does not get called: ![First spin](https://i.stack.imgur.com/1Eytw.png) From the second spin and beyond, the event gets called and the label is updated: ![Second spin](https://i.stack.imgur.com/fcLYN.png) **Tried:** Executing: `datePicker.setDate(NSDate(), animated: true` in `viewDidLoad()` solves the problem that the event doesn't get called at the first spin, but this sets the initial state of the Date Picker to the current time. Since I'm using this control to set a duration to a event, I want to let it start at 0 hour and 1 minute. This can be done with `datePicker.countDownDuration = 60` but after this, the main problem gets back again. So a solution could be setting the DatePicker with a NSDate of 1 minute, but how to do this? **Solution:** ``` var dateComp : NSDateComponents = NSDateComponents() dateComp.hour = 0 dateComp.minute = 1 dateComp.timeZone = NSTimeZone.systemTimeZone() var calendar : NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)! var date : NSDate = calendar.dateFromComponents(dateComp)! datePicker.setDate(date, animated: true) ```
2015/02/03
[ "https://Stackoverflow.com/questions/28295013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4069967/" ]
Here's @Henk-Martijn's solution **updated & simplified for Swift 3**: ``` let calendar = Calendar(identifier: .gregorian) let date = DateComponents(calendar: calendar, hour: 1, minute: 30).date! datePicker.setDate(date, animated: true) ``` Use the above code instead of something like: ``` datePicker.countDownDuration = 5_400 ```
None of these solutions work, when you use the DatePicker as an inputView for a textfield. I have attached my code below. I am still searching for a good solution for this, because none of the above fixes the problem in my scenario. ``` self.durationDatePicker.datePickerMode = .countDownTimer self.durationDatePicker.preferredDatePickerStyle = .wheels self.durationDatePicker.minuteInterval = 5 self.durationDatePicker.addTarget(self, action: #selector(CreateEventDetailsViewController.datePickerValueChanged(picker:)), for: .valueChanged) self.durationTextField.inputView = self.durationDatePicker ```
261,130
I have a folder of 28 mxds that I'm trying to export all of them into 28 JPEGs. I'm having difficulty with the script and I'm hoping someone can help figure where I went wrong. Basically, I want to be export to run automatically, so that I don't have to open each mxd to export them into JPEGs. ``` import arcpy, os >>> folderPath = r"H:\Users\2015\Map15-0001\Zone Maps - for External Website" >>> for filename in os.listdir(folderPath): ... fullpath = os.path.join(folderPath, filename) ... if os.path.isfile(fullpath): ... basename, extension = os.path.splitext(fullpath) ... if extension.lower() == ".mxd": ... mxd = arcpy.mapping.MapDocument(fullpath) ... df = arcpy.mapping.ListDataFrames(mxd,"Layers")[0] ... arcpy.mapping.ExportToJPEG(mxd, r"H:\Users\2015\Map15-0001\Zone Maps - for External Website\New"+basename+".jpg", df,resolution = 1000) ``` This is the error that I'm getting: ``` Runtime error Traceback (most recent call last): File "<string>", line 8, in <module> File "c:\program files (x86)\arcgis\desktop10.3\arcpy\arcpy\utils.py", line 182, in fn_ return fn(*args, **kw) File "c:\program files (x86)\arcgis\desktop10.3\arcpy\arcpy\mapping.py", line 1026, in ExportToJPEG layout.exportToJPEG(*args) AttributeError: DataFrameObject: Error in parsing arguments for ExportToJPEG ``` The mxds all have Data Driven Pages running on them. I was able to previously take all of the mxds and export separate PDFs. I'm running ArcMap 10.3.
2017/11/08
[ "https://gis.stackexchange.com/questions/261130", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/108747/" ]
Based upon your code and subsequent comments it sounds like you want to export the layout rather than the dataframe? If so simply replace the `df` object with the string "PAGE\_LAYOUT" in [ExportToJPEG()](http://desktop.arcgis.com/en/arcmap/10.3/analyze/arcpy-mapping/exporttojpeg.htm#S2_GUID-A061A555-079F-4EAC-AF40-BA31A89C2E23).
I think the concatenation is messing up in your export to jpeg call. Try using formatting instead of concatenation: ``` arcpy.mapping.ExportToJPEG(mxd, "H:\\Users\\2015\\Map15-0001\\Zone Maps - for External Website\\New{0}.jpg".format(basename), df,resolution = 1000) ``` <https://docs.python.org/3.4/library/string.html#string-formatting>
54,115,476
I'm trying to display nodes that have a font icon in the center of the node using 'content' and a text label underneath. My styling is currently: ``` { 'selector': 'node[icon]', 'style': { 'content': 'data(icon)', 'font-family': 'Material Icons', 'text-valign': 'center', 'text-halign': 'center' } }, { 'selector': 'node[label]', 'style': { 'label': 'data(label)', 'text-valign': 'bottom', 'text-halign': 'center' } } ``` However, this doesn't work as i assume both of the styles is used on one element (the node). There are a few solutions I've considered, such as: * Putting the label on a parent node * Use Popper.js or similar to show the label * Use a multi-lined label The first 2 seem 'hacky', and the third could cause a lot of alignment problems. Is there a better solution to this?
2019/01/09
[ "https://Stackoverflow.com/questions/54115476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2151652/" ]
I've found a solution using the extension: <https://github.com/kaluginserg/cytoscape-node-html-label>. You can create custom HTML labels for nodes which do not interfere with the base Cytoscape labels. An example of using the Material Icons: ``` // Initialise the HTML Label this.cy.nodeHtmlLabel([{ query: '.nodeIcon', halign: 'center', valign: 'center', halignBox: 'center', valignBox: 'center', tpl: (data) => { return '<i class="material-icons">' + data.icon + '</i>'; } }]); // Add the HTML Label to the node: const node = { group: 'nodes', data: { id: data.id, label: data.label, icon: data.icon }, classes: 'nodeIcon' // <---- Add the HTML Label class here }; ``` With the method you can dynamically create nodes with font icons without the need to download a load of images. [![Node Icon](https://i.stack.imgur.com/9gjR6.png)](https://i.stack.imgur.com/9gjR6.png) You can even add CSS styling to change the colour of the icon: [![enter image description here](https://i.stack.imgur.com/F9jZ6.png)](https://i.stack.imgur.com/F9jZ6.png)
If you want an icon as the nodes body, you can use it as the background image and define the label like you do: ```js var cy = window.cy = cytoscape({ container: document.getElementById('cy'), boxSelectionEnabled: false, autounselectify: true, style: [{ selector: 'node', css: { 'label': 'data(id)', 'text-valign': 'bottom', 'text-halign': 'center', 'height': '60px', 'width': '60px', 'border-color': 'black', 'border-opacity': '1', 'background-image': 'https://farm8.staticflickr.com/7272/7633179468_3e19e45a0c_b.jpg', "text-background-opacity": 1, "text-background-color": "lightgray" } }, { selector: ':selected', css: { 'background-color': 'black', 'line-color': 'black', 'target-arrow-color': 'black', 'source-arrow-color': 'black' } } ], elements: { nodes: [{ data: { id: 'n0' } }, { data: { id: 'n1' } }, { data: { id: 'n2' } }, { data: { id: 'n3' } }, { data: { id: 'n4' } }, { data: { id: 'n5' } }, { data: { id: 'n6' } }, { data: { id: 'n7' } }, { data: { id: 'n8' } }, { data: { id: 'n9' } }, { data: { id: 'n10' } }, { data: { id: 'n11' } }, { data: { id: 'n12' } }, { data: { id: 'n13' } }, { data: { id: 'n14' } }, { data: { id: 'n15' } }, { data: { id: 'n16' } } ], edges: [{ data: { source: 'n0', target: 'n1' } }, { data: { source: 'n1', target: 'n2' } }, { data: { source: 'n1', target: 'n3' } }, { data: { source: 'n2', target: 'n7' } }, { data: { source: 'n2', target: 'n11' } }, { data: { source: 'n2', target: 'n16' } }, { data: { source: 'n3', target: 'n4' } }, { data: { source: 'n3', target: 'n16' } }, { data: { source: 'n4', target: 'n5' } }, { data: { source: 'n4', target: 'n6' } }, { data: { source: 'n6', target: 'n8' } }, { data: { source: 'n8', target: 'n9' } }, { data: { source: 'n8', target: 'n10' } }, { data: { source: 'n11', target: 'n12' } }, { data: { source: 'n12', target: 'n13' } }, { data: { source: 'n13', target: 'n14' } }, { data: { source: 'n13', target: 'n15' } }, ] }, layout: { name: 'dagre', padding: 5 } }); ``` ```css body { font: 14px helvetica neue, helvetica, arial, sans-serif; } #cy { height: 100%; width: 75%; position: absolute; left: 0; top: 0; float: left; } ``` ```html <html> <head> <meta charset=utf-8 /> <meta name="viewport" content="user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, minimal-ui"> <script src="https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.2.17/cytoscape.min.js"></script> <script src="https://unpkg.com/jquery@3.3.1/dist/jquery.js"></script> <script src="https://unpkg.com/dagre@0.7.4/dist/dagre.js"></script> <script src="https://cdn.rawgit.com/cytoscape/cytoscape.js-dagre/1.5.0/cytoscape-dagre.js"></script> </head> <body> <div id="cy"></div> </body> </html> ```
52,544,754
I have problem during import tensorflow. Here is my recent stack trace: ``` (tensorflow) C:\Users\Vaidik>python Python 3.5.5 |Anaconda, Inc.| (default, Apr 7 2018, 04:52:34) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import tensorflow as tf Traceback (most recent call last): File "F:\Software\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module> from tensorflow.python.pywrap_tensorflow_internal import * File "F:\Software\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module> _pywrap_tensorflow_internal = swig_import_helper() File "F:\Software\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) File "F:\Software\Anaconda\envs\tensorflow\lib\imp.py", line 243, in load_module return load_dynamic(name, filename, file) File "F:\Software\Anaconda\envs\tensorflow\lib\imp.py", line 343, in load_dynamic return _load(spec) ImportError: DLL load failed: The specified module could not be found. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "F:\Software\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\__init__.py", line 22, in <module> from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import File "F:\Software\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\__init__.py", line 49, in <module> from tensorflow.python import pywrap_tensorflow File "F:\Software\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in <module> raise ImportError(msg) ImportError: Traceback (most recent call last): File "F:\Software\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module> from tensorflow.python.pywrap_tensorflow_internal import * File "F:\Software\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module> _pywrap_tensorflow_internal = swig_import_helper() File "F:\Software\Anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) File "F:\Software\Anaconda\envs\tensorflow\lib\imp.py", line 243, in load_module return load_dynamic(name, filename, file) File "F:\Software\Anaconda\envs\tensorflow\lib\imp.py", line 343, in load_dynamic return _load(spec) ImportError: DLL load failed: The specified module could not be found. Failed to load the native TensorFlow runtime. See https://www.tensorflow.org/install/install_sources#common_installation_problems for some common reasons and solutions. Include the entire stack trace above this error message when asking for help. ```
2018/09/27
[ "https://Stackoverflow.com/questions/52544754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8778978/" ]
Please try to create a conda environment for the required python version and install tensorflow. Follow the below steps: 1. conda create -n tf35 -c intel python=3.5 pip numpy (tf35 is the environment name) 2. activate tf35 3. conda install -c anaconda tensorflow [![enter image description here](https://i.stack.imgur.com/8OohV.png)](https://i.stack.imgur.com/8OohV.png) Thanks
Uninstall tf using ``` conda uninstall tensorflow ``` then install it again ``` python3 -m pip install tensorflow==1.8.0 --user ```
559,795
I want to set up a template document along the lines of this: > > > ``` > ================ > Doc content > > ---------------- > Merge Field1 > Merge Field2 > Merge Field3 > ---------------- > > More doc content > ================ > > ``` > > I then want to be able to open the document, load a DataTable from the database in C# and merge the fields in the template section in the middle. The DataTable will have multiple records so it needs to merge and output multiple templates to create one big document. I can't find any examples of doing this.
2009/02/18
[ "https://Stackoverflow.com/questions/559795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27294/" ]
If you are looking for information about programmatically replacing the Mail Merge fields using C# code then [this article](http://www.c-sharpcorner.com/UploadFile/amrish_deep/WordAutomation05102007223934PM/WordAutomation.aspx) might help.
I've used [this library](http://invoke.co.nz/products/help/docx.aspx) to generate MS Word 2007 documents. Hope it'll help you. P.S. Previously this library was completely free but now they've added a commercial version too. But free version contains all necessary features for you.
559,795
I want to set up a template document along the lines of this: > > > ``` > ================ > Doc content > > ---------------- > Merge Field1 > Merge Field2 > Merge Field3 > ---------------- > > More doc content > ================ > > ``` > > I then want to be able to open the document, load a DataTable from the database in C# and merge the fields in the template section in the middle. The DataTable will have multiple records so it needs to merge and output multiple templates to create one big document. I can't find any examples of doing this.
2009/02/18
[ "https://Stackoverflow.com/questions/559795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27294/" ]
I had a job doing this stuff a while back. We were using Word Automation but it's painful (because Word will do crazy things like pop up a modal dialog which will break your code). We moved to using the Aspose library. I found it fairly reasonable and quite fully featured in this area (there is good support for merge fields). It is, however, commercial. (I have no ties to the company - I've just used their software) Edit: If you only need Word 2007 support, don't bother with these guys; there are plenty of free libraries. Support for older versions is harder to find though
I've used [this library](http://invoke.co.nz/products/help/docx.aspx) to generate MS Word 2007 documents. Hope it'll help you. P.S. Previously this library was completely free but now they've added a commercial version too. But free version contains all necessary features for you.
559,795
I want to set up a template document along the lines of this: > > > ``` > ================ > Doc content > > ---------------- > Merge Field1 > Merge Field2 > Merge Field3 > ---------------- > > More doc content > ================ > > ``` > > I then want to be able to open the document, load a DataTable from the database in C# and merge the fields in the template section in the middle. The DataTable will have multiple records so it needs to merge and output multiple templates to create one big document. I can't find any examples of doing this.
2009/02/18
[ "https://Stackoverflow.com/questions/559795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27294/" ]
I had a job doing this stuff a while back. We were using Word Automation but it's painful (because Word will do crazy things like pop up a modal dialog which will break your code). We moved to using the Aspose library. I found it fairly reasonable and quite fully featured in this area (there is good support for merge fields). It is, however, commercial. (I have no ties to the company - I've just used their software) Edit: If you only need Word 2007 support, don't bother with these guys; there are plenty of free libraries. Support for older versions is harder to find though
If you are looking for information about programmatically replacing the Mail Merge fields using C# code then [this article](http://www.c-sharpcorner.com/UploadFile/amrish_deep/WordAutomation05102007223934PM/WordAutomation.aspx) might help.
55,580,150
I am trying to figure out how to write this function with the Eq function in Haskell. An easy function that I am trying to implement is: ``` f :: Eq a => [a] -> [[a]] ``` Where f will gather each repeated consecutive elements under separate sub-lists, For example: ``` f [3] = [[3]] f [1,1,1,3,2,2,1,1,1,1] = [[1,1,1],[3],[2,2],[1,1,1,1]] ``` I thought about this function: ``` f :: Eq a => [a] -> [[a]] f [] = [] f (x:[]) = [[x]] f (x:x':xs) = if x == x' then [[x, x']] ++ (f (xs)) else [[x]] ++ (bundler (xs)) ``` It seems to not work well since when it arrives to the last element, it wants to compare it to its consecutive, which clearly does not exist. Moreover, I feel like I do not use anything with the Eq => function. I would like to receive an answer that will show how to use Eq properly in my case. Thanks in advance.
2019/04/08
[ "https://Stackoverflow.com/questions/55580150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9733887/" ]
The presence of the `Eq` typeclass in your type is a red herring: it is not related to the error you report. The error you report happens because you have defined how the function should behave when the list is empty (`f [] =`) and when the list has at least two elements (`f (x:x':xs) =`), but not when the list has exactly one element. The solution will be to add a case that begins\* ``` f [x] = ???? ``` and decide how to deal with one-element lists. Or to find some other way to write the function that deals with all of its cases. --- \* Note that `f [x]` is the same thing as `f (x:[])`.
You can also use [`span`](http://hackage.haskell.org/package/base-4.12.0.0/docs/Data-List.html#v:span) and a recursive call to make it work: ``` f :: Eq a => [a] -> [[a]] f [] = [] f l@(x:xs) = grouped : f remainder where (grouped, remainder) = span (== x) l ``` Here you have the [live example](https://repl.it/repls/CheerfulStupidTrigger)
10,369,387
When a teamname is not in the database I want to enter it if not ignore it. But I do not get an error all I see is the echoed statement but it is not entered into the database. The database is MySQL and table name is 2012FallTeamstats I have a team\_id column which is autoincremented a win a loses and a percentages field. (4 total in table) ``` mysql_query("SELECT teamname FROM 2012FallTeamstats WHERE teamname = '$teamH'"); if (mysql_affected_rows() == 0) { mysql_query("INSERT INTO 2012FallTeamstats (teamname) VALUES ('$teamH')"); echo "New: <strong>".stripslashes($teamH)."</strong> (home team) inserted into the database.<br>"; } ```
2012/04/29
[ "https://Stackoverflow.com/questions/10369387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1066771/" ]
try mysql\_num\_rows() instead of mysql\_affected\_rows. code like this. ``` $result_team = mysql_query(.........); (your code) ``` then ``` if(mysql_num_rows($result_team) == 0) { //insert command } ```
What happens if you cut and paste the SQL that's printed out and enter into MySQL from the command line? I suspect that you might need to add the extra fields from the table into your SQL, but if you run the existing SQL, you'll see if there's an issue with the statement.
10,369,387
When a teamname is not in the database I want to enter it if not ignore it. But I do not get an error all I see is the echoed statement but it is not entered into the database. The database is MySQL and table name is 2012FallTeamstats I have a team\_id column which is autoincremented a win a loses and a percentages field. (4 total in table) ``` mysql_query("SELECT teamname FROM 2012FallTeamstats WHERE teamname = '$teamH'"); if (mysql_affected_rows() == 0) { mysql_query("INSERT INTO 2012FallTeamstats (teamname) VALUES ('$teamH')"); echo "New: <strong>".stripslashes($teamH)."</strong> (home team) inserted into the database.<br>"; } ```
2012/04/29
[ "https://Stackoverflow.com/questions/10369387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1066771/" ]
try mysql\_num\_rows() instead of mysql\_affected\_rows. code like this. ``` $result_team = mysql_query(.........); (your code) ``` then ``` if(mysql_num_rows($result_team) == 0) { //insert command } ```
Your not getting the result from the query amongst other things: **Notice:** `$result=` Plus `mysql_num_rows()` & `quoting column` & `or die(mysql_error());` ``` $result = mysql_query("SELECT `teamname` FROM `2012FallTeamstats` WHERE teamname = '$teamH'"); if (mysql_num_rows($result) == 0) { mysql_query("INSERT INTO `2012FallTeamstats` (teamname) VALUES ('$teamH')")or die(mysql_error()); echo "New: <strong>".stripslashes($teamH)."</strong> (home team) inserted into the database.<br>"; } ```
10,369,387
When a teamname is not in the database I want to enter it if not ignore it. But I do not get an error all I see is the echoed statement but it is not entered into the database. The database is MySQL and table name is 2012FallTeamstats I have a team\_id column which is autoincremented a win a loses and a percentages field. (4 total in table) ``` mysql_query("SELECT teamname FROM 2012FallTeamstats WHERE teamname = '$teamH'"); if (mysql_affected_rows() == 0) { mysql_query("INSERT INTO 2012FallTeamstats (teamname) VALUES ('$teamH')"); echo "New: <strong>".stripslashes($teamH)."</strong> (home team) inserted into the database.<br>"; } ```
2012/04/29
[ "https://Stackoverflow.com/questions/10369387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1066771/" ]
try mysql\_num\_rows() instead of mysql\_affected\_rows. code like this. ``` $result_team = mysql_query(.........); (your code) ``` then ``` if(mysql_num_rows($result_team) == 0) { //insert command } ```
Your second statement probably isn't being called as the mysql\_affected\_rows() doesn't give you the count from the select statement- that function is only for your CRUD operations. Try replacing this with mysql\_num\_rows()
60,492,122
When I add a floating Table of Contents to my `R-Markdown` document, it always is on the left side of the page (with the content to the right), like so: ``` --- title: "some title" author: "me" date: "3/2/2020" output: html_document: toc: TRUE toc_float: TRUE --- ``` [![Default placing of floating TOC](https://i.stack.imgur.com/azVaj.png)](https://i.stack.imgur.com/azVaj.png) --- However, I'd like to move the floating TOC to the right side of the page. How can I accomplish this? The image below is what I'd like: --- [![enter image description here](https://i.stack.imgur.com/sAZje.png)](https://i.stack.imgur.com/sAZje.png)
2020/03/02
[ "https://Stackoverflow.com/questions/60492122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5401784/" ]
Here is one simple method *based on the question*: ``` CREATE PROCEDURE [dbo].[GetLanePrediction] ( @onenumber int ) AS BEGIN DECLARE @TempZips TABLE (ID INT IDENTITY(1,1), Zip INT) INSERT INTO @TempZips (Zip) SELECT one_number + v.n FROM (VALUES (-2), (-1), (0), (1), (2)) v(n); END; ``` EDIT: You can also use a recursive CTE: ``` ;WITH n as ( SELECT -@posnegval as n UNION ALL SELECT n + 1 FROM n WHERE n < @posnegval ) INSERT INTO @TempZips (Zip) SELECT @onenumber + n.n FROM n -- WITH OPTION (maxrecursion 0); -- only needed if you'll ever have more than 100 numbers ```
Just another option using an ad-hoc tally table ``` Declare @I int =355 Declare @R int =2 Select ID = N ,Zip= -1+@I-@R+N From ( Select Top ((@R*2)+1) N=Row_Number() Over (Order By (Select NULL)) From master..spt_values n1 ) A ``` **Returns** ``` ID Zip 1 353 2 354 3 355 4 356 5 357 ```
59,965,605
```html <!DOCTYPE html> <html> <body> <div style="background-color: aqua;height:1500px;width:260px;overflow: hidden;"> some text </div> </body> </html> ``` My screen resolution is 1920 X 1200 (width X height) , I have div whose height is 1500 px. Obviously this will overflow the screen and browser adds vertical scroll by default. My requirement is make this vertical scroll disappear and anything that is overflown outside the window just clipped off. How to get this behavior with css styles? I tried overflow:hidden on div it didn't work for me ``` <!DOCTYPE html> <html> <body> <div style="background-color: aqua;height:1500px;width:260px;overflow: hidden;"> some text </div> </body> </html> ```
2020/01/29
[ "https://Stackoverflow.com/questions/59965605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11272449/" ]
Hope the below snippet could help you. ```css body{height:1200px; width:100%; overflow:hidden} ``` ```html <!DOCTYPE html> <html> <body> <div style="background-color: aqua;height:1500px;width:260px;"> some text </div> </body> </html> ```
You can prevent a page/object from overflowing by adding the overflow property. overflow | **y/x axis** overflow-y | **y axis** overflow-x | **x axis** followed up by hidden as a value hidden - The overflow is clipped, and the rest of the content will be invisible ``` body { overflow-y: hidden; } ```
45,094,790
I am trying to replace a sub-string in the errorString. i am using this code,which is not making any changes to errorString. am i following a wrong method? ``` string errorstring = "<p>&nbsp;&nbsp;&nbsp;Name:{StudentName}</p>"; errorstring.Replace("{StudentName}", "MyName"); ``` i want to replace {StudentName} in errorString with "MyName"
2017/07/14
[ "https://Stackoverflow.com/questions/45094790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6700352/" ]
Declare a new instance of that string: ``` string errorstring = "<p>&nbsp;&nbsp;&nbsp;Name:{StudentName}</p>"; errorstring = errorstring.Replace("{StudentName}", "MyName"); ``` That should work if you don't use StringBuilder.
Please follow the below steps. Step :- 1 ``` string errorstring = "<p>&nbsp;&nbsp;&nbsp;Name:{StudentName}</p>"; errorstring = errorstring.Replace("{StudentName}", "MyName"); ``` Step :- 2 ``` @Html.Raw(errorstring) ```
16,655
I was trying to host a zend-framework project on new host provider. After uploading everything and configuring the database connection I have encountered `Internal Server Error` message. My service provider told they don't installed zend-framework but I have integrated the framework as a library into the project. ![enter image description here](https://i.stack.imgur.com/AEAef.png) When i tested the server uploading `html` file it work fine. Since i don't have the Apache server accessing privilege, How can i fix that? **error log**: ``` #0 /home/myweb/public_html/library/Zend/Db/Adapter/Pdo/Mysql.php(96): Zend_Db_Adapter_Pdo_Abstract->_connect() #1 /home/myweb/public_html/library/Zend/Db/Adapter/Abstract.php(448): Zend_Db_Adapter_Pdo_Mysql->_connect() #2 /home/myweb/public_html/library/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('SET NAMES 'utf8...', Array) #3 /home/myweb/public_html/application/Bootstrap.php(144): Zend_Db_Adapter_Pdo_Abstract->query('SET NAMES 'utf8...') #4 /home/myweb/public_html/library/Zend/Application/Bootstrap/BootstrapAbstract.php(666): Bootstrap->_initDb() #5 /home/myweb/public_html/library/Zend/Application/Bootstrap/BootstrapAbstract.php(619): Zend_Application_Bootstrap_BootstrapAbstract->_executeResource('db') #6 /home/myweb/public_html/library/Zend/Application/Bootstrap/BootstrapAbstr in /home/myweb/public_html/library/Zend/Db/Adapter/Pdo/Abstract.php on line 112 [11-Jul-2011 07:35:51] PHP Warning: PHP Startup: Unable to load dynamic library '/usr/local/lib/php/extensions/no-debug-non-zts-20060613/pdo_mysql.so' - /usr/local/lib/php/extensions/no-debug-non-zts-20060613/pdo_mysql.so: undefined symbol: php_pdo_unregister_driver in Unknown on line 0 [11-Jul-2011 07:35:51] PHP Fatal error: Uncaught exception 'Zend_Db_Adapter_Exception' with message 'The mysql driver is not currently installed' in /home/myweb/public_html/library/Zend/Db/Adapter/Pdo/Abstract.php:112 Stack trace: ```
2011/07/11
[ "https://webmasters.stackexchange.com/questions/16655", "https://webmasters.stackexchange.com", "https://webmasters.stackexchange.com/users/5134/" ]
Your error log shows that the Zend framework can't find the PDO MySQL driver it needs to connect to the MySQL server. This could be for a couple of reasons: 1. It's possible your server is running an old version of PHP. (The PDO class is only included in PHP 5.1 or later.) Check what version you're running by creating a file called 'info.php' containing the following code, and opening that file in your browser: ``` <?php phpinfo(); ?> ``` Delete this file as soon as you've checked the PHP version so that others can't access it. If you're not using PHP 5.1, ask your hosting company to install it for you. If you are using PHP 5.1, read on. 2. Your hosting company doesn't have the PDO MySQL driver installed. You could contact them with the contents of your error log and ask them to install the driver, or use a different hosting company who includes the PDO MySQL driver (or, even better, one that specifically names the Zend framework in their list of supported modules).
From my reading of the error message: `Unable to load dynamic library '/usr/local/lib/php/extensions/no-debug-non-zts-20060613/pdo_mysql.so'` Looks like your server is missing some extensions. I suggest that you pay the extra for a Virtual Private Server where you will be able to install them.
3,523,409
I am using DOMDocument to manipulate / modify HTML before it gets output to the page. This is only a html fragment, not a complete page. My initial problem was that all french character got messed up, which I was able to correct after some trial-and-error. Now, it seems only one problem remains : ' character gets transformed into ? . The code : ``` <?php $dom = new DOMDocument('1.0','utf-8'); $dom->loadHTML(utf8_decode($row->text)); //Some pretty basic modification here, not even related to text //reinsert HTML, and make sure to remove DOCTYPE, html and body that get added auto. $row->text = utf8_encode(preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $dom->saveHTML()))); ?> ``` I know it's getting messy with the utf8 decode/encode, but this is the only way I could make it work so far. Here is a sample string : Input : Sans doute parce qu’il vient d’atteindre une date déterminante dans son spectaculaire cheminement Output : Sans doute parce qu?il vient d?atteindre une date déterminante dans son spectaculaire cheminement If I find any more details, I'll add them. Thank you for your time and support!
2010/08/19
[ "https://Stackoverflow.com/questions/3523409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/425422/" ]
Don't use `utf8_decode`. If your text is in UTF-8, pass it as such. Unfortunately, `DOMDocument` defaults to LATIN1 in case of HTML. It seems the behavior is this * If fetching a remote document, it should deduce the encoding from the headers * If the header wasn't sent or the file is local, look for the correspondent meta-equiv * Otherwise, default to LATIN1. Example of it working: ``` <?php $s = <<<HTML <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> Sans doute parce qu’il vient d’atteindre une date déterminante dans son spectaculaire cheminement </body> </html> HTML; libxml_use_internal_errors(true); $d = new domdocument; $d->loadHTML($s); echo $d->textContent; ``` And with XML (default is UTF-8): ``` <?php $s = '<x>Sans doute parce qu’il vient d’atteindre une date déterminante'. 'dans son spectaculaire cheminement</x>'; libxml_use_internal_errors(true); $d = new domdocument; $d->loadXML($s); echo $d->textContent; ```
`loadHtml()` doesn't always recognize the correct encoding as specified in the Content-type HTTP-EQUIV meta tag. If the `DomDocument('1.0', 'UTF-8')` and `loadHTML('<?xml version="1.0" encoding="UTF-8"?>' . $html)` hacks don't work as they didn't for me (PHP 5.3.13), try this: Add another `<head>` section immediately after the opening `<html>` tag with the correct Content-type HTTP-EQUIV meta tag. Then call `loadHtml()`, then remove the extra `<head>` tag. ```php // Ensure entire page is encoded in UTF-8 $encoding = mb_detect_encoding($body); $body = $encoding ? @iconv($encoding, 'UTF-8', $body) : $body; // Insert a head and meta tag immediately after the opening <html> to force UTF-8 encoding $insertPoint = false; if (preg_match("/<html.*?>/is", $body, $matches, PREG_OFFSET_CAPTURE)) { $insertPoint = mb_strlen( $matches[0][0] ) + $matches[0][1]; } if ($insertPoint) { $body = mb_substr( $body, 0, $insertPoint ) . "<head><meta http-equiv='Content-type' content='text/html; charset=UTF-8' /></head>" . mb_substr( $body, $insertPoint ); } $dom = new DOMDocument(); // Suppress warnings for loading non-standard html pages libxml_use_internal_errors(true); $dom->loadHTML($body); libxml_use_internal_errors(false); // Now remove extra <head> ``` See this article: <http://devzone.zend.com/1538/php-dom-xml-extension-encoding-processing/>
3,523,409
I am using DOMDocument to manipulate / modify HTML before it gets output to the page. This is only a html fragment, not a complete page. My initial problem was that all french character got messed up, which I was able to correct after some trial-and-error. Now, it seems only one problem remains : ' character gets transformed into ? . The code : ``` <?php $dom = new DOMDocument('1.0','utf-8'); $dom->loadHTML(utf8_decode($row->text)); //Some pretty basic modification here, not even related to text //reinsert HTML, and make sure to remove DOCTYPE, html and body that get added auto. $row->text = utf8_encode(preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $dom->saveHTML()))); ?> ``` I know it's getting messy with the utf8 decode/encode, but this is the only way I could make it work so far. Here is a sample string : Input : Sans doute parce qu’il vient d’atteindre une date déterminante dans son spectaculaire cheminement Output : Sans doute parce qu?il vient d?atteindre une date déterminante dans son spectaculaire cheminement If I find any more details, I'll add them. Thank you for your time and support!
2010/08/19
[ "https://Stackoverflow.com/questions/3523409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/425422/" ]
Don't use `utf8_decode`. If your text is in UTF-8, pass it as such. Unfortunately, `DOMDocument` defaults to LATIN1 in case of HTML. It seems the behavior is this * If fetching a remote document, it should deduce the encoding from the headers * If the header wasn't sent or the file is local, look for the correspondent meta-equiv * Otherwise, default to LATIN1. Example of it working: ``` <?php $s = <<<HTML <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> Sans doute parce qu’il vient d’atteindre une date déterminante dans son spectaculaire cheminement </body> </html> HTML; libxml_use_internal_errors(true); $d = new domdocument; $d->loadHTML($s); echo $d->textContent; ``` And with XML (default is UTF-8): ``` <?php $s = '<x>Sans doute parce qu’il vient d’atteindre une date déterminante'. 'dans son spectaculaire cheminement</x>'; libxml_use_internal_errors(true); $d = new domdocument; $d->loadXML($s); echo $d->textContent; ```
This was enough for me, the other answers here were overkill. Given I have an HTML document with an existing HEAD tag. HEAD tags don't have attributes and I had no issues leaving the extra META tag in the HTML for my use-case. ``` $data = str_ireplace('<head>', '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />', $data); $document = new DOMDocument(); $document->loadHTML($data); ```
3,523,409
I am using DOMDocument to manipulate / modify HTML before it gets output to the page. This is only a html fragment, not a complete page. My initial problem was that all french character got messed up, which I was able to correct after some trial-and-error. Now, it seems only one problem remains : ' character gets transformed into ? . The code : ``` <?php $dom = new DOMDocument('1.0','utf-8'); $dom->loadHTML(utf8_decode($row->text)); //Some pretty basic modification here, not even related to text //reinsert HTML, and make sure to remove DOCTYPE, html and body that get added auto. $row->text = utf8_encode(preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $dom->saveHTML()))); ?> ``` I know it's getting messy with the utf8 decode/encode, but this is the only way I could make it work so far. Here is a sample string : Input : Sans doute parce qu’il vient d’atteindre une date déterminante dans son spectaculaire cheminement Output : Sans doute parce qu?il vient d?atteindre une date déterminante dans son spectaculaire cheminement If I find any more details, I'll add them. Thank you for your time and support!
2010/08/19
[ "https://Stackoverflow.com/questions/3523409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/425422/" ]
Don't use `utf8_decode`. If your text is in UTF-8, pass it as such. Unfortunately, `DOMDocument` defaults to LATIN1 in case of HTML. It seems the behavior is this * If fetching a remote document, it should deduce the encoding from the headers * If the header wasn't sent or the file is local, look for the correspondent meta-equiv * Otherwise, default to LATIN1. Example of it working: ``` <?php $s = <<<HTML <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> Sans doute parce qu’il vient d’atteindre une date déterminante dans son spectaculaire cheminement </body> </html> HTML; libxml_use_internal_errors(true); $d = new domdocument; $d->loadHTML($s); echo $d->textContent; ``` And with XML (default is UTF-8): ``` <?php $s = '<x>Sans doute parce qu’il vient d’atteindre une date déterminante'. 'dans son spectaculaire cheminement</x>'; libxml_use_internal_errors(true); $d = new domdocument; $d->loadXML($s); echo $d->textContent; ```
As others have pointed out, `DOMDocument` and `LoadHTML` will default to LATIN1 encoding with HTML fragments. It will also wrap your HTML with something like this: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html><body>YOUR HTML</body></html> ``` So also as others have pointed out, you can fix the encoding by inserting a HEAD element into your HTML with a META element that contains the correct encoding. However, if you're working with an HTML fragment, you probably don't want the wrapping to happen and you also don't want to keep that HEAD element you inserted. The following code will insert the HEAD element, and then after processing, using regex will remove all the wrapping elements: ``` <?php $html = '<article class="grid-item"><p>Hello World</p></article><article class="grid-item"><p>Goodbye World</p></article>'; $head = '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>'; libxml_use_internal_errors(true); $dom = new DOMDocument('1.0', 'utf-8'); $dom->loadHTML($head . $html); $xpath = new DOMXPath($dom); // Loop through all article.grid-item elements and add the "invisible" class to them $nodes = $xpath->query("//article[contains(concat(' ', normalize-space(@class), ' '), ' grid-item ')]"); foreach($nodes as $node) { $class = $node->getAttribute('class'); $class .= ' invisible'; $node->setAttribute('class', $class); } $content = preg_replace('/<\/?(!doctype|html|head|meta|body)[^>]*>/im', '', $dom->saveHTML()); libxml_use_internal_errors(false); echo $content; ?> ```
3,523,409
I am using DOMDocument to manipulate / modify HTML before it gets output to the page. This is only a html fragment, not a complete page. My initial problem was that all french character got messed up, which I was able to correct after some trial-and-error. Now, it seems only one problem remains : ' character gets transformed into ? . The code : ``` <?php $dom = new DOMDocument('1.0','utf-8'); $dom->loadHTML(utf8_decode($row->text)); //Some pretty basic modification here, not even related to text //reinsert HTML, and make sure to remove DOCTYPE, html and body that get added auto. $row->text = utf8_encode(preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $dom->saveHTML()))); ?> ``` I know it's getting messy with the utf8 decode/encode, but this is the only way I could make it work so far. Here is a sample string : Input : Sans doute parce qu’il vient d’atteindre une date déterminante dans son spectaculaire cheminement Output : Sans doute parce qu?il vient d?atteindre une date déterminante dans son spectaculaire cheminement If I find any more details, I'll add them. Thank you for your time and support!
2010/08/19
[ "https://Stackoverflow.com/questions/3523409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/425422/" ]
`loadHtml()` doesn't always recognize the correct encoding as specified in the Content-type HTTP-EQUIV meta tag. If the `DomDocument('1.0', 'UTF-8')` and `loadHTML('<?xml version="1.0" encoding="UTF-8"?>' . $html)` hacks don't work as they didn't for me (PHP 5.3.13), try this: Add another `<head>` section immediately after the opening `<html>` tag with the correct Content-type HTTP-EQUIV meta tag. Then call `loadHtml()`, then remove the extra `<head>` tag. ```php // Ensure entire page is encoded in UTF-8 $encoding = mb_detect_encoding($body); $body = $encoding ? @iconv($encoding, 'UTF-8', $body) : $body; // Insert a head and meta tag immediately after the opening <html> to force UTF-8 encoding $insertPoint = false; if (preg_match("/<html.*?>/is", $body, $matches, PREG_OFFSET_CAPTURE)) { $insertPoint = mb_strlen( $matches[0][0] ) + $matches[0][1]; } if ($insertPoint) { $body = mb_substr( $body, 0, $insertPoint ) . "<head><meta http-equiv='Content-type' content='text/html; charset=UTF-8' /></head>" . mb_substr( $body, $insertPoint ); } $dom = new DOMDocument(); // Suppress warnings for loading non-standard html pages libxml_use_internal_errors(true); $dom->loadHTML($body); libxml_use_internal_errors(false); // Now remove extra <head> ``` See this article: <http://devzone.zend.com/1538/php-dom-xml-extension-encoding-processing/>
This was enough for me, the other answers here were overkill. Given I have an HTML document with an existing HEAD tag. HEAD tags don't have attributes and I had no issues leaving the extra META tag in the HTML for my use-case. ``` $data = str_ireplace('<head>', '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />', $data); $document = new DOMDocument(); $document->loadHTML($data); ```
3,523,409
I am using DOMDocument to manipulate / modify HTML before it gets output to the page. This is only a html fragment, not a complete page. My initial problem was that all french character got messed up, which I was able to correct after some trial-and-error. Now, it seems only one problem remains : ' character gets transformed into ? . The code : ``` <?php $dom = new DOMDocument('1.0','utf-8'); $dom->loadHTML(utf8_decode($row->text)); //Some pretty basic modification here, not even related to text //reinsert HTML, and make sure to remove DOCTYPE, html and body that get added auto. $row->text = utf8_encode(preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $dom->saveHTML()))); ?> ``` I know it's getting messy with the utf8 decode/encode, but this is the only way I could make it work so far. Here is a sample string : Input : Sans doute parce qu’il vient d’atteindre une date déterminante dans son spectaculaire cheminement Output : Sans doute parce qu?il vient d?atteindre une date déterminante dans son spectaculaire cheminement If I find any more details, I'll add them. Thank you for your time and support!
2010/08/19
[ "https://Stackoverflow.com/questions/3523409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/425422/" ]
`loadHtml()` doesn't always recognize the correct encoding as specified in the Content-type HTTP-EQUIV meta tag. If the `DomDocument('1.0', 'UTF-8')` and `loadHTML('<?xml version="1.0" encoding="UTF-8"?>' . $html)` hacks don't work as they didn't for me (PHP 5.3.13), try this: Add another `<head>` section immediately after the opening `<html>` tag with the correct Content-type HTTP-EQUIV meta tag. Then call `loadHtml()`, then remove the extra `<head>` tag. ```php // Ensure entire page is encoded in UTF-8 $encoding = mb_detect_encoding($body); $body = $encoding ? @iconv($encoding, 'UTF-8', $body) : $body; // Insert a head and meta tag immediately after the opening <html> to force UTF-8 encoding $insertPoint = false; if (preg_match("/<html.*?>/is", $body, $matches, PREG_OFFSET_CAPTURE)) { $insertPoint = mb_strlen( $matches[0][0] ) + $matches[0][1]; } if ($insertPoint) { $body = mb_substr( $body, 0, $insertPoint ) . "<head><meta http-equiv='Content-type' content='text/html; charset=UTF-8' /></head>" . mb_substr( $body, $insertPoint ); } $dom = new DOMDocument(); // Suppress warnings for loading non-standard html pages libxml_use_internal_errors(true); $dom->loadHTML($body); libxml_use_internal_errors(false); // Now remove extra <head> ``` See this article: <http://devzone.zend.com/1538/php-dom-xml-extension-encoding-processing/>
As others have pointed out, `DOMDocument` and `LoadHTML` will default to LATIN1 encoding with HTML fragments. It will also wrap your HTML with something like this: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html><body>YOUR HTML</body></html> ``` So also as others have pointed out, you can fix the encoding by inserting a HEAD element into your HTML with a META element that contains the correct encoding. However, if you're working with an HTML fragment, you probably don't want the wrapping to happen and you also don't want to keep that HEAD element you inserted. The following code will insert the HEAD element, and then after processing, using regex will remove all the wrapping elements: ``` <?php $html = '<article class="grid-item"><p>Hello World</p></article><article class="grid-item"><p>Goodbye World</p></article>'; $head = '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>'; libxml_use_internal_errors(true); $dom = new DOMDocument('1.0', 'utf-8'); $dom->loadHTML($head . $html); $xpath = new DOMXPath($dom); // Loop through all article.grid-item elements and add the "invisible" class to them $nodes = $xpath->query("//article[contains(concat(' ', normalize-space(@class), ' '), ' grid-item ')]"); foreach($nodes as $node) { $class = $node->getAttribute('class'); $class .= ' invisible'; $node->setAttribute('class', $class); } $content = preg_replace('/<\/?(!doctype|html|head|meta|body)[^>]*>/im', '', $dom->saveHTML()); libxml_use_internal_errors(false); echo $content; ?> ```
3,523,409
I am using DOMDocument to manipulate / modify HTML before it gets output to the page. This is only a html fragment, not a complete page. My initial problem was that all french character got messed up, which I was able to correct after some trial-and-error. Now, it seems only one problem remains : ' character gets transformed into ? . The code : ``` <?php $dom = new DOMDocument('1.0','utf-8'); $dom->loadHTML(utf8_decode($row->text)); //Some pretty basic modification here, not even related to text //reinsert HTML, and make sure to remove DOCTYPE, html and body that get added auto. $row->text = utf8_encode(preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $dom->saveHTML()))); ?> ``` I know it's getting messy with the utf8 decode/encode, but this is the only way I could make it work so far. Here is a sample string : Input : Sans doute parce qu’il vient d’atteindre une date déterminante dans son spectaculaire cheminement Output : Sans doute parce qu?il vient d?atteindre une date déterminante dans son spectaculaire cheminement If I find any more details, I'll add them. Thank you for your time and support!
2010/08/19
[ "https://Stackoverflow.com/questions/3523409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/425422/" ]
This was enough for me, the other answers here were overkill. Given I have an HTML document with an existing HEAD tag. HEAD tags don't have attributes and I had no issues leaving the extra META tag in the HTML for my use-case. ``` $data = str_ireplace('<head>', '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />', $data); $document = new DOMDocument(); $document->loadHTML($data); ```
As others have pointed out, `DOMDocument` and `LoadHTML` will default to LATIN1 encoding with HTML fragments. It will also wrap your HTML with something like this: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html><body>YOUR HTML</body></html> ``` So also as others have pointed out, you can fix the encoding by inserting a HEAD element into your HTML with a META element that contains the correct encoding. However, if you're working with an HTML fragment, you probably don't want the wrapping to happen and you also don't want to keep that HEAD element you inserted. The following code will insert the HEAD element, and then after processing, using regex will remove all the wrapping elements: ``` <?php $html = '<article class="grid-item"><p>Hello World</p></article><article class="grid-item"><p>Goodbye World</p></article>'; $head = '<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>'; libxml_use_internal_errors(true); $dom = new DOMDocument('1.0', 'utf-8'); $dom->loadHTML($head . $html); $xpath = new DOMXPath($dom); // Loop through all article.grid-item elements and add the "invisible" class to them $nodes = $xpath->query("//article[contains(concat(' ', normalize-space(@class), ' '), ' grid-item ')]"); foreach($nodes as $node) { $class = $node->getAttribute('class'); $class .= ' invisible'; $node->setAttribute('class', $class); } $content = preg_replace('/<\/?(!doctype|html|head|meta|body)[^>]*>/im', '', $dom->saveHTML()); libxml_use_internal_errors(false); echo $content; ?> ```
73,075,284
Which is the better way to create a responsive website among grid, media queries, and HTML tables.
2022/07/22
[ "https://Stackoverflow.com/questions/73075284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19317629/" ]
often neglected by developers when it comes to responsive websites: Typography. Typography! @media (min-width: 640px) { body {font-size:1rem;} } @media (min-width:960px) { body {font-size:1.2rem;} } @media (min-width:1100px) { body {font-size:1.5rem;} }
There are lots of ways to create a responsive behavior in css, you gave some good examples for them. Personally, I'm using the `Flexbox` and `Grid` display methods to align html containers and contents, and by using `Media Queries` i can make them interact responsively for any device. For example, if you wanna render a cards-based container, meaning there will be multiple `div` elements with their own contents, aligned in a straight line, i would use the `flex-wrap` property to break them instead of overflowing to one of the page sides. If the cards are getting small enough for the page, i'd use the `vw` value for my card's width at a certain page width, using `media queries`. Of course you can have your own preferences for different responsive methods, and there are a lot you can search on the internet, i just gave some of my own.
73,075,284
Which is the better way to create a responsive website among grid, media queries, and HTML tables.
2022/07/22
[ "https://Stackoverflow.com/questions/73075284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19317629/" ]
often neglected by developers when it comes to responsive websites: Typography. Typography! @media (min-width: 640px) { body {font-size:1rem;} } @media (min-width:960px) { body {font-size:1.2rem;} } @media (min-width:1100px) { body {font-size:1.5rem;} }
Use media queries and flex, Some example breakpoints, ``` // Extra large devices (large desktops, 1200px and down) @media (max-width: 1200px) { ... } // Large devices (desktops, 992px and down) @media (max-width: 992px) { ... } // Medium devices (tablets, 768px and down) @media (max-width: 768px) { ... } // Small devices (landscape phones, 576px and down) @media (max-width: 576px) { ... } ```
40,404
A Catholic friend of mine asked me this question, and I mentioned this passage: > > 41 Every year Jesus’ parents went to Jerusalem for the Passover festival. 42 **When Jesus was twelve years old,** they attended the festival as usual. 43 After the celebration was over, they started home to Nazareth, but Jesus stayed behind in Jerusalem. His parents didn’t miss him at first, 44 because they assumed he was among the other travelers. But when he didn’t show up that evening, they started looking for him among their relatives and friends. > > > 45 When they couldn’t find him, they went back to Jerusalem to search for him there. 46 Three days later they finally discovered him in the Temple, sitting among the religious teachers, listening to them and asking questions. 47 All who heard him were amazed at his understanding and his answers. > > > 48 His parents didn’t know what to think. “Son,” his mother said to him, “why have you done this to us? Your father and I have been frantic, searching for you everywhere.” > > > 49 “But why did you need to search?” he asked. **“Didn’t you know that I must be in my Father’s house?”** 50 But they didn’t understand what he meant. > > > 51 Then he returned to Nazareth with them and was obedient to them. And his mother stored all these things in her heart. > > > 52 Jesus grew in wisdom and in stature and in favor with God and all the people. > > > ~[Luke 2:41–52 (NLT)](https://www.biblegateway.com/passage/?search=Luke+2&version=NLT) > > > So, Jesus certainly knew His identity by 12 years old. However, being God, He could've known this as a baby, and I've heard this opinion expressed by various people. However, I'm wondering: is there a **Catholic** tradition that answers the question in the title? Do Catholics say Jesus grew up knowing He was the Son of God, or do they say Mary told Him?
2015/04/30
[ "https://christianity.stackexchange.com/questions/40404", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/58/" ]
Number 79 in the the YouCat asks if Jesus has a soul, a mind and a body just as we do. I don't think you're going to find a Catholic answer that speculates on what Mary may or may not have said to Him outside of scripture, although there are early extra-biblical accounts of Jesus' miracles during His hidden life. Some are spontaneous and some are at Mary's prompting, but you don't have to believe them and most Catholics don't even know of them, which is probably a good thing. So, back to the YouCat, it says Jesus "had a soul and developed psychologically and spiritually." So, in part, what He knew seems to be constrained to His human faculties. But, the Doctrine of the Hypo-static union says that His soul is Human and Divine. So... "In this soul swelled the human identity **and** his special self-consciousness." Furthermore, "Jesus new about his unity with his heavenly Father in the Holy Spirit, by whom he allowed himself to be guided in **every situation** of his life" So, I think the answer is that Mary didn't need to tell Him, although there's no reason to suppose that she did and one reason to suppose that she didn't (Our Lady had a tendency to hold things and ponder them in her heart).
If you're looking for a Catholic answer, your best bet is to look through Part 3 of St Thomas Aquinas's *Summa Theologica*. Questions 9-13 seem particularly relevant to your inquiry. You can find a digital copy of the *Summa* below, among various other places online: <http://dhspriory.org/thomas/summa/TP.html>
40,404
A Catholic friend of mine asked me this question, and I mentioned this passage: > > 41 Every year Jesus’ parents went to Jerusalem for the Passover festival. 42 **When Jesus was twelve years old,** they attended the festival as usual. 43 After the celebration was over, they started home to Nazareth, but Jesus stayed behind in Jerusalem. His parents didn’t miss him at first, 44 because they assumed he was among the other travelers. But when he didn’t show up that evening, they started looking for him among their relatives and friends. > > > 45 When they couldn’t find him, they went back to Jerusalem to search for him there. 46 Three days later they finally discovered him in the Temple, sitting among the religious teachers, listening to them and asking questions. 47 All who heard him were amazed at his understanding and his answers. > > > 48 His parents didn’t know what to think. “Son,” his mother said to him, “why have you done this to us? Your father and I have been frantic, searching for you everywhere.” > > > 49 “But why did you need to search?” he asked. **“Didn’t you know that I must be in my Father’s house?”** 50 But they didn’t understand what he meant. > > > 51 Then he returned to Nazareth with them and was obedient to them. And his mother stored all these things in her heart. > > > 52 Jesus grew in wisdom and in stature and in favor with God and all the people. > > > ~[Luke 2:41–52 (NLT)](https://www.biblegateway.com/passage/?search=Luke+2&version=NLT) > > > So, Jesus certainly knew His identity by 12 years old. However, being God, He could've known this as a baby, and I've heard this opinion expressed by various people. However, I'm wondering: is there a **Catholic** tradition that answers the question in the title? Do Catholics say Jesus grew up knowing He was the Son of God, or do they say Mary told Him?
2015/04/30
[ "https://christianity.stackexchange.com/questions/40404", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/58/" ]
Number 79 in the the YouCat asks if Jesus has a soul, a mind and a body just as we do. I don't think you're going to find a Catholic answer that speculates on what Mary may or may not have said to Him outside of scripture, although there are early extra-biblical accounts of Jesus' miracles during His hidden life. Some are spontaneous and some are at Mary's prompting, but you don't have to believe them and most Catholics don't even know of them, which is probably a good thing. So, back to the YouCat, it says Jesus "had a soul and developed psychologically and spiritually." So, in part, what He knew seems to be constrained to His human faculties. But, the Doctrine of the Hypo-static union says that His soul is Human and Divine. So... "In this soul swelled the human identity **and** his special self-consciousness." Furthermore, "Jesus new about his unity with his heavenly Father in the Holy Spirit, by whom he allowed himself to be guided in **every situation** of his life" So, I think the answer is that Mary didn't need to tell Him, although there's no reason to suppose that she did and one reason to suppose that she didn't (Our Lady had a tendency to hold things and ponder them in her heart).
This *Opening* draws from [Knowledge of Jesus Christ | New Advent](http://www.newadvent.org/cathen/08675a.htm). I believe this question is best answered by first stating what the Catholic Church teaches were the kinds of knowledge in Christ. Since Christ is God-made-man, he possesses two natures, and therefore two intellects, the human and the Divine. The kinds of knowledge in Christ's human intellect are: 1. The beatific vision. 2. Christ's infused knowledge. 3. Christ's acquired knowledge. Of these, the only one capable of increase was *experimental knowledge acquired by the natural use of His faculties, through His senses and imagination, just as happens in the case of common human knowledge.* **The question then becomes to which kind of knowledge did his knowing that he was the Son of God belong?** *Answering* From the article linked in the opening and from the Catechism of the Catholic Church, [473](http://www.vatican.va/archive/ccc_css/archive/catechism/p122a3p1.htm#473), *the human soul of Christ must have seen God face to face from the very first moment of its creation* and *the human nature of God's Son, **not by itself but by its union with the Word**, knew and showed forth in itself everything that pertains to God.* **Therefore Christ always knew he was the Son of God.** > > **CCC 473** But at the same time, this truly human knowledge of God's Son expressed the divine life of his person. "The human nature of > God's Son, *not by itself but by its union with the Word*, **knew and > showed forth in itself everything that pertains to God.**" **Such is first > of all the case with the intimate and immediate knowledge that the Son > of God made man has of his Father.** The Son in his human knowledge also > showed the divine penetration he had into the secret thoughts of human > hearts. > > >
40,404
A Catholic friend of mine asked me this question, and I mentioned this passage: > > 41 Every year Jesus’ parents went to Jerusalem for the Passover festival. 42 **When Jesus was twelve years old,** they attended the festival as usual. 43 After the celebration was over, they started home to Nazareth, but Jesus stayed behind in Jerusalem. His parents didn’t miss him at first, 44 because they assumed he was among the other travelers. But when he didn’t show up that evening, they started looking for him among their relatives and friends. > > > 45 When they couldn’t find him, they went back to Jerusalem to search for him there. 46 Three days later they finally discovered him in the Temple, sitting among the religious teachers, listening to them and asking questions. 47 All who heard him were amazed at his understanding and his answers. > > > 48 His parents didn’t know what to think. “Son,” his mother said to him, “why have you done this to us? Your father and I have been frantic, searching for you everywhere.” > > > 49 “But why did you need to search?” he asked. **“Didn’t you know that I must be in my Father’s house?”** 50 But they didn’t understand what he meant. > > > 51 Then he returned to Nazareth with them and was obedient to them. And his mother stored all these things in her heart. > > > 52 Jesus grew in wisdom and in stature and in favor with God and all the people. > > > ~[Luke 2:41–52 (NLT)](https://www.biblegateway.com/passage/?search=Luke+2&version=NLT) > > > So, Jesus certainly knew His identity by 12 years old. However, being God, He could've known this as a baby, and I've heard this opinion expressed by various people. However, I'm wondering: is there a **Catholic** tradition that answers the question in the title? Do Catholics say Jesus grew up knowing He was the Son of God, or do they say Mary told Him?
2015/04/30
[ "https://christianity.stackexchange.com/questions/40404", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/58/" ]
This *Opening* draws from [Knowledge of Jesus Christ | New Advent](http://www.newadvent.org/cathen/08675a.htm). I believe this question is best answered by first stating what the Catholic Church teaches were the kinds of knowledge in Christ. Since Christ is God-made-man, he possesses two natures, and therefore two intellects, the human and the Divine. The kinds of knowledge in Christ's human intellect are: 1. The beatific vision. 2. Christ's infused knowledge. 3. Christ's acquired knowledge. Of these, the only one capable of increase was *experimental knowledge acquired by the natural use of His faculties, through His senses and imagination, just as happens in the case of common human knowledge.* **The question then becomes to which kind of knowledge did his knowing that he was the Son of God belong?** *Answering* From the article linked in the opening and from the Catechism of the Catholic Church, [473](http://www.vatican.va/archive/ccc_css/archive/catechism/p122a3p1.htm#473), *the human soul of Christ must have seen God face to face from the very first moment of its creation* and *the human nature of God's Son, **not by itself but by its union with the Word**, knew and showed forth in itself everything that pertains to God.* **Therefore Christ always knew he was the Son of God.** > > **CCC 473** But at the same time, this truly human knowledge of God's Son expressed the divine life of his person. "The human nature of > God's Son, *not by itself but by its union with the Word*, **knew and > showed forth in itself everything that pertains to God.**" **Such is first > of all the case with the intimate and immediate knowledge that the Son > of God made man has of his Father.** The Son in his human knowledge also > showed the divine penetration he had into the secret thoughts of human > hearts. > > >
If you're looking for a Catholic answer, your best bet is to look through Part 3 of St Thomas Aquinas's *Summa Theologica*. Questions 9-13 seem particularly relevant to your inquiry. You can find a digital copy of the *Summa* below, among various other places online: <http://dhspriory.org/thomas/summa/TP.html>
40,404
A Catholic friend of mine asked me this question, and I mentioned this passage: > > 41 Every year Jesus’ parents went to Jerusalem for the Passover festival. 42 **When Jesus was twelve years old,** they attended the festival as usual. 43 After the celebration was over, they started home to Nazareth, but Jesus stayed behind in Jerusalem. His parents didn’t miss him at first, 44 because they assumed he was among the other travelers. But when he didn’t show up that evening, they started looking for him among their relatives and friends. > > > 45 When they couldn’t find him, they went back to Jerusalem to search for him there. 46 Three days later they finally discovered him in the Temple, sitting among the religious teachers, listening to them and asking questions. 47 All who heard him were amazed at his understanding and his answers. > > > 48 His parents didn’t know what to think. “Son,” his mother said to him, “why have you done this to us? Your father and I have been frantic, searching for you everywhere.” > > > 49 “But why did you need to search?” he asked. **“Didn’t you know that I must be in my Father’s house?”** 50 But they didn’t understand what he meant. > > > 51 Then he returned to Nazareth with them and was obedient to them. And his mother stored all these things in her heart. > > > 52 Jesus grew in wisdom and in stature and in favor with God and all the people. > > > ~[Luke 2:41–52 (NLT)](https://www.biblegateway.com/passage/?search=Luke+2&version=NLT) > > > So, Jesus certainly knew His identity by 12 years old. However, being God, He could've known this as a baby, and I've heard this opinion expressed by various people. However, I'm wondering: is there a **Catholic** tradition that answers the question in the title? Do Catholics say Jesus grew up knowing He was the Son of God, or do they say Mary told Him?
2015/04/30
[ "https://christianity.stackexchange.com/questions/40404", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/58/" ]
TL;DR: Briefly, the answer is that Jesus knew he was the Son of God from all eternity, and his human intellect was aware of that fact from the moment of the Incarnation. Mary did not have to tell him; Jesus, rather, would have needed to tell her. The Hypostatic Union and the Incarnation ======================================== The reason that Jesus would have had to know his identity stems fundamentally from something called the *Hypostatic Union*. As readers may recall, the Catholic Church (and the Orthodox Churches, as well as any church that accepts the Council of Chalcedon) teaches that Jesus Christ is fully God and fully man. He possesses two natures—human and divine—“without confusion, change, division or separation” ([*Council of Chalcedon*, DS 302](https://www.ewtn.com/faith/teachings/incac2.htm)). However, He is a unique Person or Hypostasis: namely, the Divine Son. (See [*Catechism of the Catholic Church* 467-469](http://www.vatican.va/archive/ccc_css/archive/catechism/p122a3p1.htm)). The important thing to understand about the Hypostatic Union is that no closer union between human and divine nature is possible: not even our definitive union with God that we will enjoy in Heaven, when we see Him “face to face” ([1 Cor. 13:12](http://biblia.com/bible/esv/1%20Corinthians%2013.12)). The human and divine natures—although distinct—are so closely united that *all* of Jesus’ actions, even his human ones, are actions *of God*, and likewise, the actions requiring Divine power are rightly said to be produced *by the man Jesus*. It is perfectly correct to say, for example, “Jesus created the universe” and “God died on the Cross.” Affirming that Jesus is a *human person*, in addition to a Divine Person, would be tantamount to the heresy of Nestorianism. In reality, he is a Divine Person only ([*CCC* 466](http://www.vatican.va/archive/ccc_css/archive/catechism/p122a3p1.htm)). Moreover, since Jesus is fully man (in addition to being fully God), his human nature must possess all of the characteristics of human nature: in particular, he must have a human intellect and a human will ([*CCC* 470-474](http://www.vatican.va/archive/ccc_css/archive/catechism/p122a3p1.htm)). Note that once a human being comes into existence (i.e., at his conception), he already possesses a complete human intellect and will. He is unable to *exercise* that intellect and will until his brain and cognitive apparatus are ready for it, but he possesses them from the beginning. It follows that Jesus possessed a human intellect from the moment of his Incarnation. ([See *Summa theologiae*, I, q. 77,](http://dhspriory.org/thomas/summa/FP/FP077.html#FPQ77OUTP1) for an overview of how the intellect and will—the “powers” of the soul—relate to the human soul they belong to.) Jesus’ three manners of obtaining human knowledge ================================================= As a consequence of the Hypostatic Union, and the fact that Jesus has possessed a human intellect from the moment of his conception, it seems an inevitable conclusion that Jesus in his human intellect must have enjoyed the Beatific Vision—that is, he must have seen God face-to-face—as soon as he became incarnate. This idea is accepted in Pope Pius XII’s encyclical [*Mystici Corporis* No. 75](http://w2.vatican.va/content/pius-xii/en/encyclicals/documents/hf_p-xii_enc_29061943_mystici-corporis-christi.html): > > For hardly was He conceived in the womb of the Mother of God, when He began to enjoy the Beatific Vision, and in that vision all the members of His Mystical Body were continually and unceasingly present to Him, and He embraced them with His redeeming love. > > > Pope Pius, in turn, took that idea from St. Thomas Aquinas’ [*Summa theologiae*, III, q. 9, a. 2](http://dhspriory.org/thomas/summa/TP/TP009.html#TPQ9A2THEP1), in which Aquinas argues that Christ did indeed have the knowledge proper to the Blessed in Heaven. Aquinas adds another argument (an argument of fittingness) for Christ to have the knowledge of the Blessed: > > it was necessary that the beatific knowledge, which consists in the vision of God, should belong to Christ pre-eminently, since the cause ought always to be more efficacious than the effect (from the *responsum*). > > > In other words, because Jesus Christ in his human nature is the cause of our salvation, it is fitting that he should experience all of the effects of that salvation before we do (for the same reason that Christ rose and ascended in to Heaven before our own resurrection). Hence, although it has never been formalized in a dogma, the idea that Jesus Christ possessed the Beatific Vision throughout his life has the status of a “probable opinion”: denying it comes perilously close to affirming a Nestorian separation of Jesus’ human nature from his Divine Nature. In addition to his Beatific Vision, Jesus would have had all of the infused knowledge necessary for him to accomplish his mission. In [III, q. 9, a. 3](http://dhspriory.org/thomas/summa/TP/TP009.html#TPQ9A3THEP1), Aquinas argues that because Jesus was perfect man (as taught by the Council of Chalcedon), his human intellect would have had knowledge of all the things actually created by him (whether in the past, in present, or in the future). This is, again, a consequence of being hypostatically united to the Divine Word: since Jesus simply *is* the Person of the Son, he must possess all the knowledge that the Son has (at least as much of it as a human intellect can hold). As FMS points out in his post, this teaching has essentially been taken up by the *Catechism* in [number 473](http://www.vatican.va/archive/ccc_css/archive/catechism/p122a3p1.htm): > > But at the same time, this truly human knowledge of God's Son expressed the divine life of his person. “**The human nature of God’s Son, not by itself but by its union with the Word, knew and showed forth in itself everything that pertains to God”** [quoting Maximus the Confessor, PG 90, 840A]. Such is first of all the case with the intimate and immediate knowledge that the Son of God made man has of his Father. > > > Finally, Jesus would have been able to learn things in the way that all human beings learn: by experience, using his senses and cognitive apparatus (i.e., his brain). (That is the argument of [III, q. 9, a. 4](http://dhspriory.org/thomas/summa/TP/TP009.html#TPQ9A4THEP1).) This was the only type of human knowledge that would have required Jesus to be developed in body. It was in this capacity that Jesus (like all of us) learned to talk, learned to recognize his mother and (foster) father, experienced the sunrise, went to school, and so on. Regarding Jesus’ knowledge of his identity ========================================== It follows that, thanks to the infused knowledge that Jesus possessed, he already had full *human* knowledge of his identity (that is, of his divinity) from the moment of his conception. Obviously, he had no way of *expressing* that knowledge until his brain and speech were sufficiently developed, but he must have had that knowledge right from the beginning. (Note that Jesus probably experienced “consciousness” in the same way we do: but as soon as his cognitive functions were in order, he would have been aware of his Hypostatic Union and hence of his identity.)
If you're looking for a Catholic answer, your best bet is to look through Part 3 of St Thomas Aquinas's *Summa Theologica*. Questions 9-13 seem particularly relevant to your inquiry. You can find a digital copy of the *Summa* below, among various other places online: <http://dhspriory.org/thomas/summa/TP.html>
40,404
A Catholic friend of mine asked me this question, and I mentioned this passage: > > 41 Every year Jesus’ parents went to Jerusalem for the Passover festival. 42 **When Jesus was twelve years old,** they attended the festival as usual. 43 After the celebration was over, they started home to Nazareth, but Jesus stayed behind in Jerusalem. His parents didn’t miss him at first, 44 because they assumed he was among the other travelers. But when he didn’t show up that evening, they started looking for him among their relatives and friends. > > > 45 When they couldn’t find him, they went back to Jerusalem to search for him there. 46 Three days later they finally discovered him in the Temple, sitting among the religious teachers, listening to them and asking questions. 47 All who heard him were amazed at his understanding and his answers. > > > 48 His parents didn’t know what to think. “Son,” his mother said to him, “why have you done this to us? Your father and I have been frantic, searching for you everywhere.” > > > 49 “But why did you need to search?” he asked. **“Didn’t you know that I must be in my Father’s house?”** 50 But they didn’t understand what he meant. > > > 51 Then he returned to Nazareth with them and was obedient to them. And his mother stored all these things in her heart. > > > 52 Jesus grew in wisdom and in stature and in favor with God and all the people. > > > ~[Luke 2:41–52 (NLT)](https://www.biblegateway.com/passage/?search=Luke+2&version=NLT) > > > So, Jesus certainly knew His identity by 12 years old. However, being God, He could've known this as a baby, and I've heard this opinion expressed by various people. However, I'm wondering: is there a **Catholic** tradition that answers the question in the title? Do Catholics say Jesus grew up knowing He was the Son of God, or do they say Mary told Him?
2015/04/30
[ "https://christianity.stackexchange.com/questions/40404", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/58/" ]
TL;DR: Briefly, the answer is that Jesus knew he was the Son of God from all eternity, and his human intellect was aware of that fact from the moment of the Incarnation. Mary did not have to tell him; Jesus, rather, would have needed to tell her. The Hypostatic Union and the Incarnation ======================================== The reason that Jesus would have had to know his identity stems fundamentally from something called the *Hypostatic Union*. As readers may recall, the Catholic Church (and the Orthodox Churches, as well as any church that accepts the Council of Chalcedon) teaches that Jesus Christ is fully God and fully man. He possesses two natures—human and divine—“without confusion, change, division or separation” ([*Council of Chalcedon*, DS 302](https://www.ewtn.com/faith/teachings/incac2.htm)). However, He is a unique Person or Hypostasis: namely, the Divine Son. (See [*Catechism of the Catholic Church* 467-469](http://www.vatican.va/archive/ccc_css/archive/catechism/p122a3p1.htm)). The important thing to understand about the Hypostatic Union is that no closer union between human and divine nature is possible: not even our definitive union with God that we will enjoy in Heaven, when we see Him “face to face” ([1 Cor. 13:12](http://biblia.com/bible/esv/1%20Corinthians%2013.12)). The human and divine natures—although distinct—are so closely united that *all* of Jesus’ actions, even his human ones, are actions *of God*, and likewise, the actions requiring Divine power are rightly said to be produced *by the man Jesus*. It is perfectly correct to say, for example, “Jesus created the universe” and “God died on the Cross.” Affirming that Jesus is a *human person*, in addition to a Divine Person, would be tantamount to the heresy of Nestorianism. In reality, he is a Divine Person only ([*CCC* 466](http://www.vatican.va/archive/ccc_css/archive/catechism/p122a3p1.htm)). Moreover, since Jesus is fully man (in addition to being fully God), his human nature must possess all of the characteristics of human nature: in particular, he must have a human intellect and a human will ([*CCC* 470-474](http://www.vatican.va/archive/ccc_css/archive/catechism/p122a3p1.htm)). Note that once a human being comes into existence (i.e., at his conception), he already possesses a complete human intellect and will. He is unable to *exercise* that intellect and will until his brain and cognitive apparatus are ready for it, but he possesses them from the beginning. It follows that Jesus possessed a human intellect from the moment of his Incarnation. ([See *Summa theologiae*, I, q. 77,](http://dhspriory.org/thomas/summa/FP/FP077.html#FPQ77OUTP1) for an overview of how the intellect and will—the “powers” of the soul—relate to the human soul they belong to.) Jesus’ three manners of obtaining human knowledge ================================================= As a consequence of the Hypostatic Union, and the fact that Jesus has possessed a human intellect from the moment of his conception, it seems an inevitable conclusion that Jesus in his human intellect must have enjoyed the Beatific Vision—that is, he must have seen God face-to-face—as soon as he became incarnate. This idea is accepted in Pope Pius XII’s encyclical [*Mystici Corporis* No. 75](http://w2.vatican.va/content/pius-xii/en/encyclicals/documents/hf_p-xii_enc_29061943_mystici-corporis-christi.html): > > For hardly was He conceived in the womb of the Mother of God, when He began to enjoy the Beatific Vision, and in that vision all the members of His Mystical Body were continually and unceasingly present to Him, and He embraced them with His redeeming love. > > > Pope Pius, in turn, took that idea from St. Thomas Aquinas’ [*Summa theologiae*, III, q. 9, a. 2](http://dhspriory.org/thomas/summa/TP/TP009.html#TPQ9A2THEP1), in which Aquinas argues that Christ did indeed have the knowledge proper to the Blessed in Heaven. Aquinas adds another argument (an argument of fittingness) for Christ to have the knowledge of the Blessed: > > it was necessary that the beatific knowledge, which consists in the vision of God, should belong to Christ pre-eminently, since the cause ought always to be more efficacious than the effect (from the *responsum*). > > > In other words, because Jesus Christ in his human nature is the cause of our salvation, it is fitting that he should experience all of the effects of that salvation before we do (for the same reason that Christ rose and ascended in to Heaven before our own resurrection). Hence, although it has never been formalized in a dogma, the idea that Jesus Christ possessed the Beatific Vision throughout his life has the status of a “probable opinion”: denying it comes perilously close to affirming a Nestorian separation of Jesus’ human nature from his Divine Nature. In addition to his Beatific Vision, Jesus would have had all of the infused knowledge necessary for him to accomplish his mission. In [III, q. 9, a. 3](http://dhspriory.org/thomas/summa/TP/TP009.html#TPQ9A3THEP1), Aquinas argues that because Jesus was perfect man (as taught by the Council of Chalcedon), his human intellect would have had knowledge of all the things actually created by him (whether in the past, in present, or in the future). This is, again, a consequence of being hypostatically united to the Divine Word: since Jesus simply *is* the Person of the Son, he must possess all the knowledge that the Son has (at least as much of it as a human intellect can hold). As FMS points out in his post, this teaching has essentially been taken up by the *Catechism* in [number 473](http://www.vatican.va/archive/ccc_css/archive/catechism/p122a3p1.htm): > > But at the same time, this truly human knowledge of God's Son expressed the divine life of his person. “**The human nature of God’s Son, not by itself but by its union with the Word, knew and showed forth in itself everything that pertains to God”** [quoting Maximus the Confessor, PG 90, 840A]. Such is first of all the case with the intimate and immediate knowledge that the Son of God made man has of his Father. > > > Finally, Jesus would have been able to learn things in the way that all human beings learn: by experience, using his senses and cognitive apparatus (i.e., his brain). (That is the argument of [III, q. 9, a. 4](http://dhspriory.org/thomas/summa/TP/TP009.html#TPQ9A4THEP1).) This was the only type of human knowledge that would have required Jesus to be developed in body. It was in this capacity that Jesus (like all of us) learned to talk, learned to recognize his mother and (foster) father, experienced the sunrise, went to school, and so on. Regarding Jesus’ knowledge of his identity ========================================== It follows that, thanks to the infused knowledge that Jesus possessed, he already had full *human* knowledge of his identity (that is, of his divinity) from the moment of his conception. Obviously, he had no way of *expressing* that knowledge until his brain and speech were sufficiently developed, but he must have had that knowledge right from the beginning. (Note that Jesus probably experienced “consciousness” in the same way we do: but as soon as his cognitive functions were in order, he would have been aware of his Hypostatic Union and hence of his identity.)
This *Opening* draws from [Knowledge of Jesus Christ | New Advent](http://www.newadvent.org/cathen/08675a.htm). I believe this question is best answered by first stating what the Catholic Church teaches were the kinds of knowledge in Christ. Since Christ is God-made-man, he possesses two natures, and therefore two intellects, the human and the Divine. The kinds of knowledge in Christ's human intellect are: 1. The beatific vision. 2. Christ's infused knowledge. 3. Christ's acquired knowledge. Of these, the only one capable of increase was *experimental knowledge acquired by the natural use of His faculties, through His senses and imagination, just as happens in the case of common human knowledge.* **The question then becomes to which kind of knowledge did his knowing that he was the Son of God belong?** *Answering* From the article linked in the opening and from the Catechism of the Catholic Church, [473](http://www.vatican.va/archive/ccc_css/archive/catechism/p122a3p1.htm#473), *the human soul of Christ must have seen God face to face from the very first moment of its creation* and *the human nature of God's Son, **not by itself but by its union with the Word**, knew and showed forth in itself everything that pertains to God.* **Therefore Christ always knew he was the Son of God.** > > **CCC 473** But at the same time, this truly human knowledge of God's Son expressed the divine life of his person. "The human nature of > God's Son, *not by itself but by its union with the Word*, **knew and > showed forth in itself everything that pertains to God.**" **Such is first > of all the case with the intimate and immediate knowledge that the Son > of God made man has of his Father.** The Son in his human knowledge also > showed the divine penetration he had into the secret thoughts of human > hearts. > > >
3,316,509
Simplify: $$\frac {x^5y^2x^3 + x^4y^5 - y^5x^7y^4}{x^4y^3}$$ I know this is probably low level stuff but I need to be able to do this specific type of question and I have no way of checking my work. If anyone could offer a step by step working I'd be appreciative
2019/08/07
[ "https://math.stackexchange.com/questions/3316509", "https://math.stackexchange.com", "https://math.stackexchange.com/users/694274/" ]
You have \begin{align\*} \frac {x^5y^2x^3 + x^4y^5 - y^5x^7y^4}{x^4y^3} &=\frac {x^8y^2 + x^4y^5 - x^7y^9}{x^4y^3} \\ &=\frac {x^4y^2\big(x^4 + y^3 - x^3y^7\big)}{x^4y^3} \\ &=\frac {x^4 + y^3 - x^3y^7}{y},\quad x\not=0. \end{align\*} That's about as far as you can go.
The highest common factor of the terms in the numerator is $x^4y^2.$ This is also a factor of the denominator, hence you can cancel it off to get $$\frac{x^4+y^3-x^3y^7}{y}.$$
3,316,509
Simplify: $$\frac {x^5y^2x^3 + x^4y^5 - y^5x^7y^4}{x^4y^3}$$ I know this is probably low level stuff but I need to be able to do this specific type of question and I have no way of checking my work. If anyone could offer a step by step working I'd be appreciative
2019/08/07
[ "https://math.stackexchange.com/questions/3316509", "https://math.stackexchange.com", "https://math.stackexchange.com/users/694274/" ]
You have \begin{align\*} \frac {x^5y^2x^3 + x^4y^5 - y^5x^7y^4}{x^4y^3} &=\frac {x^8y^2 + x^4y^5 - x^7y^9}{x^4y^3} \\ &=\frac {x^4y^2\big(x^4 + y^3 - x^3y^7\big)}{x^4y^3} \\ &=\frac {x^4 + y^3 - x^3y^7}{y},\quad x\not=0. \end{align\*} That's about as far as you can go.
An alternate way is to break the problem down into simple workable parts: $$\frac{x^5y^2x^3+x^4y^5−y^5x^7y^4}{x^4y^3}$$ $$=\frac{x^5y^2x^3}{x^4y^3}+\frac{x^4y^5}{x^4y^3}-\frac{y^5x^7y^4}{x^4y^3}$$ $$=\frac{x^8y^2}{x^4y^3}+\frac{x^4y^5}{x^4y^3}-\frac{x^7y^9}{x^4y^3}$$ $$=\frac{x^4}{y}+y^2-x^3y^6,\quad x\not=0.$$ This is equivalent to the answers given above.
3,316,509
Simplify: $$\frac {x^5y^2x^3 + x^4y^5 - y^5x^7y^4}{x^4y^3}$$ I know this is probably low level stuff but I need to be able to do this specific type of question and I have no way of checking my work. If anyone could offer a step by step working I'd be appreciative
2019/08/07
[ "https://math.stackexchange.com/questions/3316509", "https://math.stackexchange.com", "https://math.stackexchange.com/users/694274/" ]
The highest common factor of the terms in the numerator is $x^4y^2.$ This is also a factor of the denominator, hence you can cancel it off to get $$\frac{x^4+y^3-x^3y^7}{y}.$$
An alternate way is to break the problem down into simple workable parts: $$\frac{x^5y^2x^3+x^4y^5−y^5x^7y^4}{x^4y^3}$$ $$=\frac{x^5y^2x^3}{x^4y^3}+\frac{x^4y^5}{x^4y^3}-\frac{y^5x^7y^4}{x^4y^3}$$ $$=\frac{x^8y^2}{x^4y^3}+\frac{x^4y^5}{x^4y^3}-\frac{x^7y^9}{x^4y^3}$$ $$=\frac{x^4}{y}+y^2-x^3y^6,\quad x\not=0.$$ This is equivalent to the answers given above.
12,825,324
I have this class here and I using box-shadow which works fine, but it only shows the shadow on 2 sides, is there away to get the shadow on all four sides? Thanks, J ``` .contactBackground{ background-color:#FFF; padding:20px; box-shadow: 10px 10px 10px #000000; } ```
2012/10/10
[ "https://Stackoverflow.com/questions/12825324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1269625/" ]
If you set the offsets to zero, the shadow will be equal on all four sides. ``` .contactBackground{ background-color:#FFF; padding:20px; box-shadow: 0 0 10px #000000; } ```
Remove the offset definitions, and use only the blur radius (the third argument): ``` .contactBackground{ background-color: #fff; padding: 20px; box-shadow: 0 0 10px #000; } ```
12,825,324
I have this class here and I using box-shadow which works fine, but it only shows the shadow on 2 sides, is there away to get the shadow on all four sides? Thanks, J ``` .contactBackground{ background-color:#FFF; padding:20px; box-shadow: 10px 10px 10px #000000; } ```
2012/10/10
[ "https://Stackoverflow.com/questions/12825324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1269625/" ]
If you set the offsets to zero, the shadow will be equal on all four sides. ``` .contactBackground{ background-color:#FFF; padding:20px; box-shadow: 0 0 10px #000000; } ```
you need to specify box-shadow: 10px 10px 10px 10px BLACK; Right, Bottom, Left, Top or you could say box-shadow-top: 10px BLACK; etc
12,825,324
I have this class here and I using box-shadow which works fine, but it only shows the shadow on 2 sides, is there away to get the shadow on all four sides? Thanks, J ``` .contactBackground{ background-color:#FFF; padding:20px; box-shadow: 10px 10px 10px #000000; } ```
2012/10/10
[ "https://Stackoverflow.com/questions/12825324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1269625/" ]
If you set the offsets to zero, the shadow will be equal on all four sides. ``` .contactBackground{ background-color:#FFF; padding:20px; box-shadow: 0 0 10px #000000; } ```
Box-Shadow ---------- CSS3 box-shadow property has following attributes: ([W3Schools](http://www.w3schools.com/cssref/css3_pr_box-shadow.asp)) `box-shadow: h-shadow v-shadow blur spread color inset;` In your example you're offsetting shadow by 10px vertically and horizontally. Like in other comments set first two values to 0px in order to have even shadow on all sides. More on Shadows --------------- The main prefix for shadow to support latest browsers is `box-shadow`. There are 2 other ones that I recommend to use for older Mozilla and Webkit: * `-moz-box-shadow` * `-webkit-box-shadow` Also, by using `rgba` instead of hex color value you can set the alpha/opacity of the shadow: `box-shadow: 0px 0px 20px 10px rgba(0, 0, 0, 0.3);`
12,825,324
I have this class here and I using box-shadow which works fine, but it only shows the shadow on 2 sides, is there away to get the shadow on all four sides? Thanks, J ``` .contactBackground{ background-color:#FFF; padding:20px; box-shadow: 10px 10px 10px #000000; } ```
2012/10/10
[ "https://Stackoverflow.com/questions/12825324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1269625/" ]
If you set the offsets to zero, the shadow will be equal on all four sides. ``` .contactBackground{ background-color:#FFF; padding:20px; box-shadow: 0 0 10px #000000; } ```
Try: box-shadow: 0 0 10px 10px #000000;
12,825,324
I have this class here and I using box-shadow which works fine, but it only shows the shadow on 2 sides, is there away to get the shadow on all four sides? Thanks, J ``` .contactBackground{ background-color:#FFF; padding:20px; box-shadow: 10px 10px 10px #000000; } ```
2012/10/10
[ "https://Stackoverflow.com/questions/12825324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1269625/" ]
Remove the offset definitions, and use only the blur radius (the third argument): ``` .contactBackground{ background-color: #fff; padding: 20px; box-shadow: 0 0 10px #000; } ```
you need to specify box-shadow: 10px 10px 10px 10px BLACK; Right, Bottom, Left, Top or you could say box-shadow-top: 10px BLACK; etc
12,825,324
I have this class here and I using box-shadow which works fine, but it only shows the shadow on 2 sides, is there away to get the shadow on all four sides? Thanks, J ``` .contactBackground{ background-color:#FFF; padding:20px; box-shadow: 10px 10px 10px #000000; } ```
2012/10/10
[ "https://Stackoverflow.com/questions/12825324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1269625/" ]
Box-Shadow ---------- CSS3 box-shadow property has following attributes: ([W3Schools](http://www.w3schools.com/cssref/css3_pr_box-shadow.asp)) `box-shadow: h-shadow v-shadow blur spread color inset;` In your example you're offsetting shadow by 10px vertically and horizontally. Like in other comments set first two values to 0px in order to have even shadow on all sides. More on Shadows --------------- The main prefix for shadow to support latest browsers is `box-shadow`. There are 2 other ones that I recommend to use for older Mozilla and Webkit: * `-moz-box-shadow` * `-webkit-box-shadow` Also, by using `rgba` instead of hex color value you can set the alpha/opacity of the shadow: `box-shadow: 0px 0px 20px 10px rgba(0, 0, 0, 0.3);`
Remove the offset definitions, and use only the blur radius (the third argument): ``` .contactBackground{ background-color: #fff; padding: 20px; box-shadow: 0 0 10px #000; } ```
12,825,324
I have this class here and I using box-shadow which works fine, but it only shows the shadow on 2 sides, is there away to get the shadow on all four sides? Thanks, J ``` .contactBackground{ background-color:#FFF; padding:20px; box-shadow: 10px 10px 10px #000000; } ```
2012/10/10
[ "https://Stackoverflow.com/questions/12825324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1269625/" ]
Remove the offset definitions, and use only the blur radius (the third argument): ``` .contactBackground{ background-color: #fff; padding: 20px; box-shadow: 0 0 10px #000; } ```
Try: box-shadow: 0 0 10px 10px #000000;
12,825,324
I have this class here and I using box-shadow which works fine, but it only shows the shadow on 2 sides, is there away to get the shadow on all four sides? Thanks, J ``` .contactBackground{ background-color:#FFF; padding:20px; box-shadow: 10px 10px 10px #000000; } ```
2012/10/10
[ "https://Stackoverflow.com/questions/12825324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1269625/" ]
Box-Shadow ---------- CSS3 box-shadow property has following attributes: ([W3Schools](http://www.w3schools.com/cssref/css3_pr_box-shadow.asp)) `box-shadow: h-shadow v-shadow blur spread color inset;` In your example you're offsetting shadow by 10px vertically and horizontally. Like in other comments set first two values to 0px in order to have even shadow on all sides. More on Shadows --------------- The main prefix for shadow to support latest browsers is `box-shadow`. There are 2 other ones that I recommend to use for older Mozilla and Webkit: * `-moz-box-shadow` * `-webkit-box-shadow` Also, by using `rgba` instead of hex color value you can set the alpha/opacity of the shadow: `box-shadow: 0px 0px 20px 10px rgba(0, 0, 0, 0.3);`
you need to specify box-shadow: 10px 10px 10px 10px BLACK; Right, Bottom, Left, Top or you could say box-shadow-top: 10px BLACK; etc
12,825,324
I have this class here and I using box-shadow which works fine, but it only shows the shadow on 2 sides, is there away to get the shadow on all four sides? Thanks, J ``` .contactBackground{ background-color:#FFF; padding:20px; box-shadow: 10px 10px 10px #000000; } ```
2012/10/10
[ "https://Stackoverflow.com/questions/12825324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1269625/" ]
Try: box-shadow: 0 0 10px 10px #000000;
you need to specify box-shadow: 10px 10px 10px 10px BLACK; Right, Bottom, Left, Top or you could say box-shadow-top: 10px BLACK; etc
12,825,324
I have this class here and I using box-shadow which works fine, but it only shows the shadow on 2 sides, is there away to get the shadow on all four sides? Thanks, J ``` .contactBackground{ background-color:#FFF; padding:20px; box-shadow: 10px 10px 10px #000000; } ```
2012/10/10
[ "https://Stackoverflow.com/questions/12825324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1269625/" ]
Box-Shadow ---------- CSS3 box-shadow property has following attributes: ([W3Schools](http://www.w3schools.com/cssref/css3_pr_box-shadow.asp)) `box-shadow: h-shadow v-shadow blur spread color inset;` In your example you're offsetting shadow by 10px vertically and horizontally. Like in other comments set first two values to 0px in order to have even shadow on all sides. More on Shadows --------------- The main prefix for shadow to support latest browsers is `box-shadow`. There are 2 other ones that I recommend to use for older Mozilla and Webkit: * `-moz-box-shadow` * `-webkit-box-shadow` Also, by using `rgba` instead of hex color value you can set the alpha/opacity of the shadow: `box-shadow: 0px 0px 20px 10px rgba(0, 0, 0, 0.3);`
Try: box-shadow: 0 0 10px 10px #000000;
9,969,396
I'm in the middle of making a CMS and I am trying to find a WSYIWING like editors for CSS. Does anyone have any suggestions?
2012/04/01
[ "https://Stackoverflow.com/questions/9969396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/456850/" ]
In the past I have used [StyleMaster](http://westciv.com/style_master/). You should also take a look at [Espresso](http://macrabbit.com/espresso/). But in fact what I use nowadays is [COMPASS](http://compass-style.org/) which is not a GUI tool but a very smart CSS framework.
I believe he means a Javascript editor (would have posted as comment, can't do so yet) <http://jsfiddle.net/> Edit: If it is CSS, FF11 allows you to change the styles via Inspect Element -> Styles
9,969,396
I'm in the middle of making a CMS and I am trying to find a WSYIWING like editors for CSS. Does anyone have any suggestions?
2012/04/01
[ "https://Stackoverflow.com/questions/9969396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/456850/" ]
In the past I have used [StyleMaster](http://westciv.com/style_master/). You should also take a look at [Espresso](http://macrabbit.com/espresso/). But in fact what I use nowadays is [COMPASS](http://compass-style.org/) which is not a GUI tool but a very smart CSS framework.
You should check out <http://www.dockphp.com>.. It is still in development but does a pretty good job..
9,969,396
I'm in the middle of making a CMS and I am trying to find a WSYIWING like editors for CSS. Does anyone have any suggestions?
2012/04/01
[ "https://Stackoverflow.com/questions/9969396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/456850/" ]
In the past I have used [StyleMaster](http://westciv.com/style_master/). You should also take a look at [Espresso](http://macrabbit.com/espresso/). But in fact what I use nowadays is [COMPASS](http://compass-style.org/) which is not a GUI tool but a very smart CSS framework.
Rapid CSS is one the best. You can try it <http://www.rapidcsseditor.com/>
367,245
I have been trying for a few days to get a correct and working Unattended.xml answerfile for Windows 7. Trying to create a completely unattended install of Windows 7 to where a tech can insert USB drive, boot from it, and wait for the setup to complete. The image I am working from has already been sysprepped with the unattended answer file, and at every change since then. It is a time consuming process, because WDS/Server installs are not an option, only this method of pre-imaged USB devices. I have been all over technet, Serverfault (and other StackExchange sites), random blogs and such sites attempting different answerfile options that would (should/supposedly) create a completley unattended install. Using WSIM to manage/write/modify/check the answerfile and DISM to manage the image. Regardless of ANY options I put in WinPE pass, the following ALWAYS happens: * PE asks for language/locale/ * PE Displays EULA Agreement * PE Disk configuration always displays, prompting for partitioning **I need the setup to begin, process, and complete without asking the user ANYTHING** The most recent XML answerfile I have is as follows: ```xml <?xml version="1.0" encoding="utf-8"?> <unattend xmlns="urn:schemas-microsoft-com:unattend"> <settings pass="windowsPE"> <component name="Microsoft-Windows-International-Core-WinPE" processorArchitecture="x86" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <SetupUILanguage> <UILanguage>en-us</UILanguage> </SetupUILanguage> <UILanguage>en-us</UILanguage> <InputLocale>0409:00000409</InputLocale> <SystemLocale>en-us</SystemLocale> <UserLocale>en-us</UserLocale> </component> <component name="Microsoft-Windows-Setup" processorArchitecture="x86" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <DiskConfiguration> <WillShowUI>OnError</WillShowUI> <Disk wcm:action="add"> <DiskID>0</DiskID> <WillWipeDisk>true</WillWipeDisk> <CreatePartitions> <CreatePartition wcm:action="add"> <Order>1</Order> <Size>100</Size> <Type>Primary</Type> </CreatePartition> <CreatePartition wcm:action="add"> <Order>2</Order> <Type>Primary</Type> <Extend>true</Extend> </CreatePartition> </CreatePartitions> <ModifyPartitions> <ModifyPartition wcm:action="add"> <Format>NTFS</Format> <Label>System</Label> <Order>1</Order> <Active>true</Active> <PartitionID>1</PartitionID> </ModifyPartition> <ModifyPartition wcm:action="add"> <Format>NTFS</Format> <Label>OS</Label> <Order>2</Order> <PartitionID>2</PartitionID> </ModifyPartition> </ModifyPartitions> </Disk> </DiskConfiguration> <ImageInstall> <OSImage> <InstallTo> <DiskID>0</DiskID> <PartitionID>1</PartitionID> </InstallTo> <InstallFrom> <MetaData wcm:action="add"> <Key>/IMAGE/INDEX</Key> <Value>1</Value> </MetaData> </InstallFrom> <WillShowUI>OnError</WillShowUI> </OSImage> </ImageInstall> <UserData> <AcceptEula>true</AcceptEula> <ProductKey> <Key>----</Key> <WillShowUI>----</WillShowUI> </ProductKey> <FullName>----</FullName> <Organization>----</Organization> </UserData> </component> </settings> <settings pass="specialize"> <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="x86" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <CopyProfile>true</CopyProfile> <TimeZone>----</TimeZone> <ProductKey>----</ProductKey> <RegisteredOrganization>----</RegisteredOrganization> <RegisteredOwner>----</RegisteredOwner> </component> <component name="Microsoft-Windows-Deployment" processorArchitecture="x86" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <RunSynchronous> <RunSynchronousCommand wcm:action="add"> <Path>net user administrator /active:yes</Path> <Order>1</Order> </RunSynchronousCommand> </RunSynchronous> </component> <component name="Microsoft-Windows-International-Core" processorArchitecture="x86" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <InputLocale>0409:00000409</InputLocale> <SystemLocale>en-us</SystemLocale> <UILanguage>en-us</UILanguage> <UserLocale>en-us</UserLocale> </component> </settings> <settings pass="oobeSystem"> <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="x86" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <OOBE> <HideEULAPage>true</HideEULAPage> <NetworkLocation>Work</NetworkLocation> <ProtectYourPC>1</ProtectYourPC> <HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE> </OOBE> <RegisteredOrganization>----</RegisteredOrganization> <RegisteredOwner>----</RegisteredOwner> <TimeZone>TZ</TimeZone> <UserAccounts> <AdministratorPassword> <Value>aBcDe</Value> <PlainText>false</PlainText> </AdministratorPassword> <LocalAccounts> <LocalAccount wcm:action="add"> <Password> <Value>aBcDe</Value> <PlainText>false</PlainText> </Password> <Description>Local Administrator</Description> <DisplayName>Administrator</DisplayName> <Group>Administrators</Group> <Name>Administrator</Name> </LocalAccount> </LocalAccounts> </UserAccounts> <AutoLogon> <Password> <Value>aBCdE</Value> <PlainText>false</PlainText> </Password> <Enabled>true</Enabled> <LogonCount>5</LogonCount> <Username>administrator</Username> <Domain></Domain> </AutoLogon> </component> <component name="Microsoft-Windows-International-Core" processorArchitecture="x86" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <InputLocale>0409:00000409</InputLocale> <SystemLocale>en-us</SystemLocale> <UserLocale>en-us</UserLocale> <UILanguage>en-us</UILanguage> </component> </settings> <cpi:offlineImage cpi:source="wim:wimfile#Windows 7 Professional" xmlns:cpi="urn:schemas-microsoft-com:cpi" /> </unattend> ``` Does anyone else have experience with such a situation occurring, or know how to correct my answerfile so that it truly becomes unattended?
2012/03/07
[ "https://serverfault.com/questions/367245", "https://serverfault.com", "https://serverfault.com/users/111505/" ]
CNAME resource records specify a domain as an alias of another canonical domain name. As such, it cannot point to an IP address. A and AAAA records define the canonical name and point to IP addresses. CNAMEs must reference those. Create an A record for `allehotelsinparijs.nl` that points to `79.125.111.73`. Then create a CNAME record for `www.allehotelsinparijs.nl` that points to `allehotelsinparijs.nl`. Then in your webserver on the EC2 server, create a vhost for `allehotelsinparijs.nl` that does a 301 redirect to www.allehotelsinparijs.nl. Details of how to do this are out of scope for this question, but there are many examples to be found here on Serverfault and elsewhere.
You may prefer to make the CNAME point to the AMAZON Elastic IP's DNS name. eg. allehotelsinparijs.nl as CNAME to ec2-79-125-111-73.compute-1.amazonaws.com (may NOT be the actual amazon hostname) The benefit from doing this is that externally your hostname will resolve to a public IP, but internal to Amazon, it will resolve to an PRIVTE IP for your instance. (this will make calls to your site more direct and possibly cheaper when inside AWS)
8,503,799
Is there any NON-GPL ADO.NET provider for MySQL ? There is the official one from here <http://dev.mysql.com/downloads/connector/net> but unfortunately, it's under the GPL, not the LGPL. I am developing an abstract class for database access. I don't care whether the abstraction layer is going to be GPL, but if it uses MySQL (I mean the MySQL ADO.NET provider, not the MySQL database itselfs) it will be GPL, and thus, any application that uses that layer, which is something I don't want... Oh, and I know about nHibernate/Subsonic/otherORMs, but it doesn't fit my needs. ADO.NET provider short of using ODBC of course. **Edit/Clarification:** Note that by "abstract class for database access", I don't mean write my own universal ADO.NET provider. I mean writing a wrapper class around a set of already existing ADO.NET providers.
2011/12/14
[ "https://Stackoverflow.com/questions/8503799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/155077/" ]
There is DevArt's ADO.NET provider for MySQL <http://www.devart.com/dotconnect/mysql/>
Stop swallowing the Microsoft FUD. This is covered by v2 of the GPL therefore, unless you intend to modify the supplied code and redistribute it (as opposed to bundling it with your own application) your only constrained in that you need to state that the bundle includes GPL v2.0 licensed code and reference the copyright owner (which you are nearly always required to do with most commercially licensed software anyway).
8,503,799
Is there any NON-GPL ADO.NET provider for MySQL ? There is the official one from here <http://dev.mysql.com/downloads/connector/net> but unfortunately, it's under the GPL, not the LGPL. I am developing an abstract class for database access. I don't care whether the abstraction layer is going to be GPL, but if it uses MySQL (I mean the MySQL ADO.NET provider, not the MySQL database itselfs) it will be GPL, and thus, any application that uses that layer, which is something I don't want... Oh, and I know about nHibernate/Subsonic/otherORMs, but it doesn't fit my needs. ADO.NET provider short of using ODBC of course. **Edit/Clarification:** Note that by "abstract class for database access", I don't mean write my own universal ADO.NET provider. I mean writing a wrapper class around a set of already existing ADO.NET providers.
2011/12/14
[ "https://Stackoverflow.com/questions/8503799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/155077/" ]
I got the perfect answer: One can use `System.Data.Odbc` to get around it. You can always say, it's generic ODBC, has nothing in particular to do with MySQL, easily replacable. And whatever you put in the connection string is the problem of your customers. If the SQL that you send over the ODBC connection works in MySQL/MariaDB only, that's regrettable - but no legal problem ;) **Edit - 2016 Update:** You can use the MIT-licensed MySqlConnector for .NET Core (which also works for .NET) <https://github.com/mysql-net/MySqlConnector>
Stop swallowing the Microsoft FUD. This is covered by v2 of the GPL therefore, unless you intend to modify the supplied code and redistribute it (as opposed to bundling it with your own application) your only constrained in that you need to state that the bundle includes GPL v2.0 licensed code and reference the copyright owner (which you are nearly always required to do with most commercially licensed software anyway).
8,503,799
Is there any NON-GPL ADO.NET provider for MySQL ? There is the official one from here <http://dev.mysql.com/downloads/connector/net> but unfortunately, it's under the GPL, not the LGPL. I am developing an abstract class for database access. I don't care whether the abstraction layer is going to be GPL, but if it uses MySQL (I mean the MySQL ADO.NET provider, not the MySQL database itselfs) it will be GPL, and thus, any application that uses that layer, which is something I don't want... Oh, and I know about nHibernate/Subsonic/otherORMs, but it doesn't fit my needs. ADO.NET provider short of using ODBC of course. **Edit/Clarification:** Note that by "abstract class for database access", I don't mean write my own universal ADO.NET provider. I mean writing a wrapper class around a set of already existing ADO.NET providers.
2011/12/14
[ "https://Stackoverflow.com/questions/8503799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/155077/" ]
There is DevArt's ADO.NET provider for MySQL <http://www.devart.com/dotconnect/mysql/>
> > but if it uses MySQL it will be GPL > > > Ah - no. You can program it ina way it does not even KNOW it connects to MySql. * Isolate all abstractions into a separate assembly. * Implement your propietary interfaces in this (allowed). * Distribute the abstraction of mySql as gpl. Finished.
8,503,799
Is there any NON-GPL ADO.NET provider for MySQL ? There is the official one from here <http://dev.mysql.com/downloads/connector/net> but unfortunately, it's under the GPL, not the LGPL. I am developing an abstract class for database access. I don't care whether the abstraction layer is going to be GPL, but if it uses MySQL (I mean the MySQL ADO.NET provider, not the MySQL database itselfs) it will be GPL, and thus, any application that uses that layer, which is something I don't want... Oh, and I know about nHibernate/Subsonic/otherORMs, but it doesn't fit my needs. ADO.NET provider short of using ODBC of course. **Edit/Clarification:** Note that by "abstract class for database access", I don't mean write my own universal ADO.NET provider. I mean writing a wrapper class around a set of already existing ADO.NET providers.
2011/12/14
[ "https://Stackoverflow.com/questions/8503799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/155077/" ]
I got the perfect answer: One can use `System.Data.Odbc` to get around it. You can always say, it's generic ODBC, has nothing in particular to do with MySQL, easily replacable. And whatever you put in the connection string is the problem of your customers. If the SQL that you send over the ODBC connection works in MySQL/MariaDB only, that's regrettable - but no legal problem ;) **Edit - 2016 Update:** You can use the MIT-licensed MySqlConnector for .NET Core (which also works for .NET) <https://github.com/mysql-net/MySqlConnector>
> > but if it uses MySQL it will be GPL > > > Ah - no. You can program it ina way it does not even KNOW it connects to MySql. * Isolate all abstractions into a separate assembly. * Implement your propietary interfaces in this (allowed). * Distribute the abstraction of mySql as gpl. Finished.
8,503,799
Is there any NON-GPL ADO.NET provider for MySQL ? There is the official one from here <http://dev.mysql.com/downloads/connector/net> but unfortunately, it's under the GPL, not the LGPL. I am developing an abstract class for database access. I don't care whether the abstraction layer is going to be GPL, but if it uses MySQL (I mean the MySQL ADO.NET provider, not the MySQL database itselfs) it will be GPL, and thus, any application that uses that layer, which is something I don't want... Oh, and I know about nHibernate/Subsonic/otherORMs, but it doesn't fit my needs. ADO.NET provider short of using ODBC of course. **Edit/Clarification:** Note that by "abstract class for database access", I don't mean write my own universal ADO.NET provider. I mean writing a wrapper class around a set of already existing ADO.NET providers.
2011/12/14
[ "https://Stackoverflow.com/questions/8503799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/155077/" ]
I got the perfect answer: One can use `System.Data.Odbc` to get around it. You can always say, it's generic ODBC, has nothing in particular to do with MySQL, easily replacable. And whatever you put in the connection string is the problem of your customers. If the SQL that you send over the ODBC connection works in MySQL/MariaDB only, that's regrettable - but no legal problem ;) **Edit - 2016 Update:** You can use the MIT-licensed MySqlConnector for .NET Core (which also works for .NET) <https://github.com/mysql-net/MySqlConnector>
There is DevArt's ADO.NET provider for MySQL <http://www.devart.com/dotconnect/mysql/>
28,927,404
I noticed in that to disable the highlight feature of a table cell you would yse the following method: ``` override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { ... tableView.deselectRowAtIndexPath(indexPath, animated: false) } ``` What I don't understand is what's going on in the first argument `indexPath`. In the instructional book I've been reading just about every other method has been using `indexPath.row` for selecting individual cells: ``` override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "Cell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as CustomTableViewCell cell.nameLabel.text = restaurantNames[indexPath.row] cell.typeLabel.text = restaurantTypes[indexPath.row] cell.locationLabel.text = restaurantLocations[indexPath.row] } ``` Just out of curiosity I tried passing `indexPath.row` as an argument but got the error, `'NSNumber' is not a subtype of 'NSIndexPath'`. In this particular case what is the main difference between using `indexPath` and `indexPath.row`.
2015/03/08
[ "https://Stackoverflow.com/questions/28927404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3046413/" ]
From the [NSIndexPath](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSIndexPath_Class/) class reference: > > The `NSIndexPath` class represents the path to a specific node in a tree > of nested array collections. This path is known as an **index path**. > > > Table views (and collection views) use `NSIndexPath` to index their items because they are nested structures (sections and rows). The first index is the *section* of the tableview and the second index the *row* within a section. `indexPath.section` and `indexPath.row` are just a "convenience" properties, you always have ``` indexPath.section == indexPath.indexAtPosition(0) indexPath.row == indexPath.indexAtPosition(1) ``` They are documented in [NSIndexPath UIKit Additions](https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/NSIndexPath_UIKitAdditions/index.html). So `NSIndexPath` is an Objective-C class and is used by all table view functions. The `section` and `row` property are `NSInteger` numbers. (Therefore you cannot pass `indexPath.row` if an `NSIndexPath` is expected.) For a table view without sections (`UITableViewStyle.Plain`) the section is always zero, and `indexPath.row` is the row number of an item (in the one and only section). In that case you can use `indexPath.row` to index an array acting as table view data source: ``` cell.nameLabel.text = restaurantNames[indexPath.row] ``` For a table view with sections (`UITableViewStyle.Grouped`) you have to use both `indexPath.section` and `indexPath.row` (as in this example: [What would be a good data structure for UITableView in grouped mode](https://stackoverflow.com/questions/20216902/what-would-be-a-good-data-structure-for-uitableview-in-grouped-mode)). --- A *better way* to disable the selection of particular table view rows is to override the `willSelectRowAtIndexPath` delegate method: ``` override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { // return `indexPath` if selecting the row is permitted // return `nil` otherwise } ``` In addition, to disable the appearance of the cell highlight on touch-down, you can also set ``` cell.selectionStyle = .None ``` when creating the cell. All this is (for example) discussed in [UITableview: How to Disable Selection for Some Rows but Not Others](https://stackoverflow.com/questions/2267993/uitableview-how-to-disable-selection-for-some-rows-but-not-others).
NSIndexPath is an object comprised of two NSIntegers. It's original use was for paths to nodes in a tree, where the two integers represented indexes and length. But a different (and perhaps more frequent) use for this object is to refer to elements of a UITable. In that situation, there are two NSIntegers in each NSIndexPath: `indexPath.row` and `indexPath.section`. These conveniently identify the section of a UITableView and it's row. (Absent from the original definition of NSIndexPath, `row` and `section` are category extensions to it). Check out tables with ***multiple sections*** and you'll see why an NSIndexPath (with two dimensions) is a more general way to reference a UITableView element than just a one-dimensional row number.
28,927,404
I noticed in that to disable the highlight feature of a table cell you would yse the following method: ``` override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { ... tableView.deselectRowAtIndexPath(indexPath, animated: false) } ``` What I don't understand is what's going on in the first argument `indexPath`. In the instructional book I've been reading just about every other method has been using `indexPath.row` for selecting individual cells: ``` override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "Cell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as CustomTableViewCell cell.nameLabel.text = restaurantNames[indexPath.row] cell.typeLabel.text = restaurantTypes[indexPath.row] cell.locationLabel.text = restaurantLocations[indexPath.row] } ``` Just out of curiosity I tried passing `indexPath.row` as an argument but got the error, `'NSNumber' is not a subtype of 'NSIndexPath'`. In this particular case what is the main difference between using `indexPath` and `indexPath.row`.
2015/03/08
[ "https://Stackoverflow.com/questions/28927404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3046413/" ]
From the [NSIndexPath](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSIndexPath_Class/) class reference: > > The `NSIndexPath` class represents the path to a specific node in a tree > of nested array collections. This path is known as an **index path**. > > > Table views (and collection views) use `NSIndexPath` to index their items because they are nested structures (sections and rows). The first index is the *section* of the tableview and the second index the *row* within a section. `indexPath.section` and `indexPath.row` are just a "convenience" properties, you always have ``` indexPath.section == indexPath.indexAtPosition(0) indexPath.row == indexPath.indexAtPosition(1) ``` They are documented in [NSIndexPath UIKit Additions](https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/NSIndexPath_UIKitAdditions/index.html). So `NSIndexPath` is an Objective-C class and is used by all table view functions. The `section` and `row` property are `NSInteger` numbers. (Therefore you cannot pass `indexPath.row` if an `NSIndexPath` is expected.) For a table view without sections (`UITableViewStyle.Plain`) the section is always zero, and `indexPath.row` is the row number of an item (in the one and only section). In that case you can use `indexPath.row` to index an array acting as table view data source: ``` cell.nameLabel.text = restaurantNames[indexPath.row] ``` For a table view with sections (`UITableViewStyle.Grouped`) you have to use both `indexPath.section` and `indexPath.row` (as in this example: [What would be a good data structure for UITableView in grouped mode](https://stackoverflow.com/questions/20216902/what-would-be-a-good-data-structure-for-uitableview-in-grouped-mode)). --- A *better way* to disable the selection of particular table view rows is to override the `willSelectRowAtIndexPath` delegate method: ``` override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { // return `indexPath` if selecting the row is permitted // return `nil` otherwise } ``` In addition, to disable the appearance of the cell highlight on touch-down, you can also set ``` cell.selectionStyle = .None ``` when creating the cell. All this is (for example) discussed in [UITableview: How to Disable Selection for Some Rows but Not Others](https://stackoverflow.com/questions/2267993/uitableview-how-to-disable-selection-for-some-rows-but-not-others).
i see the perfect answer is from apple doc <https://developer.apple.com/documentation/uikit/uitableview/1614881-indexpath> if you print indexpath you may get [0,0] which is first item in the first section
28,927,404
I noticed in that to disable the highlight feature of a table cell you would yse the following method: ``` override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { ... tableView.deselectRowAtIndexPath(indexPath, animated: false) } ``` What I don't understand is what's going on in the first argument `indexPath`. In the instructional book I've been reading just about every other method has been using `indexPath.row` for selecting individual cells: ``` override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "Cell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as CustomTableViewCell cell.nameLabel.text = restaurantNames[indexPath.row] cell.typeLabel.text = restaurantTypes[indexPath.row] cell.locationLabel.text = restaurantLocations[indexPath.row] } ``` Just out of curiosity I tried passing `indexPath.row` as an argument but got the error, `'NSNumber' is not a subtype of 'NSIndexPath'`. In this particular case what is the main difference between using `indexPath` and `indexPath.row`.
2015/03/08
[ "https://Stackoverflow.com/questions/28927404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3046413/" ]
From the [NSIndexPath](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSIndexPath_Class/) class reference: > > The `NSIndexPath` class represents the path to a specific node in a tree > of nested array collections. This path is known as an **index path**. > > > Table views (and collection views) use `NSIndexPath` to index their items because they are nested structures (sections and rows). The first index is the *section* of the tableview and the second index the *row* within a section. `indexPath.section` and `indexPath.row` are just a "convenience" properties, you always have ``` indexPath.section == indexPath.indexAtPosition(0) indexPath.row == indexPath.indexAtPosition(1) ``` They are documented in [NSIndexPath UIKit Additions](https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/NSIndexPath_UIKitAdditions/index.html). So `NSIndexPath` is an Objective-C class and is used by all table view functions. The `section` and `row` property are `NSInteger` numbers. (Therefore you cannot pass `indexPath.row` if an `NSIndexPath` is expected.) For a table view without sections (`UITableViewStyle.Plain`) the section is always zero, and `indexPath.row` is the row number of an item (in the one and only section). In that case you can use `indexPath.row` to index an array acting as table view data source: ``` cell.nameLabel.text = restaurantNames[indexPath.row] ``` For a table view with sections (`UITableViewStyle.Grouped`) you have to use both `indexPath.section` and `indexPath.row` (as in this example: [What would be a good data structure for UITableView in grouped mode](https://stackoverflow.com/questions/20216902/what-would-be-a-good-data-structure-for-uitableview-in-grouped-mode)). --- A *better way* to disable the selection of particular table view rows is to override the `willSelectRowAtIndexPath` delegate method: ``` override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { // return `indexPath` if selecting the row is permitted // return `nil` otherwise } ``` In addition, to disable the appearance of the cell highlight on touch-down, you can also set ``` cell.selectionStyle = .None ``` when creating the cell. All this is (for example) discussed in [UITableview: How to Disable Selection for Some Rows but Not Others](https://stackoverflow.com/questions/2267993/uitableview-how-to-disable-selection-for-some-rows-but-not-others).
I was confused between indexPath and indexPath.row until i understand that the concept is the same for the TableView and the CollectionView. ``` indexPath : [0, 2] indexPath.section : 0 indexPath.row : 2 // indexPath : the whole object (array) indexPath.section : refers to the section (first item in the array) indexPath.row : refers to the selected item in the section (second item in the array) ``` Sometimes, you may need to pass the whole object (indexPath).
28,927,404
I noticed in that to disable the highlight feature of a table cell you would yse the following method: ``` override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { ... tableView.deselectRowAtIndexPath(indexPath, animated: false) } ``` What I don't understand is what's going on in the first argument `indexPath`. In the instructional book I've been reading just about every other method has been using `indexPath.row` for selecting individual cells: ``` override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "Cell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as CustomTableViewCell cell.nameLabel.text = restaurantNames[indexPath.row] cell.typeLabel.text = restaurantTypes[indexPath.row] cell.locationLabel.text = restaurantLocations[indexPath.row] } ``` Just out of curiosity I tried passing `indexPath.row` as an argument but got the error, `'NSNumber' is not a subtype of 'NSIndexPath'`. In this particular case what is the main difference between using `indexPath` and `indexPath.row`.
2015/03/08
[ "https://Stackoverflow.com/questions/28927404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3046413/" ]
Your question and confusion stems from the fact that Apple decided to use somewhat imprecise method name/signature ``` tableView.deselectRowAtIndexPath(indexPath, animated: false) ``` The "Row" word in the method signature implies that row is going to be deselected, therefore one would expect a row as a method parameter. But a table view **can have more than one section**. But, in case it doesn't have more sections, the whole table view is considered one section. So to deselect a row (a cell really) in table view, we need to tell both which section and which row (even in case of having only one section). And this is bundled together in the indexPath object you pass as a parameter. So the before-mentioned method might instead have a signature ``` tableView.deselectCellAtIndexPath(indexPath, animated: false) ``` which would be more consistent, or another option, albeit a bit less semantically solid (in terms of parameters matching the signature) ``` tableView.deselectRowInSectionAtIndexPath(indexPath, animated: false) ``` --- Now the other case - when you implement the delegate method ``` tableview:cellForRowAtIndexPath ``` here again (Apple, Apple...) the signature is not completely precise. They could have chose a more consistent method signature, for example ``` tableview:cellForIndexPath: ``` but Apple decided to **stress the fact that we are dealing with rows**. This is an 8 year old API that was never the most shining work of Apple in UIKit, so it's understandable. I don't have statistical data, but I believe having a single section (the whole tableview is one section) is the dominant approach in apps that use a table view, so you don't deal with the sections explicitly, and **work only with the row value** inside the delegate method. The row often serves as index to retrieve some model object or other data to be put into cell. Nevertheless the section value is **still there**. You can check this anytime, the passed indexPath will show the section value for you when you inspect it.
NSIndexPath is an object comprised of two NSIntegers. It's original use was for paths to nodes in a tree, where the two integers represented indexes and length. But a different (and perhaps more frequent) use for this object is to refer to elements of a UITable. In that situation, there are two NSIntegers in each NSIndexPath: `indexPath.row` and `indexPath.section`. These conveniently identify the section of a UITableView and it's row. (Absent from the original definition of NSIndexPath, `row` and `section` are category extensions to it). Check out tables with ***multiple sections*** and you'll see why an NSIndexPath (with two dimensions) is a more general way to reference a UITableView element than just a one-dimensional row number.
28,927,404
I noticed in that to disable the highlight feature of a table cell you would yse the following method: ``` override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { ... tableView.deselectRowAtIndexPath(indexPath, animated: false) } ``` What I don't understand is what's going on in the first argument `indexPath`. In the instructional book I've been reading just about every other method has been using `indexPath.row` for selecting individual cells: ``` override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "Cell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as CustomTableViewCell cell.nameLabel.text = restaurantNames[indexPath.row] cell.typeLabel.text = restaurantTypes[indexPath.row] cell.locationLabel.text = restaurantLocations[indexPath.row] } ``` Just out of curiosity I tried passing `indexPath.row` as an argument but got the error, `'NSNumber' is not a subtype of 'NSIndexPath'`. In this particular case what is the main difference between using `indexPath` and `indexPath.row`.
2015/03/08
[ "https://Stackoverflow.com/questions/28927404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3046413/" ]
Your question and confusion stems from the fact that Apple decided to use somewhat imprecise method name/signature ``` tableView.deselectRowAtIndexPath(indexPath, animated: false) ``` The "Row" word in the method signature implies that row is going to be deselected, therefore one would expect a row as a method parameter. But a table view **can have more than one section**. But, in case it doesn't have more sections, the whole table view is considered one section. So to deselect a row (a cell really) in table view, we need to tell both which section and which row (even in case of having only one section). And this is bundled together in the indexPath object you pass as a parameter. So the before-mentioned method might instead have a signature ``` tableView.deselectCellAtIndexPath(indexPath, animated: false) ``` which would be more consistent, or another option, albeit a bit less semantically solid (in terms of parameters matching the signature) ``` tableView.deselectRowInSectionAtIndexPath(indexPath, animated: false) ``` --- Now the other case - when you implement the delegate method ``` tableview:cellForRowAtIndexPath ``` here again (Apple, Apple...) the signature is not completely precise. They could have chose a more consistent method signature, for example ``` tableview:cellForIndexPath: ``` but Apple decided to **stress the fact that we are dealing with rows**. This is an 8 year old API that was never the most shining work of Apple in UIKit, so it's understandable. I don't have statistical data, but I believe having a single section (the whole tableview is one section) is the dominant approach in apps that use a table view, so you don't deal with the sections explicitly, and **work only with the row value** inside the delegate method. The row often serves as index to retrieve some model object or other data to be put into cell. Nevertheless the section value is **still there**. You can check this anytime, the passed indexPath will show the section value for you when you inspect it.
i see the perfect answer is from apple doc <https://developer.apple.com/documentation/uikit/uitableview/1614881-indexpath> if you print indexpath you may get [0,0] which is first item in the first section
28,927,404
I noticed in that to disable the highlight feature of a table cell you would yse the following method: ``` override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { ... tableView.deselectRowAtIndexPath(indexPath, animated: false) } ``` What I don't understand is what's going on in the first argument `indexPath`. In the instructional book I've been reading just about every other method has been using `indexPath.row` for selecting individual cells: ``` override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "Cell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as CustomTableViewCell cell.nameLabel.text = restaurantNames[indexPath.row] cell.typeLabel.text = restaurantTypes[indexPath.row] cell.locationLabel.text = restaurantLocations[indexPath.row] } ``` Just out of curiosity I tried passing `indexPath.row` as an argument but got the error, `'NSNumber' is not a subtype of 'NSIndexPath'`. In this particular case what is the main difference between using `indexPath` and `indexPath.row`.
2015/03/08
[ "https://Stackoverflow.com/questions/28927404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3046413/" ]
Your question and confusion stems from the fact that Apple decided to use somewhat imprecise method name/signature ``` tableView.deselectRowAtIndexPath(indexPath, animated: false) ``` The "Row" word in the method signature implies that row is going to be deselected, therefore one would expect a row as a method parameter. But a table view **can have more than one section**. But, in case it doesn't have more sections, the whole table view is considered one section. So to deselect a row (a cell really) in table view, we need to tell both which section and which row (even in case of having only one section). And this is bundled together in the indexPath object you pass as a parameter. So the before-mentioned method might instead have a signature ``` tableView.deselectCellAtIndexPath(indexPath, animated: false) ``` which would be more consistent, or another option, albeit a bit less semantically solid (in terms of parameters matching the signature) ``` tableView.deselectRowInSectionAtIndexPath(indexPath, animated: false) ``` --- Now the other case - when you implement the delegate method ``` tableview:cellForRowAtIndexPath ``` here again (Apple, Apple...) the signature is not completely precise. They could have chose a more consistent method signature, for example ``` tableview:cellForIndexPath: ``` but Apple decided to **stress the fact that we are dealing with rows**. This is an 8 year old API that was never the most shining work of Apple in UIKit, so it's understandable. I don't have statistical data, but I believe having a single section (the whole tableview is one section) is the dominant approach in apps that use a table view, so you don't deal with the sections explicitly, and **work only with the row value** inside the delegate method. The row often serves as index to retrieve some model object or other data to be put into cell. Nevertheless the section value is **still there**. You can check this anytime, the passed indexPath will show the section value for you when you inspect it.
I was confused between indexPath and indexPath.row until i understand that the concept is the same for the TableView and the CollectionView. ``` indexPath : [0, 2] indexPath.section : 0 indexPath.row : 2 // indexPath : the whole object (array) indexPath.section : refers to the section (first item in the array) indexPath.row : refers to the selected item in the section (second item in the array) ``` Sometimes, you may need to pass the whole object (indexPath).
440,680
At lunch a coworker was talking about how to calculate, say, the 100th digit of pi using a square around the circle, then a pentagon, etc, basically you end up taking the limit of the circumference as the number of sides n goes to infinity. So I tried working out the math, but I got stuck at proving: $$\lim\_{n \to \infty} 2n\tan\frac{\pi}{n} = 2 \pi$$ Any ideas how?
2013/07/10
[ "https://math.stackexchange.com/questions/440680", "https://math.stackexchange.com", "https://math.stackexchange.com/users/85781/" ]
Putting $n=\frac1h, h\to0$ as $n\to\infty$ $$\lim\_{n \to \infty} 2n\cdot\tan\frac{\pi}{n}$$ $$=2\lim\_{h\to0}\frac{\tan \pi h}h$$ $$=2\pi\lim\_{h\to0}\frac{\sin \pi h}{\pi h}\cdot \frac1{\lim\_{h\to0}\cos\pi h}$$ We know, $\lim\_{x\to0}\frac{\sin x}x=1$ and $\lim\_{x\to0}\cos x=1$
> > $\lim\_{n \to \infty} 2n(tan\frac{\pi}{n}) = \lim\_{n \to \infty} 2\pi \frac{\tan \frac{\pi}{n}}{\frac{\pi}{n}}=\lim\_{x\to 0}2\pi \frac{\tan x}{x}= 2\pi$ > > >
440,680
At lunch a coworker was talking about how to calculate, say, the 100th digit of pi using a square around the circle, then a pentagon, etc, basically you end up taking the limit of the circumference as the number of sides n goes to infinity. So I tried working out the math, but I got stuck at proving: $$\lim\_{n \to \infty} 2n\tan\frac{\pi}{n} = 2 \pi$$ Any ideas how?
2013/07/10
[ "https://math.stackexchange.com/questions/440680", "https://math.stackexchange.com", "https://math.stackexchange.com/users/85781/" ]
Putting $n=\frac1h, h\to0$ as $n\to\infty$ $$\lim\_{n \to \infty} 2n\cdot\tan\frac{\pi}{n}$$ $$=2\lim\_{h\to0}\frac{\tan \pi h}h$$ $$=2\pi\lim\_{h\to0}\frac{\sin \pi h}{\pi h}\cdot \frac1{\lim\_{h\to0}\cos\pi h}$$ We know, $\lim\_{x\to0}\frac{\sin x}x=1$ and $\lim\_{x\to0}\cos x=1$
From Taylor series we know that $$\tan x=\_0x +o(x)$$ and if $y\to+\infty$ then $\frac{x}{y}\to 0$ hence we have $$\tan\left(\frac{x}{y}\right)y=\_\infty\left(\frac{x}{y}+o\left(\frac{x}{y}\right)\right)y=\_\infty x+o(1)$$ so we can conclude.
440,680
At lunch a coworker was talking about how to calculate, say, the 100th digit of pi using a square around the circle, then a pentagon, etc, basically you end up taking the limit of the circumference as the number of sides n goes to infinity. So I tried working out the math, but I got stuck at proving: $$\lim\_{n \to \infty} 2n\tan\frac{\pi}{n} = 2 \pi$$ Any ideas how?
2013/07/10
[ "https://math.stackexchange.com/questions/440680", "https://math.stackexchange.com", "https://math.stackexchange.com/users/85781/" ]
Putting $n=\frac1h, h\to0$ as $n\to\infty$ $$\lim\_{n \to \infty} 2n\cdot\tan\frac{\pi}{n}$$ $$=2\lim\_{h\to0}\frac{\tan \pi h}h$$ $$=2\pi\lim\_{h\to0}\frac{\sin \pi h}{\pi h}\cdot \frac1{\lim\_{h\to0}\cos\pi h}$$ We know, $\lim\_{x\to0}\frac{\sin x}x=1$ and $\lim\_{x\to0}\cos x=1$
As shown in [this answer](https://math.stackexchange.com/a/75151), $$ \lim\_{x\to0}\frac{\tan(x)}{x}=1\tag{1} $$ For $x\ne0$, $(1)$ is equivalent to $$ \lim\_{y\to\infty}\frac{\tan(x/y)}{x/y}=1\tag{2} $$ multiplying $(2)$ by $x$ yields $$ \lim\_{y\to\infty}y\tan(x/y)=x\tag{3} $$ The case $x=0$ is verified trivially.
440,680
At lunch a coworker was talking about how to calculate, say, the 100th digit of pi using a square around the circle, then a pentagon, etc, basically you end up taking the limit of the circumference as the number of sides n goes to infinity. So I tried working out the math, but I got stuck at proving: $$\lim\_{n \to \infty} 2n\tan\frac{\pi}{n} = 2 \pi$$ Any ideas how?
2013/07/10
[ "https://math.stackexchange.com/questions/440680", "https://math.stackexchange.com", "https://math.stackexchange.com/users/85781/" ]
From Taylor series we know that $$\tan x=\_0x +o(x)$$ and if $y\to+\infty$ then $\frac{x}{y}\to 0$ hence we have $$\tan\left(\frac{x}{y}\right)y=\_\infty\left(\frac{x}{y}+o\left(\frac{x}{y}\right)\right)y=\_\infty x+o(1)$$ so we can conclude.
> > $\lim\_{n \to \infty} 2n(tan\frac{\pi}{n}) = \lim\_{n \to \infty} 2\pi \frac{\tan \frac{\pi}{n}}{\frac{\pi}{n}}=\lim\_{x\to 0}2\pi \frac{\tan x}{x}= 2\pi$ > > >
440,680
At lunch a coworker was talking about how to calculate, say, the 100th digit of pi using a square around the circle, then a pentagon, etc, basically you end up taking the limit of the circumference as the number of sides n goes to infinity. So I tried working out the math, but I got stuck at proving: $$\lim\_{n \to \infty} 2n\tan\frac{\pi}{n} = 2 \pi$$ Any ideas how?
2013/07/10
[ "https://math.stackexchange.com/questions/440680", "https://math.stackexchange.com", "https://math.stackexchange.com/users/85781/" ]
As shown in [this answer](https://math.stackexchange.com/a/75151), $$ \lim\_{x\to0}\frac{\tan(x)}{x}=1\tag{1} $$ For $x\ne0$, $(1)$ is equivalent to $$ \lim\_{y\to\infty}\frac{\tan(x/y)}{x/y}=1\tag{2} $$ multiplying $(2)$ by $x$ yields $$ \lim\_{y\to\infty}y\tan(x/y)=x\tag{3} $$ The case $x=0$ is verified trivially.
> > $\lim\_{n \to \infty} 2n(tan\frac{\pi}{n}) = \lim\_{n \to \infty} 2\pi \frac{\tan \frac{\pi}{n}}{\frac{\pi}{n}}=\lim\_{x\to 0}2\pi \frac{\tan x}{x}= 2\pi$ > > >
440,680
At lunch a coworker was talking about how to calculate, say, the 100th digit of pi using a square around the circle, then a pentagon, etc, basically you end up taking the limit of the circumference as the number of sides n goes to infinity. So I tried working out the math, but I got stuck at proving: $$\lim\_{n \to \infty} 2n\tan\frac{\pi}{n} = 2 \pi$$ Any ideas how?
2013/07/10
[ "https://math.stackexchange.com/questions/440680", "https://math.stackexchange.com", "https://math.stackexchange.com/users/85781/" ]
From Taylor series we know that $$\tan x=\_0x +o(x)$$ and if $y\to+\infty$ then $\frac{x}{y}\to 0$ hence we have $$\tan\left(\frac{x}{y}\right)y=\_\infty\left(\frac{x}{y}+o\left(\frac{x}{y}\right)\right)y=\_\infty x+o(1)$$ so we can conclude.
As shown in [this answer](https://math.stackexchange.com/a/75151), $$ \lim\_{x\to0}\frac{\tan(x)}{x}=1\tag{1} $$ For $x\ne0$, $(1)$ is equivalent to $$ \lim\_{y\to\infty}\frac{\tan(x/y)}{x/y}=1\tag{2} $$ multiplying $(2)$ by $x$ yields $$ \lim\_{y\to\infty}y\tan(x/y)=x\tag{3} $$ The case $x=0$ is verified trivially.
8,518,902
I'm trying to create a node (content type: song) using a form. I can set the tile/description, but when it comes to upload a file, I get this error: ``` PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'field_file1_display' cannot be null: INSERT INTO {field_data_field_file1} (entity_type, entity_id, revision_id, bundle, delta, language, field_file1_fid, field_file1_display, field_file1_description) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8); Array ( [:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 67 [:db_insert_placeholder_2] => 67 [:db_insert_placeholder_3] => song [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und [:db_insert_placeholder_6] => 55 [:db_insert_placeholder_7] => [:db_insert_placeholder_8] => ) in field_sql_storage_field_storage_write() (line 448 of /Users/blabla/_server/drupal/modules/field/modules/field_sql_storage/field_sql_storage.module). ``` This is the code I wrote. ``` function insertnode_form_submit($form, &$form_state) { $node = new StdClass(); $node->type = 'song'; $node->status = 1; $node->language = LANGUAGE_NONE; $node->title = $form['name']['#value']; $node->field_song_description[$node->language][0]['value'] = $form['description']['#value']; $file_path = drupal_realpath($form['file1']['#file']->uri); $file = (object) array( 'uid' => 1, 'uri' => $file_path, 'filemime' => file_get_mimetype($file_path), 'status' => 1, ); $file = file_copy($file, 'public://'); $node->field_file1[$node->language][0] = (array)$file; //$node->field_file1[$node->language][0] = (array)$form['file1']['#file'];//also tried this but nothing node_save($node); } ```
2011/12/15
[ "https://Stackoverflow.com/questions/8518902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1099665/" ]
You have to add into your `node` object two values : the `fid` and the `displa`y Try ``` $node->field_file1[$node->language][0]['fid'] = $file->fid; $node->field_file1[$node->language][0]['display'] = 1; ```
The way you normally do this in Drupal 7 is by using the [`managed_file`](http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html/7#managed_file) widget type which handles all the file copying/moving for you and adds the file to the files table. In your `$form_state` array you get passed the `fid` from the newly created file: In your form function: ``` $form['my_file_field'] = array( '#type' => 'managed_file', '#title' => 'File', '#upload_location' => 'public://my-files/' ); ``` Then in your form submit function: ``` // Load the file via file.fid. $file = file_load($form_state['values']['my_file_field']); // Change status to permanent. $file->status = FILE_STATUS_PERMANENT; // Save. file_save($file); $node->field_file1[$node->language] = array( 0 => array('fid' => $file->fid, 'display' => 1, 'description' => 'The description') ); ```
36,061,202
Is there an option to call `angular-translate` module (made by Pascal Precht) with additional GET parameters, not only with `queryParameter` one when using `urlLoader`? Current implementation is as follow: ``` $translateProvider.useLoader('$translateUrlLoader', { url: 'endpoint/translations', queryParameter: 'language' }); ``` and then in paritucar controller as: ``` $translate.use('en'); ``` What i need to do is to call it with more parameters, like: ``` $translateProvider.useLoader('$translateUrlLoader', { url: 'endpoint/translations', config: { queryParameter: 'language', secondParam: 'screen', thirdParam: 'client' } }); ``` and then in particular controller to be invoked it as: ``` $translate.use('en','login','pepsi'); ``` As result I need to call my API endpoint like: ``` endpoint/translations?language=en&screen=login&client=pepsi ``` Thank you!
2016/03/17
[ "https://Stackoverflow.com/questions/36061202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4582675/" ]
By the using the module called `angular-translate-loader-partial` module I think we can make this work (<https://angular-translate.github.io/docs/#/guide/12_asynchronous-loading>) Which is configured like this: ``` $translateProvider.useLoader('$translatePartialLoader', { urlTemplate: 'endpoint/translations/' + $rootScope.clientName + '/{part}/{lang}.json' }); ``` And used in controller like: ``` angular.module('pepsi').controller('sugerCtrl', function ($scope, $translatePartialLoader, $translate) { $translatePartialLoader.addPart('suger'); $translate.refresh(); }); ``` Hope this helps.
for me it works: ``` var serviceBase = 'http://localhost'; $translatePartialLoaderProvider.addPart('core'); $translateProvider.useLoader('$translatePartialLoader', { urlTemplate: serviceBase + '/api/translations?lang={lang}&module={part}' }); $translateProvider.preferredLanguage("de"); ```
70,834,436
It seems similar to write: ```perl use Const::Fast; const $xx, 77; sub test { do_something_with( $xx ); } ``` or ```perl sub test { state $xx = 77; do_something_with( $xx ); } ``` What is the better way to accomplish this: via `const` or via `state`? ```perl sub get_ip_country { my ($ip_address) = @_; my $ip_cc_database = GeoIP2::Database::Reader->new(file => '/etc/project/GeoLite2-Country.mmdb'); ... } ``` **UPD** At this sub I do not change pointer togeoip database, so it should be `const`. But I not want recreate object each time when sub is called (this is slow). So I suppose it will be faster to use `state`, despite pointer is not changed. It seems it should be `const state $ip_cc_database`
2022/01/24
[ "https://Stackoverflow.com/questions/70834436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4632019/" ]
They do not do the same thing. * `state` declares a variable that will only be initialized the first time you enter the function. It's mutable though, so you can change its value, but it will keep the value between calls to the same function. This program would for example print `78` and `79`: ``` sub test { state $xx = 77; # initialization only happens once print ++$xx . "\n"; # step the current value and print it } test; # 78 test; # 79 ``` * `const` declares an immutable (readonly) variable that, if declared in a function, would be reinitialized every time the function is called.
If you want a value that is constant, then you should use something like [Const::Fast](https://metacpan.org/pod/Const::Fast). But if you want a value that can be changed, but which retains its value between calls to a function, then you need a [state variable](https://perldoc.perl.org/functions/state). So running, this: ``` sub test { state $x = 1; say $x++; } test() for 1 .. 10; ``` Gives this: ``` 1 2 3 4 5 6 7 8 9 10 ``` But running this: ``` use Const::Fast; sub test { const my $x, 1; say $x++; } test() for 1 .. 10; ``` Gives a runtime error: ``` Modification of a read-only value attempted at const_test line 12. ```
70,834,436
It seems similar to write: ```perl use Const::Fast; const $xx, 77; sub test { do_something_with( $xx ); } ``` or ```perl sub test { state $xx = 77; do_something_with( $xx ); } ``` What is the better way to accomplish this: via `const` or via `state`? ```perl sub get_ip_country { my ($ip_address) = @_; my $ip_cc_database = GeoIP2::Database::Reader->new(file => '/etc/project/GeoLite2-Country.mmdb'); ... } ``` **UPD** At this sub I do not change pointer togeoip database, so it should be `const`. But I not want recreate object each time when sub is called (this is slow). So I suppose it will be faster to use `state`, despite pointer is not changed. It seems it should be `const state $ip_cc_database`
2022/01/24
[ "https://Stackoverflow.com/questions/70834436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4632019/" ]
They do not do the same thing. * `state` declares a variable that will only be initialized the first time you enter the function. It's mutable though, so you can change its value, but it will keep the value between calls to the same function. This program would for example print `78` and `79`: ``` sub test { state $xx = 77; # initialization only happens once print ++$xx . "\n"; # step the current value and print it } test; # 78 test; # 79 ``` * `const` declares an immutable (readonly) variable that, if declared in a function, would be reinitialized every time the function is called.
As @TedLyngmo points out in a comment to your OP, `const state` is not valid Perl. `const` is a pragma, so works at compile time, while `state` is a runtime construct. In terms of your efficiency requirement, that the `GeoIP2::Database::Reader` constructor is called only once, either will work. If you further want it to be read-only so that you cannot inadvertently invalidate the reference, you can still use both. `const` does it for you automatically, but you can duplicate that behavior with `state` with a layer of indirection: ``` sub ip_cc_database { state $db = GeoIP2::Database::Reader->new(file => '/etc/project/GeoLite2-Country.mmdb'); } sub get_ip_country { my ($ip_address) = @_; my $ip_cc_database = ip_cc_database(); ... } ``` The answer to your question about when to use one over the other is a bit more nuanced. The real difference between the two approaches is when the constructor is called. Using `const` it's during the compile phase, with `state` it's during runtime. If you're application *always* calls `get_ip_country`, and you don't care about amortizing startup costs over the lifetime of the process, `const` is simpler. However, if you don't always call `get_ip_country`, and creating the `GeoIP2::Database::Reader` object is expensive, then using `state` means you only pay for that cost if you need it. There's also the user experience to consider. If your program is interactive or if it starts generating output before you need to call `get_ip_country`, delaying creating the object until its actually needed means your program doesn't just sit there seemingly doing nothing until all of the startup has completed.
70,834,436
It seems similar to write: ```perl use Const::Fast; const $xx, 77; sub test { do_something_with( $xx ); } ``` or ```perl sub test { state $xx = 77; do_something_with( $xx ); } ``` What is the better way to accomplish this: via `const` or via `state`? ```perl sub get_ip_country { my ($ip_address) = @_; my $ip_cc_database = GeoIP2::Database::Reader->new(file => '/etc/project/GeoLite2-Country.mmdb'); ... } ``` **UPD** At this sub I do not change pointer togeoip database, so it should be `const`. But I not want recreate object each time when sub is called (this is slow). So I suppose it will be faster to use `state`, despite pointer is not changed. It seems it should be `const state $ip_cc_database`
2022/01/24
[ "https://Stackoverflow.com/questions/70834436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4632019/" ]
If you want a value that is constant, then you should use something like [Const::Fast](https://metacpan.org/pod/Const::Fast). But if you want a value that can be changed, but which retains its value between calls to a function, then you need a [state variable](https://perldoc.perl.org/functions/state). So running, this: ``` sub test { state $x = 1; say $x++; } test() for 1 .. 10; ``` Gives this: ``` 1 2 3 4 5 6 7 8 9 10 ``` But running this: ``` use Const::Fast; sub test { const my $x, 1; say $x++; } test() for 1 .. 10; ``` Gives a runtime error: ``` Modification of a read-only value attempted at const_test line 12. ```
As @TedLyngmo points out in a comment to your OP, `const state` is not valid Perl. `const` is a pragma, so works at compile time, while `state` is a runtime construct. In terms of your efficiency requirement, that the `GeoIP2::Database::Reader` constructor is called only once, either will work. If you further want it to be read-only so that you cannot inadvertently invalidate the reference, you can still use both. `const` does it for you automatically, but you can duplicate that behavior with `state` with a layer of indirection: ``` sub ip_cc_database { state $db = GeoIP2::Database::Reader->new(file => '/etc/project/GeoLite2-Country.mmdb'); } sub get_ip_country { my ($ip_address) = @_; my $ip_cc_database = ip_cc_database(); ... } ``` The answer to your question about when to use one over the other is a bit more nuanced. The real difference between the two approaches is when the constructor is called. Using `const` it's during the compile phase, with `state` it's during runtime. If you're application *always* calls `get_ip_country`, and you don't care about amortizing startup costs over the lifetime of the process, `const` is simpler. However, if you don't always call `get_ip_country`, and creating the `GeoIP2::Database::Reader` object is expensive, then using `state` means you only pay for that cost if you need it. There's also the user experience to consider. If your program is interactive or if it starts generating output before you need to call `get_ip_country`, delaying creating the object until its actually needed means your program doesn't just sit there seemingly doing nothing until all of the startup has completed.
17,978,264
Is it possible to render different pages for the same URL in express? For example, if I click on #login1, I want to be sent to /login\_page/. If I click on #login2, I should still be sent to /login\_page/. Each time, I want to render different htmls depending on which #login I clicked. So I want it to look like this. Client: ``` $("#login1").click(function(){ window.open(/login_page/,'_parent'); }); $("#login2").click(function(){ window.open(/login_page/,'_parent'); }); ``` Server: ``` app.get('/login_page/', users.login_page1); //if I clicked #login1 app.get('/login_page/', users.login_page2); //if I clicked #login2 ``` Thanks a lot for any help.
2013/07/31
[ "https://Stackoverflow.com/questions/17978264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2596680/" ]
Basically you need some field in the request to convey this information. * The simple thing: the URL, as the web was designed * If you're too cool to have the URLs be different, you can use the query string + `window.open('/login_page?from=login2', '_parent');` * If you're too cool for the query string, you could set a cookie * If you're too cool for a cookie, you could request the page via ajax with `xhr.setRequestHeader` * If you're tool cool for a custom ajax request header, you could add an image with a tracking pixel `src` attribute to the DOM just prior to loading the `login_page` and detect that in the server side session and render a different page accordingly So in summary there are at least a half-dozen ways to technically achieve this. Only the URL and the query string are reasonable, IMHO.
if I got it correctly you just want to invoke different controllers upon the same request with no parameters? you know you can just parametrise the url and get the result you need with small control logic on the server side.
17,978,264
Is it possible to render different pages for the same URL in express? For example, if I click on #login1, I want to be sent to /login\_page/. If I click on #login2, I should still be sent to /login\_page/. Each time, I want to render different htmls depending on which #login I clicked. So I want it to look like this. Client: ``` $("#login1").click(function(){ window.open(/login_page/,'_parent'); }); $("#login2").click(function(){ window.open(/login_page/,'_parent'); }); ``` Server: ``` app.get('/login_page/', users.login_page1); //if I clicked #login1 app.get('/login_page/', users.login_page2); //if I clicked #login2 ``` Thanks a lot for any help.
2013/07/31
[ "https://Stackoverflow.com/questions/17978264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2596680/" ]
Basically you need some field in the request to convey this information. * The simple thing: the URL, as the web was designed * If you're too cool to have the URLs be different, you can use the query string + `window.open('/login_page?from=login2', '_parent');` * If you're too cool for the query string, you could set a cookie * If you're too cool for a cookie, you could request the page via ajax with `xhr.setRequestHeader` * If you're tool cool for a custom ajax request header, you could add an image with a tracking pixel `src` attribute to the DOM just prior to loading the `login_page` and detect that in the server side session and render a different page accordingly So in summary there are at least a half-dozen ways to technically achieve this. Only the URL and the query string are reasonable, IMHO.
I don't believe it's possible to do this without any parameters. One solution could look like this client: ``` $("#login1").click(function(){ window.open(/login_page/1,'_parent'); }); $("#login2").click(function(){ window.open(/login_page/2,'_parent'); }); ``` Server: ``` app.get('/login_page/:id', function(req, res){ //if I clicked #login1 if(req.params.id == 1){ res.render('index1.html'); } else { res.render('index2.html'); } } ```
10,070,854
Am fooling around with this question a couple of days now but no progress. What i want to do is quite simple i think: I have an image of 320x60 which i use in the plain TableView which works oke as those cells take up the entire width (320) of the screen. The grouped cells in a TableView are 300 wide and have insets/margins left of 10 on the left and the right. Can i somehow remove those insets/margins and let the grouped cell be 320 wide? I tried setting the content inset left to -10. That does "remove" the left margin but then it's still only 300 wide. Also tried editing the XML of the storyboard (I'm working with iOS 5 - Storyboards) but no joy. This similar question here got answered as no it's not possible, hopfully something changed in 2+ years!: [Adjust cell width in grouped UITableView](https://stackoverflow.com/questions/1221873/adjust-cell-width-in-grouped-uitableview) PS i want to alter the width as the background images contain nice shadows, I've read that exesive use of shadows could mean performance issues. Also the shadow's are 5px extra around the border so that would mean -10px wide if I use the standard width. Help much appreciated!
2012/04/09
[ "https://Stackoverflow.com/questions/10070854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1321480/" ]
An **untidy solution** is to make the table view 340 pixels wide, and 10 pixels off the left edge of the screen. A **solution that involves changing properties of private classes** is to make a `UITableViewCell` subclass, and override its `layoutSubviews` method. When I log the subviews, I find these: ``` "<UIGroupTableViewCellBackground: 0x95246b0; frame = (9 0; 302 45); autoresize = W; layer = <CALayer: 0x95226b0>>", "<UITableViewCellContentView: 0x92332d0; frame = (10 0; 300 43); layer = <CALayer: 0x9233310>>", "<UIView: 0x95248c0; frame = (10 0; 300 1); layer = <CALayer: 0x951f140>>" ``` What happens if we take those subviews and fill the entire bounds available? ``` - (void)layoutSubviews; { // By default the cell bounds fill the table width, but its subviews (containing the opaque background and cell borders) are drawn with padding. CGRect bounds = [self bounds]; // Make sure any standard layout happens. [super layoutSubviews]; // Debugging output. NSLog(@"Subviews = %@", [self subviews]); for (UIView *subview in [self subviews]) { // Override the subview to make it fill the available width. CGRect frame = [subview frame]; frame.origin.x = bounds.origin.x; frame.size.width = bounds.size.width; [subview setFrame:frame]; } } ``` At this particular moment, on the iOS 5.1 simulator, this works. Now, some future version of iOS may restructure these classes, causing this method to catastrophically mangle the table layout. Your app could be rejected for changing the properties of UITableViewCellContentView... even though you're only modifying its frame. So, how much do you need to have your cells fill the table width?
You can the UITableView's Leading and Trailing Space constraints in the Size Inspector which is accessible via the Storyboard. I'm not sure when this was added, but setting the Leading Space Constraint to -10 and the Trailing Space Constraint to 10 will make the cells full width.
57,819,148
I have a main html file where i embedd Web Components. When debugging I noticed, that my Custom Elements are not marked, when I hover over them. [![enter image description here](https://i.stack.imgur.com/cEaLl.png)](https://i.stack.imgur.com/cEaLl.png) Im also not able to set the size of the custom html element from an outisde css. Here is my code: view.html ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <link href="view.css" rel="stylesheet" /> <script defer src="widget-uhr.js"></script> </head> <body> <widget-uhr></widget-uhr> <widget-uhr></widget-uhr> <widget-uhr></widget-uhr> <button>View Button</button> </body> </html> ``` widget-uhr.html ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <link href="widget-uhr.css" rel="stylesheet" /> </head> <body> <div id="time"></div> <button>Widget Button1</button> <button>Widget Button2</button> <button>Widget Button3</button> </body> </html> ``` view.css ``` body{ display:block; } button{ min-width: 250px; min-height: 100px; background-color: aqua; font-size: 32px; } ``` widget-uhr.css ``` body{ color:green; background-color: gray; } div{ color:blue; background-color: gray; } button{ background-color: red; } ``` widget-uhr.js ``` fetch( "widget-uhr.html" ) .then( stream => stream.text() ) .then( text => customElements.define( "widget-uhr", class extends HTMLElement { constructor() { super() this.attachShadow( { mode: 'open'} ) .innerHTML = text } } ) ) ``` Is the reason maybe because I inject my html from the widget via fetch?
2019/09/06
[ "https://Stackoverflow.com/questions/57819148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11094876/" ]
By default a Custom Element is *inline*, so it won't be marked in Dev Tools. To get it marked, you should define its CSS `display` propery to `block` or `inline-block`. From inside its Shadow DOM, use the `:host` CSS pseudo-class. In **widget-uhr.css**: ``` :host { display: block } ``` Or, from the main document, use the custom element name. In **view.css**: ``` widget-uhr { display: block } ```
Style from outside ================== > > Im also not able to set the size of the custom html element from an outisde css. > > > With Shadow DOM CSS selectors don't cross the shadow boundary. We have style encapsulation from the outside world. You could include the rule inside the style element in the shadow tree. ``` <style> @import url( 'view.css' ) </style> ``` [More information here](https://www.html5rocks.com/en/tutorials/webcomponents/shadowdom-201/) Chrome Inspector ================ > > When debugging I noticed, that my Custom Elements are not marked, when I hover over them. > You have to enable Shadow DOM inspector first. > > > 1. Open your dev tools with F12 2. Click on the three dots on the top right 3. Click on Settings 4. Enable option "Show user agents Shadow DOM" under Elements category
152,078
I am working on student data set in which I want to normalize the range of percentage to 0,1. But I am not clear with the actual benefits of normalizing a range.
2015/05/13
[ "https://stats.stackexchange.com/questions/152078", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/77006/" ]
Normalizing the data is done so that all the input variables have the same treatment in the model and the coefficients of a model are not scaled with respect to the units of the inputs. For instance, consider that you have a model that measures the aging of paintings based on room temperature, humidity and some other variables. If humidity is measured in litres per cubic metre and temperature in degrees Celsius, the coefficients in the model will be scaled accordingly and may have a high value for humidity and a low value for temperature (say). If you scale the variables, such as by using $(x- \mu)/\sigma$ or any other technique, variability in output due to unit change in input variables will be modeled more realistically. You may wish to rescale the predicted output to interpret the results. In regression, the $t$-values and $R^2$ values are not affected due to scaling or not scaling. However, interpreting the results becomes easier using scaling.
Some machine learning algorithms require the input data to be normalized in order to converge to a good result. Let's take for example a data set where samples represent apartments and the features are the number of rooms and the surface area. The number of rooms would be in the range 1-10, and the surface area 200 - 2000 square feet. I generated some bogus data to work with, both features are uniformly distributed and independent. Before scaling, the data could look like this (note that the axes are proportional): ![Before scaling](https://i.stack.imgur.com/Hjjp0.png) You can see that there is basically just one dimension to the data, because of the two orders of magnitude difference between the features. After standard scaling, the data would look like this (note that the axes are proportional): ![enter image description here](https://i.stack.imgur.com/8vIeq.png) Now the data is nicely distributed and a logistic regression or SVM could do a much better job classifying the samples.
15,544,555
I am developing a web application based on ASP.NET 4.0 and having some few pages with potential dangerous request(having markup codes). So instead of setting RequestValidationMode="2.0" in web.config, can I set that property only for those few pages?
2013/03/21
[ "https://Stackoverflow.com/questions/15544555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1118064/" ]
Answer hidden somewhere in msdn, hope this helps you too.. Better late then never Try this, ``` <location path="test.aspx"> <system.web> <httpRuntime requestValidationMode="2.0" /> </system.web> </location> ``` Reference <http://msdn.microsoft.com/en-us/library/hh882339(v=vs.100).aspx>
for avoiding this error: **potentially dangerous request.form value was detected from the client.** you can use page level property : `<%@ Page ... ValidateRequest="false" %>`
48,884,454
I'm currently reading up on and experimenting with the different possibilities of running programs from within C code on Linux. My use cases cover all possible scenarios, from simply running and forgetting about a process, reading from *or* writing to the process, to reading from *and* writing to it. For the first two, `popen()` is very easy to use and works well. I understand that it uses some version of `fork()` and `exec()` internally, then invokes a shell to actually run the command. For the third scenario, `popen()` is not an option, as it is unidirectional. Available options are: * Manually `fork()` and `exec()`, plus `pipe()` and `dup2()` for input/output * `posix_spawn()`, which internally uses the above as need be What I noticed is that these can achieve the same that `popen()` does, but we can completely avoid the invoking of an additional `sh`. This sounds desirable, as it seems less complex. However, I noticed that even [examples on `posix_spawn()`](https://www.systutorials.com/37124/a-posix_spawn-example-in-c-to-create-child-process-on-linux/) that I found on the Internet do invoke a shell, so it would seem there must be a benefit to it. If it is about parsing command line arguments, `wordexp()` seems to do an equally good job. What is the ~~reason behind~~ benefit of invoking a shell to run the desired process instead of running it directly? --- **Edit**: I realized that my wording of the question didn't precisely reflect my actual interest - I was more curious about the *benefits* of going through `sh` rather than the (historical) *reason*, though both are obviously connected, so answers for both variations are equally relevant.
2018/02/20
[ "https://Stackoverflow.com/questions/48884454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3316645/" ]
Invoking a shell allows you to do all the things that you can do in a shell. For example, ``` FILE *fp = popen("ls *", "r"); ``` is possible with `popen()` (expands all files in the current directory). Compare it with: ``` execvp("/bin/ls", (char *[]){"/bin/ls", "*", NULL}); ``` You can't exec `ls` with `*` as argument because `exec(2)` will interpret `*` literally. Similarly, pipes (`|`), redirection (`>`, `<`, ...), etc., are possible with `popen`. Otherwise, there's no reason to use `popen` if you don't need shell - it's unnecessary. You'll end up with an extra shell process and all the things that can go wrong in a shell go can wrong in your program (e.g., the command you pass could be incorrectly interpreted by the shell and a common security issue). [`popen()` is designed that way](http://pubs.opengroup.org/onlinepubs/9699919799/functions/popen.html). `fork` + `exec` solution is cleaner without the issues associated with a shell.
The glib answer is because the The POSIX standard ( <http://pubs.opengroup.org/onlinepubs/9699919799/functions/popen.html> ) says so. Or rather, it says that it should behave as if the command argument is passed to /bin/sh for interpretation. So I suppose a conforming implementation could, in principle, also have some internal library function that would interpret shell commands without having to fork and exec a separate shell process. I'm not actually aware of any such implementation, and I suspect getting all the corner cases correct would be pretty tricky.
48,884,454
I'm currently reading up on and experimenting with the different possibilities of running programs from within C code on Linux. My use cases cover all possible scenarios, from simply running and forgetting about a process, reading from *or* writing to the process, to reading from *and* writing to it. For the first two, `popen()` is very easy to use and works well. I understand that it uses some version of `fork()` and `exec()` internally, then invokes a shell to actually run the command. For the third scenario, `popen()` is not an option, as it is unidirectional. Available options are: * Manually `fork()` and `exec()`, plus `pipe()` and `dup2()` for input/output * `posix_spawn()`, which internally uses the above as need be What I noticed is that these can achieve the same that `popen()` does, but we can completely avoid the invoking of an additional `sh`. This sounds desirable, as it seems less complex. However, I noticed that even [examples on `posix_spawn()`](https://www.systutorials.com/37124/a-posix_spawn-example-in-c-to-create-child-process-on-linux/) that I found on the Internet do invoke a shell, so it would seem there must be a benefit to it. If it is about parsing command line arguments, `wordexp()` seems to do an equally good job. What is the ~~reason behind~~ benefit of invoking a shell to run the desired process instead of running it directly? --- **Edit**: I realized that my wording of the question didn't precisely reflect my actual interest - I was more curious about the *benefits* of going through `sh` rather than the (historical) *reason*, though both are obviously connected, so answers for both variations are equally relevant.
2018/02/20
[ "https://Stackoverflow.com/questions/48884454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3316645/" ]
Invoking a shell allows you to do all the things that you can do in a shell. For example, ``` FILE *fp = popen("ls *", "r"); ``` is possible with `popen()` (expands all files in the current directory). Compare it with: ``` execvp("/bin/ls", (char *[]){"/bin/ls", "*", NULL}); ``` You can't exec `ls` with `*` as argument because `exec(2)` will interpret `*` literally. Similarly, pipes (`|`), redirection (`>`, `<`, ...), etc., are possible with `popen`. Otherwise, there's no reason to use `popen` if you don't need shell - it's unnecessary. You'll end up with an extra shell process and all the things that can go wrong in a shell go can wrong in your program (e.g., the command you pass could be incorrectly interpreted by the shell and a common security issue). [`popen()` is designed that way](http://pubs.opengroup.org/onlinepubs/9699919799/functions/popen.html). `fork` + `exec` solution is cleaner without the issues associated with a shell.
[The 2004 version of the POSIX `system()` documentation](http://pubs.opengroup.org/onlinepubs/009695399/functions/system.html) has a rationale that is likely applicable to `popen()` as well. Note the stated restrictions on `system()`, especially the one stating "that the process ID is different": > > ***RATIONALE*** > > > ... > > > There are three levels of specification for the system() function. The > ISO C standard gives the most basic. It requires that the function > exists, and defines a way for an application to query whether a > command language interpreter exists. It says nothing about the command > language or the environment in which the command is interpreted. > > > IEEE Std 1003.1-2001 places additional restrictions on system(). It > requires that if there is a command language interpreter, the > environment must be as specified by fork() and exec. This ensures, for > example, that close-on- exec works, that file locks are not inherited, > and that the process ID is different. It also specifies the return > value from system() when the command line can be run, thus giving the > application some information about the command's completion status. > > > Finally, IEEE Std 1003.1-2001 requires the command to be interpreted > as in the shell command language defined in the Shell and Utilities > volume of IEEE Std 1003.1-2001. > > > Note the multiple references to the "ISO C Standard". [The latest version of the C standard](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf) requires that the command string be processed by the system's "command processor": > > **7.22.4.8 The `system` function** > > > Synopsis > > > > ``` > #include <stdlib.h> > int system(const char *string); > > ``` > > **Description** > > > If `string` is a null pointer, the `system` function determines > whether the host environment has a command processor. If `string` > is not a null pointer, the `system` function passes the string > pointed to by `string` to that command processor to be executed > in a manner which the implementation shall document; this might then > cause the program calling `system` to behave in a non-conforming > manner or to terminate. > > > **Returns** > > > If the argument is a null pointer, the `system` function > returns nonzero only if a command processor is available. If > the argument is not a null pointer, and the `system` function > does return, it returns an implementation-defined value. > > > Since the C standard requires that the systems "command processor" be used for the `system()` call, I suspect that: 1. Somewhere there's a requirement in POSIX that ties `popen()` to the `system()` implementation. 2. It's much easier to just reuse the "command processor" entirely since there's also a requirement to run as a separate process. So this is the glib answer twice-removed.
51,079,968
What is the equivalent of [`File.createNewFile()`](https://docs.oracle.com/javase/10/docs/api/java/io/File.html#createNewFile()) in [`java.nio.file`](https://docs.oracle.com/javase/10/docs/api/java/nio/file/package-summary.html) API (Java 7+)?
2018/06/28
[ "https://Stackoverflow.com/questions/51079968", "https://Stackoverflow.com", "https://Stackoverflow.com/users/648955/" ]
In Java 8 you've got the `Files` class which got a method called `createFile` ``` Files.createFile(java.nio.file.Path, java.nio.file.attribute.FileAttribute<T>...) ``` The `FileAttribute<T>` parameter is optional so you don't need to put something in for that. To get a `Path` there is a `Paths` class to get a path easily. ``` java.nio.file.Path get(java.lang.String path, java.lang.String... more) ```
All actual file operations are [in the `Files` class](https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#createFile(java.nio.file.Path,%20java.nio.file.attribute.FileAttribute...)): ``` Files.createFile(path); ```
52,928,983
I wonder if it is possible to use C++11's [noexcept operator](https://en.cppreference.com/w/cpp/language/noexcept) to define the noextcept specifier of e. g. a destructor that calls a method of another class (e. g. std::allocator::deallocate): ``` template <class DelegateAllocator = std::allocator<uint8_t>> class MyAllocator final { public: using allocator_type = DelegateAllocator; // ... ~MyAllocator() noexcept(noexcept(/* what to use */))) { if (memory_ != nullptr) { allocator_.deallocate(memory_, length_); } } private: allocator_type allocator_; uint8_t* memory_; // ... }; ``` Questions: What is the best solution to define noexcept dependent to the used methods of a delegated type (e. g. std::allocator)? What has to be done - when possible - to use methods of a delegated type when different overloads exist (e. g. how would I use a specific deallocate implementation when not only one is provided)?
2018/10/22
[ "https://Stackoverflow.com/questions/52928983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3054219/" ]
In [c++14](/questions/tagged/c%2b%2b14 "show questions tagged 'c++14'") this is as easy as: ``` ~MyAllocator() noexcept(noexcept(std::declval<allocator_type&>().deallocate( memory_, allocator_ ))) { if (memory_ != nullptr) { allocator_.deallocate(memory_, length_); } } ``` [Live example](http://coliru.stacked-crooked.com/a/151632101acf3946). But in [c++11](/questions/tagged/c%2b%2b11 "show questions tagged 'c++11'") it is a pain to do "properly": ``` ~MyAllocator() noexcept(noexcept(std::declval<allocator_type&>().deallocate( std::declval<uint8_t*&>(), std::declval<std::size_t&>() ))) { if (memory_ != nullptr) { allocator_.deallocate(memory_, length_); } } ``` [Live example](http://coliru.stacked-crooked.com/a/6cc915eb589a6992). So, upgrade to [c++14](/questions/tagged/c%2b%2b14 "show questions tagged 'c++14'"). You can also do it hackily: ``` ~MyAllocator() noexcept(noexcept(std::declval<allocator_type&>().deallocate( (uint8_t*)nullptr,1 ))) { ``` but you have to be careful, because passing `nullptr_t` could get you the wrong answer (hence the above cast from `nullptr` to `uint8_t*`, and avoiding using `0` as a literal).
[This stack overflow answer](https://stackoverflow.com/a/31654610/3054219) pointed me to one solution: ``` ~StackAllocator() noexcept(noexcept(std::declval<allocator_type>().*&allocator_type::deallocate)) { if (memory_ != nullptr) { allocator_.deallocate(memory_, length_); } } ``` This solution works as long as only one overload for the method exists. If anybody can provide a better solution (better to read, reusable ...) or a solution that works also with methods that have overloads please provide it. **Edit/Update:** A colleague and the answer from Yakk below provided a better solution that also covers different overloads: ``` ~StackAllocator() noexcept(noexcept(std::declval<allocator_type>().deallocate(std::declval<std::uint8_t*>(), std::declval<std::size_t>()))) { if (memory_ != nullptr) { allocator_.deallocate(memory_, length_); } } ```
1,957,950
how does this helps a multi language site ?
2009/12/24
[ "https://Stackoverflow.com/questions/1957950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196517/" ]
It does nothing to help a multi-language website per se. What it does is that it notifies the web browser that the web page is encoded in UTF-8. See [this article](http://www.joelonsoftware.com/articles/Unicode.html) for more information.
At a trivial level, If it's set across the front end, backend (I'm presuming there's some form of Content Management System that's used to enter text, etc.) and database collation it will allow non-ASCII characters to be entered, stored and subsequently output correctly. That said, this is really only skimming the surface.
1,957,950
how does this helps a multi language site ?
2009/12/24
[ "https://Stackoverflow.com/questions/1957950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196517/" ]
`UTF-8` is an [Unicode](http://en.wikipedia.org/wiki/Unicode) [character encoding](http://en.wikipedia.org/wiki/Character_encoding) (charset) which covers **all** of the characters known at the human world as outlined [here](http://www.unicode.org/charts/index.html). For example the `ISO 8859-x` doesn't cover them, it only covers the Latin characters (a-z and so on). If you want your webapp to be able to display and handle non-Latin characters, then you really need an Unicode charset, otherwise youw webapp will go [Mojibake](http://en.wikipedia.org/wiki/Mojibake). [The article of Joel](http://www.joelonsoftware.com/articles/Unicode.html) is excellent to start with and if you have a Java background you may find this article useful as well, it does not only explain the use of charsets in detail, but it also contains practical examples and complete solutions how to get it to work properly in a Java (JSP/Servlet) webapplication: [Unicode - How to get the characters right?](http://balusc.blogspot.com/2009/05/unicode-how-to-get-characters-right.html)
It does nothing to help a multi-language website per se. What it does is that it notifies the web browser that the web page is encoded in UTF-8. See [this article](http://www.joelonsoftware.com/articles/Unicode.html) for more information.
1,957,950
how does this helps a multi language site ?
2009/12/24
[ "https://Stackoverflow.com/questions/1957950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196517/" ]
`UTF-8` is an [Unicode](http://en.wikipedia.org/wiki/Unicode) [character encoding](http://en.wikipedia.org/wiki/Character_encoding) (charset) which covers **all** of the characters known at the human world as outlined [here](http://www.unicode.org/charts/index.html). For example the `ISO 8859-x` doesn't cover them, it only covers the Latin characters (a-z and so on). If you want your webapp to be able to display and handle non-Latin characters, then you really need an Unicode charset, otherwise youw webapp will go [Mojibake](http://en.wikipedia.org/wiki/Mojibake). [The article of Joel](http://www.joelonsoftware.com/articles/Unicode.html) is excellent to start with and if you have a Java background you may find this article useful as well, it does not only explain the use of charsets in detail, but it also contains practical examples and complete solutions how to get it to work properly in a Java (JSP/Servlet) webapplication: [Unicode - How to get the characters right?](http://balusc.blogspot.com/2009/05/unicode-how-to-get-characters-right.html)
At a trivial level, If it's set across the front end, backend (I'm presuming there's some form of Content Management System that's used to enter text, etc.) and database collation it will allow non-ASCII characters to be entered, stored and subsequently output correctly. That said, this is really only skimming the surface.
69,300,984
I have created one API spec document by importing open API dependency in my pom.xml but in generated swagger UI interface i have schema available only for 200 responses do I need to add other responses manually or swagger can generate it automatically
2021/09/23
[ "https://Stackoverflow.com/questions/69300984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9131551/" ]
I meet same problem, so used another workaround. Use initWith() with debug buildType makes new type to debuggable too. ``` create("foo") { // Apply debug type setting by initWith() initWith(getByName("debug")) } ``` But I think Gradle kts should add debuggable property to build type.
I think it makes sense to remove that property for libraries, given that you should define debuggable at the application level.
69,300,984
I have created one API spec document by importing open API dependency in my pom.xml but in generated swagger UI interface i have schema available only for 200 responses do I need to add other responses manually or swagger can generate it automatically
2021/09/23
[ "https://Stackoverflow.com/questions/69300984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9131551/" ]
[![LibraryTaskManager used libraryVariant.getDebuggable](https://i.stack.imgur.com/7FuRw.png)](https://i.stack.imgur.com/7FuRw.png) From what I found, the source code of `LibraryTaskManager` still uses the `libraryVariant.getDebuggable()` that is produced from buildType&productFlavor. I'm not sure why the `debuggable` / `isDebuggable` option is not availble from `LibraryBuildType`, however if anyone is looking for the workaround, use the code below: ``` // library's build.gradle.kts buildTypes { named("debug") { (this as com.android.build.gradle.internal.dsl.BuildType).isDebuggable = false } } ```
I think it makes sense to remove that property for libraries, given that you should define debuggable at the application level.
69,300,984
I have created one API spec document by importing open API dependency in my pom.xml but in generated swagger UI interface i have schema available only for 200 responses do I need to add other responses manually or swagger can generate it automatically
2021/09/23
[ "https://Stackoverflow.com/questions/69300984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9131551/" ]
[![LibraryTaskManager used libraryVariant.getDebuggable](https://i.stack.imgur.com/7FuRw.png)](https://i.stack.imgur.com/7FuRw.png) From what I found, the source code of `LibraryTaskManager` still uses the `libraryVariant.getDebuggable()` that is produced from buildType&productFlavor. I'm not sure why the `debuggable` / `isDebuggable` option is not availble from `LibraryBuildType`, however if anyone is looking for the workaround, use the code below: ``` // library's build.gradle.kts buildTypes { named("debug") { (this as com.android.build.gradle.internal.dsl.BuildType).isDebuggable = false } } ```
I meet same problem, so used another workaround. Use initWith() with debug buildType makes new type to debuggable too. ``` create("foo") { // Apply debug type setting by initWith() initWith(getByName("debug")) } ``` But I think Gradle kts should add debuggable property to build type.
67,735,198
I have a pydantic model as follows. ```py from pydantic import Json, BaseModel class Foo(BaseModel): id: int bar: Json ``` Foo.bar can parse JSON string as input and store it as a dict which is nice. ```py foo = Foo(id=1, bar='{"foo": 2, "bar": 3}') type(foo.bar) #outputs dict ``` And if i want the entire object to be a `dict` I can do ```py foo.dict() #outputs {'id': 1, 'bar': {'foo': 2, 'bar': 3}} ``` But how can I export `bar` as JSON string as following ```py {'id': 1, 'bar': '{"foo": 2, "bar": 3}'} ``` **I want to write JSON back into the database.**
2021/05/28
[ "https://Stackoverflow.com/questions/67735198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11061699/" ]
Pydantic author here. There's currently no way to do that without calling `json.dumps(foo.bar)`. You could make that a method on `Foo` if you liked, which would be easier to use but require the same processing. If performance is critical, or you need the exact same JSON string you started with (same spaces etc.) You could do one of the following: * Make `bar` a string field but add a validator to check it's valid JSON * create a custom data type to parse the JSON but also keep a reference to the raw JSON string
Do you want to convert the nest to string? ``` x = {'id': 1, 'bar': str({'foo': 2, 'bar': 3})} ``` gives ``` {'id': 1, 'bar': "{'foo': 2, 'bar': 3}"} ```
67,735,198
I have a pydantic model as follows. ```py from pydantic import Json, BaseModel class Foo(BaseModel): id: int bar: Json ``` Foo.bar can parse JSON string as input and store it as a dict which is nice. ```py foo = Foo(id=1, bar='{"foo": 2, "bar": 3}') type(foo.bar) #outputs dict ``` And if i want the entire object to be a `dict` I can do ```py foo.dict() #outputs {'id': 1, 'bar': {'foo': 2, 'bar': 3}} ``` But how can I export `bar` as JSON string as following ```py {'id': 1, 'bar': '{"foo": 2, "bar": 3}'} ``` **I want to write JSON back into the database.**
2021/05/28
[ "https://Stackoverflow.com/questions/67735198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11061699/" ]
Pydantic author here. There's currently no way to do that without calling `json.dumps(foo.bar)`. You could make that a method on `Foo` if you liked, which would be easier to use but require the same processing. If performance is critical, or you need the exact same JSON string you started with (same spaces etc.) You could do one of the following: * Make `bar` a string field but add a validator to check it's valid JSON * create a custom data type to parse the JSON but also keep a reference to the raw JSON string
The workaround that solved the problem in my scenario was to inherit BaseModel and override `dict` method. ```py class ExtendedModel(BaseModel): def dict(self, json_as_string=False, **kwargs) -> dict: __dict = super().dict(**kwargs) if json_as_string: for field, _ in self.schema()['properties'].items(): if _.get('format') == 'json-string' and field in __dict : __dict[field] = json.dumps(getattr(self, field)) return __dict ``` `self.__field__` wouldn't specify if the field's type is actually Json. It was returning as Any. So I used this approch.
67,735,198
I have a pydantic model as follows. ```py from pydantic import Json, BaseModel class Foo(BaseModel): id: int bar: Json ``` Foo.bar can parse JSON string as input and store it as a dict which is nice. ```py foo = Foo(id=1, bar='{"foo": 2, "bar": 3}') type(foo.bar) #outputs dict ``` And if i want the entire object to be a `dict` I can do ```py foo.dict() #outputs {'id': 1, 'bar': {'foo': 2, 'bar': 3}} ``` But how can I export `bar` as JSON string as following ```py {'id': 1, 'bar': '{"foo": 2, "bar": 3}'} ``` **I want to write JSON back into the database.**
2021/05/28
[ "https://Stackoverflow.com/questions/67735198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11061699/" ]
Pydantic author here. There's currently no way to do that without calling `json.dumps(foo.bar)`. You could make that a method on `Foo` if you liked, which would be easier to use but require the same processing. If performance is critical, or you need the exact same JSON string you started with (same spaces etc.) You could do one of the following: * Make `bar` a string field but add a validator to check it's valid JSON * create a custom data type to parse the JSON but also keep a reference to the raw JSON string
I faced same problem so here comes a little hacky solution with class factory (some elegant one with something like `foo: JsonVal[T]` is almost impossible to implement due to numerous internal pydantic hacks like how it works with generic type annotations). Unfortunately type inference is not working, but validation and access to parsed value are ok, considering that Fields are always stored/serialized as str. ``` from abc import ABC from typing import TypeVar, Generic, Type from pydantic import Json, parse_obj_as, BaseModel T = TypeVar('T') class JsonVal(Generic[T], str, ABC): @property def parsed(self) -> T: return None def json_val(t: Type) -> Type[JsonVal[T]]: class _JsonVal(JsonVal, str): _t: Type @classmethod def __get_validators__(cls): yield cls.validate @classmethod def validate(cls, v): parse_obj_as(Json[cls._t], v) return cls(v) @property def parsed(self): return parse_obj_as(Json[self._t], self) _JsonVal._t = t return _JsonVal class Bar(BaseModel): bar: str class Model(BaseModel): foo: json_val(list[int]) bar: json_val(Bar) m = Model.parse_obj({"foo": '[1,2,3]', "bar": '{"bar":"baz"}'}) print(m) print(m.foo, type(m.foo), m.foo.parsed, type(m.foo.parsed)) print(m.bar, type(m.bar), m.bar.parsed, type(m.bar.parsed)) print(m.json()) # foo='[1,2,3]' bar='{"bar":"baz"}' # f[1,2,3] <class '__main__.json_val.<locals>._JsonVal'> [1, 2, 3] <class 'list'> # f{"bar":"baz"} <class '__main__.json_val.<locals>._JsonVal'> bar='baz' <class '__main__.Bar'> # f{"foo": "[1,2,3]", "bar": "{\"bar\":\"baz\"}"} ```
37,314,302
me trying to make distinct data in temporary table, trying to simple it with create table #tabletemp still got wrong, it says unrecognize data type near distinct and comma or closing bracket was expected near ponumber here's the code : ``` CREATE TEMPORARY TABLE t1( SELECT DISTINCT PONumber varchar(10), POdate varchar(10), customername varchar(35), description varchar(22) FROM tb_po ); SELECT p.PONumber, p.podate, p.customername, p.description, ( SELECT SUM(q.deliveryqty) FROM tb_spb q WHERE p.PONumber = q.PONumber AND p.description = q.description ) AS Total FROM t1 p ```
2016/05/19
[ "https://Stackoverflow.com/questions/37314302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6349536/" ]
You don't need to create a temporary table to get the result that you want. Here is my revised query based on your query: ``` SELECT DISTINCT p.PONumber, p.POdate, p.customername, p.[description], SUM(q.deliveryqty) FROM tb_po p INNER JOIN tb_spb q ON p.PONumber = q.PONumber AND p.description = q.description GROUP BY p.PONumber,p.POdate,p.customername,p.[description] ```
You have to first create the table then insert into the table. For SQL server You can do like this. ``` CREATE TABLE TEMPORARY( PONumber varchar(10), POdate varchar(10), customername varchar(35), description varchar(22) ); insert into TEMPORARY SELECT DISTINCT PONumber varchar(10), POdate varchar(10), customername varchar(35), description varchar(22) FROM tb_po ; ``` If you want to create temp table in SQL server then you have use # before table name. For reference <http://www.c-sharpcorner.com/uploadfile/b19d5a/temporary-and-global-temporary-table-in-sql-server-2008/>
37,314,302
me trying to make distinct data in temporary table, trying to simple it with create table #tabletemp still got wrong, it says unrecognize data type near distinct and comma or closing bracket was expected near ponumber here's the code : ``` CREATE TEMPORARY TABLE t1( SELECT DISTINCT PONumber varchar(10), POdate varchar(10), customername varchar(35), description varchar(22) FROM tb_po ); SELECT p.PONumber, p.podate, p.customername, p.description, ( SELECT SUM(q.deliveryqty) FROM tb_spb q WHERE p.PONumber = q.PONumber AND p.description = q.description ) AS Total FROM t1 p ```
2016/05/19
[ "https://Stackoverflow.com/questions/37314302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6349536/" ]
If you really need it to be in a temporary table, another approach is using "SELECT INTO" wherein you wont need to declare the creation of a temporary table. (Although creating a table then inserting records is the more preferred method <https://stackoverflow.com/a/6948850/6344844>) ``` SELECT DISTINCT p.PONumber, p.POdate, p.customername, p.[description], SUM(q.deliveryqty) INTO #TEMPTABLE_NAME FROM tb_po p INNER JOIN tb_spb q ON p.PONumber = q.PONumber AND p.description = q.description GROUP BY p.PONumber,p.POdate,p.customername,p.[description] SELECT * FROM #TEMPTABLE_NAME DROP TABLE #TEMPTABLE_NAME ```
You have to first create the table then insert into the table. For SQL server You can do like this. ``` CREATE TABLE TEMPORARY( PONumber varchar(10), POdate varchar(10), customername varchar(35), description varchar(22) ); insert into TEMPORARY SELECT DISTINCT PONumber varchar(10), POdate varchar(10), customername varchar(35), description varchar(22) FROM tb_po ; ``` If you want to create temp table in SQL server then you have use # before table name. For reference <http://www.c-sharpcorner.com/uploadfile/b19d5a/temporary-and-global-temporary-table-in-sql-server-2008/>
56,104
I want to install **Oracle's JRE** and to update to the latest version with the Software Updater when they released. Is there a Ubuntu package that is provided by Canonical or Oracle? Before release Java 7, I followed [this way](https://askubuntu.com/questions/5459/how-can-i-install-the-latest-version-of-sun-java-jre) to install **Java 6**. But it doesn't work for **Java 7**. There is no package `sun-java7-xxx`. How can you install **Java 7**?
2011/08/07
[ "https://askubuntu.com/questions/56104", "https://askubuntu.com", "https://askubuntu.com/users/5717/" ]
Here is a tested and working solution for installing Oracle JDK 7 and all its files so "javac" and everything else works: [How To Install Oracle Java 7 (JDK) In Ubuntu](http://www.webupd8.org/2011/09/how-to-install-oracle-java-7-jdk-in.html) Here are the commands (just for convenience): 1. Download the latest Oracle JDK 7 from [here](http://www.oracle.com/technetwork/java/javase/downloads/jdk-7u3-download-1501626.html). 2. Extract the downloaded Oracle Java JDK archive in your home folder - a new folder called "jdk1.7.0\_03" (for Java JDK7 update 3) should be created. Rename it to "java-7-oracle" and move it to /usr/lib/jvm using the following commands: > > > ``` > cd > sudo mkdir -p /usr/lib/jvm/ #just in case > sudo mv java-7-oracle/ /usr/lib/jvm/ > > ``` > > 3. Install Update Java package created by Bruce Ingalls (packages available for Ubuntu 11.10, 11.04, 10.10 and 10.04): > > > > ``` > sudo add-apt-repository ppa:nilarimogard/webupd8 > sudo apt-get update > sudo apt-get install update-java > > ``` > > 4. Now run the following command in a terminal to install Oracle Java JDK: > > > > ``` > sudo update-java > > ``` > > ![Select the Java Version that you want to install and set as the default](https://i.stack.imgur.com/UZDU8.png) > > > After a few minutes, Oracle Java JDK should be successfully installed on your Ubuntu machine. You can check out the version by running these commands in a terminal: > > > ``` > java -version > javac -version > > ``` > > --- > > **NOTICE! This part below here of this answer no longer works due to Java changing how their binaries are released. It has been left as-is for historical reasons.** > > > Update Oracle has released Java 8 (stable). To install it, use the following commands: ``` sudo add-apt-repository ppa:webupd8team/java sudo apt-get update sudo apt-get install oracle-java8-installer ``` More information @ WebUpd8: [Install Oracle Java 8 In Ubuntu Via PPA Repository [JDK8]](http://www.webupd8.org/2012/09/install-oracle-java-8-in-ubuntu-via-ppa.html)
Installing Oracle Java (JDK/JRE): ================================= You can automate the task of installing/uninstalling Oracle Java (JDK/JRE) from a downloaded (tar.gz) source with this script: [oraji](https://github.com/neurobin/oraji). Steps: 1. [Download](http://www.oracle.com/technetwork/java/javase/downloads/index.html) the tar.gz source of your desired jdk/jre version. 2. run `sudo oraji /path/to/the/jdk_or_jre/archive` Uninstall: ========== run `sudo oraji -u` and confirm the jdk/jre version to be uninstalled.
56,104
I want to install **Oracle's JRE** and to update to the latest version with the Software Updater when they released. Is there a Ubuntu package that is provided by Canonical or Oracle? Before release Java 7, I followed [this way](https://askubuntu.com/questions/5459/how-can-i-install-the-latest-version-of-sun-java-jre) to install **Java 6**. But it doesn't work for **Java 7**. There is no package `sun-java7-xxx`. How can you install **Java 7**?
2011/08/07
[ "https://askubuntu.com/questions/56104", "https://askubuntu.com", "https://askubuntu.com/users/5717/" ]
There is a [similar answer](https://askubuntu.com/a/56119/44179) on how to install JRE 7. Install Java JDK ================ The manual way -------------- * [Download](http://www.oracle.com/technetwork/java/javase/downloads/index.html) the 32-bit or 64-bit Linux "compressed binary file" - it has a ".tar.gz" file extension. * Uncompress it `tar -xvf jdk-8-linux-i586.tar.gz` (32-bit) `tar -xvf jdk-8-linux-x64.tar.gz` (64-bit) The JDK 8 package is extracted into `./jdk1.8.0` directory. N.B.: Check carefully this folder name since Oracle seem to change this occasionally with each update. * Now move the JDK 8 directory to `/usr/lib` ``` sudo mkdir -p /usr/lib/jvm sudo mv ./jdk1.8.0 /usr/lib/jvm/ ``` * Now run ``` sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.8.0/bin/java" 1 sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.8.0/bin/javac" 1 sudo update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/lib/jvm/jdk1.8.0/bin/javaws" 1 ``` This will assign Oracle JDK a priority of 1, which means that installing other JDKs will [replace it as the default](https://askubuntu.com/q/344059/23678). Be sure to use a higher priority if you want Oracle JDK to remain the default. * Correct the file ownership and the permissions of the executables: ``` sudo chmod a+x /usr/bin/java sudo chmod a+x /usr/bin/javac sudo chmod a+x /usr/bin/javaws sudo chown -R root:root /usr/lib/jvm/jdk1.8.0 ``` N.B.: Remember - Java JDK has many more executables that you can similarly install as above. `java`, `javac`, `javaws` are probably the most frequently required. This [answer lists](https://askubuntu.com/a/68227/14356) the other executables available. * Run ``` sudo update-alternatives --config java ``` You will see output similar to the one below - choose the number of jdk1.8.0 - for example `3` in this list (unless you have have never installed Java installed in your computer in which case a sentence saying "There is nothing to configure" will appear): ``` $ sudo update-alternatives --config java There are 3 choices for the alternative java (providing /usr/bin/java). Selection Path Priority Status ------------------------------------------------------------ 0 /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java 1071 auto mode 1 /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java 1071 manual mode * 2 /usr/lib/jvm/jdk1.7.0/bin/java 1 manual mode 3 /usr/lib/jvm/jdk1.8.0/bin/java 1 manual mode Press enter to keep the current choice[*], or type selection number: 3 update-alternatives: using /usr/lib/jvm/jdk1.8.0/bin/java to provide /usr/bin/java (java) in manual mode ``` Repeat the above for: ``` sudo update-alternatives --config javac sudo update-alternatives --config javaws ``` **Note for NetBeans users!** You need to [set the new JDK as default](https://stackoverflow.com/a/2809447/1505348) editing the configuration file. --- If you want to enable the Mozilla Firefox plugin: ``` 32 bit: ln -s /usr/lib/jvm/jdk1.8.0/jre/lib/i386/libnpjp2.so ~/.mozilla/plugins/ 64 bit: ln -s /usr/lib/jvm/jdk1.8.0/jre/lib/amd64/libnpjp2.so ~/.mozilla/plugins/ ``` N.B.: You can link the plugin (`libnpjp2.so`) to `/usr/lib/firefox/plugins/` for a system-wide installation (`/usr/lib/firefox-addons/plugins` from 15.04 onwards). For Ubuntu 13.10, the path to the plugin directory is `/usr/lib/firefox/browser/plugins/`. Depending on your configuration, you might need to update the apparmor profile for Firefox (or other browsers) in `/etc/apparmor.d/abstractions/ubuntu-browsers.d/java`: ``` # Replace the two lines: # /usr/lib/jvm/java-*-sun-1.*/jre/bin/java{,_vm} cx -> browser_java, # /usr/lib/jvm/java-*-sun-1.*/jre/lib/*/libnp*.so cx -> browser_java, # with those (or adapt to your new jdk folder name) /usr/lib/jvm/jdk*/jre/bin/java{,_vm} cx -> browser_java, /usr/lib/jvm/jdk*/jre/lib/*/libnp*.so cx -> browser_java, ``` Then restart apparmor: ``` sudo /etc/init.d/apparmor restart ``` The easy way (Obsolete) ----------------------- > > **Note:** WebUpd8 team's PPA has been discontinued with effective from April 16, 2019. Thus this PPA doesn't have any Java files. More information can be found on [PPA's page on Launchpad](https://launchpad.net/~webupd8team/+archive/ubuntu/java). Hence this method no longer works and exists because of hostorical reasons. > > > The easiest way to install the JDK 7 is to do it with the Web Up8 Oracle Java OOS. However, it is believed that this PPA is sometimes out of date. Also note [the dangers of using a PPA](https://askubuntu.com/questions/35629/are-ppas-safe-to-add-to-my-system-and-what-are-some-red-flags-to-watch-out). This installs JDK 7 (which includes Java JDK, JRE and the Java browser plugin): ``` sudo apt-get install python-software-properties sudo add-apt-repository ppa:webupd8team/java sudo apt-get update sudo apt-get install oracle-java7-installer # or if you want JDK 8: # sudo apt-get install oracle-java8-installer # these commands install Oracle JDK7/8 and set them as default VMs automatically: # sudo apt-get install oracle-java7-set-default # sudo apt-get install oracle-java8-set-default ``` *[Source](http://www.webupd8.org/2012/01/install-oracle-java-jdk-7-in-ubuntu-via.html)* N.B.: Before someone screams *this is against the Oracle redistribution license* - the PPA does not actually have Java in the personal repository. Instead, the PPA directly downloads from Oracle and installs it. The Script way ============== If you're on a fresh installation of Ubuntu with no previous Java installations, this script automates the process outlined above if you don't want to type all that into a console. Remember, you **still need to download Java from Oracle's website** -- Oracle's links are not `wget` friendly. Before using this **make sure** that this script is in the same directory as the `.tar.gz` file extension that you downloaded and there are **no** files that start with jdk-7 in the same folder. If there are, please move them out of the folder temporarily. Remember to make the script executable (`chmod +x <script's file>`). ``` #!/bin/sh tar -xvf jdk-7* sudo mkdir /usr/lib/jvm sudo mv ./jdk1.7* /usr/lib/jvm/jdk1.7.0 sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.7.0/bin/java" 1 sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.7.0/bin/javac" 1 sudo update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/lib/jvm/jdk1.7.0/bin/javaws" 1 sudo chmod a+x /usr/bin/java sudo chmod a+x /usr/bin/javac sudo chmod a+x /usr/bin/javaws ``` If you want to install the plugin for Firefox then add this to the end of the script: ``` mkdir ~/.mozilla/plugins ln -s /usr/lib/jvm/jdk1.7.0/jre/lib/amd64/libnpjp2.so ~/.mozilla/plugins/ sudo /etc/init.d/apparmor restart ``` Check if installation was successful ==================================== You can check if the installation succeeded with the following command: ``` java -version ``` You should see something like ``` java version "1.8.0" Java(TM) SE Runtime Environment (build 1.8.0-b132) Java HotSpot(TM) 64-Bit Server VM (build 25.0-b70, mixed mode) ``` You can check if the JRE Mozilla plugin has been successful by using the [official oracle website](http://java.com/en/download/installed.jsp). --- For Java 6: [How do I install Oracle JDK 6?](https://askubuntu.com/questions/67909/how-to-install-oracle-java-jdk-6)
For me it's a little bit different. For Ubuntu 12.04 LTS Precise (Desktop): 1. Download `jre-*.tar.gz` 2. `tar -zxvf jre-*.tar.gz` 3. `mkdir /usr/lib/jvm/` 4. `mv jre* /usr/lib/jvm/` 5. `ln -s /usr/lib/jvm/jre*/bin/java /usr/bin/` That's all. To make sure it's correct: ``` java -version ``` If you want to add plug in for Firefox or Chrome: 1. `mkdir ~/.mozilla/plugins` 2. `ln -s /usr/lib/jvm/jre*/lib/i386/libnpjp2.so ~/.mozilla/plugins/` Special Note: If you have a fresh 64 bit install, you may experience the following error when running `java -version` ``` -bash: ./java: No such file or directory ``` This is caused by a dependency on the `libc6-i386` package which is not included by default in 64 bit Ubuntu Desktop 12.04 LTS. To install this package, run: `sudo apt-get install libc6-i386`
56,104
I want to install **Oracle's JRE** and to update to the latest version with the Software Updater when they released. Is there a Ubuntu package that is provided by Canonical or Oracle? Before release Java 7, I followed [this way](https://askubuntu.com/questions/5459/how-can-i-install-the-latest-version-of-sun-java-jre) to install **Java 6**. But it doesn't work for **Java 7**. There is no package `sun-java7-xxx`. How can you install **Java 7**?
2011/08/07
[ "https://askubuntu.com/questions/56104", "https://askubuntu.com", "https://askubuntu.com/users/5717/" ]
Installing Oracle Java (JDK/JRE): ================================= You can automate the task of installing/uninstalling Oracle Java (JDK/JRE) from a downloaded (tar.gz) source with this script: [oraji](https://github.com/neurobin/oraji). Steps: 1. [Download](http://www.oracle.com/technetwork/java/javase/downloads/index.html) the tar.gz source of your desired jdk/jre version. 2. run `sudo oraji /path/to/the/jdk_or_jre/archive` Uninstall: ========== run `sudo oraji -u` and confirm the jdk/jre version to be uninstalled.
OS: Ubuntu 18.04 LTS I am surprised no one has mentioned `conda` . Link: <https://docs.conda.io/en/latest/miniconda.html> I installed java in one of my conda environments and used the `java` command without problems.
56,104
I want to install **Oracle's JRE** and to update to the latest version with the Software Updater when they released. Is there a Ubuntu package that is provided by Canonical or Oracle? Before release Java 7, I followed [this way](https://askubuntu.com/questions/5459/how-can-i-install-the-latest-version-of-sun-java-jre) to install **Java 6**. But it doesn't work for **Java 7**. There is no package `sun-java7-xxx`. How can you install **Java 7**?
2011/08/07
[ "https://askubuntu.com/questions/56104", "https://askubuntu.com", "https://askubuntu.com/users/5717/" ]
For me it's a little bit different. For Ubuntu 12.04 LTS Precise (Desktop): 1. Download `jre-*.tar.gz` 2. `tar -zxvf jre-*.tar.gz` 3. `mkdir /usr/lib/jvm/` 4. `mv jre* /usr/lib/jvm/` 5. `ln -s /usr/lib/jvm/jre*/bin/java /usr/bin/` That's all. To make sure it's correct: ``` java -version ``` If you want to add plug in for Firefox or Chrome: 1. `mkdir ~/.mozilla/plugins` 2. `ln -s /usr/lib/jvm/jre*/lib/i386/libnpjp2.so ~/.mozilla/plugins/` Special Note: If you have a fresh 64 bit install, you may experience the following error when running `java -version` ``` -bash: ./java: No such file or directory ``` This is caused by a dependency on the `libc6-i386` package which is not included by default in 64 bit Ubuntu Desktop 12.04 LTS. To install this package, run: `sudo apt-get install libc6-i386`
OS: Ubuntu 18.04 LTS I am surprised no one has mentioned `conda` . Link: <https://docs.conda.io/en/latest/miniconda.html> I installed java in one of my conda environments and used the `java` command without problems.
56,104
I want to install **Oracle's JRE** and to update to the latest version with the Software Updater when they released. Is there a Ubuntu package that is provided by Canonical or Oracle? Before release Java 7, I followed [this way](https://askubuntu.com/questions/5459/how-can-i-install-the-latest-version-of-sun-java-jre) to install **Java 6**. But it doesn't work for **Java 7**. There is no package `sun-java7-xxx`. How can you install **Java 7**?
2011/08/07
[ "https://askubuntu.com/questions/56104", "https://askubuntu.com", "https://askubuntu.com/users/5717/" ]
Get the JDK from Oracle/Sun; download the Java JDK at: <http://www.oracle.com/technetwork/java/javase/overview/index.html> Please download or move the downloaded file to your home directory, `~`, for ease. Note: * Don't worry about what JDK to download for JEE. * Please skip copying the Prompt " user@host:~$ ". * Hit enter after each command. Run in a terminal.. ``` user@host:~$ sudo mkdir -p /usr/lib/jvm/ user@host:~$ sudo mv jdk-7u4-linux-i586.tar.gz /usr/lib/jvm/ user@host:~$ cd /usr/lib/jvm/ user@host:~$ sudo tar zxvf jdk-7u4-linux-i586.tar.gz ``` Now enable Java (by running individually): ``` user@host:~$ sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.7.0_04/bin/java" 1 user@host:~$ sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.7.0_04/bin/javac" 1 user@host:~$ sudo update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/lib/jvm/jdk1.7.0_04/bin/javaws" 1 ``` Close all browsers. Create a Mozilla plugins folder in your home directory: ``` user@host:~$ mkdir ~/.mozilla/plugins/ ``` Create a symbolic link to your Mozilla plugins folder. For 64-bit systems, replace ‘i386’ with ‘amd64’: ``` user@host:~$ ln -s /usr/lib/jvm/jdk1.7.0/jre/lib/i386/libnpjp2.so ~/.mozilla/plugins/ ``` Testing: ``` user@host:~$ java -version ``` Output: ``` java version "1.7.0_04" Java(TM) SE Runtime Environment (build 1.7.0_04-b20) Java HotSpot(TM) Server VM (build 23.0-b21, mixed mode) ``` Testing: ``` user@host:~$ javac -version ``` Output: ``` javac 1.7.0_04 ``` Verify JRE at <http://java.com/en/download/installed.jsp>.
OS: Ubuntu 18.04 LTS I am surprised no one has mentioned `conda` . Link: <https://docs.conda.io/en/latest/miniconda.html> I installed java in one of my conda environments and used the `java` command without problems.
56,104
I want to install **Oracle's JRE** and to update to the latest version with the Software Updater when they released. Is there a Ubuntu package that is provided by Canonical or Oracle? Before release Java 7, I followed [this way](https://askubuntu.com/questions/5459/how-can-i-install-the-latest-version-of-sun-java-jre) to install **Java 6**. But it doesn't work for **Java 7**. There is no package `sun-java7-xxx`. How can you install **Java 7**?
2011/08/07
[ "https://askubuntu.com/questions/56104", "https://askubuntu.com", "https://askubuntu.com/users/5717/" ]
To me the Debian way (sic) would be to create your own package. You install `java-package` ``` sudo apt-get install java-package ``` You download the Oracle tar.gz archive. You create your deb package ``` fakeroot make-jpkg jdk-7u79-linux-x64.tar.gz ``` An you install it ``` sudo dpkg -i oracle-java7-jdk_7u79_amd64.deb ```
OS: Ubuntu 18.04 LTS I am surprised no one has mentioned `conda` . Link: <https://docs.conda.io/en/latest/miniconda.html> I installed java in one of my conda environments and used the `java` command without problems.
56,104
I want to install **Oracle's JRE** and to update to the latest version with the Software Updater when they released. Is there a Ubuntu package that is provided by Canonical or Oracle? Before release Java 7, I followed [this way](https://askubuntu.com/questions/5459/how-can-i-install-the-latest-version-of-sun-java-jre) to install **Java 6**. But it doesn't work for **Java 7**. There is no package `sun-java7-xxx`. How can you install **Java 7**?
2011/08/07
[ "https://askubuntu.com/questions/56104", "https://askubuntu.com", "https://askubuntu.com/users/5717/" ]
This worked for my development needs of being able to run/compile 1.6 or 1.7. Previously I was just running 1.6 from a Ubuntu apt package. 1. Download [1.7 gzip](http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html). 2. Extract to folder 3. Update JAVA\_HOME and PATH in bash file ``` JAVA_HOME=/opt/java/jdk1.7.0_25 export JAVA_HOME PATH=$JAVA_HOME/bin:$PATH export PATH ```
For me it's a little bit different. For Ubuntu 12.04 LTS Precise (Desktop): 1. Download `jre-*.tar.gz` 2. `tar -zxvf jre-*.tar.gz` 3. `mkdir /usr/lib/jvm/` 4. `mv jre* /usr/lib/jvm/` 5. `ln -s /usr/lib/jvm/jre*/bin/java /usr/bin/` That's all. To make sure it's correct: ``` java -version ``` If you want to add plug in for Firefox or Chrome: 1. `mkdir ~/.mozilla/plugins` 2. `ln -s /usr/lib/jvm/jre*/lib/i386/libnpjp2.so ~/.mozilla/plugins/` Special Note: If you have a fresh 64 bit install, you may experience the following error when running `java -version` ``` -bash: ./java: No such file or directory ``` This is caused by a dependency on the `libc6-i386` package which is not included by default in 64 bit Ubuntu Desktop 12.04 LTS. To install this package, run: `sudo apt-get install libc6-i386`
56,104
I want to install **Oracle's JRE** and to update to the latest version with the Software Updater when they released. Is there a Ubuntu package that is provided by Canonical or Oracle? Before release Java 7, I followed [this way](https://askubuntu.com/questions/5459/how-can-i-install-the-latest-version-of-sun-java-jre) to install **Java 6**. But it doesn't work for **Java 7**. There is no package `sun-java7-xxx`. How can you install **Java 7**?
2011/08/07
[ "https://askubuntu.com/questions/56104", "https://askubuntu.com", "https://askubuntu.com/users/5717/" ]
Get the JDK from Oracle/Sun; download the Java JDK at: <http://www.oracle.com/technetwork/java/javase/overview/index.html> Please download or move the downloaded file to your home directory, `~`, for ease. Note: * Don't worry about what JDK to download for JEE. * Please skip copying the Prompt " user@host:~$ ". * Hit enter after each command. Run in a terminal.. ``` user@host:~$ sudo mkdir -p /usr/lib/jvm/ user@host:~$ sudo mv jdk-7u4-linux-i586.tar.gz /usr/lib/jvm/ user@host:~$ cd /usr/lib/jvm/ user@host:~$ sudo tar zxvf jdk-7u4-linux-i586.tar.gz ``` Now enable Java (by running individually): ``` user@host:~$ sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.7.0_04/bin/java" 1 user@host:~$ sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.7.0_04/bin/javac" 1 user@host:~$ sudo update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/lib/jvm/jdk1.7.0_04/bin/javaws" 1 ``` Close all browsers. Create a Mozilla plugins folder in your home directory: ``` user@host:~$ mkdir ~/.mozilla/plugins/ ``` Create a symbolic link to your Mozilla plugins folder. For 64-bit systems, replace ‘i386’ with ‘amd64’: ``` user@host:~$ ln -s /usr/lib/jvm/jdk1.7.0/jre/lib/i386/libnpjp2.so ~/.mozilla/plugins/ ``` Testing: ``` user@host:~$ java -version ``` Output: ``` java version "1.7.0_04" Java(TM) SE Runtime Environment (build 1.7.0_04-b20) Java HotSpot(TM) Server VM (build 23.0-b21, mixed mode) ``` Testing: ``` user@host:~$ javac -version ``` Output: ``` javac 1.7.0_04 ``` Verify JRE at <http://java.com/en/download/installed.jsp>.
You can download the latest [Oracle JDK 8](https://www.oracle.com/java/technologies/javase-jdk8-downloads.html), then you open a terminal with '**Ctrl + Alt + t**' and enter the following commands: ``` cd /usr/lib/jvm ``` *If the /usr/lib/jvm folder does not exist, enter this command will create the directory `sudo mkdir /usr/lib/jvm`* Then extract the **jdk-{version}.tar.gz** file in that directory using this command. ``` sudo tar -xvzf ~/Downloads/jdk-{version}.tar.gz ``` The the following command to open the environment variables file. ``` sudo vim /etc/environment ``` In the opened file, add the following bin folders to the existing PATH variable. ``` PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/lib/jvm/jdk-{version}/bin:/usr/lib/jvm/jdk-{version}/db/bin:/usr/lib/jvm/jdk-{version}/jre/bin" J2SDKDIR="/usr/lib/jvm/jdk-{version}" J2REDIR="/usr/lib/jvm/jdk-{version}/jre" JAVA_HOME="/usr/lib/jvm/jdk-{version}" DERBY_HOME="/usr/lib/jvm/jdk-{version}/db" ``` Save the changes and close the vim. Then enter the following commands to inform the system about the Java's location. ``` sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk-{version}/bin/java" 0 sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk-{version}/bin/javac" 0 sudo update-alternatives --set java /usr/lib/jvm/jdk-{version}/bin/java sudo update-alternatives --set javac /usr/lib/jvm/jdk-{version}/bin/javac ``` To verify the setup enter the following commands and make sure that they print the location of java and javac as you have provided in the previous step. ``` update-alternatives --list java update-alternatives --list javac ``` Now restart the terminal again and enter following commands. ``` java -version javac -version ``` If you get the installed Java version as the output, you have successfully installed the Oracle JDK in your system.