text
stringlengths
70
452k
dataset
stringclasses
2 values
How to find the dynamic range of ADC? I bought a Analog to Digital Converter but did not gave much attention to Dynamic range. The resolution is 12 Bit. Minimum input voltage is 0V and maximum is 5V. The problem is I don't have the datasheet and want to know how can I find the Dynamic range of this ADC? Additional info: It says it has 10Megasample per sec of sample-rate. Did you mean 'I have a homework question that noone wants to answer so I try it this way'? http://electronics.stackexchange.com/questions/118457/analog-to-digital-converter-and-resolution Regarding 1.76 db, to my understanding it comes from the factor 1/2:1/3 = 1.5 in dB. 1/2 is for calculating the signal power assuming a narrowband quasi sinusoidal signal. 1/3 is for calculating quantization noise power assuming a uniform distribution with +/-LSB/2. The dynamic range is the ratio of the maximum voltage to the minimum voltage that the ADC can convert. The maximum voltage is 5 volts. Since it is a 12-bit converter, it has a resolution of 1 in \$2^{12}\$ or 4096. Thus the minimum voltage, for which the ADC would have only the least significant bit set, is 5V/4096 = 1.22 millivolts. So the dynamic range of your ADC is 5/1.22mV = 4096 = 72.2 dB. In general, the dynamic range is only a function of the number of bits, not the maximum input voltage. But I calculated using voltage to show you the details. I thought that the resolution would be 1.22mV and the dynamic range is analogous to the input range - 5V. The wiki says "[Dynamic Range is] .. the ratio between the largest and smallest possible values of a changeable quantity". @Barry you said it has a resolution of 2¹²-1 or 4095 but according to the wiki http://en.wikipedia.org/wiki/Analog-to-digital_converter it is just 2¹²? The dynamic range is the ratio (usually expressed in dB) between the noise floor of the ADC and the maximum input. As Brian says in his comment, the quantization noise sets a lower limit on the noise floor at the actual sample rate, however the noise of a real ADC will be higher than the quantization noise. Also, if you take your 10Msps ADC and band-limit and decimate the output to a lower sample rate the dynamic range can be increased, by as much as 10dB for a decade of down-sampling. What do you mean by quantization noise and noise of the ADC? I understand what quantization is, but not its use in the context of noise. Do you mean that the dynamic range of the ADC will be impacted due to the quantization of noise superimposed on the signal we are attempting to digitize? (i.e. signal to sample + noise floor?) @sherrellbc There will be some internal noise in addition to the quantization noise. The effective number of bits (ENOB) of a "24-bit" ADC might be 19 bits under certain conditions, so if you use 24 bits in the calculation you'll be overly optimistic. I see - similar to calculating significant digits beyond the precision you know certain variables to. How much you determien the ENOF of a particular ADC? Experimentation with high-precision voltages? How exactly would you define "quantization noise"? I find very little when searching that term. From what I gather the definition seems to parallel quantization error, but are they exactly the same thing? @sherrellbc ENOB is often listed in the datasheet. It's always less than the actual number of bits (because quantization noise sets a lower floor). THE dynamic range of your ADC is calculated as DR= 6.021*N + 1.763 dB where N= is the number of bits i.e 12 bit DR= 74dB. Can you explain the constant 1.763dB here? I can understand that each new bit doubles the voltage range, so provides ~6dB of dynamic range, but not sure how a 0 bit ADC would have 1.763dB of dynamic range ;) I found a link to a very in depth derivation here: http://www.analog.com/media/en/training-seminars/tutorials/MT-229.pdf This is actually the signal-to-noise ratio of an ADC, the dynamic range is subtly different.
common-pile/stackexchange_filtered
Centroid given a list of vectors I have to calculate the mean vector given a list of vectors such as this one '((2 3 56) (22 45 34) (21 2 23) (4 8 3) (4 4 1) (4 4 5)) In short words I have to find the centroid given a list of lists. (defun vsum (x y) (cond ((not (= (list-length x) (list-length y))) (error "dimension error!")) ((null (first x)) NIL) (t (cons (+ (first x) (first y)) (vsum (rest x) (rest y)))))) I already created this simple function but I'm having major troubles in getting it used in a recursive way (I prefer it against the loop) to accomplish my task. I need that to be dimension agnostic, too (e.g. vectors of size 2 or 3 mostly). In this case there is no need of loops or recursion, only primitive functionals: (defun centroid (list) (when list (let ((list-length (length list)) (dimension (length (first list)))) (unless (every (lambda (v) (= (length v) dimension)) (rest list)) (error "Dimension error!")) (mapcar (lambda (x) (/ x list-length)) (reduce (lambda (x y) (mapcar #'+ x y)) list))))) The formula used is that for a finite set of points (see Wikipedia). First a check is done to see if all the vectors have the same dimension (the part with every), then the sum is calculated with the (reduce (lambda (x y) (mapcar #'+ x y)) list) part, and finally each coordinate is divided by the number of points (the mapcar part). Thanks! That works perfectly well. I thought about applying the same recursion model I made with the sum function above and I didn't give the right weight to the mapcar keyword. APPLY has a limited argument size. Don't use APPLY for list processing. APPLY is thought as a mechanism for function calls with computed arglists. (reduce (lambda (x y) (mapcar #'+ x y)) list) If we are going to check all these errors, we should also check for an input empty list. In this case, the centroid could be a vector of all zeros: but we don't know how many dimensions it must have. I think in this case what the above code will do is try to call the (lambda (x y) ..) with no arguments, resulting in a hard to understand error message. (The division by list-length, which is zero, won't be reached). @Kaz if the list is empty the result of the previous function is nil, since the body is enclosed in a when, and this seems to me a reasonable result (rather than a zero vector, which is actually a point that could be generated by some other input). I prefer it against the loop But it makes no sense. Recursive functions are harder to use and can cause stack overflows. Your vsum function is better written as (defun vsum (x y) (assert (= (length x) (length y)) ; both lists of equal length (x y) ; the lists, can be repaired "Dimension error") ; the error message (mapcar #'+ x y)) ; simple mapping Above version is better to use interactively in case of an error, due to the use of ASSERT shorter clearer without stack overflow problems for larger input lists The mapcar expression can be written using loop as: (loop for x1 in x and y1 in y collect (+ x y)) Which is still clearer and shorter than your recursive code.
common-pile/stackexchange_filtered
Early 80s sci-fi movie, cyborg(?), shooting .. had this stuck in my mind for about 30 years This is an incredibly vague scene depiction, but I'm trying to recall a sci-fi movie I watched as a very young kid. It would have been out perhaps early 80s. I don't recall any of the story but the image has stuck in my head and for years I always wanted to know what the movie was about. I recall a man (possibly a cyborg) who carried a shield, and for the scene I recalled drove/hovered around on something that resembled a segway or a one person standing hover craft. There was a lot of shooting going on. He may (may!) have had red infared vision like terminator (although I may just be getting that part mixed up with terminator :) I know if I saw the scene again, I'd sure to recognize it. Anyway if anyone has the slightest inclination to what film this may be, I'd love to hear. Sorry there isn't much more I recall, I guess this is the last chance for me to put this to bed :) Space Mutiny? That had shooting, at least. Hmm 1988, it would have been sooner than that. But thanks for your suggestion. You might be thinking of The Eliminators. The timing fits, and the trailer has most everything you're describing: a guy with a shield, a cyborg on a one-person vehicle (though it's tank treads, not a hovercraft), and shooting. Haha, that is totally it! Completely different from how I recall it, I just remember the cyborg guy. Don't remember a ninja, and the action guy (although I vaguely recall the woman). Anyway looks terrible, can't wait to watch it :) I see the full length movie is on YouTube too. Thanks a lot! It's cool moments like this that make me like this site. Happy to see that the mystery was solved after all these years :D Wow - the movie features both Tasha Yar AND a Borg drone a year before TNG aired. I call time-travel hijinks. @Omegacron It's Tasha's home planet, before she joined Starfleet. ELIMINATORS: (Fox, 1986) D: Peter Manoogian S: Paul De Meo, Danny Bilson P: Charles Band. A vengeful "mandroid" is played by R.J. Reynolds tobacco heir Patrick Reynolds. This PG movie throws in everything: a lesbian river queen, a flying robot, a prehistoric tribe, kung fu. Andrew Prince as a riverboat pilot costars with Denise Crosby as a scientist and Conan Lee as Ninja. It was shot in Spain but is set in South America. ("Psychotronic Video Guide" by Michael Weldon. p. 182)
common-pile/stackexchange_filtered
Initializing a Tesseract I try to get some text of an image by using OCR. I have to initialize a Tesseract for that and this was my try: Imports Emgu.CV Imports Emgu.Util Imports Emgu.CV.Structure Imports Emgu.CV.OCR Imports Emgu.CV.UI Imports Emgu.CV.CvEnum Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim lolProcess() As Process = Process.GetProcessesByName("lolClient") Dim snap As New CScreenFromWindow Dim OCRz As Tesseract = New Tesseract("tessdata", "eng", Tesseract.OcrEngineMode.OEM_TESSERACT_ONLY) OCRz.Recognize(New Image(Of Bgr, Byte)(snap.GetFromAll(lolProcess(0)))) MsgBox(OCRz.GetText()) End Sub End Class When launching my code I get the following error: "System.TypeInitializationException" "Emgu.CV.OCR.Tesseract" caused an exception I have googled a lot, but can't find my mistake. I've downloaded EMGU from this link and installed the .exe. Then I added every .dll from the bin-directory as a reference to my project. I also added all opencv_XXXXX.dll-files to my project. Then I also added the tessdata-directory to my project. I've marked all the added dlls as "Always copy to output-directory". There are opencv_XXXXXX.dll-files for x86 and x64. I tried to swap them to x64 but those also don't work. Does anybody see my mistake? This are the error-messages and stack-traces: System.ArgumentException: Unable to create ocr model using Path tessdata and language eng. bei Emgu.CV.OCR.Tesseract.Init(String dataPath, String language, OcrEngineMode mode) in c:\Emgu\emgucv-windows-universal-gpu <IP_ADDRESS>7\Emgu.CV.OCR\Tesseract.cs:Zeile 226. bei Emgu.CV.OCR.Tesseract..ctor(String dataPath, String language, OcrEngineMode mode) in c:\Emgu\emgucv-windows-universal-gpu <IP_ADDRESS>7\Emgu.CV.OCR\Tesseract.cs:Zeile 118. bei Dodgemaster.Form1.Button1_Click(Object sender, EventArgs e) in X:\Dokumente\Visual Studio 2013\Projects\Dodgemaster\Dodgemaster\Form1.vb:Zeile 16. A Hello World test-programm works fine. So it can't be something wrong with the references, right? Can you provide the full error message including stack trace ++ any inner exceptions etc. https://stackoverflow.com/a/75531269/4973087 When you have referenced the .dlls try changing the "copy to output directory" value in the properties to "Copy always" Also try running it on 3.5 .NET framework. Failing that try following this: https://www.youtube.com/watch?v=RqvvXJXuRYY&list=UUxAnMtjN08ryThpgYTBmILg Really helpful tutorial. That's excactly the video I am working with. I think I have done all the things he did, but still I get an error. "copy always" is active and on 3.5 it doesn't work neither. And your machine supports CUDA? That could be one problem. I have an AMD-Radeon, so CUDA shouldn't work for me. But I've downloaded a new Emgu from this link and it says nothing from CUDA and is for x64, but still the same error. Hmm, not sure I can help then i'm afraid. Might be worth checking your new emgu install at: yourinstall\Emgu.CV.Example\OCR and there should be a C# version of OCR in there you can maybe work from? unless it absolutely HAS to be in VB? Yes, it has to be VB. Even some example programs from myinstall\solution aren't working. Some do, some throw an exception. After several reinstalls of different emgu-installs I finally found one, that works. It's an older version, not the current one, but it is for x64. Having in mind that EVERY needed file/dll HAS TO be for x64 and working excactly as in the video, I finally got it work. Seemed to be an x86/x64 issue. You have to change the DPath from "tessdata" to "". Dim OCRz As Tesseract = New Tesseract("", "eng", OcrEngineMode.TesseractOnly) That's how I got mine to work.(libemgucv-windows-universal-cuda-<IP_ADDRESS>8)
common-pile/stackexchange_filtered
Problem getting methods in JavaScript from Java Spring Boot model objects I am trying to build an application using Spring Boot (Java 15, Spring Boot 2.4.2) and Thymeleaf (version 2.4.2), which would allow me to add some electronic parts to database and generally use the database in an accessible way. One type of those electronic parts are resistors, one of the attributes of which is resistance. To add the resistance, user should type in the value of number of the resistance and choose unit from a list (mΩ, Ω, kΩ or MΩ), which is shown below: <div class="custom-select"> <label>Resistance</label> <input type="number" step="0.01" th:field="*{resistor.resistance}"> <select th:field="*{resistor.resistanceUnit}" > <option value="mΩ">mΩ</option> <option value="Ω">Ω</option> <option value="kΩ">kΩ</option> <option value="MΩ">MΩ</option> </select><br/> </div> Screenshot of typing in the resistance Then, after submitting the data to ResistorController class, the controller calls the method in Resistor class to convert the resistance to single Double value, which will be easier to sort by a database: Method in ResistorController: @PostMapping("/add") public String addResistor(@ModelAttribute("resistor") Resistor resistor, Model model) { resistor.convertValuesFromUnitized(); model.addAttribute("resistor", resistor);//converting method mentioned above resistor.setId(resistorService.addResistor(resistor)); return "resistor/registrationDone"; } Part of Resistor class: @Data public class Resistor extends BaseComponent { private String type; private double resistance; private int tolerance; private double power; ... private String resistanceUnit;//mΩ, Ω, kΩ, MΩ public String writeResistance() {//**This is a method mentioned in the text below** if (resistance < 1) return resistance*1000+"mΩ"; else if (resistance < 1000) return resistance+"Ω"; else if (resistance >= 1000 && resistance < 1_000_000) return resistance/1000 + "kΩ"; else return resistance/1_000_000 + "kΩ"; } ... public void convertValuesFromUnitized() {//**This is the mentioned above converting method** switch (resistanceUnit) { case "mΩ" -> resistance /= 1000; case "kΩ" -> resistance *= 1000; case "MΩ" -> resistance *= 1_000_000; } ... } public void convertValuesToUnitized() { if (resistance < 1) { resistance *= 1000; resistanceUnit = "mΩ"; } else if (resistance < 1000) resistanceUnit = "Ω"; else if (resistance >= 1000 && resistance < 1_000_000) { resistance /= 1000; resistanceUnit = "kΩ"; } else { resistance /= 1_000_000; resistanceUnit = "MΩ"; } ... } ... } In the database, I don't store units (mΩ, Ω, kΩ or MΩ) to avoid data redundancy. But in my html file, which shows list of all resistors, I want to show the resistance attribute with units, so I convert the number values again to "unitized" values using the second method (writeResistance()) in the Resistor class (↑↑attached above↑↑). Part of the html file with the list of all resistors: <td th:text="${resistor.writeResistance()}">Resistance</td> All the code above works fine, but my problem is when I want to filter the resistors list using e.g. name of the resistor (resistor model). I'm trying to do it in JavaScript to have live changes - without submitting data to the controller and filtering it at the database level. Fragment of HTML file, which refers to the JavaScript filter function: <th><input type="text" id="nameFilter" onkeyup="filterTable()"/></th> The JavaScript filter function itself: function filterTable() { let resistors = /*[[${resistors}]]*/ "res"; let resistorsFiltered = []; console.clear(); for(let i=0; i<resistors.length; ++i) { let name = resistors[i].name.toLowerCase(); if(name.includes(document.getElementById("nameFilter").value)) { resistorsFiltered.push(resistors[i]); } } //building new table body: let table = document.getElementById("resistorsTableBody"); table.innerHTML=''; for(let i=0; i<resistorsFiltered.length; ++i) { let resistor = resistorsFiltered[i]; console.log(resistor); /** * I write about below commented out code in the text below */ /*let Resistor = Java.type(pl.argo.ArgoInventory.resistor.Resistor); let resistor = new Resistor(resistorsFiltered[i]);*/ let row = ` <tr> <td>${resistorsFiltered[i].name}</td> <td>${resistorsFiltered[i].casing}</td> <td>${resistorsFiltered[i].manufacturer}</td> <td>${resistorsFiltered[i].typeOfAssembly}</td> <td>${resistorsFiltered[i].type}</td> <td>${resistorsFiltered[i].writeResistance()}</td> ... </tr>`; table.innerHTML += row; } } The resistorsFiltered[i].writeResistance() method doesn't work - Intellij Idea doesn't find any methods assigned to the resistor variable, nor does Chrome browser. Intellij Idea message: enter image description here Chrome message: enter image description here I think this is because while transforming Java object to JavaScript object, the transformed object has only its fields, but not its methods. My question is: How to "brake the limit" and use the Java object methods (the object is the Model Attribute) in this JavaScript script? I tried the metod below: let Resistor = Java.type(pl.argo.ArgoInventory.resistor.Resistor); let resistor = new Resistor(resistorsFiltered[i]); which I put earlier in the JavaScript filtrerTable() function in the code above. Unfortunately this method doesn't work - the Chrome browser tells that "Java is not defined": enter image description here But this isn't my main problem. I want to refer to my Model Attribute (resistor object) and not just a method from "some" Java class. Is it somehow possible to use the Java Model Attribute object methods in JavaScript file? If yes, can someone propose a method to do it? Or, if not, can someone recommend me a method which would somehow fit my needs? In the addition, I will add, that I spent a few hours to find a sollution, bo unfortunately nothing suited my problem. Stupid question: You did replace let resistors = /*[[${resistors}]]*/ "res"; with something sensible didn't you? As far as I read in the thymeleaf documentacion link, this is the way to access the model attributes. So the /*[[${resistors}]]*/ is the model attribute and "res" is the default value while loading staticly without thymeleaf. Maybe the "res" is stupid default value, but I put it here only as an example. You asked about the name, right? Or am I completly doing this wrong? I'm truly new to any JavaScript files, so it is possible that I did something silly. Ignore me. I know nothing about thymeleaf. I didn't realise it was interpolating the value from somewhere else.
common-pile/stackexchange_filtered
discoverSchema converts the column names to small case from camel case in loopback disoverSchema function in loopback converts all the camel-cased column names to small-case. After reading a bit I found out its loopback-datasource-juggler which is responsible for this. Also, I read that its possible to preserve the naming strategy using name-mapper but have no idea how to use that. below is the piece of code where the table has camel-cased names but modelDef returned is having small-case names. Any help will be appreciated. ' ds.discoverSchema(tableName, function(err, modelDef) { if (err) { console.log(err); throw err; } Where did you come across the name-mapper? According to https://loopback.io/doc/en/lb3/Model-definition-JSON-file.html there is no option to retain the naming strategy. here the issue is was being discussed https://github.com/strongloop/loopback-connector-mysql/issues/57 where @reymodfeng has given this link for the solution https://github.com/strongloop/loopback-datasource-juggler/blob/master/lib/datasource.js#L1304 for the more detailed explanation of issue, you can refer this link https://github.com/strongloop/loopback-datasource-juggler/issues/1268
common-pile/stackexchange_filtered
Updating a Matplotlib plot with user imput Once again I am in need of aid... I am very new to python and I am trying to plot the Mandelbrot set in a GUI. Currently I am working on a function where I can change the colors in which the fractal is rendered in. The problem is that I cant figure out how to replace the old plot with a new one. Everything up to the point where the plot needs to be re-plotted works (the terminal even pauses as if it is recalculating but does not yield anything). I have tried inserting fig.clf() in all the different places that have been suggested by the internet but I still cannot figure it out. Attached is a excerpt of the code will run. Specific locations of this code are located in the function called mandelbrot_image and the class MainPage. Thank you in advance. import matplotlib matplotlib.use("TkAgg") from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib.figure import Figure import tkinter as tk from tkinter import ttk from tkinter import * #import tkinter.messagebox from tkinter import messagebox import numpy as np from numba import jit from matplotlib import colors #maths and display code derived/inspired from Jean Francois Puget #https://www.ibm.com/developerworks/community/blogs/jfp/entry/My_Christmas_Gift?lang=en @jit def mandelbrot(z,maxiter,horizon,log_horizon): c = z for n in range(maxiter): az = abs(z) if az > horizon: return n - np.log(np.log(az))/np.log(2) + log_horizon z = z*z + c return 0 @jit def mandelbrot_set(xmin,xmax,ymin,ymax,width,height,maxiter): horizon = 2.0 ** 40 log_horizon = np.log(np.log(horizon))/np.log(2) r1 = np.linspace(xmin, xmax, width) r2 = np.linspace(ymin, ymax, height) n3 = np.empty((width,height)) for i in range(width): for j in range(height): n3[i,j] = mandelbrot(r1[i] + 1j*r2[j],maxiter,horizon, log_horizon) return (r1,r2,n3) def mandelbrot_image(xmin=-2.,xmax=0.5,ymin=-1.25,ymax=1.25,width=10,height=10,\ maxiter=1000,cmap='hot',gamma=0.3): #the coords and cmap are essentially a filler for the imput in the plot() function at the bottom of the code dpi = 80 img_width = dpi * width img_height = dpi * height x,y,z = mandelbrot_set(xmin,xmax,ymin,ymax,img_width,img_height,maxiter) fig = Figure(figsize=(width, height)) ax = fig.add_subplot(111) ticks = np.arange(0,img_width,3*dpi) x_ticks = xmin + (xmax-xmin)*ticks/img_width ax.set_xticks(ticks); ax.set_xticklabels(x_ticks) y_ticks = ymin + (ymax-ymin)*ticks/img_width ax.set_yticks(ticks); ax.set_yticklabels(y_ticks) ax.set_title("The Mandelbrot set") norm = colors.PowerNorm(gamma) #fig.clf() ax.imshow(z.T,cmap=cmap,origin='lower',norm=norm) return fig LARGE_FONT= ("Verdana", 12) NORM_FONT= ("Verdana", 10) class base(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) tk.Tk.wm_title(self, "Mandelbrot Renderer") container = tk.Frame(self) container.pack(side="top", fill="both", expand = True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (StartPage, MainPage): frame = F(container, self) self.frames[F] = frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame(StartPage) def show_frame(self, cont): frame = self.frames[cont] frame.tkraise() class StartPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self,parent) label = tk.Label(self, text="Start Page", font=LARGE_FONT) label.pack(pady=10,padx=10) button = ttk.Button(self, text="Lets Begin", command=lambda: controller.show_frame(MainPage)) button.pack() class MainPage(tk.Frame): def var_states(self): #this is supposed to send code to run plot() again but it doesnt do it print (self.combobox.get()) print (self.colr) self.plot () def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = tk.Label(self, text="Graph Page!", font=LARGE_FONT) label.pack(pady=10,padx=10) values = ['jet', 'rainbow', 'ocean', 'hot', 'cubehelix','gnuplot','terrain','prism', 'pink'] button1 = ttk.Button(self, text="Back to Home", command=lambda: controller.show_frame(StartPage)) button1.pack() button2 = ttk.Button(self, text="Re-Render", command=self.plot) button2.pack() self.mvar = IntVar() self.cbutton = ttk.Checkbutton(self, text="shadow",onvalue=0, offvalue=1, variable=self.mvar) self.cbutton.pack() self.combobox = ttk.Combobox(self, values=values) self.combobox.current(0) self.combobox.pack(side = RIGHT) global colr self.colr = self.combobox.get() self.plot () def plot (self): colr = self.combobox.get() print (colr) #fig.clf() this does nothing and crashes fig = mandelbrot_image(-0.8,-0.7,0,0.1,cmap=colr) #this is calling the method with the coordinates of the plot and the color scheme #fig.clf()this works but just leaves the screen completely blank canvas = FigureCanvasTkAgg(fig, self) #fig.clf()this works but just leaves the screen completely blank canvas.show() #canvas.clf() #fig.clf() this works but just leaves the screen completely blank canvas.get_tk_widget().pack(side = BOTTOM, fill=tk.BOTH, expand=True) toolbar = NavigationToolbar2TkAgg(canvas, self) toolbar.update() canvas._tkcanvas.pack(side = BOTTOM, fill=tk.BOTH, expand=True) app = base() app.geometry ("800x600") app.mainloop() If you want to update the figure, you shouldn't create it in a function which is called several times. Instead you can create the figure in in the MainPage's init function and only update the content of its subplot. Therefore, the plot function could only clear the axes (not the figure!) and call the mandelbrot_image function to which the axes to plot to can be delivered as an argument. Finally the canvas has to be redrawn using canvas.draw() for the new plot to appear in the GUI. import matplotlib matplotlib.use("TkAgg") from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib.figure import Figure import Tkinter as tk #replace with tkinter for python 3 import ttk import numpy as np from numba import jit from matplotlib import colors #maths and display code derived/inspired from Jean Francois Puget #https://www.ibm.com/developerworks/community/blogs/jfp/entry/My_Christmas_Gift?lang=en @jit def mandelbrot(z,maxiter,horizon,log_horizon): c = z for n in range(maxiter): az = abs(z) if az > horizon: return n - np.log(np.log(az))/np.log(2) + log_horizon z = z*z + c return 0 @jit def mandelbrot_set(xmin,xmax,ymin,ymax,width,height,maxiter): horizon = 2.0 ** 40 log_horizon = np.log(np.log(horizon))/np.log(2) r1 = np.linspace(xmin, xmax, width) r2 = np.linspace(ymin, ymax, height) n3 = np.empty((width,height)) for i in range(width): for j in range(height): n3[i,j] = mandelbrot(r1[i] + 1j*r2[j],maxiter,horizon, log_horizon) return (r1,r2,n3) def mandelbrot_image(ax, xmin=-2.,xmax=0.5,ymin=-1.25,ymax=1.25,width=10,height=10,\ maxiter=1000,cmap='hot',gamma=0.3): #the coords and cmap are essentially a filler for the imput in the plot() function at the bottom of the code dpi = 80 img_width = dpi * width img_height = dpi * height x,y,z = mandelbrot_set(xmin,xmax,ymin,ymax,img_width,img_height,maxiter) ticks = np.arange(0,img_width,3*dpi) x_ticks = xmin + (xmax-xmin)*ticks/img_width ax.set_xticks(ticks); ax.set_xticklabels(x_ticks) y_ticks = ymin + (ymax-ymin)*ticks/img_width ax.set_yticks(ticks); ax.set_yticklabels(y_ticks) ax.set_title("The Mandelbrot set") norm = colors.PowerNorm(gamma) ax.imshow(z.T,cmap=cmap,origin='lower',norm=norm) LARGE_FONT= ("Verdana", 12) NORM_FONT= ("Verdana", 10) class base(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) tk.Tk.wm_title(self, "Mandelbrot Renderer") container = tk.Frame(self) container.pack(side="top", fill="both", expand = True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (StartPage, MainPage): frame = F(container, self) self.frames[F] = frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame(StartPage) def show_frame(self, cont): frame = self.frames[cont] frame.tkraise() class StartPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self,parent) label = tk.Label(self, text="Start Page", font=LARGE_FONT) label.pack(pady=10,padx=10) button = tk.Button(self, text="Lets Begin", command=lambda: controller.show_frame(MainPage)) button.pack() class MainPage(tk.Frame): def var_states(self): #this is supposed to send code to run plot() again but it doesnt do it print (self.combobox.get()) print (self.colr) self.plot () def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = tk.Label(self, text="Graph Page!", font=LARGE_FONT) label.pack(pady=10,padx=10) values = ['jet', 'rainbow', 'ocean', 'hot', 'cubehelix','gnuplot','terrain','prism', 'pink'] button1 = tk.Button(self, text="Back to Home", command=lambda: controller.show_frame(StartPage)) button1.pack() button2 = tk.Button(self, text="Re-Render", command=self.plot) button2.pack() self.mvar = tk.IntVar() self.cbutton = tk.Checkbutton(self, text="shadow",onvalue=0, offvalue=1, variable=self.mvar) self.cbutton.pack() self.combobox = ttk.Combobox(self, values=values) self.combobox.current(0) self.combobox.pack(side = tk.TOP) self.width, self.height = 10, 10 fig = Figure(figsize=(self.width, self.height)) self.ax = fig.add_subplot(111) self.canvas = FigureCanvasTkAgg(fig, self) self.canvas.show() toolbar = NavigationToolbar2TkAgg(self.canvas, self) toolbar.update() self.canvas.get_tk_widget().pack(side = tk.BOTTOM, fill=tk.BOTH, expand=True) self.plot () def plot (self): colr = self.combobox.get() print (colr) self.ax.clear() mandelbrot_image(self.ax, -0.8,-0.7,0,0.1,cmap=colr) self.canvas.draw() app = base() app.geometry ("800x600") app.mainloop() Note: In newer versions of matplotlib you should use NavigationToolbar2Tk instead of NavigationToolbar2TkAgg. you are god. Thanks for helping me out once again, I honestly would still be stuck with a tkinter window with a few buttons without you. With this help I should be able finish a few things that I need to add and then complete this program for good (I will put it on my github, along with my future python projects that are now possible thanks to you) Your help has definitely helped me gain better understanding on matplotlib,tkinter and in Python in general. I couldn't have asked for a better more perfect asset/tutor. (Thank for for literally writing this code with me) You can show your gratitude by upvoting questions and answers that have been useful for you when trying to solve problems, including of course answers to your own questions. Be aware that SO is not a code-writng service and that you cannot rely on always finding someone who has the time for answering those kinds of questions. For the future I recommend (re)reading [ask] and how to provide a [mcve]. Creating such minimal examples will also help you to find a solution yourself. Thank you, I will be shortening my code next time I ask. I also up-voted your answers, but because I have a less than 15 reputation they are not publicly displayed (they are supposedly recorded however).
common-pile/stackexchange_filtered
Set localhost port fixed/static for project debugging in vs2015 l am using Asp.Net Maker 2016 for generating my project. So, l browse my project via vs2015. The problem is after I generate my project from Asp.Net Maker tool and open it in vs2015, the URL of my project is changed. something like : http://localhost:51624/ADD I want to set the port fixed not dynamic so, how I can do this in vs2015 or Asp.Net 2016 Maker tool? Visual Studio uses IIS Express to run Web Projects. When a project is run first time IISExpress creates an entry to applicationhost.config file for the project and assigns a random port to it. The file is located at - %userprofile%\Documents\IISExpress\config folder. Project entries in the file looks like this - <site name="ProjectName" id="5"> <application path="/" applicationPool="Clr4IntegratedAppPool"> <virtualDirectory path="/" physicalPath="d:\physical path" /> </application> <bindings> <binding protocol="http" bindingInformation="*:59302:localhost" /> </bindings> </site> Notice the bindingInformation="*:59302:localhost" in the above section. Here the port number is 59302. You can change this port number to anything you like and next time Visual Studio runs the project it will use your assigned port number. Its best to close all instances of VS and also confirm that IISExpress is not running before changing the file. Also, keep a backup of the file beforehand just in case. The port you assign also needs to be free. i.e. no other application should be using the port. Else Visual Studio will fail to run the application.
common-pile/stackexchange_filtered
Create custom lead button to look up that leads url in the search box At my old company we had a custom lead button that read "Who's Working?" When you clicked the button it would run a search for url from the leads email. The point was to see all the stuff going on at that account so reps wouldn't step on each-others toes. I have the button but just need to know what to fill in on the edit custom button page. How can this be done in PE? What exactly do you mean by "search for url from the leads email"? Please explain Do you possibly mean launch a report from button? Here's a post on how to create the button you asked about from Anthony Zhang of SalesLoft. Brilliant, I agree! http://www.salesmane.com/the-whos-working-button-in-salesforce/ Oh, I just noticed Kyle Porter asked the question, and Anthony Zhang works for your company now. Guess you already found your solution! :)
common-pile/stackexchange_filtered
QLPreviewController playback video I've found strange behaviour on the QLPreviewController modal where Im trying to preview a video and QLPreviewController carries on playing a video after I've dismissed the modal via the "done" button which is provided by default. Any ideas on why this could be happening or how I can stop the playback? Found the problem. I extended QLPreviewController and in viewWillDisappear i didn't call [super viewWillDisappear] which was causing the video to still playback in the background.
common-pile/stackexchange_filtered
Executing Child Component Function from Parent Component Problem: I'm facing an issue with executing a function from a child component when triggered by an event in the parent component. Here's a breakdown of my situation: I have a React application with two components: ParentComponent and ChildComponent. In ChildComponent, there's a function handleFocusInput that's responsible for focusing on an input field. In ParentComponent, I have a function handleClickJumpToError that should execute handleFocusInput when it's triggered. Code: ChildComponent: import React, { useRef } from 'react'; const ChildComponent = ({ onJumpToError }) => { const newPasswordRef = useRef(null); const handleFocusInput = () => { if (newPasswordRef.current) { newPasswordRef.current.focus(); } }; return ( <div> <input ref={newPasswordRef} type="text" /> <button onClick={() => { handleFocusInput(); onJumpToError(); }}>Focus Input and Jump</button> </div> ); }; export default ChildComponent; ParentComponent: import React from 'react'; import ChildComponent from './ChildComponent'; const ParentComponent = () => { const handleClickJumpToError = () => { console.log("Jumping to error"); // Perform any actions related to jumping to error }; return ( <div> <ChildComponent onJumpToError={handleClickJumpToError} /> </div> ); }; export default ParentComponent; Desired Outcome: I want to trigger the handleFocusInput function from ChildComponent whenever the handleClickJumpToError function is executed in ParentComponent. Currently, when the button in ChildComponent is clicked, the input is focused, but I also want to perform the actions from handleClickJumpToError. Question: How can I ensure that the handleFocusInput function is executed in ChildComponent when the handleClickJumpToError function is triggered in ParentComponent? Is there a better way to handle this interaction between parent and child components? Any help or suggestions would be greatly appreciated. Thank you in advance! try this: in children component delete handleFocusInput function: import React, { useRef } from "react"; export const ChildComponent = ({ onJumpToError }) => { const newPasswordRef = useRef(null); return ( <div> <input ref={newPasswordRef} type="text" /> <button onClick={() => { onJumpToError(newPasswordRef.current); }} > Focus Input and Jump </button> </div> ); }; and parent component add item focus in function: const handleClickJumpToError = (item) => { console.log("Jumping to error"); if(item) item.focus(); // Perform any actions related to jumping to error };
common-pile/stackexchange_filtered
VSeWSS 1.3 created web part solution not adding SafeControl entries We have several VSeWSS 1.3 projects that add web parts to SharePoint. We have a problem with one of the projects in that it does not add SafeControl entriees for the web parts when deploying. It also deploys the solution Global. I have looked add the solution file but can't find anything there that is different from the other projects. The solution is adding things in the Template folder. What am I missing? I found that the project had a referane to an other sharepoint project. This made sharepoint look at this solution as a global solution. Removing the referance fixed the problem.
common-pile/stackexchange_filtered
remove a bunch of rows by rownames - how do I initialize a null string in R? I have this sparse-matrix I named N: 4 x 4 sparse Matrix of class "dgCMatrix" C1 C2 C3 C4 V1 . 3 5 2 V2 . 5 1 . V3 . . . . V4 . . 4 . I'm trying to remove rows that have two or more missing values. I expect to end up with this: C1 C2 C3 C4 V1 . 3 5 2 I wrote this piece of code: #iterate on rows and count: #how many values in row ri are bigger than 0 # if count is not bigger than limit, remove row ri limit = 3 for(ri in 1:nrow(N)){ count <- length(which(N[ri,]>0)) if (count <limit){ tmp <- paste("V",ri,sep="") rmv <- paste (rmv, tmp, sep= " ") } } #now remove specific row names N <- N[!rownames(N) %in% rmv, ] The problem is - this doesn't work since in the first loop rmv is unspecified and I receive an error: "object 'rmv' not found" How can I initalize rmv? If I use: rmv <- "" Then I get a string that starts with an empty space, for example: > rmv [1] " V2" and then my final line doesn't work: N <- N[!rownames(N) %in% rmv, ] Also - this is the very first code I have ever written in R, so if there is anything major I'm missing in the basic concepts I'd love to read it (this has taken me 6 hours and a lot of reading in stackoverflow and different R tutorials, but I'm pretty proud of myself getting this far, this is my first question). Thanks! Are you really using a sparse matrix for a 4-by-4 matrix? Or was that just for the example? (Your real matrix size could influence the answers you get.) Just an example. My real sparse-matrix contains ~50,000 rows and ~100,000 columns With a large sparse matrix, you'll need to work with the matrix's summary, or as.matrix will make you run out of memory: library(Matrix) M <- sparseMatrix(i = c(1, 1, 1, 2, 2, 4), j = c(2, 3, 4, 2, 3, 2), x = c(3, 5, 2, 5, 1, 4)) M[tabulate(summary(M)$i) > 2, , drop = FALSE] # 1 x 4 sparse Matrix of class "dgCMatrix" # # [1,] . 3 5 2 Step-by-step to see how it works: summary(M) # 4 x 4 sparse Matrix of class "dgCMatrix", with 6 entries # i j x # 1 1 2 3 # 2 2 2 5 # 3 4 2 4 # 4 1 3 5 # 5 2 3 1 # 6 1 4 2 tabulate(summary(M)$i) # [1] 3 2 0 1 tabulate(summary(M)$i) > 2 # [1] TRUE FALSE FALSE FALSE thanks, this works! I used it also on the columns. One thing I'm wondering about given your solution: I read the data from a csv file, and then change it to a matrix. the data in the file is structured: i,j,x. So maybe I don't need the Matrix? tried to work straight on the dataframe, but that didn't work. Or am I missing something? Assuming your sparse matrix is called N, this should do it: N[rowSums(as.matrix(N) == 0) < 2, ] A small example with some data from ?xtabs: d.ergo <- data.frame(Type = paste0("T", rep(1:4, 9*4)), Subj = gl(9, 4, 36*4)) set.seed(15) # a subset of cases: N <- xtabs(~ Type + Subj, data = d.ergo[sample(36, 10), ], sparse = TRUE) N # 4 x 9 sparse Matrix of class "dgCMatrix" # 1 2 3 4 5 6 7 8 9 # T1 . 1 . 1 . 1 . 1 . # T2 1 . . . . . 1 . 1 # T3 . . . . 1 . . . . # T4 1 . . . . . 1 . . rowSums(as.matrix(N) == 0) ## How many missing # T1 T2 T3 T4 # 5 6 8 7 ## Let's remove any with more than 7 missing N[rowSums(as.matrix(N) == 0) < 7, ] # 2 x 9 sparse Matrix of class "dgCMatrix" # 1 2 3 4 5 6 7 8 9 # T1 . 1 . 1 . 1 . 1 . # T2 1 . . . . . 1 . 1 Thank you, that is much simpler... I just tried your solution on my original file which contains ~50,000 rows and 100,000 columns. However I received an error: 'problem too large'. I'm not suggesting that my solution would work better. Any idea what would work? @nafrtiti, honestly, no idea. I don't usually work with sparse matrices. Thanks again Ananda. Actually I don't think its a "sparse matrix" issue. Returning to my original question - if I only knew how to initialize a String to a null value I think my original piece of code should work since it proceeds line by line thus should be able to handle a big file @nafrtiti, Out of curiosity, are you using the Matrix package? I believe if you search with your favorite search engine for R error: 'problem too large' you will find several posts relating to this error and that package, with some suggestions on what to follow too.
common-pile/stackexchange_filtered
Hyperlink color in firefox changes depending on URL I am new to html and css. I have 2 links one after the other. I have set the a:link and a:hover classes in css. The second link has a purple link color, where it should be silver. They both have a gold hover color which is as it should be. The second link color is correct if I change the link from href="http://*******.blogspot.co.uk/search/label/Past%20Performances" to href="http://*******.co.uk/search/label/Past%20Performances". So by removing .blogspot. from the url. I tried it in Chrome and it doesn't seem to have that problem. CSS: a:link { color: var(--silver-color); text-decoration: underline; } a:hover { color: var(--gold-color); text-decoration: underline; } HTML <a title="Send email to Erica"<EMAIL_ADDRESS>target="_blank">emailing us</a>. <a title="Erica's blog page" href="http://********.blogspot.co.uk/search/label/Past%20Performances" target="_blank">Erica's blog</a> You just have to specify :visited selector Just to add I made sure the order is first :link then :visited then :hover. Works now.
common-pile/stackexchange_filtered
Bail bond mission GTA 5 I was doing the bail bond mission with Trevor and found the second character Maude requested but on engaging his gang members i accidentally killed him, I know there is a way to replay all the main missions, strangers and freaks etc but is there a way to replay this bail bond mission? Unconfirmed: I have read that there is no current option to replay the bail bond missions (I cannot find it either)....(other than starting a new game) According to the info from GTA forums and players it would seem that there is no way to replay the bail bond missions. So if you want the achievement of returning one of them alive, you should be careful and save before the missions. You only need to return one of them alive to get the achievement/trophy. Here's a thread about the bail bond missions. thats alive or alive acheivement right? i got that for first mission for the second one though i killed him You can kill them now if you want, you just get a little less money. There's only one achievement/trophy for bringing a mark back. According to the info from this forums and players, it would seem that there is no way to replay the Bail Bond missions. So if you want the achievement of returning one of them alive, you should be careful and save before the missions. You only need to return one of them alive to get the achievement/trophy.
common-pile/stackexchange_filtered
Dense, codense, finite subcategory I found in some lecture notes a statement, that there exists an inclusion of full subcategory $\mathcal C \hookrightarrow \mathcal D$ which is both dense and codense, and moreover $\mathcal C$ is finite and $\mathcal D$ is large, however no example were given, so I'd appreciate to see such one A trivial example would be an equivalence of categories, where $D$ is the result of adjoining to $C$ a class of isomorphisms. Right, that's really a trivial example. Are there some similarly easy examples where we assume $\mathcal C$ to be essentially large? I suppose that by large you mean a category which is not small, but possibly locally small. As pointed out to me by Hayato Nasu, such an example can be found at Example 1 of the paper Isbell, John R., Small adequate subcategories, J. Lond. Math. Soc. 43, 242-246 (1968). ZBL0155.03601. This particular situation is also mentioned in Example 8.7 of Avery, Tom; Leinster, Tom, Isbell conjugacy and the reflexive completion, Theory Appl. Categ. 36, 306-347 (2021). ZBL1467.18004. The example consists of the category of sets and so-called partial bijections between them. In this category, the full subcategory given by a two-element set is dense and codense.
common-pile/stackexchange_filtered
Model properties not filled on jquery Ajax post I have a strange issue doing an ajax post. The data is sent to the request, but for some reason the data does not arrive in the controller function. This is my post function: $.ajax({ type: 'POST', url: url, contentType: 'application/x-www-form-urlencoded; charset=utf-8', data: data, success: function (data) { if (data.redirect) { window.location.replace(data.redirect); } else { $(dest).replaceWith(data); } }, error: function (xhr, status, err) { //alert('Response code:' + xhr.status + '\r\n[Error:' + err + '] ' + status); } }); Nothing too uch out of the ordinary there. When I set a breakpoint in this function I do see the data I expect: But when I arrive at my controller function the properties of the viewmodel aren't filled: I've tried to add attributes to the parameter, like [FromBody] and sorts, but most of the time that results in a 415. The date is retrieved with $("form").serialize() if that would make a difference. I've used the function in the past, when I was still using plain MVC, and this worked back then. I believe the last time the project was in .NET Core 2.1 and this is running .NET 5, don't know if that has an impact on how the code should be implemented. Been struggling with this for several hours, I just need to get this to work, so I implement a cleaner way to have multiple posts buttons on one form instead of the single submit. You don't wanna know what they've been doing so far. Are you able to tranform your query string data into an object before the ajax request? The controller method is expecting an object, no? data: {'Id': 911234567, 'Language': 'nl', 'FirstName': 'Jeff'} you need to post antiforgerytoken validation since you have it in your action, add to ajax headers: { RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val() }, or remove an antiforgerytoken validation from the action also redirect is not exist in a response, try .... if (data) { window.location.replace(data); } .... Indeed some issues with handling the redirects, but I'll sort that out. Need to find an indication when something is a redirect response or a regular view response I bet what you are looking for is to send the whole model thru AJAX post. In that case your data parameter of AJAX should look like: data: JSON.stringify(data); Json.Stringify() converts the object to JSON String and controller can recognize that JSON and will map your object properties to it If you debug the controller you can use this.HttpContext in the immediate window to check what's been passed though e.g. ?this.HttpContext.Request.Form or ?this.HttpContext.Request.QueryString or ?new StreamReader(this.HttpContext.Request.Body).ReadToEndAsync().Result it's likely the data doesn't match the HomeModelView object, you could also add a bind to the controller action public IActionResult CurrentDossier([Bind("PropertyNameInModel,AnotherPropertyNameInModel") HomeViewModel model) I hope this helps The data was indeed in the context. Apparently the issue lied somewhere else. First you need to update your ajax data section by convert data to JSON string as shown below i .e. var jsonData = JSON.stringify(data); $.ajax({ type: 'POST', url: url, contentType: 'application/x-www-form-urlencoded; charset=utf-8', data: jsonData , success: function (data) { if (data.redirect) { window.location.replace(data.redirect); } else { $(dest).replaceWith(data); } }, error: function (xhr, status, err) { //alert('Response code:' + xhr.status + '\r\n[Error:' + err + '] ' + status); } }); then in your controller action change the method parameter from HomeViewModel to string i.e. public IActionResult CurrentDossier(string data) Then inside that method convert JSON string to HomeViewModel i.e. public IActionResult CurrentDossier(string data) { HomeViewModel model = JsonConvert.DeserializeObject<HomeViewModel>(data); } Hope this helps Stringifying the data did gave a weird result, it resulted in the string: ""Id=91123456789&Language=nl&UserFirstName=Jeff&__RequestVerificationToken=CfDJ8..."" Change your content-type to application/json It's not good practice to send object data via URL parameter I found the issue, it didn't had anything to do with the controller or the jQuery. Aparrently it only works when the Properties have actual getters & setters. Originally my viewmodel was written like: public class HomeViewModel { public string Id; public string UserFirstName; public string Language; public string __RequestVerificationToken; public List<DossierViewModel> Dossiers; ... } But it worked when written like this: public class HomeViewModel { public string Id { get; set; } public string UserFirstName { get; set; } public string Language { get; set; } public List<DossierViewModel> Dossiers { get; set; } ... } Thanks for everyone's help and effort. glad you sussed it in the end, it's one of that easy to make mistakes that drive to crazy and that you kick yourself for afterwards lol Glad you found it . Could have saved you & others some time if the model class was added to your original question.
common-pile/stackexchange_filtered
splitting a string with some kind of whitespace I've got the following code: $output2 = 'text&NewLine;&NewLine;more text&NewLine;&NewLine;ja'; $explode = explode('&NewLine;&NewLine;', $output); This works fine and the $explode array prints the following: Array ( [0] => text [1] => meer text [2] => ja ) However, the following code doesn't work and I don't know how to fix it: $output = 'text &NewLine; &NewLine;more text &NewLine; &NewLine;ja'; $explode = explode('&NewLine;&NewLine;', $output); The $explode array prints the following: Array ( [0] => text &NewLine; &NewLine; //more text &NewLine; &NewLine;ja ) This might seem like a weird question. But the first example is a test I made manually. But the second example is what is actually returned from the database. You probably need to split by "&NewLine;\n&NewLine;" (note the double quotes and the \n). You can use preg_split to split your string: <?php $output = 'text &NewLine; &NewLine;more text &NewLine; &NewLine;ja'; $explode = preg_split('/(&NewLine;|(\r\n|\r|\n))+/', $output, -1, PREG_SPLIT_NO_EMPTY); demo: https://ideone.com/KU0v9t (ideone) or https://eval.in/887393 (eval.in) The following solution to split on double &NewLine;: $output = 'text &NewLine; &NewLine;more text &NewLine; &NewLine;ja &NewLine;nein'; $explode = preg_split('/(\r\n|\r|\n)*(&NewLine;(\r\n|\r|\n)*){2}/', $output, -1, PREG_SPLIT_NO_EMPTY); demo: https://ideone.com/0txh5O I have doubt on this site, Giving wrong result : https://eval.in/887381 This indeed worked, thanks. However, with the actual database output it prints the following: Array ( [0] => text [1] => [2] => [3] => [4] => more text [5] => [6] => [7] => [8] => ja ) @user2486 that's the same result i'm getting. Yes I think its a fault of eval.in see update: the problem was the spaces (by my formatting) and the new line with \r or \r\n. @SebastianBrosch Thank you so much, i would like to ask one more question. How can i make sure it only splits when a double new line is added? It now split for every new line, but i would like to have it split for every 2 new lines. Adding one line in your code $output =str_replace("\r\n","",$output ); to combine all string in one line so that it would like your first example. $output =str_replace("\r\n","",$output ); $explode = explode('&NewLine;&NewLine;', $output); print_r($explode); Live demo : https://eval.in/887371 $explode = preg_split('/&NewLine;\s*&NewLine;/', $output); normalize your string by removing all new line like chars: $output = trim(preg_replace('/\s+/', '',$output)); then explode it. As User2486 says, the problem is that there are some hidden characters you are not watching like \n and \r In your first example you have 'text&NewLine;&NewLine;more text&NewLine;&NewLine;ja' and in the second 'text\r\n&NewLine;\r\n&NewLine;more text\r\n&NewLine;\r\n&NewLine;ja'
common-pile/stackexchange_filtered
Asp.Net Core [FromRoute] auto url decode If we have such controller endpoint in Asp.Net Core: [HttpGet("/api/resources/{someParam}")] public async Task<ActionResult> TestEndpoint([FromRoute] string someParam) { string someParamUrlDecoded = HttpUtility.UrlDecode(someParam); // do stuff with url decoded param... } Is there some way to configure [FromRoute] parsing behavior in such way that it will inject into someParam already url decoded value? Can you share examples? My particular usecase almost the same as attached in first message. I just changed variable names. In fact, I just want to receive here ([FromRoute] string someParam) value, which already has been url decoded. And remove string someParamUrlDecoded = HttpUtility.UrlDecode(someParam); operations from controller methods. So I think there should be some point, where it is possible to intercept value, which will be injected as value of parameter annotated with [FromRoute] attribute and change it. But I haven't found the way. Can you share example values for someParam? I have such value for someParam: 384865_38A/X before url encoding. So without encoding this leads to 404 response code. One way to achieve whatever you're trying to do is to create a custom Attribute. Within the attribute you can essentially intercept the incoming parameter and perform whatever you need. Attribute Definition: public class DecodeQueryParamAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { string param = context.ActionArguments["param"] as string; context.ActionArguments["param"] = "Blah"; // this is where your logic is going to sit base.OnActionExecuting(context); } } And within the controller, you'll need to decorate the action method with the attribute as done below. Route can be modified according to your need. [HttpGet("/{param}")] [Attributes.DecodeQueryParamAttribute] public void Process([FromRoute] string param) { // value of param here is 'Blah' // Action method } As a word of caution, when you are going to have encoded strings being passed as query string parameters, you may want to check about allowing Double Escaping and its implications. this seems to be working in my local, but when i deploy in any windows server then it's not working. any possible reason you can think of? I was able achieve this by adding a custom middleware to update the route values: app.Use((context, next) => { if (context.Request.RouteValues.ContainsKey("someParam")) { context.Request.RouteValues["someParam"] = HttpUtility.UrlDecode(context.Request.RouteValues["someParam"]?.ToString()); } return next(context); }); I have implemented the solution with a Constraint like this: public class UrlDecodeStringConstraint: IRouteConstraint { public bool Match(HttpContext? httpContext, IRouter? route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection) { values[routeKey] = WebUtility.UrlDecode(values[routeKey].ToString()); return true; } } In your Startup.cs class: builder.Services.Configure<RouteOptions>(options => { options.ConstraintMap.Add("UrlDecodeString", typeof(UrlDecodeStringConstraint)); }); In your controller: [HttpGet("getperson/{personName:UrlDecodeString}")] public async ValueTask<ActionResult<Person>> GetPerson([FromRoute] string personName)
common-pile/stackexchange_filtered
Can I use the water that collects on our large pool cover? My wife and I have a large inground pool that we winterize and cover all winter. It collects a hefty sum of water and other organic material all winter and in the spring I end up pumping this bog water off into the yard and shoveling the solid stuff onto the brush pile to burn. It's not chlorinated or treated, it's just whatever hits the cover after we close it up for the winter. I was curious if there was any value in spraying the garden with it? We start our garden from seed in the house so hitting it with some potentially good water from the get go might be swell. Is there is some nutritional value from all the decaying leaves and pine needles? Is there any testing I can do with it? We have quite a few pine trees and I would be worried about the acidity? Can I salvage some compost from the solids? It seems like such a waste to throw onto a brush pile or away. We're trying to be environmentally conscious and all. The water won't have huge amounts of nutrients, but will contain a good amount of microbes. You can use it to water your plants, but I see no reason for spraying it on the leaves. It will be a little acidic, but regular (at least every 3-4 years) pH tests will catch any harmful trends long before they become an issue, which they likely won't. About the solids, Definitely compost, don't burn! Once dried, it would make a great high-carbon addition to the compost heap. If you have a lot, you can also mulch with it. To make it look nice (if you usually use mulch only for aesthetic purposes), you could spread it in a thin layer, and spread another thin layer of regular mulch on top. The wind ruined everything. I put the solids on the compost pile but much of the water ended up in the pool. Consider it something like compost tea. Yes it has value but how you deal with it is a whole different problem. :) Can you add some more detail to this answer?
common-pile/stackexchange_filtered
Google Play Game Services C++ SDK does not find NativeSdkEntryPoints java class The Google Play Games Services works well, but there comes following error after creating GameServices object. I'm using SDK with cocos2d-x. Java Activity is initialized within JNI_OnLoad. Creating the GameServices object is initialized as descripted in Googles C++ SDK docs. Google Play Game Services C++ SDK 1.2 Google Play Services Revision 20 Android NDK 9d 10-22 08:07:43.474: E/GamesNativeSDK(26078): Exception in dalvik/system/DexClassLoader.loadClass: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.games.NativeSdkEntryPoints" on path: DexPathList[[zip file "/data/data/com.CompanyName.MyApp/app_.gpg.classloader/921cd45b6e4d26e0809d5e163b7327ee.jar"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]. Is this error critical? And how can I fix this? Yes, it's critical, and it looks like you aren't including the necessary library in your package. I have Android library project for Google Play added, and Google Play Game Services C++ SDK included. I would guess that Java class which wasn't found, should be inside the Android library project or at least included there.. I'm seeing the same problem with NativeSdkEntryPoints being missing. I'm using the latest google-play-services_lib and can log in to google play if I use java, but it doesn't find NativeSdkEntryPoints. Examining the jar file, the class does not seem to exist at all. The error is not critical and you can ignore it. From much experimentation myself after getting the same error message, the classes do not appear to exist in google-play-services jar, but they are not required anyway. All the normal services function correctly through the cpp lib despite the error message. Do you get callback for RealTimeMultiplayer().SendReliableMessage(room, participant, callback) function? For me, GPGS informs in log that reliable message was successful, but the callback doesn't get called. Callback was created with lambda, like: [this](gpg::MultiplayerStatus const &result) {} Sorry I'm not using the real time multiplayer service. I'm using achievements, leaderboards, cloud messaging and cloud saved games (snapshots). All of which function correctly (including callbacks) despite the reported error about NativeSdkEntryPoints.
common-pile/stackexchange_filtered
How do I get the cartesian product of 2 vectors by using Iterator? I have 2 Vecs: let x = vec!['1', '2', '3']; let y = vec!['a', 'b', 'c']; Now I want to use iterator to make a new vec like this ['1a', '1b', '1c', '2a', '2b', '2c', '3a', '3b', '3c']. How can I do? Why not simply two loops, one inside the other one ? I'm learning about iterator, so I want to do it to understand how it works I edited the title because it wasnt correct. Pairing would mean to the pairs of matching indexes values, aka zip. From your example what you really want is the cartessian product This is so weird that it can't be done with std::iter::Product. Here is how to do it with vanilla Rust iterators: fn main() { let x = vec!['1', '2', '3']; let y = vec!['a', 'b', 'c']; let product: Vec<String> = x .iter() .map(|&item_x| y .iter() .map(move |&item_y| [item_x, item_y] .iter() .collect() ) ) .flatten() .collect(); println!("{:?}", product); } Explanation The easiest way to construct a String from two chars is to collect iterator over the chars: let string: String = [item_x, item_y].iter().collect(); For each item in x we iterate over y and construct such string. x.iter().map(|&item_x| y.iter.map(move |&item_y| ...)); We use pattern matching to get value in the map closure rather then references. Because of that and the fact that the char has Copy trait, we can move item_x into inner closure, resolving any lifetime issues. As the result of the code above we get an iterator over iterators over Strings. To flatten that iterator, we use flatten method (who would think?). Then we collect the flat iterator into the resulting Vec. Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=bf2987ed96303a0db0f629884492011e Easiest way would be to use the cartesian product macro available in the itertools crate use itertools::iproduct; // 0.10.1 fn main() { let x = vec!['1', '2', '3']; let y = vec!['a', 'b', 'c']; let product: Vec<String> = iproduct!(x, y) .map(|(a, b)| format!("{}{}", a, b)) .collect(); println!("{:?}", product); } Playground The existing answers make sense if your goal is to get the Cartesian product of two iterators. If you've got vectors or slices already though (like in the original question) you can do a little better: fn main() { let x = vec!['1', '2', '3']; let y = vec!['a', 'b', 'c']; let result: Vec<String> = product(&x, &y) .map(|(a, b)| format!("{}{}", a, b)) .collect(); println!("{:?}", result) } fn product<'a: 'c, 'b: 'c, 'c, T>( xs: &'a [T], ys: &'b [T], ) -> impl Iterator<Item = (&'a T, &'b T)> + 'c { xs.iter().flat_map(move |x| std::iter::repeat(x).zip(ys)) } Playground Any iterator based solution will necessarily require storing the full contents of the iterator somewhere, but if you already have the data in a vector or array you can use the known size to only store the indices instead. Can't it be done more easily with something that looks like this? xs.flat_map(|x| repeat(x).zip(ys)) @feature_engineer - that is absolutely a more elegant version. I'll update my answer.
common-pile/stackexchange_filtered
Error after exporting and building a tensorflow graph After i trained a model successfully, exported the graph with the freeze_graph.py and built it with the customized /tensorflow/examples/label_image/main.cc using bazel, i am getting following runtime error. Running model failed: Invalid argument: Matrix size-compatible: In[0]: [150,4], In[1]: [600,36][[Node: local3/MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/job:localhost/replica:0/task:0/cpu:0"(local3/Reshape, local3/weights/read)]] I am pretty confused because all previous step has been successful and i am wondering about the [150, 4]. My batch_size is 150 and 4 is the number of classes, but why is this tensor an input for the matmul-operation in my local-layer? This code is showing the local3 layer. The pool4 layer looks like this [150x10x10x6] # local3 with tf.variable_scope('local3') as scope: # Move everything into depth so we can perform a single matrix multiply. reshape = tf.reshape(pool4, [FLAGS.batch_size, -1]) dim = reshape.get_shape()[1].value weights = _variable_with_weight_decay('weights', shape=[dim, 36], stddev=0.04, wd=0.0004) biases = _variable_on_cpu('biases', [36], tf.constant_initializer(0.1)) local3 = tf.nn.relu(tf.matmul(reshape, weights) + biases, name=scope.name) For the model I've used the cifar10-tutorial from tensorflow as a starting point. My local3 layer relies pretty much on the layer from the tutorial. Ok i didn't understand the error but i have solved it by modifying the local3-Layer # local3 with tf.variable_scope('local3') as scope: # Move everything into depth so we can perform a single matrix multiply. weights = _variable_with_weight_decay('weights', shape=[600, 36], stddev=0.04, wd=0.0004) biases = _variable_on_cpu('biases', [36], tf.constant_initializer(0.1)) dense1 = tf.reshape(pool4, [-1, weights.get_shape().as_list()[0]]) local3 = tf.nn.relu_layer(dense1, weights, biases) # Relu activation _activation_summary(local3) I've seen the local-layer definition in this repo https://github.com/HamedMP/tensorflow_export_cpp_example I'am wondering about the tf.nn.relu_layer() method, because it seemed not documented in tho API-Reference.
common-pile/stackexchange_filtered
Does IPv6 Prefix Delegation work with SLAAC, without the need of a DHCPv6 server/client? All the (cisco) documentation I found about this topic always uses a DHCPv6 server or client to configure Prefix Delegation. But I never read that this is a requirement. Can Prefix Delegation be configured without a DHCPv6 server or client? Prefix delegation is a DHCPv6 option. You cannot do it without DHCP. Here is the RFC: https://www.rfc-editor.org/rfc/rfc3633
common-pile/stackexchange_filtered
New ceiling light works does not work I have an old ceiling rose configuration and tried connecting a new chandelier 5 bulb style light but it keeps tripping the mains when I try to turn it on. The electrician I first had out said there was a fault with the new light so I got a new one. Same thing. I've put the ceiling rose configuration back and it works fine with a single bulb but not with the new light. "New ceiling light works does not work" I need help with that one. Your new light probably has insufficient terminals and you're connecting wires which should not be connected, causing a dead short. You need a 4-terminal ceiling rose or connection block: live (red, or brown); neutral (black, or blue); switched live (black with red marker); and earth (bare, sleeved green-yellow). The earths should all go in the brass terminal to the top left - I can't see where they connect at all, they must not be left unconnected and pushed up into the ceiling - and the lives should be in the middle terminal marked Loop, not in a separate terminal. http://wiki.diyfaq.org.uk/index.php/House_Wiring_for_Beginners#Lighting Thank you I will try that. The earth was pushed up into ceiling by the electrician :/ eeek! I had earthed my light when I tried it but he didnt
common-pile/stackexchange_filtered
Angular 2 AsynPipe isn't working with an Observable I'm getting the following error: EXCEPTION: Cannot find a differ supporting object '[object Object]' in [files | async in Images@1:9] Here's the relevant part of the template: <img *ngFor="#file of files | async" [src]="file.path"> Here's my code: export class Images { public files: any; public currentPage: number = 0; private _rawFiles: any; constructor(public imagesData: ImagesData) { this.imagesData = imagesData; this._rawFiles = this.imagesData.getData() .flatMap(data => Rx.Observable.fromArray(data.files)); this.nextPage(); } nextPage() { let imagesPerPage = 10; this.currentPage += 1; this.files = this._rawFiles .skip((this.currentPage - 1) * imagesPerPage) .take(imagesPerPage); console.log("this.files:", this.files); } } The console.log at the end shows that it's an observable: this.imagesData.getData() return a regular RxJS observable from Angular's Http service, so why wouldn't async pipe work with it? Maybe the way I'm using flatMap() is wrong and it messes something up? If I try to subscribe to this observable like that: this.files = this._rawFiles .skip((this.currentPage - 1) * imagesPerPage) .take(imagesPerPage) .subscribe(file => { console.log("file:", file); }); It prints a list of objects as expected: *ngFor only iterates over an array, not a series of events therefore your Observable needs to return an array instead of a series of objects. I'd go for an Observable<File[]> using the scan operator. See also https://github.com/angular/angular/issues/6392 Try with an Observable<File[]> instead: this.files = this._rawFiles .skip((this.currentPage - 1) * imagesPerPage) .take(imagesPerPage) .map(file => [file]) .startWith([]) .scan((acc,value) => acc.concat(value)) This should require no manual code to subscribe and should work perfectly with your current template. I do something very similar in this blog post. Thanks. It works, although it's not exactly pretty. I'm already receiving an array from server and only converting it to a stream to be able to use RxJS's utility methods (skip and take). If I have to convert to array every time like that, it would be easier to not use RxJS for the array manipulation altogether
common-pile/stackexchange_filtered
Why can't I access objects through the window object when using jQuery? I'm trying to access a function through the window object. In my code, my function gets referred to by a string so I have to use the window object (or eval) to grab it. I tested out my code in pure JavaScript and it works perfectly. But when using jQuery it fails. Here is my test code: function speak(words, callback){ for(var i=0;i<10000;i++){ console.log(words); } if(callback) callback.call(); } console.log(window['speak']);​ Here is a link to the pure JavaScript version which works. Here is a link to the jQuery version which doesn't work. What do I need to do to make this work in jQuery? You didn't declare speak as a member of window, and JSFiddle actually wraps it in a document.ready callback. You'll need to explicitly set window.speak = speak as part of your code if you want it available on the window object. Alternatively, you need to configure your fiddle to execute without a wrapper rather than onDomReady Oh I see. Hmm. So any function not in a document.ready callback is automatically declared as a member of window, but if it is in a document.ready then it is not? @Aust, functions and variables declared in the global scope are implicitly added to the global object, functions and variables declared within another function persist only within the function. When writing JavaScript, it's advisable to write all code within a closure, so as to avoid accidental global pollution.
common-pile/stackexchange_filtered
VS.NET - Add in for automatically formatting C# code Is there any VS.NET add in for formatting C# as you type based on the given rules? Except for ReSharper, as it does so many other things and slows down VS.NET due to that, so I'm looking for a light add-in just for code formatting. I just came across codemaid a few minutes ago. @xecaps12 seems like it's not doing code formatting as user type I don't feel ReSharper is slowing down my system that much. No, it's not automatic. You do have to invoke it by either the shortcut or selecting from the menu. The Continuous Formatting extension formats C# code automatically as you type. To give rules you can use the built-in Visual Studio engine or external tools like ReSharper and CodeRush.
common-pile/stackexchange_filtered
BluRay-R, DVD+R, DVD-R I am presently saving data on DVD+R was always told to use +R, but never knew why. I am looking into possibly upgrading to BluRay, but can only find -R writable discs: What is the difference between +R and -R, and why are there no +RW BluRay discs? I can only find 25GB writable discs, but there are 50GB+ discs, so where do I find those? So what does your research show? Because the Wikipedia article explains in great detail. Since you're going to be using BluRays for archiving, you may want to get the quad-layer ones (there are 4 layer types: single [25GB], dual [50GB], triple (XL) [100GB], and quad [128GB]). FYI: BluRays have an extremely hard protective layer over their magnetic film medium, so it's vastly more difficult to scratch them (you have to be quite determined to do so) DVD-R (and DVD-RW), DVD+R (and DVD+RW), DVD-RAM, and BD-R (and BD-RW) are simply four different formats for optical mediums. The DVD Forum first created the DVD-RAM in 1996 as the re-writable and Random Access version of the DVD-ROM. However, they never marketed it properly, and a DVD-RAM cannot be read by a DVD-ROM drive (although there are hybrid drives). As of June 2019, there are no remaining manufacturers of DVD-RAM media, meaning the format is mostly dead. Panasonic created the DVD-R as the recordable version and DVD-RW as the re-writable version in 1997, and the DVD Forum accepted this as a standard. DVD-Rs are mostly compatible with DVD-ROMs, so it was possible to develop cheap DVD-ROM drives that could read DVD-Rs (even if they could not write them). In 2002, a group of manufacturers (driven by Sony) created a competing standard to DVD-R(W) called +R and +RW. (They weren't allowed to call it DVD+R and DVD+RW because they were competing with the official standard of the DVD Forum. The DVD Forum only accepted DVD+R(W) as an alternative to DVD-R(W) in 2006.) This created a "format war" because the two formats were mutually incompatible. While multi-format computer drives quickly became affordable and the norm, DVD Video Recorders even to this day typically only support one format, or are at least functionally restricted. What is the difference between +R and -R For a user, there are no differences. There are technical differences between the two formats, and there are some "lessons learned" in the DVD+R, simply by virtue of having 5 years of experience with DVD-R when they designed it. But the reason why DVD+R was created was purely political. There are no meaningful differences for the end user. why are there no +R BluRay writable discs? Such a format war between different manufacturers who developed incompatible competing formats simply never happened in the BluRay Disc Association, so that is why there aren't multiple incompatible competing formats like there are for DVDs. I am finding BluRay writable drives hard to get in the UK, with some shops only selling 1 (Argos) and other shop selling none at all (PC World). Are they old technology? @Rewind Blu-ray Disc Recordable is simply irrelevant. Too expensive, too inflexible, too late. Flash drives offer superior performance at a very competitive price point. why are there no +R BluRay writable discs? There is no technical meaning in the "+R" – it's part of a marketing name, and all it means is "like -R but improved". The whole DVD+R is a newer format that was meant to improve over the older DVD-R format (like version 2.0). Meanwhile, BluRay (BD-R) already had the same improvements incorporated from day 1. But it too had a competing format which was called "HD-DVD", so instead of BD-R vs BD+R you actually had BD-R vs HD-DVD-R. What is the difference between +R and -R Here's a Wikipedia article. Two examples noted there is that the DVD+R format has better error correction, and allows drives to better calibrate their power for the specific disc, which I assume leads to slightly higher quality recording and slightly better resilience to physical damage. Another difference between DVD-R and DVD+R is that the newer +R format has a different way of defining sector addresses (ADIP), which allows the drive to seek more precisely at high speeds, so writers can easily continue after a buffer underrun, and the discs can fit slightly more data. (This feature also allows DVD+RW discs to immediately be used for random writing as the drive can seek to and overwrite any sector at any time, whereas DVD-RWs and CD-RWs could only do this after the necessary addresses were written in a lengthy "MRW formatting" step.) BD-R already uses ADIP from the very beginning. (However, HD DVD-R uses LPP just like DVD-R, so you could perhaps say that BD is the "+" of HD DVD.)
common-pile/stackexchange_filtered
CORS policy blocks XMLHttpRequest With Ionic Angular running in on my localhost I made this call to my Django backend (running on different localhost): test() { return this.httpClient.get(endpoint + '/test', { headers: { mode: 'no-cors' }, }); } And on the backend side I have following code to respond: @csrf_exempt def test(request): response = json.dumps({'success': True}) return HttpResponse(response, content_type='application/json', headers={'Access-Control-Allow-Origin': '*'}) I have also this in my settings.py file: INSTALLED_APPS = [ ... 'corsheaders', ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', ] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True Still, I get this error message in my console: Access to XMLHttpRequest at 'http://<IP_ADDRESS>:8000/test' from origin 'http://localhost:8100' has been blocked by CORS policy: Request header field mode is not allowed by Access-Control-Allow-Headers in preflight response. What am I doing wrong? You need to just add one more setting CORS_ALLOW_ALL_HEADERS=True Other than the above you do not need to set a header on each response. Just simply respond back with payload as @csrf_exempt def test(request): response = json.dumps({'success': True}) return HttpResponse(response, content_type='application/json', headers={'Access-Control-Allow-Origin': '*'})
common-pile/stackexchange_filtered
Python NOOP replacement Often I need to temporary comment some code, but there are situations like the following where commenting a single line of code will get a syntax error if state == False: print "Here I'm not good do stuff" else: # print "I am good here but stuff might be needed to implement" Is there something that might act as an NOOP to keep this syntax correct? The operation you're looking for is pass. So in your example it would look like this: if state == False: print "Here I'm not good do stuff" else: pass # print "I am good here but stuff might be needed to implement" You can read more about it here: http://docs.python.org/py3k/reference/simple_stmts.html#pass In Python 3, ... makes a pretty good pass substitute: class X: ... def x(): ... if x: ... I read it as "to be done", whereas pass means "this page intentionally left blank". It's actually just a literal, much like None, True and False, but they optimize out all the same. I discovered that if you put the code in tripe quoted comment '''comment''' it acts like a NOOP, so you can put a triple quoted commentary that will act as a NOOP in case the code gets deleted or commented with #. For the above case: if state == False: '''this comment act as NOP''' print "Here I'm not good do stuff" else: '''this comment act as NOP and also leaves the else branch visible for future implementation say a report or something''' # print "I am good here but stuff might be needed to implement" You should use pass (http://docs.python.org/reference/simple_stmts.html#pass) as the noop. This has the advantage of being short and having no additional meaning (the string can be interpreted in unwanted ways by the program). @Nobody Do you have an example of unwanted behavior to know what to avoid? Bare strings should be okay but you must be careful to not write doctests into these strings (if they are not wanted). Apart from that there is the unnecessary parsing of lengthy strings, that will be evaluated and returned just to be ignored (maybe this will be optimized away). I cannot come up with more than corner cases that are very unlikely but nonetheless pass is the way to go because it was made for this situation. If you use comments this way you break the rule of comments: that they can be removed without changing the programs semantics. Agreed. You could also do 1+1, say -- the point is that pass already means "do nothing", so that someone else reading the code understands that it does nothing. Multiline strings can be used as comments and they generate no code. Also, as long as these strings are not placed after def or class or at the beginning of a module, and thus are not docstrings, doctest ignores these strings.
common-pile/stackexchange_filtered
Changing the quality of icons on leaflet I'm creating a map with the leaflet package for R but I feel a bit disappointed with the quality of the icons and would like to improve it. I'm using free png icons from The Noun Project. The pngs look just fine but when plotted, they lose their "smoothness" and look low quality. library('leaflet') library('sf') points = data.frame(p = seq(15, 75, 15), long = c(-85, -80, -78, -75, -82), lat = c(34, 36, 37, 38, 35)) %>% st_as_sf(coords = c('long', 'lat'), crs = 4326) fork_icon = makeIcon( iconUrl = "https://static.thenounproject.com/png/2036274-200.png", iconWidth = 20, iconHeight = 20) circle_icon = makeIcon( iconUrl = "https://static.thenounproject.com/png/1904581-200.png", iconWidth = 15, iconHeight = 15) basemap = leaflet(points[c(1,4),],options = leafletOptions(crs = leafletCRS(crsClass = "L.CRS.EPSG4326"))) %>% addTiles() %>% addMarkers(icon = fork_icon) %>% addMarkers(data = points[c(2,3),], icon = circle_icon) That looks like: Now if I don't "compress" the icons with the makeIcon options iconWidth and iconHeight, they look nice and smooth again. Any leads on how to keep the icons smooth while keeping them in a convenient size? If you reduce a png with such delicate features to 15px there's not much you can do. I would suggest trying to use SVG images. This can be done using divIcon, like in this example: https://codepen.io/localhorst/pen/BJxzGW *Disclaimer: The codepen is not my code, credit goes to this guy and I haven't tested it myself.
common-pile/stackexchange_filtered
Using AddIpAddress()/DeleteIpAddress() with info from GetAdaptersAddresses() I need to change the IP address and submask of a specific network interface from a C/C++ program. In Windows documentation, I have found that I should use AddIPAddress()/DeleteIpAddress() from the Windows API. However, DeleteIpAddress(), for instance, requires a NTEContext as a parameter. I have found an example that uses GetAdaptersInfo() to get the index of the interface and context. However, the page also explicitly states that: On Windows XP and later:  Use the GetAdaptersAddresses function instead of GetAdaptersInfo. But, while GetAdaptersInfo() populates an IP_ADAPTER_INFO struct in which the index/NTEcontext are present, GetAdaptersAddresses() provides an IP_ADAPTER_ADDRESSES struct in which there are no such members. What should I do with the newer GetAdaptersAddresses() function to get the index/context for interfaces? Do you need to remove an IP address that you didn't add? AddIPAddress()/DeleteIpAddress() only work for IPv4, but GetAdaptersAddresses() supports IPv6. Try using [Create|Delete]UnicastIpAddressEntry() and related functions instead. They accept information that you can get from GetAdaptersAddresses(), GetUnicastIpAddressTable(), etc @SolomonUcko yes, because i want to change programmatically the ip / netmask of the address. @RemyLebeau I have noticed there is a method SetUnicastIpAddressEntry(). I have filled the InterfaceIndexmember of an initialized MIB_UNICASTIPADDRESS_ROW struct with the IfIndex of the target interface (got using GetAdapterAddresses()) and the Address.Ipv4 field with a custom ip. The MIB_UNICASTIPADDRESS_ROW struct is passed to the method, but ip does not change. What am I missing ? GetAdaptersInfo() seems to be the only way to do it... Based on https://learn.microsoft.com/en-us/windows/win32/iphlp/managing-network-adapters, you should be able to use the following: GetAdapterIndex GetPerAdapterInfo IP_PER_ADAPTER_INFO_W2KSP1 IP_ADDR_STRING Something like this should work: ULONG IfIndex = 0; /* check error returned */ GetAdapterIndex(AdapterName, &IfIndex); IP_PER_ADAPTER_INFO/*_W2KSP1?*/ PerAdapterInfo; ULONG OutBufLen = sizeof(PerAdapterInfo); /* check error returned */ GetPerAdapterInfo(IfIndex, &PerAdapterInfo, &OutBufLen); /* check error returned */ DeleteIPAddress(PerAdapterInfo.DnsServerList.Context); P.S. For older versions of Windows, this might work: https://microsoft.public.vb.winapi.narkive.com/TW7rVsdu/how-to-obtain-ntecontext-for-use-in-deleteipaddress-without-first-calling-addipaddress This example retrieves the IP_ADAPTER_ADDRESSES structure for the adapters associated with the system and prints some members for each adapter interface. The following example retrieves the IP address table to determine the interface index for the first adapter, then adds the IP address specified on command line to the first adapter. The IP address that was added is then deleted. I combined the two programs and modified the code. It can output network card description, IP address, MAC address and DNS address. Also, it can add the IP address to the first adapter and delete the same address. Caution: The DeleteIPAddress() function deletes an IP address previously added using AddIPAddress(). If you just only use AddIPAddress() to add an IP address, after that you need to delete it manually. This picture shows the IP added, and you can delete the added IP by “edit” on the left side. Here is the code: #pragma comment (lib, "Ws2_32.lib") // Link with Iphlpapi.lib #pragma comment(lib, "IPHLPAPI.lib") #include<WinSock2.h> #include<WS2tcpip.h> #include<iostream> #include<IPHlpApi.h> using namespace std; #pragma warning(disable:4996) int main() { PIP_ADAPTER_ADDRESSES pAddresses = nullptr; IP_ADAPTER_DNS_SERVER_ADDRESS* pDnServer = nullptr; ULONG outBufLen = 0; DWORD dwRetVal = 10; char buff[128]; DWORD bufflen = 128; int i; PMIB_IPADDRTABLE pIPAddrTable; DWORD dwSize =128; UINT iaIPAddress; UINT imIPMask; ULONG NTEContext = 0; ULONG NTEInstance = 0; LPVOID lpMsgBuf; pIPAddrTable = (MIB_IPADDRTABLE*)VirtualAlloc(&dwSize, sizeof(PMIB_IPADDRTABLE), MEM_RESERVE, NULL); pIPAddrTable = (MIB_IPADDRTABLE*)malloc(150 * sizeof(MIB_IPADDRTABLE)); GetAdaptersAddresses(AF_UNSPEC, 0, NULL, pAddresses, &outBufLen); pAddresses = (IP_ADAPTER_ADDRESSES*)malloc(outBufLen); if ((dwRetVal = GetAdaptersAddresses(AF_INET, GAA_FLAG_SKIP_ANYCAST, NULL, pAddresses, &outBufLen)) == NO_ERROR) { while (pAddresses) { printf("%S, %.2x-%.2x-%.2x-%.2x-%.2x-%.2x: \n", pAddresses->FriendlyName, pAddresses->PhysicalAddress[0], pAddresses->PhysicalAddress[1], pAddresses->PhysicalAddress[2], pAddresses->PhysicalAddress[3], pAddresses->PhysicalAddress[4], pAddresses->PhysicalAddress[5]); PIP_ADAPTER_UNICAST_ADDRESS pUnicast = pAddresses->FirstUnicastAddress; pDnServer = pAddresses->FirstDnsServerAddress; if (pDnServer) { sockaddr_in* sa_in = (sockaddr_in*)pDnServer->Address.lpSockaddr; printf("DNS:%s\n", inet_ntop(AF_INET, &(sa_in->sin_addr), buff, bufflen)); } if (pAddresses->OperStatus == IfOperStatusUp) { printf("Status: active\n"); } else { printf("Status: deactive\n"); } for (i = 0; pUnicast != NULL; i++) { if (pUnicast->Address.lpSockaddr->sa_family == AF_INET) { sockaddr_in* sa_in = (sockaddr_in*)pUnicast->Address.lpSockaddr; printf("IPV4 Unicast Address:%s\n", inet_ntop(AF_INET, &(sa_in->sin_addr), buff, bufflen)); } else if (pUnicast->Address.lpSockaddr->sa_family == AF_INET6) { sockaddr_in6* sa_in6 = (sockaddr_in6*)pUnicast->Address.lpSockaddr; printf("IPV6:%s\n", inet_ntop(AF_INET6, &(sa_in6->sin6_addr), buff, bufflen)); } else { printf("\tUNSPEC"); } pUnicast = pUnicast->Next; } printf("Number of Unicast Addresses: %d\n", i); pAddresses = pAddresses->Next; } } else { LPVOID lpMsgBuf; printf("Call to GetAdaptersAddresses failed.\n"); if (FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwRetVal, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL)) { printf("\tError: %s", lpMsgBuf); } } if (GetIpAddrTable(pIPAddrTable, &dwSize, 0) == ERROR_INSUFFICIENT_BUFFER) { GlobalFree(pIPAddrTable); } // Make a second call to GetIpAddrTable to get the // actual data we want if ((dwRetVal = GetIpAddrTable(pIPAddrTable, &dwSize, 0)) == NO_ERROR) { printf("\t Address: %d\n", pIPAddrTable->table[0].dwAddr); printf("\t Mask: %d\n", pIPAddrTable->table[0].dwMask); printf("\t Index: %d\n", pIPAddrTable->table[0].dwIndex); printf("\t BCast: %d\n", pIPAddrTable->table[0].dwBCastAddr); printf("\t Reasm: %d\n", pIPAddrTable->table[0].dwReasmSize); } else { printf("Call to GetIpAddrTable failed.\n"); } // IP and mask we will be adding iaIPAddress = inet_addr("<IP_ADDRESS>"); imIPMask = inet_addr("<IP_ADDRESS>"); if ((dwRetVal = AddIPAddress(iaIPAddress, imIPMask, pIPAddrTable->table[0].dwIndex, &NTEContext, &NTEInstance)) == NO_ERROR) { printf("\tIP address added.\n"); } else { printf("Error adding IP address.\n"); if (FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwRetVal, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR)&lpMsgBuf, 0, NULL)) { printf(" Error: %d"); } LocalFree(lpMsgBuf); } if ((dwRetVal = DeleteIPAddress(NTEContext)) == NO_ERROR) { printf("\t IP Address Deleted.\n"); } else { printf("\t Call to DeleteIPAddress failed.\n"); } free(pAddresses); VirtualFree(&dwSize, 0, MEM_RELEASE); return 0; } This is not what the OP asked for as it uses the NTEContext returned from AddIPAddress() in order to delete the IP address. What the OP wants (and me as well) is the NTEContext without first using AddIPAddress(). I don't know why MS has made this so difficult... @trojanfoe MSDN explained: To use DeleteIPAddress, AddIPAddress must first be called to get the handle NTEContext. The previous procedure assumes that AddIPAddress has already been called somewhere in the code, and NTEContext has been saved and remains uncorrupted. It's not practical though in a situation where you want to provide a library to set interface addresses and later remove them, without the need to hold onto the NTEContext somehow. The only way to do it seems to use GetAdaptersInfo(), which the docs warn you against using on Windows XP and later.
common-pile/stackexchange_filtered
ValidationMessage already triggered when loading the view When I load a view all the validation messages are already triggered, so it won't stop me from submitting to POST if leave all the values as null View (shortened): @model MyProject.ViewModel.VentasViewModel @{ Layout = null; } @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="row"> @Html.LabelFor(model => model.NombreCliente, htmlAttributes: new { @class = "control-label col-md-2", style = "color:black" }) <div class="col-md-4"> @Html.EditorFor(model => model.NombreCliente, new { htmlAttributes = new { @class = "form-control", placeholder = "E.j. Juan", style = "width:350px" } }) @Html.ValidationMessageFor(model => model.NombreCliente, "", new { @class = "text-danger" }) </div> </div> </div> <input type="submit" value="Create" class="btn btn-primary" /> } Controller: public ActionResult Create(VentasViewModel newProduct) { var details = db.DetallesVentaTMPs.ToList(); newProduct.DetallesVentas2 = details; ViewBag.LocalidadId = new SelectList(db.Localidads, "LocalidadId", "Name"); return View(newProduct); } VentasViewModel(shortened too): namespace MyProject.ViewModel { public class VentasViewModel { [Required(ErrorMessage = "Campo requerido")] //<-This what I get [StringLength(50, ErrorMessage = "El campo desbe estar entre {2} y {1} caracteres", MinimumLength = 3)] [Display(Name = "Nombre")] public string NombreCliente { get; set; } [Required(ErrorMessage = "The field {0} is required")] [Range(1, Int32.MaxValue, ErrorMessage = "You must select a {0}")] [Display(Name = "Localidad")] public int LocalidadId { get; set; } public Localidad Localidad { get; set; } public List<DetallesVentaTMP> DetallesVentas2 { get; set; } } } I really have no clue what could be causing this. Any hint? Please provide VentasViewModel code You're right @RajdeepDebnath, done. You included unobtrusive libraries? I don't know what's that, but I have some other views in which I have no issues like this Are you loading some jquery javascripts ion the other view (which is working)? Yes I am, but I removed them and debugged and the issue persists @RajdeepDebnath You can enable client side validation which will prevent from the form being submitted unless all validation error goes away. How do I do that? Let us continue this discussion in chat. I added it the steps to answer, let me know if you face any issue Would you come to the chat room for a sec? You need to include below 3 files in your _layout.cshtml file or better way is to put them in BundleConfig.cs file. This will work based on data annotation set in your model class. This will enable asp.net mvc to fire client side validation without server side roudtrip. <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"></script> <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.16.0/jquery.validate.min.js"></script> <script src="https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script> or public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); } You can also enable/disable it from web.config <appSettings> <add key="ClientValidationEnabled" value="true"/> //enabled, set 'false' to disable </appSettings>
common-pile/stackexchange_filtered
How to refresh as well as savstate of datatable when status is updated in laravel In my project, I want to refresh as well as savestate of the data table (datatable saveState) while updating the status in Laravel, the status is getting updated into the database but the data table is not refreshed nor the savestate is done, I am not able to understand where I am doing the mistake, below here is the code that I am using Route Route::get('/list-category', [CategoryController::class, 'listcategory'])->name('listcategory'); Controller public function changestatus($id){ $cat_statuss = Category::find($id); if (!empty($cat_statuss)) { // dd('Record is available.'); $cat_status = Category::where('id',$id)->first(); $status = $cat_status->status; $statuss = 'active'; if($status=='active'){ $statuss = 'inactive'; }else{ $statuss = 'active'; } $cat_status->status = $statuss; if($cat_status->update()){ // return redirect('/list-category')->with('status_change','Updated Successfully.'); return response()->json(array( 'success' => true, 'message'=> 'Status Changed Successfully.', 'errors' => false ), 200); }else{ return response()->json(array( 'success' => false, 'errors' => array('status_change_err'=>'Oops! There is an error.') ), 400); } }else{ // dd('Record is not available.'); return response()->json(array( 'success' => false, 'errors' => array('status_change_err'=>'Category Not Found.') ), 404); } } List Category Page <td> <a href="category_status/{{$cate->id}}" onclick="return confirm('Are you sure want to change the status?');" class="status_button btn btn-sm btn-<?php if($cate->status=='inactive'){ echo 'danger'; }else{ echo 'success'; } ?>" data-id="{{$cate->id}}"> <?php if($cate->status=='active'){ echo 'Active'; }else{ echo 'Inactive'; } ?></a> </td> <script> var table = $('#example2').DataTable( { stateSave: true } ); $(document).on('click','.status_button',function(e){ e.preventDefault(); var statusid = $(this).attr('data-id'); url = $(this).attr('href'); $.ajax({ url:url, method:"GET", data:{"_token": "{{ csrf_token() }}"}, dataType:'json', success:function(response){ // console.log(response); swal({ title: "Added", text: response.message, type: "success" }, function () { }); }, error: function(response) { swal("Error", response.responseJSON.errors.status_change_err, "error"); } }); }); </script> What do you mean by "savestate of the data table"? Are you referring to the DataTables stateSave option, or something different? Can you [edit] your question to clarify? @andrewjames yes DataTables stateSave OK - then go ahead and add the stateSave option to your DataTable. I saw your edits - that is not how you define initialization options for DataTables. See the example in the documentation. In your case it would be: var table = $('#example2').DataTable( { stateSave: true } ); @andrewjames when i am using only this nothing happens Saying "nothing happens" is not really very helpful. Please [edit] your question. Describe the specific steps you take, the results you expect to happen, and the results which actually happen. Also provide any error messages (as formatted text) from the browser's console. But first, you need to correct your stateSave code, as described in my previous comment. @andrewjames 'nothing happens' means data table did not get refreshed and my status button is not showing inactive as I am changing active status to inactive You are still not applying DataTable options correctly. You apply these once, at the start of your code. Instead of var table = $('#example2').DataTable(); use var table = $('#example2').DataTable( { stateSave: true } );. Look at the documentation I linked to. (Also, if you are using ajax, then why not use DataTables' built-in support for ajax? And you did not [edit] your question.) @andrewjames okay i did that but the same results data table is not refreshing but now statesave happens but there is one another problem now when page 2 data is updated after refreshing the page by default the page 2 is shown I want the page 1 during the page refresh
common-pile/stackexchange_filtered
cant set the size of a multi line text box mvc can anyone tell me why this wont work ? no matter what I use for cols & rows, the text box is always the same size @Html.TextAreaFor(model => model.Report.EmailMessage,new { htmlAttributes = new { @class = "form-control", @cols = 100, @rows = 20 } }) You can remove the html attributes and the below code should work. @Html.TextAreaFor(model => model.Report.EmailMessage, new { @class = "form-control", @cols = 100, @rows = 20 }) Or you could employ the following overload for TextAreaFor: public static MvcHtmlString TextAreaFor<TModel, TProperty>( this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, int rows, int columns, object htmlAttributes ) Producing: @Html.TextAreaFor(model => model.Report.EmailMessage, 20, 100, new { @class = "form-control" }) Relevant link to MSDN article.
common-pile/stackexchange_filtered
How can I expand my current setup? I currently have an HTTP server running on a single machine (it runs Ubuntu Server Edition, if that helps). In the past that has been sufficient, but as traffic has grown I have begun to need more power and storage space. I have a second machine, and have installed Ubuntu Server Edition on it. How do I get the two to run in unison? How is this usually done in professional setups? Thanks, your answers are appreciated. Are you just running apache? Please list all the technologies that are being accessed over http, such as php , mysql? What does your web app do? Have you identified the bottle necks? if so, what are they? Does you webapp keep session state? if so how? I am running PHP, MySQL, and CGI. I don't know where the bottlenecks are. I think the best way to do this would be to set it up similar to the professional setups, but I don't know how to do this. Where would be the right way to go? Are there any 'write' operations involved ? Is your PHP using mod_php, fastcgi, or ordinary command-line CGI? I no write operations are involved in your setup, you could simply use a round robin DNS setup. If that's not the case, your first option having two servers might be to use and tune 1 as a web and 1 as database server. This will introduce an additional SPOF. Should just upgrade the first machine and optimise it for running a webserver & database. First you should connect them with some fast network. You may run some caching reverse proxy like nginx. You may move MySQL to the second host. You can also try to to make distributed. Requests to the static data should be served by simpler things like nginx/lighthttpd/... on one machine or on two machines (in round-robin fashion). Read-only complex requests should be properly cached. Cache may run on other host. Complex write requests may be done some centralized manner (only on one machine; with roles separation (web server/database)). Alternatively, you may consider doing scalable system with multiple nodes that can handle all requests, but it is going to be more complicated and should be considered if there will be further massive growth. If the system is mostly read-only (like a collection of movies available for download), you may set up 2 hosts responsible for parts of content. Alternatively, if the data protection against crash is more important, you may do two identical hosts with the same data and round-robin requests to them on router. Before you do anything you need to better understand where your loads are and what your bottleneck is. It is very easy to throw faster hardware or more servers at the problem, but you may find a few specific software changes may yield the results you are after. To start with you could use some very basic, command line tools like top and the sysstat package to get a basic idea of what is going on. i.e. You first need to identify if the slowdown is caused by the CPU, network, I/O or just poorly configured software. There is plenty of information on the Web related to using these tools to identify problems (Google is your friend). Not only will this help you to understand what is going on better, it will also mean if you introduce new hardware it is actually helping to solve the problem.
common-pile/stackexchange_filtered
Need to add values into existing rows and columns I have a table called CUSTOMERS with 5 columns and 3 rows: LAST_NAME, FIRST_NAME, ADDRESS, CITY, ORDER_PRICE and I keep screwing it up and having to delete new rows I create because I'm unsure how to insert into the ORDER_PRICE column, values for rows 1 2 and 3. i've tried insert into, update table clauses but i'm doing something wrong. Can anyone tell me how to insert values into rows 1, 2, & 3 or column ORDER_PRICE? ORDER_PRICE is of sata type NUMBER Thanks Assuming firstname+lastname is unique: update CUSTOMERS set ORDER_PRICE = 4.7 where FIRST_NAME = 'The' and LAST_NAME = 'Dude' update CUSTOMERS set ORDER_PRICE = 4.2 where FIRST_NAME = 'Big' and LAST_NAME = 'Lebowsky' ... what if i have a stock apples which qty is 50 then if i entered bill details,how can add old qty + new qty @Anburaj_N: You'd say set qty = qty + 12 To change the value of a column or columns in an existing row you should use an UPDATE statement, as in UPDATE CUSTOMERS SET ORDER_PRICE = 123.45, CITY = 'San Luis Obispo' WHERE FIRST_NAME = 'Bob' AND LAST_NAME = 'Jarvis'; If you want to create a NEW row you'll want to use an INSERT statement: INSERT INTO CUSTOMERS (LAST_NAME, FIRST_NAME, ADDRESS, CITY, ORDER_PRICE) VALUES ('Jarvis', 'Bob', '12345 Sixth St', 'Cucamonga', '123.45'); Share and enjoy.
common-pile/stackexchange_filtered
Leaflet fitBounds issue on mobile/small viewport I've been running into some odd issues with Leaflet's fitBounds method that only seem to occur when I test it in a mobile-sized browser window (either on a mobile device or a desktop). I am giving fitBounds a southwest corner and a northeast corner corresponding to two markers. On a full-sized screen it works fine; the map recenters between the two at an appropriate zoom level (you can see both). But on a small screen with portrait orientation, the map center seems to be slightly east of the center between the two markers, and the markers are each slightly out of the window. If I drag-pan the map the slightest bit, it suddenly jumps east, seemingly recentering on the proper centerpoint between the two markers. Here is my code for this: var bounds = L.latLngBounds([coordLats[0], coordLons[0]], [coordLats[1], coordLons[1]]); map.fitBounds(bounds); fixZoom(); function fixZoom(){ var z = map.getZoom() z = z > 18 ? 18 : z; //don't go beyond max zoom! map.setZoom(z); }; coordLats and coordLongs are arrays with the two markers' latitudes and longitudes respectively, ordered least to greatest. Any ideas? First of all, don't use this crude maxZoom hack. There is an option in L.TileLayer to set the max zoom. L.tileLayer('http://tiles.lyrk.org/lr/{z}/{x}/{y}', { maxZoom: 18 }).addTo(map); In addition to that make sure that you include a proper viewport. If you don't provide that, Leaflet may have some unwanted behavior. <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
common-pile/stackexchange_filtered
Sequence Strategy for MYSQL not working (EclipseLink, Glassfish) Sequence Strategy for MYSQL not working I have an Id defined in my entity: @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; When persisting an entity I get the following error. I checked several hints, but noone worked for me. Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.7.0.v20170811-d680af5): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'OPTION SQL_SELECT_LIMIT=DEFAULT' at line 1 Error Code: 1064 Call: UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ? bind => [2 parameters bound] Query: DataModifyQuery(name="SEQUENCE" sql="UPDATE SEQUENCE SET SEQ_COUNT = SEQ_COUNT + ? WHERE SEQ_NAME = ?") MYSQL Version : 8 SQL "UPDATE SEQUENCE ..." can be executed from the workbench without problems. "OPTION SQL_SELECT_LIMIT=DEFAULT" seems not to be valid. I guess "OPTION SQL_SELECT_LIMIT=DEFAULT" is coming implicitely when .persist() is called, because of the sequence strategie. Any help hints ? UPDATE Switching to strategy = GenerationType.IDENTITY does not invoke "OPTION SQL_SELECT_LIMIT=DEFAULT" and it works fine. Strange. MySQL version? Where is 'OPTION SQL_SELECT_LIMIT=DEFAULT' coming from? Wherever it is, it isn't valid for MySQL. AUTO means let the JPA provider do whatever the heck they want. SEQUENCE means use a datastore sequence. Leave it as AUTO and you get no predictable behaviour Auto uses table sequencing, which is why you see just a "UPDATE" sql statement, and the "SQL_SELECT_LIMIT" option isn't something the EclipseLink MySQLPlatform class adds, so it might be a driver setting. This should be looked into as it might affect your other queries - show the full stack trace, and make sure you haven't added any native settings somehow. Maybe this link helps : https://stackoverflow.com/questions/33096466/generationtype-auto-vs-generationtype-identity-in-hibernate
common-pile/stackexchange_filtered
Is it correct to say : "Can you confirm this email reach you properly ?" When I write an email to someone, I like to get a confirmation that the guy in front received and read properly my email. So I'd like to know if : Can you confirm this email reach properly. Is it correct? I'm not sure, but I think you're perhaps looking for something like Please confirm receipt of this email/letter. Note that "an email reaching the recipient" is not the same thing as "the recipient having received and read the email". Your request is actually an analog of the following question, with a that-clause, with the word that omitted: Can you please confirm that this email {verb} you? Can you please confirm this email {verb} you? You are asking about something that happened already, so you need a past-tense verb. Compare: Can you confirm (that) the train departed on time yesterday? We don't use the bare infinitive depart in the that-clause; rather we use a tensed (finite) verb, departed. Can you confirm (that) the email reached you? Can you please confirm that this email has reached you? It should be past tense. And "reach" in this case is transitive, that is, you have to say who or what it reached. So, "Can you confirm this email reached you properly?" It's more common to make it a request rather than a question. And "properly" is pretty much implied. So the more common phrasing would be: "Please confirm this email reached you."
common-pile/stackexchange_filtered
PostSharp 1.5 and .Net 4 Postsharp is great, but only the 1.5 version is still opensource. Does it work with .net 4.0? If not, are there any other good AOP weavers out there? I'm not interested in the proxy type. Why not use the community version of Postsharp 2.0? To answer my own question: PostSharp 1.5 does appear to work with .net 4.0. I have a [Cache] Attribute working just fine in a .net 4.0 Class Library. Now, maybe some parts of it don't work, but i haven't hit those. Gael can you enlighten me here? That said, the community edition of the latest PostSharp seems like the way to go. Thank you Gael for providing a commercially usable lite version of this great product. See my answer - we're using PostSharp with ASP.NET 4 projects (v<IP_ADDRESS>9) with no issues! PostSharp 1.5 will not run on .NET 4.0. There's a discussion of alternatives on http://www.sharpcrafters.com/postsharp/alternatives. I think its great you have the alternatives listed on your site. CCI stuffs looks neat. What are the restrictions on your community version. Restrictions on the community edition are listed on: http://www.sharpcrafters.com/postsharp/purchase/compare. Basically, the community edition is just a little better than OSS alternatives; the professional edition is much better. I'm not sure I agree with the other answers... We're using PostSharp on some ASP.NET 4 projects at work with no problems! I don't remember us having to do anything tricky to get this to work, so if you're getting errors, post them here, and maybe we can help. What version are you using? This answer was over 4 years ago. We were using an old version IIRC, though we ripped it out of our app a few years ago for a huge host of reasons! Running PostSharpo 1.5 from VS2010 is not supported but I've managed to make it work but it took some tinkering. In the .csproj file add the following line: <PropertyGroup> <PostSharpUseCommandLine>True</PostSharpUseCommandLine> </PropertyGroup> This would make PostSharp run until you can upgrade to a newer and better version.
common-pile/stackexchange_filtered
JTS Geometry.intersects() method produces infinite loop I'm trying to check whether a Multipolygon intersects with which Polygon in a list, using JTS library. However, the method stucks in an infinite loop and end with an out of heap space error. The method works fine for pairs that apparently don't intersect. The infinite loop starts when the first pair that's likely to intersect appears. Here are the coordinate sequence of the two problematic Geometry objects, (GeoJson format): Edit 1 - adding the code: Multipolygon: [ [ [ [ 24.899993263111575, 60.168590212519007, 0.0 ], [ 24.8921845577913, 60.170930189360085, 0.0 ], [ 24.906727352467691, 60.177129472862902, 0.0 ], [ 24.912750145776748, 60.178210672366426, 0.0 ], [ 24.915824674917332, 60.1759297188066, 0.0 ], [ 24.916581969097017, 60.175298383750082, 0.0 ], [ 24.921993683436096, 60.17592332951083, 0.0 ], [ 24.924298430649159, 60.176277074203171, 0.0 ], [ 24.925777801589089, 60.176578177900481, 0.0 ], [ 24.927069958749666, 60.176812746915481, 0.0 ], [ 24.934606301659603, 60.17770118209701, 0.0 ], [ 24.93829154797028, 60.17943631088842, 0.0 ], [ 24.943101975190991, 60.179746422785151, 0.0 ], [ 24.946157646983945, 60.177893553297686, 0.0 ], [ 24.949063929828164, 60.176872818864446, 0.0 ], [ 24.948884500413151, 60.176763003129317, 0.0 ], [ 24.947435273641268, 60.175810147107796, 0.0 ], [ 24.947645652172458, 60.174545608314318, 0.0 ], [ 24.953922745030216, 60.17465838879788, 0.0 ], [ 24.952114223411215, 60.172614801031834, 0.0 ], [ 24.952535692362105, 60.169038476544031, 0.0 ], [ 24.954301749734213, 60.168843140472724, 0.0 ], [ 24.954352635736257, 60.167875977512914, 0.0 ], [ 24.954382959437606, 60.167722794336058, 0.0 ], [ 24.94618172965189, 60.167514740158367, 0.0 ], [ 24.94537429422477, 60.167437294026875, 0.0 ], [ 24.946805477127789, 60.166445009469363, 0.0 ], [ 24.946239227186837, 60.166289851133151, 0.0 ], [ 24.94605715808019, 60.166369202625063, 0.0 ], [ 24.944895457595461, 60.165955522827154, 0.0 ], [ 24.943796685615666, 60.166732851647168, 0.0 ], [ 24.943804264808218, 60.16695638982231, 0.0 ], [ 24.94339656134855, 60.167013101789991, 0.0 ], [ 24.943005307041311, 60.1672873863494, 0.0 ], [ 24.942815762910648, 60.167233708186423, 0.0 ], [ 24.942650545385295, 60.167130925185603, 0.0 ], [ 24.9407231754085, 60.166436365685314, 0.0 ], [ 24.940722537913366, 60.166342333123318, 0.0 ], [ 24.940730039071539, 60.166232085046666, 0.0 ], [ 24.94054008676806, 60.166146432407373, 0.0 ], [ 24.940689883918264, 60.166032286309964, 0.0 ], [ 24.938850589801866, 60.165384512580708, 0.0 ], [ 24.938374768557253, 60.165445980685028, 0.0 ], [ 24.938302460409481, 60.165202578885371, 0.0 ], [ 24.937168766625486, 60.1648185467416, 0.0 ], [ 24.936325303890971, 60.164523435250963, 0.0 ], [ 24.935515249176746, 60.165055276075314, 0.0 ], [ 24.935162131372266, 60.165067012171299, 0.0 ], [ 24.935243484405692, 60.165243301611966, 0.0 ], [ 24.934771879418953, 60.165604942333808, 0.0 ], [ 24.935697179525107, 60.165921540021522, 0.0 ], [ 24.935678441330882, 60.16607022900051, 0.0 ], [ 24.93562630412751, 60.166223958343842, 0.0 ], [ 24.93432941740414, 60.16639906762866, 0.0 ], [ 24.934086151809726, 60.16643747924013, 0.0 ], [ 24.933996000970303, 60.166879775928571, 0.0 ], [ 24.933494220741714, 60.166503500060202, 0.0 ], [ 24.930639585658206, 60.166879026400828, 0.0 ], [ 24.930477360716871, 60.167021165775722, 0.0 ], [ 24.93012338167825, 60.166940112911924, 0.0 ], [ 24.926990522351048, 60.167324416451343, 0.0 ], [ 24.926831203850465, 60.167593482122442, 0.0 ], [ 24.92584998697993, 60.167800919963199, 0.0 ], [ 24.925440947757817, 60.167842026167428, 0.0 ], [ 24.925464402293027, 60.167636210840456, 0.0 ], [ 24.925057233085131, 60.167426343568081, 0.0 ], [ 24.924638431368617, 60.167314445885701, 0.0 ], [ 24.924653932101634, 60.166777681068048, 0.0 ], [ 24.924239526771945, 60.166656330235163, 0.0 ], [ 24.923909713383374, 60.166769702593491, 0.0 ], [ 24.919742746576386, 60.166669946668634, 0.0 ], [ 24.919486254229472, 60.168947489628216, 0.0 ], [ 24.917865586081348, 60.169052961010145, 0.0 ], [ 24.913389466202162, 60.169206955531649, 0.0 ], [ 24.908339577064975, 60.169298848862468, 0.0 ], [ 24.899993263111575, 60.168590212519007, 0.0 ] ], [ [ 24.936135087425775, 60.173864750028308, 0.0 ], [ 24.935822882124054, 60.173818038029538, 0.0 ], [ 24.935698898369246, 60.173449814747812, 0.0 ], [ 24.935042425364173, 60.172863964505616, 0.0 ], [ 24.934700282784398, 60.172293513337216, 0.0 ], [ 24.934235985164971, 60.171993255866646, 0.0 ], [ 24.93458616422809, 60.171768472366658, 0.0 ], [ 24.935119957047309, 60.171965193243153, 0.0 ], [ 24.935650390363076, 60.171879257705569, 0.0 ], [ 24.936025502093653, 60.171926942487744, 0.0 ], [ 24.936234782914752, 60.171605759312015, 0.0 ], [ 24.937662268667879, 60.172287296440999, 0.0 ], [ 24.936135087425775, 60.173864750028308, 0.0 ] ] ] ] Polygon: [ [ [ 24.94068318546399, 60.17336319841633 ], [ 24.93618043398334, 60.17329314372988 ], [ 24.936039655930326, 60.17553644290522 ], [ 24.940542714024545, 60.17560650391693 ], [ 24.94068318546399, 60.17336319841633 ] ] ] Here's the piece of code used to generate Polygon: public Polygon toPolygonJTS(GeometryFactory factory, LinearRing polygonRingHolder, ArrayList<LinearRing> holeHolder, ArrayList<Coordinate> coordinateHolder) { if (!this.jtsDrawn) { boolean isHole = false; // list of points stored in array list for (ArrayList<ArrayList<Double>> linearRing : this.geometry .getCoordinates()) { for (ArrayList<Double> point : linearRing) { // add the point to array coordinateHolder.add(new Coordinate(point.get(0), point .get(1))); } if (!isHole) { // create a LinearRing for the polygon polygonRingHolder = new LinearRing( new CoordinateArraySequence( coordinateHolder .toArray(new Coordinate[coordinateHolder .size()])), factory); } else { // add LinearRing to a list of polygons specifying holes holeHolder.add(new LinearRing(new CoordinateArraySequence( coordinateHolder .toArray(new Coordinate[coordinateHolder .size()])), factory)); } // clear coordinate holder for the next loop coordinateHolder.clear(); } // create a polygon and store in object property this.polygon = new Polygon(polygonRingHolder, holeHolder.toArray(new LinearRing[holeHolder.size()]), factory); } return this.polygon; } For MultiPolygon: public MultiPolygon toMultiPolygonJTS(GeometryFactory factory, ArrayList<Polygon> polygonList, LinearRing polygonRingHolder, ArrayList<LinearRing> holeHolder, ArrayList<Coordinate> coordinateHolder) { if (!this.jtsDrawn) { boolean isHole = false; for (ArrayList<ArrayList<ArrayList<Double>>> polygon : this.geometry.coordinates) { for (ArrayList<ArrayList<Double>> linearRing : polygon) { for (ArrayList<Double> point : linearRing) { coordinateHolder.add(new Coordinate(new Coordinate(((Double) (point.get(0) * 100000)).intValue(), ((Double) (point .get(1) * 100000)).intValue()))); } if (!isHole) { polygonRingHolder = new LinearRing( new CoordinateArraySequence( coordinateHolder .toArray(new Coordinate[coordinateHolder .size()])), factory); } else { holeHolder .add(new LinearRing( new CoordinateArraySequence( coordinateHolder .toArray(new Coordinate[coordinateHolder .size()])), factory)); } coordinateHolder.clear(); } // create a polygon and add to a list polygonList.add(new Polygon(polygonRingHolder, holeHolder .toArray(new LinearRing[holeHolder.size()]), factory)); } // create multipolygon from list of polygon, and store in object this.multiPolygon = new MultiPolygon( polygonList.toArray(new Polygon[polygonList.size()]), factory); } return this.multiPolygon; } Check if two Geometrys intersect: public boolean collidesJTS(MapSquarePolygonFeature mapsquare, GeometryFactory factory, ArrayList<Polygon> polygonList, LinearRing polygonRingHolder, ArrayList<LinearRing> holeHolder, ArrayList<Coordinate> coordinateHolder) { return this.multiPolygon.intersects(mapsquare.toPolygonJTS(factory, polygonRingHolder, holeHolder, coordinateHolder)); } Edit 2: The code runs well if I create distance from the two Geometrys, e.g. multiply the Polygon's x and y by 10. Could we see the code that invokes intersects? That may help diagnose the problem.
common-pile/stackexchange_filtered
GIT says I have no commits in repo -- how to recover? Using Win7, 64-bit. I use the GitExtensions GUI, which has been working fine for 3 months. Today I did a commit, immediately pushed to my server repo, and shut down. When I powered back up later in the day and tried to do another (local) commit, GitExtensions told me that I have NEVER committed to that repo and showed 119 files with changes. Obviously something got fried, so my first thought was to do a pull from my server repo. Guess what? The server repo is also showing that I have NEVER committed to it. So then my next thought was GitExtensions is lying to me. So I moved over to Tortoise GIT and did a "View Log". Guess what? GitExtensions isn't lying. Tortoise GIT also shows that I have NEVER committed to my repo. When I physically browse in the repo, I can see all the object files with reasonable-looking timestamps covering the 3 months I've been working on this project. How can I get GIT to recover and realize that I have 3 months of commits STILL IN THERE? The only articles I've seen are on how to recover individual lost commits that need to make use of an earlier commit as a starting point. Obviously that's not going to help me since I can't see ANY commits. Thanks for your help. First, back up your repository so that any attempted fixes that fail don't corrupt it worse. git fsck can help find and fix errors in the repository. git reflog can help you identify orphaned commits and reconstruct the history. This answer on the "bad default revision" error may help. If fsck does nothing for you, my first thought would be to try to reset the remote repository's HEAD back one commit and then try a re-clone. FYI when the error described happens git reflog actually fails saying there are "no commits" - so it's actually no use Check what you get for "git log master" or any other branch. If that works, you can use "git bundle" to explicitly export commits and all related objects. Rinse and repeat for ask other branches in .git/refs. It would probably be best to drop down to the command line to get this fixed. Download the latest msysgit. Is the .git folder still in there? If it is that is where git stores all it's information. If not, then there is nothing to get back. If not, then your local git is gone. If you .git is still there, try running git log and see what it shows. If your .git folder is gone, then you should be able to do a "new" clone from your server to retrieve everything. Yes, the .git folder is there and I can see all the objects still in there. Did a "git log" and got this message: "fatal: bad default revision 'HEAD'." And I can't clone from the server. The remote repo is exhibiting the same behavior. It's like the GUI tools I use corrupted the commit and then, because I immediately pushed to the server, that corruption got transferred to the server repo as well. So your GUI tool performed a forced push without asking your?! No, there's an option in the GUI to perform a push immediately after the commit. I usually enable that option so that my latest work is immediately stored on two different machines. I guess the lesson learned is to keep the server repo behind the local by at least one power cycling of my development machine.
common-pile/stackexchange_filtered
Is it possible to use 1 html file to view different items on different pages? I am currently in the process of creating a website for a small enterprise. I made a nav item called "Collections" where it is divided into various categories for the type of products that will be sold (Rings, Bracelets etc). And then Under "Rings" (when selected), multiple items that can be bought are displayed in a gallery form (image + a "click here for more details"just below). When you select an individual item, a new page (target="_blank") will open that will display price/description of said selected item. Since in the future, there will probably be hundreds of items with their price/descriptions, should i make an individual html file for each? Or is there a way to have 1 html file and a new page opening depending on which item was selected? Aren't you trying to create a dynamic site? If you use a server side scripting language like php or whatever, you need to create only one html-like model of your desired product details page, the server side script will handle everything else according to user's request and fetch everything needed from database. And if you are thinking that you will create each product's page individually, then that is unusual, time consuming and not really used anywhere for business purpose. Since you want to build an e-commerce site, you would need a back-end language to achieve it I believe you are looking for single page application, since you are building an e-commerce website there would be click events to show product description.creating individual page for each product is time consuming.From your question i believe you want load the product details on the same page which can be achieved by loading data from your back end and implementing a templating system in the front end. have a look at https://angular.io/ Since you're looking at creating an e-commerce site and needing help on the simpler bits then I would suggest that you look into using a dedicated hosted e-commerce platform such as Shopify, Squarespace or if you want to self host Magento or Prestashop. This is because once money is involved, rolling your own platform when you're not an expert isn't a great idea. There's a post here: https://www.upwork.com/hiring/for-clients/self-hosted-vs-hosted-e-commerce-platforms-right/ which could help you decide what is best for you. I should not have used the word e-commerce, my bad. Payment through the website itself will not be available. I don't think it's a link-only answer. Although providing with a relevant piece of information, it should be deleted because it simply does not answers the OP's question (should i make an individual html file for each?)
common-pile/stackexchange_filtered
Renamed image does not appear in imageView After renaming an image with this code: String path = "/storage/emulated/0/Download/"; File from = new File (path, "old.jpg"); File to = new File (path, "new.jpg"); from.renameTo (to); String newpath = to.getAbsolutePath(); If I try to open the gallery and select the same image (which has changed its name) this is not displayed in the imageView. Why? Additional information: if I try to print the URI of the image while selecting it from the gallery it appears in the console: D/picUri: content://com.google.android.apps.photos.contentprovider/blablabla/ORIGINAL/NONE/2094062349 Bear in mind that changes that you make to the filesystem will take time to reflect in gallery apps, as those apps work off the of MediaStore. And, note that you will not be able to use your code on Android Q (by default) or Android R (for all apps), as we now have very restricted access to external storage. How can I solve it? I must necessarily rename the image and then use it immediately "I must necessarily rename the image" -- why? Why not save the image with the correct name in the first place? Because the images are downloaded from the internet, I have to set the right name based on the style I want to give to the photo. If for example the user selects the Monet effect, the photo must become "monet.jpg" because it is processed in this way by the PHP server
common-pile/stackexchange_filtered
Calculating score for a level with time and lives variation I am developing a game where based on steps to be performed in a particular level, time and lives are pre-calculated. As the level gets completed, remaining lives and time are retrieved. Calculating score based on remaining time and lives will not work in this system, as the same level with smaller number of steps will have less time and lives than level with more steps. Can I count score based on time and lives efficiency? If yes, then how to calculated the score so that it is unbiased? I am stuck as it is my first game development. Any constructive criticism is appreciated. Do nothing Consider that you are deciding the time and lives to complete the level. If the margin the player has to complete the level remains the same, then the player would complete both the short and the long levels with about the same time and lives remaining. In which case there would no need to adjust for it, as the adjustment was already done when you decided how much time and lives to give the player. Also, perhaps correctness is not the goal. You might want it to be easier or harder to get points on advanced levels. Simple normalization The idea is to use a proportion. Or percentage, if that makes it easier for you to reason about. So instead of using the remaining time directly, you use how much is the remaining time of the total time. And the same idea for lives. This would be correct the time and lives you give the player grows linearly with the complexity of the game. Again, perhaps correctness is not the goal. Complexity metric You would have some complexity metric that tries to capture how hard the levels are. Then you do some computation over your complexity metric to come up with the time and lives. An example of complexity metric would be the number of steps needed to solve the level. Yet, it does not consider all the alternative options the player might try, only the ideal path. The more things the player could do at any particular moment, the more work they might need to figure out the solution. Submitted to your consideration: We know that any - standard - Rubik Cube can be solved in at most 20 steps. But that 20 does not capture all the possible moves that do not solve the Rubik Cube, nor the skill needed to know which moves to do in order to solve it. So, the actual complexity of the game might actually be an exponential function of the number of steps needed to solve the level. It might be a better idea to incorporate your complexity metric into the scoring directly. So you can use the quickness to solve the level in complexity over time for scoring. In other words, the score could be based on the complexity of the level divided by the time the player took to complete it. Experiment What do engineers do when they don't know? They fuck around and find out do basic research. Which in this case would mean to get a set of test players to try the games and record how much time and lives they take to complete the levels, and compare it to the time and lives you would be given them. This will give you some idea of: How generous is the computations you are using to give them time and lives. How does the time and lives used by the players scale with your complexity metric. You might also discover that the player struggle in unexpected ways and times. Even might struggle more in levels you consider easier. Also, players might give you ideas. And then, having your results, you can decide if you are going to adjust the computation, or the score, or both. And then you repeat the experiment. This time adding more test players so you have a mix of people who have tried the game before and other that don't. And perhaps you do further refinements or stick with what you got. Ultimately what you do is tweak values and pick something that works in practice. Even if you don't fully understand it, you would have empirical evidence that it works. Other Alternatives Perhaps it is better to add collectibles for points, or the game design allows for style points. Or perhaps the game does not need score at all. Losing a live is already lost time, so a leader board based on time might be enough.
common-pile/stackexchange_filtered
Terminate compound statements in IPython I am new to python (and programming), so please forgive me if I don't follow the correct nomenclature. It makes finding answers to even the most trivial questions hard. Thanks! In IPython I typed the following: for i in s: print([s:i] The white space was added by IPython automatically. Hitting return twice does not get me back to the iPython prompt, however. In other words I cannot end the compound statement. What do I need to do? Many thanks! Try to hit return more than twice. Also maybe you're leaving a parenthesis or a square bracket opened. Besides your expression [s:i] doesn't make much sense. Paulo, thank you! Yes, I did not close the parenthesis. Can you imagine, I did not see this at all, even after staring at the screen for minutes to find a mistake!!! That has happened to me numerous times :) Glad you could fix it.
common-pile/stackexchange_filtered
In Microsoft Outlook 2016, immediately mark an new email as read In Outlook 2016 and in Folder view Pane, when I receive a new e-mail and I'm reading it as follows: It's not immediately marked as read until I click on another e-mail or I press CTRL+Q. How can I change this? You can specify the seconds it takes to mark a message as read. Setting this value to 0 will mark them immediately, as you want - see this link for a detailed how-to: https://www.laptopmag.com/articles/instantly-mark-messages-read-outlook Thank you! That's what I needed In Outlook: Click File Click Options Click Mail Check "Mark items as read when viewed in the Reading Pane" Set "Wait" to zero Click OK Thank you, that's exactly what I needed! I didn't choose your answer because it wasn't the first and also to encourage the new user, but of course you got +1.
common-pile/stackexchange_filtered
Is the real-imaginary Schanuel's conjecture equivalent to the full Schanuel's conjecture? Schanuel's conjecture says the following about the transcendence of numbers related by the complex exponential function: Given any $n$ complex numbers $z_1, ... z_n$ that are linearly independent over the rational numbers $\mathbb{Q}$, the field extension $\mathbb{Q}(z_1, ..., z_n, e^{z_1}, ..., e^{z_n})$ has transcendence degree at least $n$ over $\mathbb{Q}$. I would like to control the real and imaginary parts of the numbers separately. Thus I'm interested in the restriction to real and imaginary numbers $z_1, ... z_n$. Since for imaginary numbers $yi$, the function values $e^{yi}$, $\cos y$ and $\sin y$ are definable from each other by algebraic functions, the real-imaginary Schanuel's conjecture can be stated using only real functions as follows: Given any $m+n$ real numbers $x_1, ... x_m, y_1, ... y_n$ such that each of the sets $x_1, ... x_m$ and $y_1, ... y_n$ are linearly independent over the rational numbers $\mathbb{Q}$, the field extension $\mathbb{Q}(x_1, ... x_m, y_1, ... y_n, e^{x_1}, ..., e^{x_m}, \cos y_n, ... \cos y_n)$ has transcendence degree at least $n$ over $\mathbb{Q}$. Is this conjecture equivalent to the full Schanuel's conjecture? I know that it's implied by Schanuel's conjecture since $x_1, ... x_m, y_1i, ... y_ni$ are linearly dependent, that is the equation $a_1x_1+ ... +a_mx_m+b_1i+ ... +b_ny_ni=0$ has a rational solution $a_1, ..., a_m, b_1, ..., b_n$ iff it is a simultaneous solution of the two equations $a_1x_1+ ... +a_mx_m=0$ and $b_1+ ... +b_ny_n=0$. In the converse direction we have $$\overline{\mathbb{Q}(z_1, \overline{z_1}, ..., z_n, \overline{z_n}, e^{z_1}, e^{\overline{z_1}}, ..., e^{z_n}, e^{\overline{z_n}})}=\overline{\mathbb{Q}(\Re z_1 \Im z_1, ..., \Re z_n, \Im z_n, e^{\Re z_1}, e^{\Im z_1}, ..., e^{\Re z_n}, e^{\Im z_n})}$$ (where $\overline{F}$ denotes the algebraic closure of the field $F$, $\overline{z}$ denotes the complex conjugate of $z$, $\Re z$ denotes the real part of $z$, and $\Im z$ denotes the imaginary part of $z$), but I'm having trouble proving that linear independence of $z_1, \overline{z_1}, ..., z_n, \overline{z_n}$ is equivalent to linear independence of $\Re z_1 \Im z_1, ..., \Re z_n, \Im z_n$. Additionally, I'm not sure if I can prove that Schanuel's conjecture for $n$-tuples closed under complex conjugation is equivalent to Schanuel's conjecture for all $n$-tuples. This is not a complete solution; writing a complete solution turned out to be harder than I thought. I'm having trouble proving that linear independence of $z_1,\overline{z_1},...,z_n,\overline{z_n}$ is equivalent to linear independence of $\Re z_1, \Im z_1, ..., \Re z_n, \Im z_n$. Assume as induction hypothesis that $z_1,\overline{z_1},...,z_n,\overline{z_n}$ and $\Re z_1, \Im z_1, ..., \Re z_n, \Im z_n$ span the same vector subspace of $\mathbb{C}$ over $\mathbb{Q}$. Then there are four possibilities for whether the real and imaginary parts of $z_{n+1}$ is linearly independent with any maximal linearly independent subset of $z_1, ..., z_n$: $\Re z_{n+1}$ and $i\Im z_{n+1}$ are both linear combinations of $z_1,\overline{z_1},...,z_n,\overline{z_n}$. By the induction hypothesis it is equivalent that they are both linear combinations of $\Re z_1, i\Im z_1, ..., \Re z_n, i\Im z_n$, meaning that $\Re z_{n+1}$ is a linear combination of $\Re z_1, ..., \Re z_n$ and $\Im z_{n+1}$ is a linear combination of $\Im z_1, ..., \Im z_n$. Thus $\Re z_{n+1}$ and $\Im z_{n+1}$ are both in the vector space spanned by $\Re z_1, \Im z_1, ..., \Re z_n, \Im z_n$. $\Re z_{n+1}$ is linearly independent with $\Re z_1, ..., \Re z_n$, thus linearly independent with $\Re z_1, i\Im z_1, ..., \Re z_n, i\Im z_n$, thus linearly independent with $z_1,\overline{z_1},...,z_n,\overline{z_n}$, whereas $\Im z_{n+1}$ $\Im_{n+1}$ is a linear combination of $\Im z_1, ..., \Im z_n$, thus $i\Im_{n+1}$ is a linear combination of $\Re z_1, i\Im z_1, ..., \Re z_n, i\Im z_n$, thus $i\Im_{n+1}$ is a linear combination of $z_1,\overline{z_1},...,z_n,\overline{z_n}$. Then $z_1,\overline{z_1},...,z_n,\overline{z_n}, z_{n+1}$, $z_1,\overline{z_1},...,z_n,\overline{z_n}, \overline{z_{n+1}}$, $z_1,\overline{z_1},...,z_n,\overline{z_n}, z_{n+1}, \overline{z_{n+1}}$, and $\Re z_1, i\Im z_1, ..., \Re z_n, i\Im z_n, \Re z_{n+1}$ span the same vector space, whose dimension is $1$ greater than the dimension of the vector space spanned by either of $z_1,\overline{z_1},...,z_n,\overline{z_n}$ or $\Re z_1, i\Im z_1, ..., \Re z_n, i\Im z_n$. $\Re z_{n+1}$ is a linear combination of $\Re z_1, ..., \Re z_n$, thus a linear combination of $\Re z_1, i\Im z_1, ..., \Re z_n, i\Im z_n$, thus a linear combination of $z_1,\overline{z_1},...,z_n,\overline{z_n}$, whereas $\Im z_{n+1}$ $\Im_{n+1}$ is linearly independent with $\Im z_1, ..., \Im z_n$, thus $i\Im_{n+1}$ is linearly independent with $\Re z_1, i\Im z_1, ..., \Re z_n, i\Im z_n$, thus $i\Im_{n+1}$ is linearly independent with $z_1,\overline{z_1},...,z_n,\overline{z_n}$. Then $z_1,\overline{z_1},...,z_n,\overline{z_n}, z_{n+1}$, $z_1,\overline{z_1},...,z_n,\overline{z_n}, \overline{z_{n+1}}$, $z_1,\overline{z_1},...,z_n,\overline{z_n}, z_{n+1}, \overline{z_{n+1}}$, and $\Re z_1, i\Im z_1, ..., \Re z_n, i\Im z_n, \Im z_{n+1}$ span the same vector space, whose dimension is $1$ greater than the dimension of the vector space spanned by either of $z_1,\overline{z_1},...,z_n,\overline{z_n}$ or $\Re z_1, i\Im z_1, ..., \Re z_n, i\Im z_n$. $\Re z_{n+1}$ is linearly independent with $\Re z_1, ..., \Re z_n$, thus linearly independent with $\Re z_1, i\Im z_1, ..., \Re z_n, i\Im z_n$, thus linearly independent with $z_1,\overline{z_1},...,z_n,\overline{z_n}$, and $\Im z_{n+1}$ $\Im_{n+1}$ is linearly independent with $\Im z_1, ..., \Im z_n$, thus $i\Im_{n+1}$ is linearly independent with $\Re z_1, i\Im z_1, ..., \Re z_n, i\Im z_n$, thus $i\Im_{n+1}$ is linearly independent with $z_1,\overline{z_1},...,z_n,\overline{z_n}$. By the induction hypothesis $z_1,\overline{z_1},...,z_n,\overline{z_n}$ and $\Re z_1, i\Im z_1, ..., \Re z_n, i\Im z_n$ span the same vector space, and $a_1 z_1, ..., a_n z_n, a_{n+1} z_{n+1} =0$ is equivalent to $a_1 \Re z_1, ..., a_n \Re z_n, a_{n+1} \Re z_{n+1} =0$ and $a_1 \Im z_1, ..., a_n \Im z_n, a_{n+1} \Im z_{n+1}$ simultaneously, so the dimension of the vector space spanned by either of $z_1,\overline{z_1},...,z_n,\overline{z_n}, z_{n+1}, \overline{z_{n+1}}$, and $\Re z_1, i\Im z_1, ..., \Re z_n, i\Im z_n, \Im z_{n+1}$ is $2$ greater than the dimension of the vector space spanned by either of $z_1,\overline{z_1},...,z_n,\overline{z_n}$ or $\Re z_1, i\Im z_1, ..., \Re z_n, i\Im z_n$. In all cases, $z_1,\overline{z_1},...,z_n,\overline{z_n}, z_{n+1}, \overline{z_{n+1}}$ and $\Re z_1, \Im z_1, ..., \Re z_n, \Im z_n, \Re z_{n+1}, \Im z_{n+1}$ span the same vector subspace. By induction (the base case is trivial) this applies to every $n$-tuple of complex numbers for every natural number $n$.
common-pile/stackexchange_filtered
Whats the best Windows Server platform to run Apache / PHP / MySQL? Anyone out there running this setup ? What is the best Windows Server setup to keep it running smooth ? Thans Er... Linux? For stability, freeness and betterness. 'nuf said. For production? VMWare and LAMP? Did you take a look at how to solve the security issues in Xampp/Wamp? I agree, and would be using the LAMP box I am working on... except im being forced to migrate ALL LAMP projects to a windoze box... :/ This is why I cannot use it... :( Aww :-( I feel your pain. Erm...Server 2008 R2 64-bit is a bit of a generic answer but it's the right one, if you want the best Windows server release, well that's it. Obviously you'll have to decide the particular version (Standard, Enterprise etc.) for your system but that's the only answer I think you'll get. I very much like the product USBWebserver: http://www.usbwebserver.net/en/ This package combines PHP and MySQL (+ PhpMyAdmin) in one simple package. Simply start the .exe and the product starts php and mysql on your system. Try Xampp. It is easy and smooth running on all platforms. Check this out. On a Windows Server ? is that the best option ? Is it robust enough ? I will vote +1 for Wamp over Xampp Im using WAMP fine on my local dev machine, but its not a soluition for a live production box... You can use Wamp the best tool for Apache, PHP, Mysql. I am using it since 3 years its great so far
common-pile/stackexchange_filtered
How do you hide a hidden list? If you set the SPList.Hidden property to true, the list isn't shown in the Quick Launch, All Site Content, Lookup lists, etc. However, it is still possible to navigate to the list by typing in the list's URL, or by using an old bookmark. So how do you actually hide a list, so that it won't display under any circumstances? SPList.BreakRoleInheritance(false) ? @VedranRasol: Not a bad solution, but I'd rather avoid stripping all the permissions if possible. I don't understand the point of using a list if no one is supposed to be able to see it. Why not just create a database / table? @tylerrrr07: The data needs to be accessed programmatically by web parts, but not directly through the UI. Also, I should mention that this is for a 3rd party solution (where we're the 3rd party), so requiring direct SQL Server access is generally considered a faux-pas. I ran into the same requirement in a recent project, basically preventing access to any list view or form of a particular (hidden) list via the Web browser. SharePoint designer isn't allowed on Web Application level and Web services (including client object model) is blocked by a custom HTTP handler, so the concerns mentioned in other answers didn't apply to this project. Removing permissions was not an option because lookup fields of the list are used on other lists and should work for anybody, but accessing the list itself shouldn't be possible. Instead of the tedious task of messing with URL-rewriter rules on the IIS server or a custom HTTP handler, which has several disadvantages as described later, the solution was to develop a custom SharePoint DelegateControl as described here https://littletalk.wordpress.com/2010/11/18/create-an-additionalpagehead-control-packed-into-a-feature-in-visual-studio-2010/ The DelegateControl contains code to check for a particular SharePoint group membership. If the current user isn't a member the following code blocks access to the list view & forms ASPX pages (note that the code has been simplified and might need more polishing): string currentUrl = Request.Url.ToString().ToLower(); SPWeb currentWeb = SPControl.GetContextWeb(Context); SPList currentList = SPContext.Current.List; if (!currentUrl.Contains("/_layouts/") && (currentList != null && currentList.Title == "Your List Name")) { Response.Clear(); Response.StatusCode = 403; Response.Status = "403 - Forbidden"; Response.StatusDescription = "Access is denied"; string accessDeniedPage = SPUtility.AccessDeniedPage; string redirectUrl = "/_layouts/" + accessDeniedPage + "?Source=" + currentUrl; Response.Redirect(SPUrlUtility.CombineUrl(currentWeb.Url, redirectUrl), true); } Unlike a custom HTTP handler the custom SharePoint DelegateControl will only fire its code when an ASPX page is hit which IMHO is a big advantage because the HTTP handler fires on every single request (even a JS/CSS/GIF etc. file) which puts additional load on the SharePoint Web frontend, plus the deployment of a HTTP handler is cumbersome because it has to be added to each web.config (including each extended Web Application) either manually or by writing a proper custom feature event receiver handling all the web.config modification heavy lifting. Because of those reasons I take HTTP handlers only as last resort ;-) The above approach is working just fine even on a high volume Web site for more than a year now. This is an excellent suggestion. I've created a normal WebControl derivative, which I've inserted directly into the custom master page. Works beautifully, thanks. You can access all sorts of things in SharePoint by typing in a url or by merely changing the querystring. If the list must be hidden always, then change security on the list so that only those with proper permissions can see it. If you really are set on this, you can also implement some form of URL Rewriter on the IIS server hosting SharePoint and block requests for that list, though that can be a bit annoying to maintain across a farm. Hmmm... couple of ideas come to mind, although neither is particularly awesome. 1) Create a custom HTTP handler that detects if a user is browsing to one of the list url's and redirect the user 2) Link a javascript file in your master page that does the same thing (checks the url to see if it contains /Lists/YourList) and redirect the user somewhere else. There may be a more elegant approach, but I'm still drinking my first cup of coffee... The problem is, that the list EXISTS.. so unless you set the permissions where NO ONE can get to it, a user that knows the url can get to it. good luck, Mark It should be pointed out that, without touching the permissions, just because it is hidden or redirected in the UI does not mean it is not accessible through other means. SharePoint designer, web services, object model, etc. will still see it. It's the old 'security through obscurity' discussion. If hiding is all you want, SPList.Hidden and Mark's 2nd option will do it.
common-pile/stackexchange_filtered
Composite ViewModels in a WPF application I came accross the following situation: I have 2 view models and a single view which contains 2 user controls on which the view models will be bound to. The first VM is a Search functionality which returns a list of Persons, and the second VM is a more detailed description of each person. I want to do the following: public CompositeVM { public SearchVM SearchViewModel{get;set;} public DescriptionVM DescriptionViewModel{get;set;} } As I have said, the search view model also incorporates a list of found persons, so I wish that when I select a person the DescriptionVM to be updated accordingly. How can I achieve this type of communication between VMs? Should I set a SelectedPerson property on the SearchVM and pass it to the DescriptionVM when the selected list item changes (pretty high coupling to me)? Is there a more simple approach to this matter? Why you don't add the DescriptionViewModel as a property of SearchVM? Then you still can bind UserControl to it ... {Binding SearchViewModel.DescriptionViewModel} Well I thought of that, but the DescriptionVM is more complex that just viewing some properties: it also has some functionality for editing, creating, etc and I didn't ant this functionality to be interwined with the searching. Also, the searching has more complex functionality as well. I just thought that it would be better (architecturally) that these VMs should be separated and aggregated in a composite VM. Ok, that's a good reason. So do you design same ViewModel for different views?(just curious) It's possible for CompositeVM to subscribe to SearchViewModel's PropertyChanged event and set DescriptionViewModel.SetSelectedPerson(SearchViewModel.SelectedPerson). There is no coupling here between SearchVM and DescriptionVM, since they're not aware of each other. CompositeVM knows them both, and is also who's in charge of their interaction. Ok, I'll take your answer for the maintaining low coupling. Thanks! Alternatively you can use the Mediator-Observer pattern, such as the Messenger class in MVVM Light: http://blog.galasoft.ch/archive/2009/09/27/mvvm-light-toolkit-messenger-v2-beta.aspx The Messenger class is pretty useful, but for my school project it seems like an overhead.. Why not implement your own simpler version? If MVVM itself is not an overkill for your project...
common-pile/stackexchange_filtered
JavaFX: How to add calculated Integer value to TableColumn I have a bill table where I want to list all products which are on the bill. I saved the ProductInBill objects within an ArrayList<ProductInBill> on the bill. When I created a TableView my common approach is to create the JavaFX fields. On the controller class, I have my fields: @FXML public TableColumn<ProductInBill, String> finishedBillProductNameColumn; @FXML public TableColumn<Integer, Integer> finishedBillProductNumberColumn; @FXML public TableColumn<ProductInBill, Integer> finishedBillProductPriceBruttoLabel; @FXML public TableColumn<Integer, Integer> finishedBillProductTotalAmountColumn; @FXML public TableView finishedBillProductTable; Then I am using a setUp() method with the code like: private void setUpFinishedBillProductTable() { finishedBillProductNameColumn.setCellValueFactory(new PropertyValueFactory<ProductInBill, String>("productName")); finishedBillProductPriceBruttoLabel.setCellValueFactory(new PropertyValueFactory<ProductInBill, Integer>("productPrice")); } Also there is an updateBillTable() method to load the necessary ProductInBill objects, save them to an TableList and give it to the table. private void updateFinishedBillProductTable(Bill bill) { LOG.info("Start reading all Products from Bill"); for(ProductInBill product : bill.getProducts()){ finishedBillProductCurrent.add(product); } finishedBillProductTable.getItems().clear(); if(!finishedBillProductCurrent.isEmpty()) { for (ProductInBill p : finishedBillProductCurrent) { finishedBillProductTableList.add(p); } //here i want to calculate some other Integer values based on the ProductInBill values and insert them to the table too. finishedBillProductTable.setItems(finishedBillProductTableList); } } This is all working very good. My problem now is, that I have also a field on my TableView with calculated Integer values which I don't want to save within an object. Take for example the finishedBillProductNumberColumn. I want iterate on my ArrayList, find all products with the same name and populate the number of the same items to the table. How can I do this? I found only solutions where I have to use a value from my object to insert something to my TableView. You just have to write a custom CellValueFactory for those case instead of using premade ones. Using PropertyValueFactory is just an handy short cut to fill cells with members. For your example: finishedBillProductNameColumn.setCellValueFactory(new PropertyValueFactory<ProductInBill, String>("productName")); is just a shorter way to do: finishedBillProductNameColumn.setCellValueFactory( cellData -> { ProductInBill productInBill = cellData.getValue(); return data == null ? null : new SimpleStringProperty(productInBill.getProductName()); }); That being said, i have an 100% preference for the second syntax. Because on the first one if you rename the member, and you forgot to change it there, you won't know there is a mistake until you get there in the application. Plus it allow to display different value than just the members. As a concrete example for your finishedBillProductNumberColumn you could do: First change the definition(the first Generic type is the one received with cellData.getValue(): @FXML public TableColumn<ProductInBill, Integer> finishedBillProductNumberColumn; and then define the CellValueFactory you want like: finishedBillProductNumberColumn.setCellValueFactory( cellData -> { ProductInBill productInBill = cellData.getValue(); if(productionInBill != null){ Long nbProduct = finishedBillProductTable.getItems().stream().filter(product -> product.getProductName().equals(productInBill.getProductName())).count(); return new SimpleIntegerProperty(nbProduct.intValue()).asObject(); } return null; }); Hope it helped!
common-pile/stackexchange_filtered
How to confirm a radio button selection with an alert box So i have this code: <html> <head> <title>Form</title> <script type="text/javascript"> function showConfirmationDialog() { var textbox = document.getElementById('textbox'); var location = document.getElementById('location'); alert('You chosen:'+'\n'+'\n'+'Name: '+textbox.value +'\n'+'Address: ' +location.value+'\n'); } function formfocus() { document.getElementById('textbox').focus(); } window.onload = formfocus; var option; </script> </head> <body> Your name: <input type="text" name="FirstName" id="textbox" <br><br/> Your Address: <input type="text" name="address" id="location" <br></br><br></br> Choose your location: <form name="Radio" id="destination" action=""> Bristol: <input type="radio" name="selection" value="bristol" onClick="option=0"> &nbsp;&nbsp;&nbsp; London: <input type="radio" name="selection" value="london" onClick="option=1"> &nbsp;&nbsp;&nbsp; Birmingham: <input type="radio" name="selection" value="birmingham" onClick="option=2" /> </form> <br></br> Click: <input type="button" value="Submit" onclick="showConfirmationDialog();" /><br></br> </body> </html> ... This code basically represents a form for a user to fill in and at the end select one of three option provided via the radio buttons. What I wanted to find out was that how do I get the selection from one radio button which the user will need to select, displayed within the alert box after they press submit. please clarify what you want to achieve @Zoltan, he wants the user to confirm his/her selection upon submission. @Spartan, make sure you add a DOCTYPE. It looks like you are probably using HTML 4.01 You need to loop through the selection radios to get the checked value: var selection = document.Radio.selection; var selectionResult = ""; for(var i = 0; i < selection.length; i++) { if(selection[i].checked) { selectionResult = selection[i].value; } } alert('You chosen:'+'\n'+'\n'+'Name: '+textbox.value +'\n'+'Address: ' +location.value+'\n' + 'Location: '+selectionResult); Something like this... function getSelRadioValue() for(i = 0; i< document.forms['Radio'].elements['selection'].length ; i++){ if(document.forms['Radio'].elements['selection'][i].checked == true) return document.forms['Radio'].elements['selection'][i].value; } return null; } var selectedRadioValue = getSelRadioValue(); //use this variable in your alert. if(selectedRadioValue == null) alert("please select a destination"); else if(confirm("You have selected " + selectedRadioValue)) //deal with success He'd probably want to use confirm() instead of alert(). sure... I was just answering his question about how to get the value... if he's looking for a confirmation, then you're absolutely right, he should use confirm. I edited my answer with that slight enhancement, thanks for the note. :)
common-pile/stackexchange_filtered
Why do I get reference error for fetch when I do unit tests using Jest? I'm new to unit tests using Jest but basically I have a file client.js looking like this: function add(a, b) { return a + b; } const fetcher = () => { return fetch('http://localhost:3000/').then(res => res.json); } module.exports = {add, fetcher}; The client.test.js is as follows: const client = require('../client'); test('Testing addition', () => { expect(client.add(1, 2)).toBe(3); }); test('Yet another addition', () => { expect(client.add(3, 10)).toBe(13); }); test('Testing a promise', () => { return client.fetcher().then(data => { expect(data).toBe(1824); }) }); When I try to run tests it throws an error ReferenceError: fetch is not defined. How do I fix this? You can't test client-side code on the server. fetch only exists inside a browser environment. Note that it's res => res.json() @ChrisG So what framework should I use for unit tests for client-side? Either: Define a fetch function somewhere (e.g. by loading the node-fetch module that is available on NPM) Use the --experimental-fetch flag when you run Node (and make sure it is version 17.5 or newer @CupOfGreenTea — Not if you run it with Node.js. Curiously I ran into problems out of the box using --experimental-fetch it seems like Jest overwrites the globals and I lost access to fetch() / Response / Request etc - I was able to resolve by injecting them in jest.config.js - globals: { fetch, Response, Request } - feels dirty - but I assume in a month or two someone else will fix it properly! How do we get jest test to use the --experimental-fetch flag? Or better yet, running jest using node 18 where we don't need that flag anymore, jest still throws "ReferenceError: fetch is not defined", but I can execute the same code just fine :(
common-pile/stackexchange_filtered
What's the best CSS property for detecting browser support for selectors I'm writing some Modernizr extensions to detect browser support for things such as :first-child, :last-child in CSS. In order to do so I'm applying a style and then checking to see if teh element has that style. What's the most-reliable CSS property to use as my test style? e.g. color is a bad choice as if you enter in #123abc the browser may convert it to rgb(#,#,#) So I'm looking for a property that Is supported across browsers Won't be mutated to a different format by the browser At the moment I'm using width, which is probably OK, but thought I'd check here anyway. I'm totally in favour of feature detection over browser detection. But as much as it pains me to say it, :first-child and :last-child support has only ever been an issue for IE <=v8, and that's not going to change. So your goal could be achieved with an IE-detection script, for which there are several well-defined solutions. I do agree it would be nicer to do it with feature detection though, but I thought I should point that out. :) Maybe on the desktop this is true, but I'm not sure about mobile (I actually have no idea whether any mobile browsers don't support first/last-child, but this in itself is a good reason to test for it). I'll also be writing test for nth-child and a few other selectors which are more of an unknown generally. I just wrote this http://jsfiddle.net/laustdeleuran/3rEVe/ yesterday, which does exactly what you're talking about - it feature detects support for the :last-child pseudo selector. I'm also using width as my style to check on, and it seems to be working just fine. I've so far tested it with succes in IE6-8 on Windows XP; IE9, Chrome 12, Safari 5, FireFox 4 and Opera 11 on Windows 7 and Opera 11, FireFox 4, Safari 5 and Chrome 12 on Mac. Feel free to use it as it if you want to.
common-pile/stackexchange_filtered
How to compute the size of the allocated memory for a general type I need to work with some databases read with read.table from csv (comma separated values ), and I wish to know how to compute the size of the allocated memory for each type of variable. How to do it ? edit -- in other words : how much memory R allocs for a general data frame read from a .csv file ? This post may be useful to check the memory of allocated objects in an R session. In particular Tony Breyal's modification of Dirk's function. I do not see there how to compute on paper the size of a table that has integers and categorical variables. Sorry, never heard of someone wanting to do that before. I should have misread your question. My question is : if I look with the eye to a cvs file, how can I compute on paper how much memory R allocs ? for integer values, I think the answer of David answers correctly. Have you read ?Memory? It maybe a nice place to start. Computing on paper is usually not as good an idea as actually running object.size. What if your operating system, version of R, or specifics of your variable are different? Yes. As I re/commented, I wanted to say that I wanted to understand it in general, algorithmically. You can get the amount of memory allocated to an object with object.size. For example: x = 1:1000 object.size(x) # 4040 bytes This script might also be helpful- it lets you view or graph the amount of memory used by all of your current objects. In answer to your question of why object.size(4) is 48 bytes, the reason is that there is some overhead in each numeric vector. (In R, the number 4 is not just an integer as in other languages- it is a numeric vector of length 1). But that doesn't hurt performance, because the overhead does not increase with the size of the vector. If you try: > object.size(1:100000) / 100000 4.0004 bytes This shows you that each integer itself requires only 4 bytes (as you expect). Thus, summary: For a numeric vector of length n, the size in bytes is typically 40 + 8 * floor(n / 2). However, on my version of R and OS there is a single slight discontinuity, where it jumps to 168 bytes faster than you would expect (see plot below). Beyond that, the linear relationship holds, even up to a vector of length 10000000. plot(sapply(1:50, function(n) object.size(1:n))) For a categorical variable, you can see a very similar linear trend, though with a bit more overhead (see below). Outside of a few slight discontinuities, the relationship is quite close to 400 + 60 * n. plot(sapply(1:100, function(n) object.size(factor(1:n)))) @alinsoar: Is your question "why does a numeric vector of length 1 take up 48 bytes"? @alinsoar: my latest edit explains why it's 48 bytes. Is there some other reason you find it surprising? Yes. You can confirm this with plot(sapply(1:100000, function(n) object.size(1:n))), which shows a linear plot. @alinsoar: I show how to do the computation for factor variables in my answer. For reasons I explain in my comment above, it is still a better idea to do object.size on your own variables rather than compute on paper. @alinsoar: In any case, you should try both of my plot lines of code on your own machine to make sure this matches your OS and version of R. -- perfect. I did not think to make a plot of memo allocation. great.
common-pile/stackexchange_filtered
lazysizes need to work for only device width. not for device height I have a problem with https://github.com/aFarkas/lazysizes <img class="figure-image lazyload" src="{{ image.src|resizeDynamic(800) }}" srcset="{{ placeholderImage(800, 800 / image.aspect) }}" data-srcset=" {{ image.src|resizeDynamic(1920) }} 1920w, {{ image.src|resizeDynamic(1440) }} 1440w, {{ image.src|resizeDynamic(1320) }} 1320w, {{ image.src|resizeDynamic(1024) }} 1024w, {{ image.src|resizeDynamic(800) }} 800w, {{ image.src|resizeDynamic(600) }} 600w, {{ image.src|resizeDynamic(375) }} 375w" data-sizes="auto" alt="{{ image.alt|e }}"> on browser, above image works for only width. but on mobile, it is considering about the max value of device's width and device's height. for example, iPhoneX have a 375 x 812 demension. but on portrait mode (width 375px), image is pulling for {{ image.src|resizeDynamic(1024) }} 1024w. , not pulling 375px width image. I thought that it is working for max value for real device. also on landspace mode (width 812px), image is pulling for {{ image.src|resizeDynamic(1920) }} 1920w, this is very strange thing. I attached images about my issues. but I want to make this considering about device's width like PC. I was googling for this thing. it recommend me Picture tag like the following <picture> <source data-srcset="assets/imgs/6.jpg" media="(max-width: 500px)" /> <source data-srcset="assets/imgs/7.jpg" media="(max-width: 1024px)" /> <source data-srcset="assets/imgs/9.jpg" /> <img class="lazyload" data-src="assets/imgs/8.jpg" alt="image with artdirection" /> </picture> but I think that using Picture tag seems to not good... If any advice, please let me know thanks :) The iOS browsers behaviour might be correct here - it‘s pulling the bigger / wider images as it has a higher density display (retina) and that for would need an image asset with a bigger resolution (2x and even 3x depending in the iPhone). This is as well comparable to other browsers implementations.
common-pile/stackexchange_filtered
Look up value from array in another array, and then match a second value Google Apps Script Javascript JSON API I'm importing data from my crm Pipedrive into Google sheets using Google Apps Script. This is part of a larger process but I'm at an impasse with this section of the script. I need to return a value by matching two parts of one array to another array. First I pull all deal fields, which returns custom field keys and their id/label pairs. Here's a simplified output example: { "success": true, "data": [ { "id": 12500, "key": "c4ecbe01c34994ede3a50c0f8", "name": "Lead Type", "options": [ { "label": "Expired", "id": 28 }, { "label": "Sale", "id": 29 }, { "label": "Rent", "id": 30 }, { "label": "Other", "id": 31 } ], "mandatory_flag": false } ] } Then I have separate info from a specific deal that includes an id. I need to match the below id 28 to the above array and return the label Expired: var leadType = dealresponse.data["c4ecbe01c34994ede3a50c0f8"]; which returns 28 I don't know what '28' means so that's why I need to match it to the label Expired. The dealFields array is long, maybe 50 or 100 of the above array objects. And there are around 10 custom deal field keys where I will have to return the label base on matching the key and id. I think I have to loop each key and id to return the label. But not sure of the optimum way to do this and save on processing power. I tried: for (var i in dealFieldsresponse) { if (dealFieldsresponse[i].data.key == "c4ecbe01c34994ede3a50c0f8") { for (var j in dealFieldsresponse[j]) { if (dealFieldsresponse[j].id == "28") { Logger.log(dealFieldsresponse[j].label); } } } } It's not working. I'm new at javascript and programming in general so this is my best guess and I appreciate any insights. Edit: here's a bigger chunk of code that I have to work with: // Get deal fields data var dealFieldsurl = URL +'/v1/dealFields?api_token='+ API_TOKEN; var options = { "method": "get", "contentType": "application/json", }; var dealFieldsresponse = UrlFetchApp.fetch(dealFieldsurl, options); dealFieldsresponse = JSON.parse(dealFieldsresponse.getContentText()); // Get deal data var dealurl = URL +'/v1/deals/' + dealId + '?api_token='+ API_TOKEN; var options = { "method": "get", "contentType": "application/json", }; var dealresponse = UrlFetchApp.fetch(dealurl, options); dealresponse = JSON.parse(dealresponse.getContentText()); var propertyAddress = dealresponse.data["9bd1d8c4f07f5795fd8bffb16f3b63c6547d7d3a"]; var leadType = dealresponse.data["c4ecbe01c3494d1be52432f4a3194ede3a50c0f8"]; var dealType = dealresponse.data["a4269fb4730cf7fd1787752be94eacbc4b0de24e"]; var dealSource = dealresponse.data["d76fa2d6f8454a51f7d64d981cd9320877bc2ea0"]; var marketingFor = dealresponse.data["58cb55090b55652b7f89a8b44074682d874c548a"]; var dateListedOnMarket = dealresponse.data["aa49c7b95a7d151bec4c2d936f6ab40d0caea43c"]; var dateTakenOffMarket = dealresponse.data["660c1250b0a641a10ff9121c2df124ff89c13052"]; var askingPrice = dealresponse.data["1de94dbf589fda7a3a3248662cd24f03d512a961"]; And the dealFieldsresponse variable stores an array with many objects containing arrays. Here are two primary objects, as you can see each has a key and then options. I need to match the key and then find the id within options for each key { "id": 12500, "key": "c4ecbe01c3494d1be52432f4a3194ede3a50c0f8", "name": "Lead Type", "order_nr": 64, "field_type": "set", "add_time": "2020-08-20 19:33:22", "update_time": "2020-08-20 19:33:22", "last_updated_by_user_id": 11678191, "active_flag": true, "edit_flag": true, "index_visible_flag": true, "details_visible_flag": true, "add_visible_flag": true, "important_flag": true, "bulk_edit_allowed": true, "searchable_flag": false, "filtering_allowed": true, "sortable_flag": true, "options": [ { "label": "Expired", "id": 28 }, { "label": "Sale", "id": 29 }, { "label": "Rent", "id": 30 }, { "label": "Other", "id": 31 } ], "mandatory_flag": false }, { "id": 12502, "key": "a4269fb4730cf7fd1787752be94eacbc4b0de24e", "name": "Deal Type", "order_nr": 65, "field_type": "set", "add_time": "2020-08-20 19:57:12", "update_time": "2020-08-20 19:57:12", "last_updated_by_user_id": 11678191, "active_flag": true, "edit_flag": true, "index_visible_flag": true, "details_visible_flag": true, "add_visible_flag": true, "important_flag": true, "bulk_edit_allowed": true, "searchable_flag": false, "filtering_allowed": true, "sortable_flag": true, "options": [ { "label": "Lease", "id": 37 }, { "label": "Financing", "id": 38 }, { "label": "Assign", "id": 39 }, { "label": "ST", "id": 40 }, { "label": "Other (see notes)", "id": 41 } ], "mandatory_flag": false }, Edit 2: how do I return the labels for multiple ids? const obj = { "a4269fb4730cf7fd1787752be94eacbc4b0de24e": {id: 37,38}, "58cb55090b55652b7f89a8b44074682d874c548a": {id: 44,45}, "2ec54cce0d091b69b1fd1a245c7aad02b57cadb8": {id: 126}, "fab84c732295022ecd7bdf58892a62cb4d8ecf24": {id: 50,52,54}, }; For example, I'd want the first to return red, blue as a string, and the second to return green, orange as a string. Assuming the labels that match the ids are colors. The third one only has one id, but the fourth one has three. How do I account for this? And I'd like my output to be some kind of array where I can then say search key a4269fb4730cf7fd1787752be94eacbc4b0de24e and return value red, blue as a string Although I'm not sure whether I could correctly understand about your goal, I proposed a modified script as an answer. Could you please confirm it? If that was not the result you expect, I apologize. At that time, can you provide the result value you expect? By this, I would like to modify it. Thank you for replying. I'm surprised that your question was updated. Unfortunately, I cannot understand what you want to do from your updated question. But I could understand that my answer was not suitable for your updated question. So I have to delete my answer. Because I don't want to confuse other users. This is due to my poor English skill. I deeply apologize for this. By the way, can I ask you about what you want to do for your updated question? I think your answer is good and it worked for one instance - in other words, one key searching. My question is, is there a way to scale it bigger because there are multiple keys (each with an id needed to return a label) to search? For example, say I have key c4ecbe01c3494d1be52432f4a3194ede3a50c0f8 and id 28 to search as well as key a4269fb4730cf7fd1787752be94eacbc4b0de24e and id 37? The id 37 is only output from the above so I can't set that in advanced but I can make it a variable I suppose. The return I'm looking for are the labels Expired and Lease Thank you for replying. In your updated question, I cannot understand whether key is required to be corresponding to id. For example, when the key is c4ecbe01c34994ede3a50c0f8, you want to retrieve the value of lavel of the id 28. When the key is other value, you want to retrieve the value of lavel of the id 28? You want to use the same id? I noticed that your comment has been updated. By this, I could understand about your goal. Can you give me a time to update my answer? Absolutely, thanks for what you've explain to me so far Ok so I know the key in advanced - it is a fixed value. I then do a get request, and using the key c4ecbe01c34994ede3a50c0f8, it returns an id of let's say 28. Then what I need to do is take the key and the id and use them return real value I want, which is the label, which is Expired in this example Although I'm not sure whether I could correctly understand about your goal, I proposed a modified script as an answer. Could you please confirm it? If that was not the result you expect, I apologize. At that time, can you provide the result value you expect? By this, I would like to modify it. I believe your goal as follows. You want to retrieve the value of label using key and id from the JSON object in your question using Google Apps Script. As a sample situation, you want to retrieve the value of "label": "Expired" using "key": "c4ecbe01c34994ede3a50c0f8" and "id": 28. The JSON object has the arrays of data and options. Both arrays have the several elements. Modification points: If dealFieldsresponse is the JSON object in your question, dealFieldsresponse.data and dealFieldsresponse.data[].options are 1 dimensional array. When you want to retrieve the value of key and id, it is required to loop those arrays. When above points are reflected to your script, it becomes as follows. Modified script: const searchKey = "c4ecbe01c34994ede3a50c0f8"; // Please set the value of key. const searchId = 28; // Please set the value of id. const dealFieldsresponse = { "success": true, "data": [ { "id": 12500, "key": "c4ecbe01c34994ede3a50c0f8", "name": "Lead Type", "options": [ { "label": "Expired", "id": 28 }, { "label": "FSBO", "id": 29 }, { "label": "FRBO", "id": 30 }, { "label": "Other", "id": 31 } ], "mandatory_flag": false } ] }; const data = dealFieldsresponse.data; for (let i = 0; i < data.length; i++) { if (data[i].key == searchKey) { const options = data[i].options; for (let j = 0; j < options.length; j++) { if (options[j].id.toString() == searchId.toString()) { // Logger.log(options[j].label); console.log(options[j].label); } } } } Other sample: As other sample script, how about the following script? In this sample, the result values are put in an array. const searchKey = "c4ecbe01c34994ede3a50c0f8"; // Please set the value of key. const searchId = 28; // Please set the value of id. const dealFieldsresponse = { "success": true, "data": [ { "id": 12500, "key": "c4ecbe01c34994ede3a50c0f8", "name": "Lead Type", "options": [ { "label": "Expired", "id": 28 }, { "label": "FSBO", "id": 29 }, { "label": "FRBO", "id": 30 }, { "label": "Other", "id": 31 } ], "mandatory_flag": false } ] }; const res = dealFieldsresponse.data.reduce((ar, {key, options}) => { if (key == searchKey) { options.forEach(({id, label}) => { if (id == searchId) ar.push(label); }); } return ar; }, []); console.log(res) Added: When you want to retrieve the multiple values using the multiple key and id, how about the following sample script? In this sample script, the key c4ecbe01c34994ede3a50c0f8 and id 28 and the key a4269fb4730cf7fd1787752be94eacbc4b0de24e and id 37 are searched and the values of label are retrieved. const obj = { "c4ecbe01c34994ede3a50c0f8": {id: 28}, "a4269fb4730cf7fd1787752be94eacbc4b0de24e": {id: 37} }; // Please set the key and id you want to search. const dealFieldsresponse = { "success": true, "data": [ { "id": 12500, "key": "c4ecbe01c34994ede3a50c0f8", "name": "Lead Type", "options": [ { "label": "Expired", "id": 28 }, { "label": "FSBO", "id": 29 }, { "label": "FRBO", "id": 30 }, { "label": "Other", "id": 31 } ], "mandatory_flag": false } ] }; dealFieldsresponse.data.forEach(({key, options}) => { if (obj[key]) { options.forEach(({id, label}) => { if (id == obj[key].id) obj[key].label = label; }); } }); console.log(obj) Result: When above script is run, the following result is obtained. { "c4ecbe01c34994ede3a50c0f8":{"id":28,"label":"Expired"}, "a4269fb4730cf7fd1787752be94eacbc4b0de24e":{"id":37} } At above sample JSON object, the label of the key c4ecbe01c34994ede3a50c0f8 and id 28 is retrieved. Thanks for your reply, you've understood what I want to do. This makes sense what you're saying but I actually need to incorporate this into a larger script. First I do a GET request for several of these fields. Then the result is the id and then I need to feed that into the search to loop and find the label. I've edited the above code to show you what my script looks like @823g4n8901 Thank you for replying. I'm surprised that your question was updated. Unfortunately, I cannot understand what you want to do from your updated question. But I could understand that my answer was not suitable for your updated question. So I have to delete my answer. Because I don't want to confuse other users. This is due to my poor English skill. I deeply apologize for this. By the way, can I ask you about what you want to do for your updated question? Some of my keys contain multiple ids - I would like to look up the return the label for each id and return all the labels as a string. I've edited the above @823g4n8901 About your updated question, I noticed that you had already posted it as new question, and an answer has already been posted. In this case, I would like to respect the existing answer. By the way, in the current stage, there are 2 same questions in your questions. So please remove the additional question of Edit 2: how do I return the labels for multiple ids?. Because when your initial question is changed, other users who see your question are confused. By the way, {id: 50,52,54} is not correct for JSON object. Please be careful this.
common-pile/stackexchange_filtered
Can we find upper bound for loss functions? Is it easy to find upper bound for loss functions like 0-1 loss and hinge loss ?!. I always find this sentence, which is "hinge loss is an upper bound of 0-1 loss", Can we compute the upper bound of convex loss functions?!. Does convex loss function have upper bound?! if yes how to find it ?! Thanks It is not entirely clear what your question entails. Could you be more explicit? I always find this sentence, which is "hinge loss is an upper bound of 0-1 loss". Can we compute the upper bound of convex loss functions?!. Does convex loss function have upper bound?! if yes how to find it ?! What do you think about my answer? If it is helpful and clear, you may accept it by clicking on the tick mark to the left. Otherwise, you may ask for further clarification. This is how Cross Validated works. One loss function can be an upper bound of another loss function. E.g. $|e|$ is an upper bound of $\sqrt{|e|}$ in the interval $(-\infty,-1]\cup [1,\infty)$ but the opposite is the case in the interval $[-1,1]$. At the same time, most of the loss functions are not bound by a constant (as opposed to another function). I don't think , all surrogate loss functions are unbounded. How can 0-1 loss become upper bound ?! @missRan, in your question, you talk about a bound for 0-1 loss, not that 0-1 loss itself can be a bound. This is an important distinction. Actually, hinge loss is tight upper bound of 0-1 loss, but it's not clear how this can happen. Could you please clarify?!. @missRan, could you give a reference for the claim?
common-pile/stackexchange_filtered
Changing UK visa appointment date I am applying for a UK standard visitor visa from Egypt through TLScontact Cairo Visa Application Centre. I booked my appointment for 28 June 2018. I have some personal circumstances that will prevent me from attending on this date. I have contacted UK Visas & Immigratio,n asking if I can re-schedule my appointment date, but they replied that “you cannot re-schedule an appointment once you have missed your appointment.” I haven't missed it; it's still 2 days away. I logged into my account on Visa4UK, clicked on 'View Appointment' followed by 'Update Appointment’ and found that I can re-schedule my appointment! So I changed my appointment date to 5 July 2018 and printed a new booking confirmation with the new appointment date. Does this means that I have successfully changed the appointment date? I am afraid that on 5 July when I go to my new appointment date, I will find that my appointment was on 28 June and I have missed it. I don't understand. You logged in, the system said you can change your appointment, you changed your appointment, and now you want to US to tell you if you changed your appointment? VTC: OP has changed the appointment and received a confirmation and a new date; Does this means that I have successfully changed the appointment date? is confusing (and impossible for anyone here to answer).
common-pile/stackexchange_filtered
Launching Activity from PendingIntent singleTop not working I have a PendingIntent set as the contentIntent inside of a foreground notification and this PendingIntent should launch the last running activity with singleTop so that another instance of the activity is not created. The issue I am having is that when Don't keep Activities is set in the developer options a duplicate activity is created at the top of the stack (A,B,C,C) where I would like (A,B,C) where C is the last running activity. I know it is duplicated because when I use the back button I see two identical activities before reaching my previous activities. How are you determining that there are multiple instances as you say? It would help if you discuss why you want to do this. Launch modes are much more complicated then they appear at first and have all manner of caveats and quirky behavior. You are better off using the default launch mode if at all possible. Have you read what Don't keep activities is? https://stackoverflow.com/questions/22400859/dont-keep-activities-what-is-it-for
common-pile/stackexchange_filtered
Run commands in Docker during run process I want to be able to run a docker run... command for my custom Ubuntu command where the docker will run two commands as if they were typed once the docker begins running. I have my docker mounted to a local folder and have a custom code within the mounted folder, I want running the docker to also run cd Project and ./a.out within the docker but I am not sure how to do that in one long command. I have tried docker run --mount type=bind,source="/home/ec2-user/environment/Project",target="Project" myubuntu cd Project && ./a.out but I get an OCI runtime create failed. I have also tried docker run --mount type=bind,source="/home/ec2-user/environment/Project",target="Project" myubuntu -c 'cd Project && ./a.out' but get the same error. Ultimately, it would be nice to have my mounted directory, cd Project, ./a.out, and exit command in my Dockerfile so that the docker container opens, runs the compiled code within a.out, and then exits with a simple docker run myubuntu command but I know that mounting within the Dockerfile requires the image be rebuilt every time that local folder changes. So that leaves me with being able to open the docker container, run my two commands, and exit the container with 1 docker run command line. Your target should be an absolute path. Did you mean /Project? Also try ... myubuntu bash -c 'cd /Project && ./a.out. You need to provide executable as pointed out by Mark below. Is ./a.out a compiled binary; don't you have to rebuild that every time your local content changes too? What does your current Dockerfile look like? (Everything after the image name replaces Dockerfile CMD, with identical semantics.) I think you want to start a shell that runs your two commands: docker run --mount ... myubuntu /bin/bash -c 'cd somewhere && do something' Thank you! I was able to get that working and it has saved me so much
common-pile/stackexchange_filtered
Amplifying current for PWM load My load requires a PWM wave input with at least 5 mA and 5-15 V but my controller can only provide up to 2 mA. My first thought was to use two NPN transistors like this. I used two so that the PWM input was not inverted. But the voltage and current provided to my load would depend on the resistance of my load. I have also thought about using a buffer op amp or transistor. The problem with an op amp would probably the slew rate and I do not have access to any. I am guessing the transistor buffer would have to be set up like above, but again would not the resistance of the load impact the voltage and current delivered? I think I am missing something conceptually important because I do not think it should be this hard to design something like this. Do you want to deliver a fixed 5 mA current to your load, and let the load set the voltage (typical of a LED load), or do you want to deliver a fixed voltage (you appear to be using 10 V in your simulations), and let the load draw the current it likes, up to 5 mA (typical for most other types of load) ? Note that you cannot set both voltage and current. I need at least 5v (5-15) and 5mA So you need a 15 V output with a fixed current limit of 5 mA maximum? This would result in 5 V at 1 kohm load, 10 V at 2 kohm load and 15 V at 3 kohm load. I do not know what the resistance of the load is. The load is a device that is controlled by PWM. Also I need 5mA minimum, sorry for being unclear. You can use a two transistor buffer so the output is sink and also supplied with transitors (not sinking with resistor like your second schematic). The Vcc should be the same or little higher than Vsig otherwise the upper transistor will saturate and make slow falling output edge. There is no need a base resistors. if I only had 10v could I add base resistors to make sure that the transistors work? What is your Vsig amplitude and what Vcc do you have available? This simple BJT circuit will work in the low kHz range and can deliver up to 100 mA, however there is no overload protection. At higher frequencies the values of R3 and R4 need to be lower. The input accepts typical MCU output levels. There is no active pull down at the output, so it cannot be used to drive capacitive loads like MOSFET gates.
common-pile/stackexchange_filtered
SQL - How to convert columns to rows I have the following SQL script: DECLARE @Month AS INT = 5 --Set the MONTH for which you want to generate the Calendar. DECLARE @Year AS INT = 2015 --Set the YEAR for which you want to generate the Calendar. DECLARE @StartDate AS DATETIME = CONVERT(VARCHAR,@Year) + RIGHT('0' + CONVERT(VARCHAR,@Month),2) + '01' DECLARE @EndDate AS DATETIME = DATEADD(DAY,-1,DATEADD(MONTH,1,@StartDate)); SELECT SUM(CASE WHEN DATEPART(DW, DATEADD(DD,number,@StartDate)) = 1 THEN DATEPART(DAY, DATEADD(DD,NUMBER,@StartDate)) END) AS Sunday, SUM(CASE WHEN DATEPART(DW, DATEADD(DD,number,@StartDate)) = 2 THEN DATEPART(DAY, DATEADD(DD,NUMBER,@StartDate)) END) AS Monday, SUM(CASE WHEN DATEPART(DW, DATEADD(DD,number,@StartDate)) = 3 THEN DATEPART(DAY, DATEADD(DD,NUMBER,@StartDate)) END) AS Tuesday, SUM(CASE WHEN DATEPART(DW, DATEADD(DD,number,@StartDate)) = 4 THEN DATEPART(DAY, DATEADD(DD,NUMBER,@StartDate)) END) AS Wednesday, SUM(CASE WHEN DATEPART(DW, DATEADD(DD,number,@StartDate)) = 5 THEN DATEPART(DAY, DATEADD(DD,NUMBER,@StartDate)) END) AS Thursday, SUM(CASE WHEN DATEPART(DW, DATEADD(DD,number,@StartDate)) = 6 THEN DATEPART(DAY, DATEADD(DD,NUMBER,@StartDate)) END) AS Friday, SUM(CASE WHEN DATEPART(DW, DATEADD(DD,number,@StartDate)) = 7 THEN DATEPART(DAY, DATEADD(DD,NUMBER,@StartDate)) END) AS Saturday FROM master.dbo.spt_values v WHERE DATEADD(DD,number,@StartDate) BETWEEN @StartDate AND DATEADD(DAY,-1,DATEADD(MONTH,1,@StartDate)) AND v.type = 'P' GROUP BY DATEPART(WEEK, DATEADD(DD,number,@StartDate)) This script generates this table: But I would like to get a list like this: Any clue? I can maybe understand the sequential rows, but what is the use case for the ones with NULL? I need the null ones because Im going to build a calendar view on a report designer. possible duplicate of SQL - How to get a complete month calendar table In what way is this different to your other question? I have marked as duplicate Its different approach. If you're trying to create output in a specific format it is usually better to use a report generator; it is very awkward to output data in specific formats via SQL. @DourHighArch: I disagree - and the technique used to produce formats such as this is a standard practice for folding a pivoted report that has a multitude of uses besides simple formatting. Try this: DECLARE @Month AS INT = 5 --Set the MONTH for which you want to generate the Calendar. DECLARE @Year AS INT = 2015 --Set the YEAR for which you want to generate the Calendar. DECLARE @StartDate AS DATETIME = CONVERT(VARCHAR,@Year) + RIGHT('0' + CONVERT(VARCHAR,@Month),2) + '01' DECLARE @EndDate AS DATETIME = DATEADD(DAY,-1,DATEADD(MONTH,1,@StartDate)); with m1 as ( SELECT SUM(CASE WHEN DATEPART(DW, DATEADD(DD,number,@StartDate)) = 1 THEN DATEPART(DAY, DATEADD(DD,NUMBER,@StartDate)) END) AS Sunday ,SUM(CASE WHEN DATEPART(DW, DATEADD(DD,number,@StartDate)) = 2 THEN DATEPART(DAY, DATEADD(DD,NUMBER,@StartDate)) END) AS Monday ,SUM(CASE WHEN DATEPART(DW, DATEADD(DD,number,@StartDate)) = 3 THEN DATEPART(DAY, DATEADD(DD,NUMBER,@StartDate)) END) AS Tuesday ,SUM(CASE WHEN DATEPART(DW, DATEADD(DD,number,@StartDate)) = 4 THEN DATEPART(DAY, DATEADD(DD,NUMBER,@StartDate)) END) AS Wednesday ,SUM(CASE WHEN DATEPART(DW, DATEADD(DD,number,@StartDate)) = 5 THEN DATEPART(DAY, DATEADD(DD,NUMBER,@StartDate)) END) AS Thursday ,SUM(CASE WHEN DATEPART(DW, DATEADD(DD,number,@StartDate)) = 6 THEN DATEPART(DAY, DATEADD(DD,NUMBER,@StartDate)) END) AS Friday ,SUM(CASE WHEN DATEPART(DW, DATEADD(DD,number,@StartDate)) = 7 THEN DATEPART(DAY, DATEADD(DD,NUMBER,@StartDate)) END) AS Saturday FROM master.dbo.spt_values v WHERE DATEADD(DD,number,@StartDate) BETWEEN @StartDate AND DATEADD(DAY,-1,DATEADD(MONTH,1,@StartDate)) AND v.type = 'P' GROUP BY DATEPART(WEEK, DATEADD(DD,number,@StartDate)) ) select --m.RowNo, [WeekDay] = d.[WeekDay] ,[Date] = d.[Date] ,[Month] = datename(month,@StartDate) ,[Year] = @Year from ( select row_number() over (order by Sunday) as RowNo, * from m1 )m cross apply (values (0,'Sunday', isnull(cast(Sunday as varchar(2)),' ')) ,(1,'Monday', isnull(cast(Monday as varchar(2)),' ')) ,(2,'Tuesday', isnull(cast(Tuesday as varchar(2)),' ')) ,(3,'Wednesday', isnull(cast(Wednesday as varchar(2)),' ')) ,(4,'Thursday', isnull(cast(Thursday as varchar(2)),' ')) ,(5,'Friday', isnull(cast(Friday as varchar(2)),' ')) ,(6,'Saturday', isnull(cast(Saturday as varchar(2)),' ')) ) d(DayNo, [WeekDay], [Date]) order by m.RowNo, d.DayNo ; which yields as desired: WeekDay Date Month Year --------- ---- ------------------------------ ----------- Sunday May 2015 Monday May 2015 Tuesday May 2015 Wednesday May 2015 Thursday May 2015 Friday 1 May 2015 Saturday 2 May 2015 Sunday 3 May 2015 Monday 4 May 2015 Tuesday 5 May 2015 Wednesday 6 May 2015 Thursday 7 May 2015 Friday 8 May 2015 Saturday 9 May 2015 Sunday 10 May 2015 Monday 11 May 2015 Tuesday 12 May 2015 Wednesday 13 May 2015 Thursday 14 May 2015 Friday 15 May 2015 Saturday 16 May 2015 Sunday 17 May 2015 Monday 18 May 2015 Tuesday 19 May 2015 Wednesday 20 May 2015 Thursday 21 May 2015 Friday 22 May 2015 Saturday 23 May 2015 Sunday 24 May 2015 Monday 25 May 2015 Tuesday 26 May 2015 Wednesday 27 May 2015 Thursday 28 May 2015 Friday 29 May 2015 Saturday 30 May 2015 Sunday 31 May 2015 Monday May 2015 Tuesday May 2015 Wednesday May 2015 Thursday May 2015 Friday May 2015 Saturday May 2015 Here is a SQL Fiddle that generates arbitrary sequences of dates in the format you want. I leave the UNION ALL of the NULL results as an exercise for the reader. http://sqlfiddle.com/#!3/9eecb7/275 Here is another version: DECLARE @d DATE = '20150501'; WITH m AS(SELECT 1 AS d UNION ALL SELECT d+1 FROM m WHERE d < datediff(d, @d, dateadd(m, 1, @d))), dt AS(SELECT YEAR(@d) y, DATENAME(m, @d) m, d, DATENAME(dw, DATEADD(dd, d-1, @d)) wd FROM m ), wk AS (SELECT * FROM (VALUES (1, 'Monday'), (2, 'Tuesday'), (3, 'Wednesday'), (4, 'Thursday'), (5, 'Friday'), (6, 'Saturday'), (7, 'Sunday')) w(d, n)) SELECT 1 o, y, m, d, wd FROM dt UNION ALL SELECT 0, YEAR(@d), DATENAME(m, @d), NULL, w.n FROM wk w WHERE d < (SELECT d FROM wk WHERE n = (SELECT TOP 1 wd FROM dt ORDER BY d)) UNION ALL SELECT 2, YEAR(@d), DATENAME(m, @d), NULL, w.n FROM wk w WHERE d > (SELECT d FROM wk WHERE n = (SELECT TOP 1 wd FROM dt ORDER BY d DESC)) ORDER BY o , d Output: o y m d wd 0 2015 May NULL Monday 0 2015 May NULL Tuesday 0 2015 May NULL Wednesday 0 2015 May NULL Thursday 1 2015 May 1 Friday 1 2015 May 2 Saturday 1 2015 May 3 Sunday 1 2015 May 4 Monday 1 2015 May 5 Tuesday 1 2015 May 6 Wednesday 1 2015 May 7 Thursday 1 2015 May 8 Friday 1 2015 May 9 Saturday 1 2015 May 10 Sunday 1 2015 May 11 Monday 1 2015 May 12 Tuesday 1 2015 May 13 Wednesday 1 2015 May 14 Thursday 1 2015 May 15 Friday 1 2015 May 16 Saturday 1 2015 May 17 Sunday 1 2015 May 18 Monday 1 2015 May 19 Tuesday 1 2015 May 20 Wednesday 1 2015 May 21 Thursday 1 2015 May 22 Friday 1 2015 May 23 Saturday 1 2015 May 24 Sunday 1 2015 May 25 Monday 1 2015 May 26 Tuesday 1 2015 May 27 Wednesday 1 2015 May 28 Thursday 1 2015 May 29 Friday 1 2015 May 30 Saturday 1 2015 May 31 Sunday
common-pile/stackexchange_filtered
make subdomain have a namespace as root? Would it be possible to have a namespace to be the root for a subdomain in rails 3? Currently my routes are: namespace :mobile do resources :home resources :profiles root :to => "/mobile/home#index" end constraints subdomain: 'm' do root :to => 'mobile/home#index' resources :home resources :profile resources :messages root :to => 'mobile/home#index' end You can but the namespace inside a subdomain constraint if that's what you're asking constraints subdomain: 'm' do namespace :mobile do resources :home resources :profiles end resources :messages root :to => 'mobile/home#index' end Or there's this answer here: From Namespace to Subdomain? which advocates this approach: constraints :subdomain => "mobile" do scope :module => "mobile", :as => "mobile" do resources :profiles resources :home end end
common-pile/stackexchange_filtered
Unable to install R package When I tried to install the package coxphf, the following error appeared. Please let me know how to solve this: install.packages("coxphf") > Installing package into ‘C:/Users/User/R/win-library/3.4’ > (as ‘lib’ is unspecified) > trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.4/coxphf_1.12.zip' Warning in install.packages : cannot open URL 'https://cran.rstudio.com/bin/windows/contrib/3.4/coxphf_1.12.zip': HTTP status was '404 Not Found' Error in download.file(url, destfile, method, mode = "wb", ...) : cannot open URL 'https://cran.rstudio.com/bin/windows/contrib/3.4/coxphf_1.12.zip' Warning in install.packages : download of package ‘coxphf’ failed Error is understandable. All the links you have provided returns 404 errors. If @Usernamenotfound 's answer below solved your problem, please mark it as the correct answer :) You might also upvote it. It was very nice of him/her to dig around and find a working link to the package for you. Looks like the package isn't available on CRAN at that address. After digging around, I found the package here: https://cran.rstudio.com/bin/windows/contrib/3.4/coxphf_1.13.zip Download it and follow instructions here: http://stat.columbia.edu/~gelman/bugsR/alternate_install.html It's not expected behavior though, I'm not sure what's causing it, but this workaround will do fine for now Thank you for your rapid reply. I wonder there is some relation between coxphf revised only March 3. 2018. I can download it, and put download file into R/library/ . It goes well. Thank you very much!!
common-pile/stackexchange_filtered
Update using select query with multiple Rows in Oracle Can any one please help me to solve this issue Table Name:RW_LN LN_ID RE_LN_ID RE_PR_ID LN001 RN001 RN002 LN002 RN002 RN003 LN003 RN003 RN001 LN004 RN001 RN002 MY Update Query is: update table RW_LN set RE_LN_ID=( select LN_ID from RW_LN as n1,RW_LN as n2 where n1.RE_LN_ID = n2.RE_PR_ID) MY Expected Result is: LN_ID RE_LN_ID LN001 LN003 LN002 LN004 LN003 LN002 LN004 LN003 This above query shows error as SUB QUERY RETURNS MULTIPLE ROWS.Can any one provide the solution for this, I am Beginner in Oracle 9i.So Stuck in the logic please show what result you want after your update, cause your query doesn't help much. hI pLEASE REFER MY EXPECTED RESULT FORMAT,THANKS so the problem is : LN002 has RE_LN_ID : RN002, which can be related to RE_PR_ID from LN001 or LN004. Why do you choose LN004 (this is usefull to build the query) @Sajini: The edits you made to your question made it completely meaningless. Don't do that. Just guessing, but possibly this is what you want. update RW_LN n1 set RE_LN_ID=( select n2.LN_ID from RW_LN n2 where n1.RE_LN_ID = n2.RE_PR_ID) where exists ( select null from RW_LN n2 where n1.RE_LN_ID = n2.RE_PR_ID and n2.ln_id is not null) At the moment there is no correlation between the rows you are updating and the value being returned in the subquery. The query reads as follows: For every row in RW_LN change the value of RE_LN_ID to be: the value of LN_ID in a row in RW_LN for which: the RE_PR_ID equals the original tables value of RE_LN_ID IF there exists at least one row in RW_LN for which: RE_PR_ID is the same as RE_LN_ID in the original table AND LN_ID is not null If you want to take the "biggest" corresponding LN_ID, you could do update RW_LN r1 set r1.RE_LN_ID = (select MAX(LN_ID) FROM RW_LN r2 where r1.RE_LN_ID = r2.RE_PR_ID); see SqlFiddle But you should explain why you choose (as new RE_LN_ID) LN004 instead of LN001 for LN_ID LN002 (cause you could choose both) you can try to solve this with a distinct update table RW_LN set RE_LN_ID=( select distinct LN_ID from RW_LN as n1,RW_LN as n2 where n1.RE_LN_ID = n2.RE_PR_ID) if that still returns multiple rows, it means you are missing a join somewhere along the way or potentially have a bad schema that needs to use primary keys.
common-pile/stackexchange_filtered
php - array - Illegal string offset I am trying to display single value from array of values. If I use print_r($arr) it shows this values { "a": 14, "b": 3, "c": 61200, "d": [ "2014-04-22 12:00:06", "2014-04-23 12:00:06", "2014-04-24 12:00:06" ] } But when I tried to use echo $arr->a and $arr['a']. It shows illegal string offset 'a'. How to get single value from array of values? decode it to an array first? looks like json so need decode first with json_decode() $d = '{"a":14,"b":3,"c":61200,"d":["2014-04-22 12:00:06","2014-04-23 12:00:06","2014-04-24 12:00:06"]}'; $j = json_decode($d); echo '<pre>'; print_r($j); echo $j->a; Decode from JSON: $v = json_decode('{ "a": 14, "b": 3, "c": 61200, "d": [ "2014-04-22 12:00:06", "2014-04-23 12:00:06", "2014-04-24 12:00:06" ] }'); echo $v->a; The input looks like JSON - try the following to parse the JSON data: $json_string = '{ "a": 14, "b": 3, "c": 61200, "d": [ "2014-04-22 12:00:06", "2014-04-23 12:00:06", "2014-04-24 12:00:06" ] }'; $vals = json_decode($json_string); echo $vals->a; More information would be useful. What version of PHP are using? Are you using a web engine (Apache, Nginx, etc) or just command line? Correct me if I'm wrong but I am assuming your using json_decode and making an it an object. $obj = json_decode('{"a":14,"b":3,"c":61200,"d":["2014-04-22 12:00:06","2014-04-23 12:00:06","2014-04-24 12:00:06"]}'); echo "Result: " . $obj->a; Result: 14 This worked just fine in PHP Versions 5.3, 5.4, 5.5 Try this $arr = json_decode($arr); echo $arr->a
common-pile/stackexchange_filtered
How to change text in another div by clicking on different icons I'm mainly an inbound marketer, but I'm good at HTML and CSS. My knowledge doesn't go beyond these two. I'm currently building a homepage for my business. I'm stuck at this point. I have the main homepage with six icons which represent a different benefit. I want a separate div placed below, which will respond to the icons being clicked by changing text. The best example of a website doing this is Kiss Metrics on their Homepage. I do not know JS or jQuery, is there any way this can be done using CSS? What does "I'm not a Javascript or JQuery ready." mean? Does it mean you don't want to use JavaScript, and only use CSS? This can't be done with CSS only. I don't think you can do this just with CSS. You can use CSS to make changes to the element that you click on, but you need Javascript to have it affect other elements. It means I don't know Javascript or JQuery yet. I don't mind using Javascript to this action but I would be out of my comfort zone The javascript can be as simple as one line, so don't worry about that. start by writing your html and css. write all your different text's in a separate div each, display: hidden them all, then we'll shou you how to swap which one is display when a button is clicked. If it can't be done using Javascript is there a template for the code on Javascript? How to hide div by onclick using javascript?. It IS (partly) possible to achieve using css only. See my answer below. Hi Roy and Bennet_an http://jsfiddle.net/HedpA/20/. I have done a rough version of what I may use. What would be the next steps to get things to work like the kiss metrics site you can do this with jQuery: $("#imgDiv1").click(function () { $("#textDiv2", "#textDiv3", "#textDiv4", "#textDiv5", "#textDiv6").hide(); $("#textDiv1").show(); }); code explanation: for each image div you assign a click function to hide all other textDivs and show desired div. hi Henser I have a small script $('#icon-slideshow').find('li a').click(function (e) { e.preventDefault(); // prevent usual hyperlink click behavior (changing location) // hide all but the clicked one $('#icon-text').children('div').hide(); // find div to show var div = (this.href.match(/#(.+)/)[1]); $('#' + div).show(); }); $('#txt1').show(); it works on jfiddle but doesn't work on the brwser Actually this IS possible using CSS3 only, thanks to :target - you can apply different styles for targeted elements onclick. Live jsFiddle demo html: <div id="icons"> <a href="#txt1">ICON1</a> <a href="#txt2">ICON2</a> <a href="#txt3">ICON3</a> </div> <div id="text"> <span id="txt1">Benefit 1</span> <span id="txt2">Benefit 2</span> <span id="txt3">Benefit 3</span> </div> CSS: #text span { display:none; } #text span:target { display:block; } Please note: The text will disappear as soon as an element outside of #icons is clicked. It's really recommended doing this kind of tasks using jQuery. It's really easy, try it. Thanks Roy. I tried using the #links in my browser but they don'y seem to work with the file It works on JFiddle but on normal browser Let me be clearer. How am I supposed to make the link "#text1", "#text2" links work, so that the text responds I created a jfiddle here but it doesn't seem to work http://jsfiddle.net/HedpA/20/ how do i get the text to respond and how would javascript work? Remove the pound characters from your ids - e.g instead of Ah Thank You. I just did that, my lack of attention. Now that is done I notice that the link dragging the page down toward the . How can javscript or jquery be used improve it to make it similar to kiss metrics? you can go with something like henser's answer. But there are more efficient solutions, research further in stackoverflow or google. Without JavaScript - no. With JavaScript you may use document.getElementById('elementId').style.display='none' to make an element disappear, and document.getElementById('elementId').style.display='block' to make it appear. jQuery would be a better solution anyway. Although I don't have an extensive experience of javascript yet, I must say that this will be solely accomplished by using javascript. I'm a web developer student and speaking of experience, HTML & CSS really just focused more on structuring/styling.
common-pile/stackexchange_filtered
Target only one element with Angular I have a little problem with Angular, but I really don't find any solution. I have a ngRepeat with several elements. One of them, a simple button, had to change color on click. But if I click on it, other buttons change color too. How can I target only one ? In my Controller : $scope.changeClass = function(){ var x = angular.element(this); $scope.class = "icon-fav"; if ($scope.class === "icon-fav"){ $scope.class = "icon-fav-clicked"; } else{ $scope.class = "icon-fav"; } }; HTML : <button ng-class="class" class="actions-icon animated bounceInUp icon-fav" ng-click="changeClass();tagLike(post)" ng-show="isLoggedIn()"></button> Thanks by advance ! Place a "clicked" attribute on you objects in the ngRepeat, and use ng-style to set the class. Quick and dirty example: <button ng-class="{'icon-fav-clicked': post.clicked, 'icon-fav': !post.clicked}" class="actions-icon animated bounceInUp icon-fav" ng-click="post.clicked=true;tagLike(post)" ng-show="isLoggedIn()"></button> You can set the post.clicked = true in the tagLike() function for a cleaner ng-click. You are welcome, and BTW - you should try to avoid making DOM changes via the controller as much as possible, it's not the best practice. Try learning about directives for UI manipulation, as that is their purpose :)
common-pile/stackexchange_filtered
Predictive distribution Reading Bishop's book, I was trying to prove eq 2.19. I have seen this and this and I understand how $$p(x=1|D)=\int_0^1p(x=1|μ)p(μ|D)dμ$$ My question is in the second part. How does $$\int_0^1p(x=1|μ)p(μ|D)dμ=\int_0^1\mu p(μ|D)dμ$$ In other words, how does $p(x=1|\mu)$ equal to $\mu$. What is Bishop's book? Bishop - Pattern Recognition And Machine Learning - Springer 2006 I don't have the book in front of me but presumably $x$ is a binomial random variable with mean $\mu$. This translates to $P(x=1)=\mu$ and $P(x=0)=1-\mu$, where $\mu$ is the probability of heads (Work out $E[x]$ to confirm this).
common-pile/stackexchange_filtered
MFMailComposeViewController delegate method not working in iOS 16.0 or above device when device orientation is in portrait mode I present MFMailComposeViewController on top of another viewController and that viewController support both landscape and portrait orientation. Here is the way I tried if MFMailComposeViewController.canSendMail() { let mc = MFMailComposeViewController() mc.mailComposeDelegate = self mc.setSubject(emailTitle) mc.setMessageBody(messageBody, isHTML: false) mc.setToRecipients(toRecipents) mc.modalPresentationStyle = .fullScreen // Present MailComposeViewController self.present(mc, animated: true) } this work totally fine and also I added delegate method too like this extension RateViewController: MFMailComposeViewControllerDelegate{ func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { switch result { case .cancelled: print("Mail cancelled") case .saved: print("Mail saved") case .sent: print("Mail sent") case .failed: print("Mail sent failure: \(error?.localizedDescription ?? "")") default: break } // Close the Mail Interface controller.dismiss(animated: true) { self.dismiss(animated: true) } } } I tested this one in more than one iPhone devices, other than iOS 16.1.2 device delegate method call properly, in iOS 16.1.2 device it also calling properly when device in landscape orientation, for portrait orientation it is not call the delegate method. what can be the possible reason for this? Sounds like a bug in 16.1.2. There is probably nothing you can do about it seems like it was a bug of iOS version 16.1.2 , after I update that devices now it works fine.
common-pile/stackexchange_filtered
Show that any subset of $(\mathbb{N},d)$ is open and closed Show that any subset of $(\mathbb{N},d)$ is open and closed, where $$d(m,n) = \frac{|m-n|}{1+|m-n|}$$ my attempt: let $A \subset \mathbb{N}$ then for any $x \in A$ we have that $B(x,1/3) = \{x\} \subset A$ Hence $A$ is open. (here $B(x,1/3)$ is the open ball centered at $x$ with radius $1/3$). I am struggling to show that $A$ is also closed. You showed that any subset is open. In particular, for a fixed $A$, the complement of $A$ is also open. Hence $A$ is closed. @ThibautDumont of course! thanks. This is equivalent to show that any singleton is open. Indeed, if this is the case, every subset is a union of singletons, so it is open. And if every subset is open, every subset is also closed. Your proof is good to show that $B(x,1/3)=\{x\}$, which precisely says $\{x\}$ is open. Indeed $$ \frac{|x-n|}{1+|x-n|}<\frac{1}{3} $$ is equivalent to $$ 3|x-n|<1+|x-n| $$ or $$ |x-n|<\frac{1}{2} $$ If $n\ne x$, of course $|x-n|\ge1$ (when $x,n\in\mathbb{N}$). Hi, thanks for responding. You say this is equivalent to showing every singleton is open. I don't quite see how this is equivalent, could you expand on that please? @DH. If every subset is open, every singleton, in particular, is. If every singleton is open, then any subset is open, because any set is the union of singletons and unions of open sets are open. Saying that every subset is open is the same as saying that every subset is closed, because closed sets are the complements of open sets. Take a sequence $a_n\in \mathbb{N}$ such that $\lim_{n\rightarrow\infty} a_n=x\in \mathbb{N}$. Since $B(x,1/3)=\{x\}$ there exists $n_0$ such that for $n\geq n_0$ $a_n\in B(x,1/3)=\{x\}$, so the sequence $a_n$ is eventually constant iguals to $x$ and then $x\in A$ which means that $A$ is closed.
common-pile/stackexchange_filtered
Grails hbm2ddl.SchemaUpdate Unsuccessful error when i am running my grails application i am getting schemaUpdate fail error; hbm2ddl.SchemaUpdate Unsuccessful: alter table lifecycle add index FKEDFAE76ABF1565B0 (round_up_emailed_updated_by_id), add constraint FKEDFAE76ABF1565B0 foreign key (round_up_emailed_updated_by_id) references user (id) hbm2ddl.SchemaUpdate Too many keys specified; max 64 keys allowed hbm2ddl.SchemaUpdate Unsuccessful: alter table lifecycle add index FKEDFAE76A166A0DC5 (training_advice_telecommunicated_updated_by_id), add constraint FKEDFAE76A1 66A0DC5 foreign key (training_advice_telecommunicated_updated_by_id) references user (id) hbm2ddl.SchemaUpdate Too many keys specified; max 64 keys allowed hbm2ddl.SchemaUpdate Unsuccessful: alter table lifecycle add index FKEDFAE76AA40386D9 (laptops_arranged_actor_id), add constraint FKEDFAE76AA40386D9 foreign key ( laptops_arranged_actor_id) references role (id) hbm2ddl.SchemaUpdate Too many keys specified; max 64 keys allowed what does it mean? and what causes this error? Although you did not post your database engine and version, I am going to take a guess that you are using MySQL 5.0 or greater. I am using MySQL 5.5.25 and InnoDB as my engine, and came across the following discovery: As of MySQL 5.0, there is a maximum of 64 indices per table. Someone attempted to create a table having more than 64 foreign keys using MySQL 5.0 and got the exact text in their error message that you got: Too many keys specified. Max 64 keys allowed Here is their bug report on bugs.mysql.com Bug #51450. If you are running MySQL 5.0 or greater and this is the error you are encountering, then it is not an issue with Grails or hbm2ddl, but with your underlying database engine. Apparently you have specified too many foreign keys; apparently a maximum of 64 keys is allowed. You mean .. in a single class i can have only 64 foreign keys... ?
common-pile/stackexchange_filtered
ax.get_position wont give me position of all plots on multiple subplots I am trying to overlap a matrix of subplots. The code I am using is: fig, axes = plt.subplots(ncols =2, nrows = 2, figsize=(8,8), sharey=True, facecolor = "#FFFFFF", subplot_kw=dict(polar=True) ,constrained_layout=True) fig.tight_layout(h_pad=-5) directions = [1,-1] for ax,direction in zip(axes.ravel(), directions): shift_axes = 0.2 if direction == 1 else -0.2 box = ax.get_position() print(box) box.x0 = box.x0 + shift_axes #x0 first coordinate of the box box.x1 = box.x1 + shift_axes #x1 last coordinate of the box ax.set_position(box) Which returns: If I print the results of box, I get only the first two. What am I doing wrong? try directions = [1, -1, 1, -1] and think what zip does when its arguments are not the same length! btw, you'd better use a shifts = [+0.2, -0.2, +0.2, -0.2] then for ax, shift in zip(axes.flat, shifts): ... OMG! how could I miss that... thanks! Someone wrote a song about that feeling "And there's another memory that gets stuck \ Inside the walls of my skull, waiting for its turn to talk \ And it may be a few years \ But you can bet it's there, waiting still \ For me to be left alone in a room full of things that I've done", btw it's one of my favorite songs, for one reason or another :-) ...a whole cake... ;)
common-pile/stackexchange_filtered
Add var +1 to Label on button press (kivy) Source func - add_click add +1 to self.click to Label (self.RightBar) by press button I write a function for the game (clicker), the essence of which is that by pressing the button in the label a counter was added. def add_click(self, instance): self.click += 1 def build(self): self.click = "0" Body = BoxLayout(orientation = "vertical", size_hint = [1,.8], spacing = 0.7) Land = BoxLayout() LeftBar = Image(source = "/storage/emulated/0/kivy/image/84.jpg", size_hint = [None, None], size = [1080, 610]) self.RightBar = Label(text = "MONEY:" + "\n" + "\nUNITS:" + "\n" + "\nDAY:" + "\n" + "\nCLICKS:" + " " + self.click, size_hint = [.3,1], valign = "top", halign = "left", text_size = [750,900]) Land.add_widget(LeftBar); Land.add_widget(self.RightBar); Body.add_widget(Land); NavBar = BoxLayout(size_hint = [1, .55], spacing = 0.8) Body.add_widget(NavBar); Body.add_widget(Button(text = "*click*", font_size = 20, background_normal = "", background_color = [.11,.11,.10,.4], size_hint = [1,1.7], on_press = self.add_click)); return Body Change the following: Step 1 From string: self.click = "0" To numeric: self.click = 0 Step 2 From: self.RightBar = ... + self.click, ... To: self.RightBar = ... + str(self.click), ... Snippets def build(self): self.click = 0 ... self.RightBar = Label(text = "MONEY:" + "\n" + "\nUNITS:" + "\n" + "\nDAY:" + "\n" + "\nCLICKS:" + " " + str(self.click) Output Perhaps like yours too it's possible. I found a solution by rewriting the function like that: def add_click(self, instance): self.click = int(self.click) self.click += 1 self.click = str(self.click) self.RightBar.text = str("MONEY:"+"\n"+"\nUNITS:"+"\n"+"\nDAY:"+"\n"+"\nCLICKS:"+" "+self.click)
common-pile/stackexchange_filtered
Bootcamp - Stuck on "Partitioning Disk..." When attempting to add a Windows 10 (April 2018, build 1803) partition to my 2019 iMac, I get stuck on "Partitioning disk..." perpetually. When I look at Disk Utility, the OSXRESERVED and BOOTCAMP partitions appear: My iMac is running the latest stable release of macOS, 10.14.5 (18F132). Is there a known bug/solution to this problem? Just making sure, you waited enough time before quitting out of Bootcamp? I had to wait for around 20 - 30 mins for it to finish partitioning. Apple released a patch for my issue here: https://support.apple.com/kb/DL2007
common-pile/stackexchange_filtered
How should we deal with incorrect comments? On this site, there is a tendency for users to answer questions with terse comments. It's especially prevalent for low quality questions which are in danger of being closed. Recently, I've been noticing a lot of comments that are misleading or downright incorrect, especially on lower quality questions. I want to respond to them somehow, but I see no way to: You can't downvote comments, and existing flag reasons don't apply to incorrect comments. I can't reply in a comment, for two reasons: long discussions in comments are frowned upon and often deleted, and it often takes many more words to correct a misconception than to make one. 500 characters often isn't enough to respond. I can't reply in an answer, because answers should address the question, not its comments. Since there are no easy responses, and there's no glory to be had anyway (these questions usually quickly plummet off the front page), these comments almost always stand uncorrected. This misleads the OP and gives our site a bad name to anybody who knows their stuff and sees the question later. How can we deal with this issue? Could you give some examples? There aren't any examples because this problem never happens. Terse, incisive comments are always correct. That's actually the real reason why comments can't be downvoted; it's documented in the secret StackExchange API. @heather I don't want to name names, since it would get ugly and personal. But there are two risk factors. (1) If a user's answers' scores are at least 25% negative, all comments are bad. (2) If a user usually writes good answers only in freshman physics things (newtonian mechanics, homework and exercises, electromagnetism), most of their comments on SR or QM or (especially!!) QFT are bad. They are overreaching past their domain of expertise. I don't understand why you can't reply in the comments. You said it's because long discussions are often deleted. But isn't that exactly what you want? For those incorrect comments to be deleted. And if you have more than 500 words to say, write it across 2 comments. Then eventually flag the first comment in the discussion as obsolete or for a mod to delete the whole discussion. Then magic happens. Then the incorrect comment is gone. Problem solved @knzhou i'm completely with you on this one, something needs to be changed to make it more clear how to respond to this! on the other hand i do find that the moderators handle flags that were put for this reason rather well. Without naming names, I have made a point to consistently flagging a particular users comments who tends to post pseudo-answers as comments as "not constructive". @Numrok Thanks for the tip! I started doing this too, with good results. This ties directly into a larger issue with flag that recently came up. The moderators are currently not deleting answer for being wrong because it is not they who should pass that judgement unilaterally, so it seems inconsistent if they deleted comments for being wrong. So there are two options here: The nuclear option: Delete any comment that gives an answer if it is flagged as not constructive, no matter its correctness. Do nothing: Leave answers in comments alone. Although I belong to the users who leave answers in comments if I'm too lazy or too busy to expand them into a full answer, or because I plainly don't think the question deserves that much effort on my part, or also because some of my comment-like answers have incurred a number of upvotes that are frankly ridiculuous and I don't want my rep to be inflated by giving such effortless answers, I say: Nuke answers in comments if they are flagged. Comments are for clarifying questions, pointing out inconsistencies, giving reasons for close/delete/down votes or otherwise improving the post being commented on. They are, obviously, often used for other things - making jokes, giving pseudo-answers, debating related topics, and more. Which is fine as long as no one is bothered by those comments. But as soon as such comment bother someone - indicated by a flag - all comments not evidently serving the primary purpose of comments should be deleted, mercilessly and without considering the abstract "value" or "correctness" of their content. The unique quality of the SE model is precisely that it does not allow the free form of forums, and we should not compromise on that. What kind of false modesty is this? Why should you not want to increase your rep, however ridiculously out of proportion it may be to the effort? If you don't want your terse answers to over-inflate your rep, you can post it as a Community Wiki. I agree with this. The simple solution is to follow the guidelines: comments are not recommended for answering questions. Nota bene that the minimum length for answers is quite brief. A terse, one- or two-sentence answer that is correct is perfectly acceptable. As John Duffield comments above : Who is going to judge the value or correctness of comments? Are we going to subject them to voting as we do questions? If there is no justification for deleting incorrect Answers, why should we delete comments - just because we don't like them? @sammygerbil: no one is going to judge that in my proposal - I'm saying delete all flagged comment-answers regardless of correctness. I'm terrible for leaving answers as comments, but even I agree that any comment-answers flagged should be nuked. I accept the risk I take when I foolishly answer in the comments @sammygerbil wrote: "Why should you not want to increase your rep, however ridiculously out of proportion it may be to the effort?" - because an increase in rep, as an end and divorced from its cause, is of no value to him? @AlfredCentauri : If he does not value it, why should he care if it increases? @sammygerbil, if I don't value debt, does it follow that I shouldn't care if my debt increases? @AlfredCentauri : That is correct. But if you do care if it increases then you obviously do place a value on it, albeit a negative value. I don't understand. The question is about comments that are incorrect, yet this highly voted answer is about the completely orthogonal issue of comments that should have been posted as answers. And I fail to see how deleting comments that should be answers could possibly be beneficial to the site. Surely, the best situation is that an answer appears as an answer, the second-best is that it appears as a comment and the worst (assuming the answer is correct) is that it doesn't appear at all. Going from 2 to 3 makes the site worse, not better. This answer addresses the case where a comment is valid as a comment - that is, it's attempting to improve its parent post, not to answer the question - but it's simply wrong. The preferred way to deal with incorrect comments is to respond with a comment of your own. Now, you made a fair point about why you might not want to do that: I can't reply in a comment, for two reasons: long discussions in comments are frowned upon and often deleted, and it often takes many more words to correct a misconception than to make one. but here's an easy way to solve both problems: write something like This is incorrect because (short summary reason). If you'd like to discuss this further, we can do so in [chat]. And if the original commenter then ignores your invitation to chat and tries to respond in another comment: As I said, we can continue to discuss this in [chat]. and leave it at that. If you don't actually want to get into an argument, that's fine; you can take the discussion to the chat room and respond once or twice then give up. Heck, you don't even have to follow it up in chat at all. (In that case, you could use wording along the lines of "the place to discuss this is [chat]") The point of making this comment is not to actually start a debate. The point is (1) to show that there exists a counterargument to the original comment, and (2) if the original commenter does want to argue their point, to remove that argument from the wrong venue (the comment section) and put it in the right one (a chat room). I especially want to emphasize that our reluctance to hold discussions in the comments is not a reason to avoid responding to comments. Yes, extended comment discussions are frowned upon, but one or two rounds of back-and-forth commenting do not count as an extended discussion. What does make an extended discussion is when you have several rounds of comments and it shows no signs of stopping. And even if you do get sucked into a discussion, it's not really that bad. Nobody gets punished for that. The worst that happens (or some might say best) is that the whole comment chain gets moved to chat or deleted - which, in fact, is a roundabout way of getting rid of the original, allegedly incorrect comment. I feel that the advice here does not much address the real problem of new, less expert users absorbing misinformation from short, confidently toned, incorrect comments which are difficult to debunk without taking a considerable amount of time and writing a full answer. @DanielSank, what new, less expert users absorb is not within our span of control. Indeed, a perfectly correct comment may be misinterpreted or taken out of context by new, less expert users. Finally, the OP's question is "How should we deal with incorrect comments?" and not "How should we deal with new, less expert users absorbing misinformation from comments". @DanielSank I disagree. I think a response of "No, that's wrong. (short reason)" is quite effective at preventing people from absorbing misinformation from the original comment. It's not 100% effective, of course, but nothing is, and we have to draw the line somewhere. I think this is a reasonable place to do it. And the backup tactic of forcing the whole conversation to be migrated to chat handles some fraction of those cases where a simple followup comment doesn't work. @DavidZ "Nobody gets punished for that. The worst that happens (or some might say best) is that the whole comment chain gets moved to chat or deleted". IMO there is someone who gets punished in directly: the person who asked the question. i feel like wrong comments or pseudo-answers at comments often obscure the actual question. personally when i read a question with a comments battle i often just don't bother thinking about the question. @Numrok I meant to exclude that sort of thing by using the word "punished", but anyway, I agree that's a problem. That's why we aggressively delete comments which are flagged or have outlived their usefulness: they do distract from the original post. Dealing with this requires liberal use of comment flags. I don't think there's much more we can do without a major change to the comment system, but that's not up to us. @DavidZ i completely agree, just to clarify: i think the moderators are doing an amazing job in dealing with flagged comments. But I think the flag reasons could be slightly adjusted/better explained to prevent the image "and existing flag reasons don't apply to incorrect comments" (from knzhou's question). I am aware that this is not a solution, especially for stubborn users, but a friendly comment to the point of "you are misleading/mixing things up/wrong here" will still work wonders for a number of the more reasonable users. Your own comment can then easily be deleted by you after you've achieved your goal. A bit of a hassle, though .. Apart from them, in the flagging options for comments, I see both "unconstructive" and "other". Isn't especially the first one useful for exactly that? A misleading short pseudo answer is unconstructive and depending on the way the people who have access to the flag queue handle this / interpret this, this could be an easy way to get rid of those, would it not? Apart from that, dmckee's suggestion could prove useful because people might be discouraged from giving pseudo-answers in comments if they see them deleted. Thus, the overall amount of pseudo-answers (and thus the wrong ones, too) might decrease. The main issue here are, in my view, actually just a few users who post a lot of misleading comments. I did not want to get personal in any way and I want to try to avoid raising the "ban people" flag - even though I do see the wisdom of adressing that issue at some point In my above comment, I meant to start with "The main issue here is that there are, in my view, actually [...]". I've noticed many "answers" in the comments that weren't posted because they wanted someone else to expand it, etc. However, I haven't noticed incorrect answer-comments. I was going to say adding down votes to comments seems best, but it almost seems like encouraging it, because they now have the same options as answers. I think what would be best is to post another comment asking them to post it as an answer. If they don't, you could post the answer under "community" and down vote it (and then flag the comment for deletion, delete your original comment, etc), because really, the policy is to not use comments for answers. When a comment-answer comes up that is correct, encourage them to post it as an answer, or do so yourself (expansion might be necessary). Along this line of thought, maybe comments should be restructured so people don't post comment-answers. What that would entail, I don't know...probably a Meta question for another time. =) That's just my two cents. Update: Per a discussion in chat with DavidZ and EmilioPisanty, what if there was a flag queue for non-moderators (maybe users with 15k+ rep) that covered all comment flags. Another flag for comments would be added for pseudo-answers, and these flags would also go into this same queue, therefore allowing either the original finder of the pseudo-answer to fix it, or 15k+ users to fix it. Then the system could down vote or up vote as the answer's content entails. I posted this (at Emilio Pisanty's suggestion) as a feature request on the mother meta here. Please up vote this feature request if you think this is a good idea. I think this addresses some of the concerns brought up in the comments below this answer and concerns brought up in the discussion with DavidZ. Update 2: The new feature request is here; I started a bounty on it as it is 3 years old. I don't know. Asking people to turn their comments into answers has a very low success rate, in my experience. It certainly doesn't work on me. If people aren't motivated to write an answer, they probably won't. Then you can post it as an answer yourself...some people can be persuaded to do so. If you really want, just copy and paste into a community answer. If by "community" you mean community wiki mode, that's certainly an option, but I do want to point out that when you make an answer out of someone else's comment, there is no requirement or expectation that you make it community wiki. If that other person wanted the rep, they should have posted the answer themselves. @DavidZ I know; I was referencing community wiki for bad/wrong answers. Ah, I see what you mean. That's okay, but I would personally recommend against posting an incorrect answer in the first place. @DavidZ, the point is to take the incorrect comment-answer and post it as a real answer so users can down vote it like they would a normally wrong answer...to let the system take care of it without doing anything special. As such, it's actually a good thing to post this particular type of bad answer and then have the related comment deleted, because it's easier to show that it is wrong. Good stuff heather. @David Z : who says an answer is wrong? All the downvotes in the world won't make a right answer wrong, especially when it's backed up with supporting references. The real issue here is how to justify the claim that a comment is an incorrect answer. @JohnDuffield: heather did, in the comment right above yours, and the comment two above that. heather: yes, I believe I got your point. I think we agree that wrong answers can offer some value by showing readers (by downvotes) that the content of the answer is wrong. If I understand correctly, you consider this value enough to make posting wrong answers, knowing that the answers are wrong, a useful thing to do. Right? It's a reasonable opinion, I'm just saying I don't agree with it. If you care to discuss further, I'd be happy to explain why elsewhere, perhaps in [chat] or a separate meta Q. @DavidZ, you sort of have it. The difference is I consider posting a wrong answer important only if it has been given as a comment, where there isn't any super effective way to show it is wrong. By moving these pseudo-answers into an answer, the system shows they are wrong via down votes, without any need for extra features. I would be interested in learning why you disagree with this...it just seems like the best option to me. @heather ah, then we do have a significant disagreement. Can you pop into chat now? @DavidZ, sure, I'm interested in your point of view. This is an issue on the site right now. For my own part I've started trying very hard not to write pseudo-answers in the comments and I am more willing to consider pseudo-answer as "not constructive" comments than I had been. Aside: I wrote this in as a comment first. But, I'm trying not to write pseudo-answer so much these days... Poll (use votes on this post to indicate your feelings): How do people feel about the prospect of mods killing pseudo-answer comments if the same notion appears in an answer (by anyone, not just the author of the comment)? Personally, though, I have no problem with correct pseudo-answers. Since most pseudo-answers are correct, removing all of them seems to be a net loss. I just want to get rid of the wrong ones somehow. Well, my poll as currently constructed is about getting rid of pseudo-answers that are redundant with real answers. We mostly try to avoid mods judging correctness, so the removal of wrong pseudo-answers should be thrown on the reviewers. I'm ambivalent on the notion suggested, but I'm very much in favor of removing all pseudo-answers posted in comments, over time. Those that are not already duplicated by answers should be converted to answers, if anyone thinks they're worth keeping. Does upvote mean I want mods to kill comments or the other way around? Er ... I understood that upvoted mean "Yes, please delete them", and down votes mean "Save the pseudo-answers!". I downvoted. There are people who will claim some comment is incorrect without justification because it exposes some error in their answer. They'll call for deletion, and if you comply you're into censorship, and before you know it you're promoting and protecting pseudoscience. It would be better if people could downvote comments. Note though that even that isn't perfect. All the upvotes in the world won't make a wrong answer right, and vice versa. Ditto for comments. I see horseshit comments with umpteen upvotes. Forgive me if I don't provide an example. -1. I'm with John Duffield on this - except that I disagree about down-voting comments - simply ignore them! Up-vote correct comments instead... Save the Pseudo-Answers! Save the Answers-in-Comments! Initially I found them inhibiting, but actually they are very useful for me in testing my understanding of the question, and gauging an answer. All relevant comments are valuable, whether correct or not. They stimulate debate, and allow participation without having to risk a hail of down-votes. If we delete incorrect comments, this inhibits users from answering. And it is a form of censorship. @sammy On the matter of censorship. I don't know if you've noticed the occasional pattern of users who get downvoted when they post answers, switch to posting only comments and always, always, always post a followup to anyone who disagrees with them, insisting that they are right no matter what evidence is presented to them. Personally I find it generates a destructive atmosphere. All gate-keeping shuts people down at some level. We're seeking the amount and kind that means people of good will can participate without the site getting eaten by trolls. I can think of at least one person you might be alluding to. However, I do not agree that gate-keeping and censorship is the best way of tackling this "problem". Far more effective to remain polite, "disengage" and ignore what you consider to be bad behaviour - as good parents know. Engaging with and attacking what you consider to be "trolling" and "destructive" only draws attention to it. Moreover, you are presuming that such people are not acting out of good will and sincere beliefs. As a Moderator, you should be patient, fair, and respectful to all - not swift to judge. I agree with rob - although I cannot tell if he is being serious or sardonic when he says that "terse, incisive comments are always correct". I think this is not an issue. Heather asked for examples but none have been provided. There are far more serious issues which need addressing, such as the Homework Policy which almost daily causes rancour among those who don't agree with the Vote-to-Close. If the Asker does not show signs of being mislead by incorrect comments, I suggest that there is no need to correct them, and it is best to ignore them. Comments do not have the status of an official Answer which has been upvoted by the community. As the Help Centre says, they are "temporary post-it notes". If you are bothered by incorrect comments, the most constructive response you can make is to post a clearly correct Answer - which does not have to be encyclopaedic. If a terse comment is always correct, this must be even more true of a terse answer. And however terse, it is almost certain to be upvoted if it is correct. Posting and down-voting an incorrect answer is unnecessary and counter-productive. Posting it as an Answer only draws attention to something which may have been buried and forgotten in a babble of comments. Terse, incisive comments are never correct. @rob : Make you mind up! That's the exact opposite of your comment to the Question! Terse - like incisive - means concise, succinct. Not necessarily rude or cutting. @sammygerbil, exact definition: "sparing in the use of words; abrupt." The correctness of terse, incisive comments cannot be determined a priori. @rob : What's going on here? First they're always correct. Then they're never correct. Now their correctness cannot be determined a priori. Are they subject to Heisenberg's Uncertainty Principle? Are they more elusive than Schrodinger's Cat?? Perhaps I am not being terse enough. @rob : You are being pithy. @sammygerbil Terse.
common-pile/stackexchange_filtered
How can I turn an op address into the right kind of B::OP? In a running Perl program if I have an Op address (either by B::Concise, Devel::Callsite or via mysterious other ways) is there a simple way to cast that into the right kind of B::OP, short of walking an Opcode tree? To try to make this clearer, here's some code: use Devel::Callsite; use B::Concise qw(set_style); use B; sub testing { sub foo { callsite() }; my $op_addr = foo; printf "Op address is 0x%x\n", $op_addr; # I can get OPs by walking and looking for $op_addr, # but I don't want to do that. my $walker = B::Concise::compile('-terse', '-src', \&testing); B::Concise::walk_output(\my $buf); $walker->(); # walks and renders into $buf; print $buf; } testing(); When this is run you'll see something like: $ perl /tmp/foo.pl Op address is 0x2026940 B::Concise::compile(CODE(0x1f32b18)) UNOP (0x1f40fd0) leavesub [1] LISTOP (0x20aa870) lineseq # 8: my $op_addr = foo; COP (0x1f7cd80) nextstate BINOP (0x20aba80) sassign UNOP (0x20ad200) entersub [2] UNOP (0x1f39b80) null [148] OP (0x1fd14f0) pushmark UNOP (0x1f397c0) null [17] SVOP (0x1f39890) gv GV (0x1fa0968) *foo OP (0x2026940) padsv [1] ^^^^^^^^^^ .... So 0x2026940 is the address of a B::OP and and which according to this has next(), sibling(), name() methods. If the address were say 0x20aa870 that would be the address of a LISTOP which has in addition a children() method. I added B::Concise just to show what's going on. In practice I don't want to walk the optree, because I'm assuming/hoping that the address is in fact where that listop resides. So perhaps there are two parts, first casting an address to B::Op which I believe is the parent class, but after that I'd like to know which kind of Op, (UNOP, BINOP, LISTOP) we are then talking about. If I can get the cast part done, the second part is probably easy: all B::OP's have a name() method, so from that I can figure out what subclass of OP I have. EDIT: ikegami's solution is now part of Devel::Callsite version 1.0.1 al though it isn't quite right. Could you give some example code, please? @Schwern ok code added. Does this make it clear? Crossposted from PerlMonks. just in case it worked, I tried B::svref_2object( bless(\$op_addr, 'B::SV')->object_2svref ). but it didn't :) This duplicates B's internal make_op_object. use B qw( ); use Inline C => <<'__EOS__'; static const char * const opclassnames[] = { "B::NULL", "B::OP", "B::UNOP", "B::BINOP", "B::LOGOP", "B::LISTOP", "B::PMOP", "B::SVOP", "B::PADOP", "B::PVOP", "B::LOOP", "B::COP", "B::METHOP", "B::UNOP_AUX" }; SV *make_op_object(IV o_addr) { const OP *o = INT2PTR(OP*, o_addr); SV *opsv = newSV(0); sv_setiv(newSVrv(opsv, opclassnames[op_class(o)]), o_addr); return opsv; } __EOS__ Example use: use Devel::Callsite qw( callsite ); my $site = sub { return callsite() }; my $addr = $site->(); my $op = make_op_object($addr); say $op->name; So simple that I wonder why didn't I think of this before? ;-) I will be adding this to Devel::Callsite in a future version. Have any thoughts how much if this varies over the various Perl versions. (I can check this myself, but if you happen to know...) That may be true but op_class isn't in Perl versions 5.24 or earlier. You probably you can duplicate the 5.26 code in earlier versions though. As I mention on perlmonks, although the name field is correct, the address changes and the other fields like parent are wrong. Sigh. Re "Have any thoughts how much if this varies over the various Perl versions.", When mucking with not just Perl internals, but the internals of another module, breakage is to be expected. Just be sure to test your module with against dev releases of Perl, and the release candidates specifically. (p5p already does this for you, but it's best if you do it too.) p5p is always happy to help find a solution to breakage they cause. Re "op_class isn't in Perl versions 5.24 or earlier", Then look at older versions of ext/B/B.xs to see what the module did before Re "the address changes and the other fields like parent are wrong", You're printing the address of the B objects, not the address of the ops themselves. printf("op: %s (0x%x), parent: %s (0x%x)\n", $op->name, $$op, $parent->name, $$parent); Thanks for the information and clarification. I need to put all of this on hold and focus on other things, but if/when I come back to this I'll use your suggestions with respect to Perl versions other than 5.26.
common-pile/stackexchange_filtered
Pandas, I get dataframe full of nan when reading from xlsx I am reading from an Excel file ".xslx", it's consist of 3 columns, but when I read from it, I get a DF full of nans, I checked the table in Excel, it consists of normal cells no formulas no hyperlinks. My code: data = pd.read_excel("Data.xlsx") df = pd.DataFrame(data, columns=["subreddit_group", "links/caption", "subreddits/flair"]) print(df) Here is the excel file: Here is the output: your columns in the pd.DataFrame call don’t match the columns from the file. You should also add the ^caption part (and you can remove them later with .rename) Also for future questions, please don’t post images of data. It’s more useful for everyone, and you probably would have seen your error when copying and pasting the excel contents. Thanks for the answer, I see where I got it wrong, and I will keep that in mind for future questions. The column parameter of pd.Dataframe() function doesn't set column names in result dataframe, but selects columns from the original file. See pandas documentation : Column labels to use for resulting frame when data does not have them, defaulting to RangeIndex(0, 1, 2, …, n). If data contains column labels, will perform column selection instead. So you shouldn't provide column parameter and after the file is read, rename columns of the dataframe: df = pd.DataFrame(data) df.columns = ['subreddit_group', 'links/caption', 'def']
common-pile/stackexchange_filtered
How can I run the same python script in parallel started from a cron job? I have a watchfolder where files are dropped. Via a cronjob I start a python script that first checks for new files. def file_to_process(): filePath = "".join([base_url_gpfs, '/*']) if glob.glob(filePath + "*.xml"): set_pid_file() #find oldest xml file and change into corresponding mxf file xmlToProcess = min(glob.glob(filePath + "*.xml"), key=os.path.getctime) fileToProcess = xmlToProcess[:-3] + 'wav' if not os.path.isfile(fileToProcess): sys.exit(logger.error("{} not found".format(fileToProcess, filePath))) return xmlToProcess, fileToProcess else: os._exit(0) If so, it creates a pid file and uploads the file to a cloud service. def set_pid_file(): if os.path.isfile(pidfile): logger.info('Process is already running') os._exit(0) else: pid = str(os.getpid()) f = open(pidfile, 'w') f.write(pid) When the processing in the cloud is done, I remove the pid file but the script is still running and performing other tasks. At that moment a new instance of the script can start again when there is a new file available. But it seems to lose track somewhere when the script is running multiple times and it fails. So I'm looking for a more reliable way to run different instances of the same script in parallel. There are a lot of ways to approach this, but perhaps the easiest modification to what you are already doing would be to instead create a pid file (essentially a lock) per input file, rather than a lock for the process overall. You could signal that a few ways as well...rename the files as you start processing them, move them to a new "in process" folder, or drop a lock file unique to each file (perhaps based on the name of the file). Then multiple cron jobs should be able to run at once and not interfere.
common-pile/stackexchange_filtered
SED with variable that migth contain " / " I have this code: echo $content | grep -o '<a href="[a-z]\+[^>"]*' | sed -ne 's/^<a href="\(.*\)/\1/p' | sed -ne 's~/^http[s]*:\/\/*\(.*\)/\1/p' | sed -ne "s;/\([^/]*\)\/\(.*\)/$1:::$2:::\1:::\2/;p" If you look at the last sed command, you can see the variable $2. And the $2 variable might contain a forward-slash "/", and this will obviously cause problems. How can I avoid this problem ? Simple, change the sed delimiters.. sed -ne "s~\([^/]*\)\/\(.*\)~$1:::$2:::\1:::\2~p" Your last two sed commands should be, sed -ne 's~^http[s]*:\/\/*\(.*\)~\1~p' | sed -ne "s;\([^/]*\)\/\(.*\);$1:::$2:::\1:::\2;p" or sed -ne "s;\([^/]*\)\/\(.*\);$1:::$2:::\1:::\2;p" Tested and not working, I get this error: unterminated `s' command post the full traceback on your question Posted the full code I use if that is what you mean with full traceback @Jozo pls have a check on second and third sed commands.. You need to replace sed delimiter / with ;
common-pile/stackexchange_filtered
Cardinality of a subset of an ordinal Let $\alpha$ be an ordinal number. How can I show that every subset $x$ of $\alpha$ has either the same cardinality as $\alpha$ or there exists an cardinal number $\beta$ such that $|x|=\beta < |\alpha|$? First prove that if $x\subseteq\alpha$, then there is an ordinal $\beta\leq\alpha$ such that $x$ is order isomorphic to $\beta$ (that is to say, $\beta$ is the order type of $x$). Then you only need to prove that if $\beta\leq\alpha$, then the cardinality of $\beta$ is at most that of $\alpha$. This should be a fairly easy exercise in applying definitions. How do you prove the existence of $\beta$? How easy/hard depends on what you already know. For example, if you know that every well-ordered set is isomorphic to a unique ordinal, simply note that $x$ is a well-ordered set, and use the various comparability theorems on well-orders to argue that its order type cannot be larger than $\alpha$ itself. If you do not know that, then prove this by induction on $\alpha$, but this tends to be more complicated since it includes ad-hoc proofs of several other basic theorems on well-orders. What does it mean when you say order type of an ordinal is larger than other ordinal? Thanks! @2pirsquared: The order type of a well-ordered set is an ordinal. So it's just a statement about comparing two ordinals. Hi, I see the existence of $\beta$. But why we have $\beta \leq \alpha$? Thanks! @2pirsquared: Since $x$ is a subset of $\alpha$, there is an order embedding of $\beta$ into $\alpha$. @2pirsquared: I'm not sure what you're trying to prove. Sorry, I just confused myself earlier. I want to show that $\beta $ is a cardinal i.e it's not equinumerous with any other ordinals that's strictly less that it. I feel like I have to do an initial segment argument for that. Am I on the right track? Thanks! @2pirsquared: It's not necessarily a cardinal. It's an ordinal. But if $\xi$ is an ordinal, then $|\xi|\leq\xi$. So if $|\beta|\leq\beta<\alpha$, what does it tell you about the cardinality of $\beta$? @Asaf Karagila: It's not equinumerous with any other ordinals that's strictly less than it. And we know that $x$ is isomorphic to $\beta$. So $x$ is equinumerous to $ |\beta|$? Let $\alpha^+$ denote the Hartogs number of $\alpha$, i.e. the least ordinal of greater cardinality than $\alpha$. This concept is well-defined for any set. The Hartogs number of any $x\subseteq\alpha$ is at most $\alpha^+$. If it's exactly $\alpha^+$, $x$ bijects with $\alpha$; if not, $x$ bijects with some lesser ordinal.
common-pile/stackexchange_filtered
Interface in method signature inside interface definition I want to have something like this: type MyInterface interface { MyMetod(interface{}) } and to have the type type MyType struct {} with method func (mt *MyType) MyMethod(SomeConcreteType) { // body } implementing MyInterface. But it seems that Go can't handle this. I recieve an error that says that it have MyMethod(SomeConcreteType) but it wants MyMethod(interface{}). Why is this so, and what would be a good solution to this problem? Why is this? It's the language design. Solution would be to match the interface: type MyType struct{} func (mt *MyType) MyMethod(v interface{}) { v, ok := v.(SomeConcreteType) if !ok { panic("!ok") } v.doStuff() } Yes, this seems to be the best solution in the general case. However my case is a little bit special, so I think I'll just drop the MyInterface in favor of interface{} and use reflection to force-call MyMethod on it. @mzdravkov I'd run benchmarks, because I'd almost bet using my method would be a hell lot faster than using reflection. Damn it, you are right. Didn't thought about the performance of reflection. And I'm writing a game engine :D Although, this is not in a performance critical part... I will think about it. Thanks for the notice.
common-pile/stackexchange_filtered
Java realm and secured request I'm developing a game with separated and isolated universes (like ogame for those who know this game). One player (account) is associated with one universe but one player (physical) can create one account per universe. So a player can login to multiple universes and switch universe when he is playing. To do this, I have created Authentication class which stored id of logged player and universe name (which is the schema name in my PostgreSQL database). So, an Authentication object represents a logged player. To manage application roles, I use a custom realm which gather only id and universe name (from my Authentication object) to process SQL request and get group name to convert it to roles. All these mecanisms work fine. I'm wondering if it really secured to do that ? Can a attacker send request to my realm and inject in his request id and universe name to process authentication directly ? Because my realm doen't need neither password nor username (processed before in my application to create Authentication object), such malicious request will probably work. So my question is only to know if request to my realm can be made outside my Java application (or my Glassfish server) ? With Firefox and Firebug, we don't see the request sent to my realm. Does it mean that nobody can see how informations are sent to my realm to process authentication ? Ty Assuming that the request happens outside of the application, and originates from the client, then if you don't verify username/password, chances are that someone could make a request outside of your application and violate your security. You should require the submittal of the username/password at the time of submittal of realm/universe and verify at that time that the user is authorized for the request they are making. Don't just make sure that the username/password is valid, but verify that they are registered for the universe they are logging into and the realms/roles they are trying to access. If you don't require this, you open yourself up for attacks. Firefox and Firebug is nice, but it doesn't show you the raw requests. To really see the requests and what is going on, you should use a packet sniffer like Wireshark. If you can see the request there, then you are vulnerable. Also make sure that the username/password is encrypted and is not viewable in plain text, otherwise attackers could extract user's credentials by sniffing the wire. If all the processing happens server side and there is no client request originating (and you see nothing in Wireshark on the client side), then you are probably safe. I know that it's probably a "strange" way to authenticate user but my purpose is to allow user to connect AT SAME TIME many accounts and thus, thanks to a drop down list, to switch account without logout/login again. I will check as adviced packets with Wireshark and if I will have any doubt, I will refactor my code. Thank you
common-pile/stackexchange_filtered
Vaadin - generate table dynamically I have a Vaadin application. One of it's components is a table. I need a possibility to add as many columns as the user wants (well, let's say max. 20 at the moment) to that table. At the beginning, there are 5 colums, so in fact the user can add column 6 - 20. However, after doing "layout.addComponent(...)", this table is not editable any more. I tried 2 things: There is a variable which stores the current number of rows and is increased by 1 for every click on an "add" button. With every click, 1 column is added to the table. Another idea was to hold the columns numbers in a variable (like idea 1) and the value of the cells somewhere in a Collection (whatever). After click on the "add" button, the whole table is removed, then all columns are added (all that have been there + a new one) and it is added to the layout. However, none of these ideas works. Any suggestions? I think it should be enough to invoke addContainerProperty on the Container that is linked to your Table. Doing that should fire a PropertySetChangeEvent to the Table. Unless, of course, if you have limited the visible columns using Table.setVisibleColumns. If this doesn't help you, a piece of code could help solving the problem. If MyContainer extends IndexedContainer, you have full freedom; just as a sample, I have Statistics which is simply (dynamic) Map serialized in ZooKeeper, and MyContainer listens to ZooKeeper changes: public class MyContainer extends IndexedContainer { ... public void process(final ModelChangeEvent event) { ... for (Map.Entry<String, Long> entry : newTask.getCounters().entrySet()) { addContainerProperty(entry.getKey(), Long.class, 0L); Property property = getContainerProperty(taskName, entry.getKey()); property.setValue(entry.getValue()); } fireContainerPropertySetChange(); ... } When we add new (key, value) pair to Map, we will get new column automatically, where "key" is column title, and "value" is cell value. No needs to call "fire"; it will be called automatically by IndexedContainer implementation (check sources).
common-pile/stackexchange_filtered
Android Wifi Manager network switching not working In my application I have to show list of access points and then connect to a selected network. When the app is launched and a network is selected the connection goes through and the selected network is also reflected in the phone settings->wifi. But when I try to switch network after launch the following happens the selected network gets connected then its disconnected wifi scans and then connects to the previously connected network The behavior is same for saved and new network. How do I get the error for the selected network getting disconnected. I am checking for Open and WPA2 network types. My Code public WifiConfiguration exists(String SSID) { List<WifiConfiguration> existingConfigs = wifiManager.getConfiguredNetworks(); for (WifiConfiguration existingConfig : existingConfigs) { if (existingConfig.SSID.equals("\""+SSID+"\"")) { return existingConfig; } } return null; } private WifiConfiguration CreateWifiInfo(String SSID, String Password, WifiCipherType Type) { WifiConfiguration config = new WifiConfiguration(); config.SSID = "\"" + SSID + "\""; if(Type == WifiCipherType.WIFICIPHER_NOPASS) { config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); } else if(Type == WifiCipherType.WIFICIPHER_WPA2) { config.preSharedKey = "\""+Password+"\""; config.hiddenSSID = true; } else { return null; } return config; } public boolean Connect(String SSID, String Password, WifiCipherType Type) WifiConfiguration tempConfig = this.exists(SSID); int netID = -1; if(tempConfig == null) { Log.i(MainActivity.TAG, "Network is new, so adding new one."); WifiConfiguration wifiConfig = this.CreateWifiInfo(SSID, Password, Type); netID = wifiManager.addNetwork(wifiConfig); Log.i(MainActivity.TAG, "New net ID : " + Integer.toString(netID)); } else { netID = tempConfig.networkId; Log.i(MainActivity.TAG, "Found net ID: " + Integer.toString(netID)); } boolean bRet = wifiManager.enableNetwork(netID, true); bRet here returns true for the selected network. Any Suggestions Thanks P What device are you trying this on? HTC one android version 4.3
common-pile/stackexchange_filtered
Google Street View Black Screen I am trying to put a Google Streetview Panorama instance inside of a tab inside of an offcanvas element using Bootstrap 5. If the default tab is the tab that contains the Streetview everything works fine as is demonstrated here: https://codepen.io/taylormhicks90-the-bold/pen/OJxxqQN If I use a different tab as the default tab the Streetview is initially black and doesn't work unless you make it fullscreen first as is demonstrated here: https://codepen.io/taylormhicks90-the-bold/pen/YzrrgroWhile I have a workaround of using the streetview tab as the default tab this in not the desired functionality. I have spent a few hours digging through googles docs and trying different workarounds. Just hopping someone can help explain why this is happening and what I can do to get it functioning properly or at least point me in the right direction. I even tried this where I load the streetview while the streetview tab is the default tab and then change the tab to the pictures tab after the streetview has loaded, but it doesn't work.https://codepen.io/taylormhicks90-the-bold/pen/RwLLdeP html: <div class='container'> <div class='row'> <div class='col-12'> <h1>My Page</h1> <button class='btn btn-primary' data-bs-toggle="offcanvas" data-bs-target="#offcanvas" >Click Here For Off Canvas</button> </div> </div> </div> <!--Off Canvas--> <div class="offcanvas offcanvas-bottom" tabindex="-1" id="offcanvas" data-bs-backdrop="false"> <div class="offcanvas-header"> <ul class="nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item" role="presentation"> <button class="nav-link active" id="pictures-tab" data-bs-toggle="tab" data-bs-target="#pictures" type="button" role="tab" aria-controls="pictures" aria-selected="true">Pictures </button> </li> <li class="nav-item" role="presentation"> <button class="nav-link" id="streetview-tab" data-bs-toggle="tab" data-bs-target="#streetview" type="button" role="tab" aria-controls="streetview" aria-selected="false">Street View </button> </li> <li class="nav-item" role="presentation"> <button class="nav-link" id="map-tab" data-bs-toggle="tab" data-bs-target="#map" type="button" role="tab" aria-controls="map" aria-selected="false">Map </button> </li> </ul> <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button> </div> <div class="offcanvas-body"> <div class="tab-content h-100" id="myTabContent"> <div class="tab-pane fade show active" id="pictures" role="tabpanel" aria-labelledby="home-tab"> <div class="row"> <div class='col-12'> <p> My Pictures Go Here </p> </div> </div> </div> <div class="tab-pane fade h-100" id="streetview" role="tabpanel" aria-labelledby="profile-tab"> <div id="streetviewContainer" class="h-100 w-75 mx-auto"></div> </div> <div class="tab-pane fade h-100" id="map" role="tabpanel" aria-labelledby="contact-tab"> <div id="mapContainer" class="h-100 w-75 mx-auto"></div> </div> </div> </div> </div> <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMaps&v=weekly" async ></script> Javascript: let map,streetView; function initMaps() { const location = { lat: 42.345573, lng: -71.098326 }; map = new google.maps.Map(document.getElementById("mapContainer"), { center: location, zoom: 19, }); new google.maps.Marker({ position: location, map, }); streetView = new google.maps.StreetViewPanorama( document.getElementById("streetviewContainer"), { position: location, zoom: 0, } ) } Move StreetView call (new google.maps.StreetViewPanorama) into a function and then activate this function only when tab is active. function loadStreetView() { streetView = new google.maps.StreetViewPanorama( document.getElementById("streetviewContainer"), { position: location, zoom: 0, } ); } // listen to street view tab button only. let streetviewTab = document.querySelector('#streetview-tab'); // listen to on shown. streetviewTab.addEventListener('shown.bs.tab', function (event) { loadStreetView(); }); Only use this when default tab is not StreetView. Reference: Bootstrap 5 tab events Thank you this works. I did modify it so that the event listener removes it self so that the streetview is only loaded the first time that the tab is show. Not sure it makes a difference but it seems like the right approach to me.
common-pile/stackexchange_filtered
Dynamic single-line printing in Python (time?) I'd like to make a simple clock (CLI) that prints the time into one line, and updates it every second. Is this even possible? Should I just print a new line every second? This is what I have at the moment, which functions terribly: import calendar, time a = 1 while a == 1: print (calendar.timegm(time.gmtime())) Curses Programming with Python. With the proper library, then: possible duplicate of How to refresh curses window correctly?. @jww: Curses is probably overkill for this. Not to mention that it would make his code much less portable—while '\r' won't work everywhere, it will work in more places than Curses, most notably on Windows (which, for all we know, is what the asker is using). If I understand, what you want to do is write the time, then, a second later, overwrite it with the new time, and so on. On most terminals, printing a carriage return without a newline will take you back to the start of the same line. So, you can almost just do this: print('\r{}'.format(calendar.timegm(time.gmtime())), end='') In general, there's a problem with this: the carriage return doesn't erase the existing text, it just lets you overwrite it. So, what happens if the new value is shorter than the old one? Well, in your case, that isn't possible; you're printing a 10-digit number that can never turn into a 9-digit number. But if it were a problem, the easiest solution would be to change that {} to something like {<70}, which will pad a short line with spaces, up to 70 characters. (Of course if your lines could be longer than 70 character, or your terminal could be narrower than 70, don't use that number.) Meanwhile, if you just do this over and over as fast as possible, you're wasting a lot of CPU and I/O, and possibly screwing up your terminal's scrollback buffer, and who knows what else. If you want to do this once per second, you should sleep for a second in between. So: while True: print('\r{}'.format(calendar.timegm(time.gmtime()))) time.sleep(1) If you want to get fancy, you can take over the whole terminal with curses on most non-Windows platforms, msvcrt console I/O on Windows, or even manually printing out terminal escape sequences. But you probably don't want to get fancy. print function print newline (\n) after the string you passed. Specify carriage return (\r) explicitly does what you want. To print every second, call time.sleep(1) after printing. import calendar import time while 1: print(calendar.timegm(time.gmtime()), end='\r') time.sleep(1) UPDATE To make cursor remains at the end of the line, prepend \r: print('\r', calendar.timegm(time.gmtime()), sep='', end='') +1, though I would prepend the \r instead of appending it, so that the cursor remains at the end of the line. @uʍopǝpısdn, updated the answer accordingly. Thank you for comment.
common-pile/stackexchange_filtered
The Duchess of Cambridge has been delivered of a son Recently the Duchess of Cambridge gave birth to a healthy baby boy. The announcement from Buckingham Palace said "The Duchess of Cambridge has been delivered of a son." This struck me as a very odd grammatical structure that I don't quite understand. Of course I understand what is meant: "She gave birth to a male child" and I presume it is put this way for the purposes of delicacy. But I was wondering if someone could explain how this grammatical structure works. It is an interesting use of the genitive. That which was within her, she is now delivered of.
common-pile/stackexchange_filtered
Javascript ES6 "not a function" error I have been working on a bunch of JavaScript tutorials that are using some ES6. So far two of the lessons have been throwing the same error, and being new to JavaScript I'm still trying to understand the logic, and so not very good at debugging. I have tried using Babel to convert the ES6 code to plain JavaScript, thinking it was a browser issue, but the same error occurs. Any help would be greatly appreciated. The ES6 JavaScript const inputs = document.querySelectorAll('.controls input'); function handleUpdate() { const suffix = this.dataset.sizing || ''; document.documentElement.style.setProperty(`--${this.name}`, this.value + suffix); } inputs.forEach(input => input.addEventListener('change', handleUpdate)); inputs.forEach(input => input.addEventListener('mousemove', handleUpdate)); The "Babel" compiled JavaScript var inputs = document.querySelectorAll('.controls input'); function handleUpdate() { var suffix = this.dataset.sizing || ''; document.documentElement.style.setProperty('--' + this.name, this.value + suffix); } inputs.forEach(function (input) { return input.addEventListener('change', handleUpdate); }); inputs.forEach(function (input) { return input.addEventListener('mousemove', handleUpdate); }); The Error inputs.forEach is not a function document.querySelectorAll does not return an array. It returns array-like DOM collection, which has no forEach.You can use Array.prototype.forEach.call(inputs, function(input) { ... });. Thank you Yeldar Kurmangaliyev this worked perfectly @YeldarKurmangaliyev See forEach method of Node.childNodes? I appreciate the resource, very helpful indeed. Use Array.from() to convert NodeList returned by Document.querySelectorAll() to Array. You can then use .forEach() chained to input at remainder of javascript. const inputs = Array.from(document.querySelectorAll('.controls input')); This worked well in Firefox thank you. However in Chrome (version 41.0.2272.89) I keep getting this error Unexpected token =>. The rest of my ES6 is working in Chrome but not "arrow functions". Why is this? @OldGill Why are you using chrome version 41? chrome stable is at version 55. Arrow functions are supported at chromium, chrome 45+. See Arrow functions I think its to do with my old operating system. I'm on OSX Lion 10.7.5 and my Chrome is up to date for this version. I have been reluctant to update my system after reading about serious performance issues updating older OSX to Yosemite. I'm not sure if the same issues exist with El Capitan or Sierra, I will have to do some reading on these. @OldGill See https://groups.google.com/a/chromium.org/forum/#!msg/chromium-discuss/0IAwnW-ysXs/kkUkizyGnVkJ , https://download-chromium.appspot.com/?platform=mac . The last link is a raw build of chromium. The availability of the raw build is down for *nix, though is apparently up for mac, as the site states "Updated 20 minutes ago". There are some procedures necessary to run the raw build, though possible. Have not tried OSX, not sure if additional measures need to be taken for osx. See https://chromium.googlesource.com/chromium/src/+/master/docs/linux_suid_sandbox_development.md @OldGill Note, chrome is a branded version of chromium build, and chrome has some caveats; e.g., tracking, etc. chromium is FOSS, chrome is not. See What's the difference between Google Chrome and/or Chromium? What are the advantages/disadvantages to each? I appreciate your help and resources, I will definitely look into this. First, two things to double check: Are you running this function before the DOM has finished parsing? If so, wrap this code in a DOMContentLoaded event listener, like this: document.addEventListener('DOMContentLoaded', function() { //code here }); Does your browser environment support the forEach method on DOM NodeLists. To check, console.log(NodeList.prototype.forEach); You should get something like: function forEach() { [native code] } if not, it's not supported, hence your error. To combat no support for NodeList.forEach, you can try this: var inputs = [].slice.call(document.querySelectorAll('.controls input')); This will now output an array of elements instead of a NodeList and give you access to the Array.prototype functions
common-pile/stackexchange_filtered
How to check user status on my app? In App Billing I´m implementing In app Billing on my app, which let the user go to a "premium version of the app". In the premium version of the app the user will be able to click 3 buttons and use their functions. But that is not the problem. The problem is how to check if the user has purchased the "premium version" yet and use all the app functions? This is my code: private void promptForUpgrade() { AlertDialog.Builder upgradeAlert = new AlertDialog.Builder(this); upgradeAlert.setTitle("Upgrade?"); upgradeAlert.setMessage("Do you want to upgrade to unlimited version?"); upgradeAlert.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //set progress dialog and start the in app purchase process upgradeDialog = ProgressDialog.show(selector.this, "Please wait", "Upgrade transaction in process", true); /* TODO: for security, generate your payload here for verification. See the comments on * verifyDeveloperPayload() for more info. Since this is a SAMPLE, we just use * an empty string, but on a production app you should carefully generate this. */ String payload =<EMAIL_ADDRESS> try { mHelper.launchPurchaseFlow(selector.this, SKU_PREMIUM, RC_REQUEST, mPurchaseFinishedListener, payload); } catch (IabHelper.IabAsyncInProgressException e) { e.printStackTrace(); } } }).setNegativeButton("Nop", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); upgradeAlert.show(); } and this is the OnIabPurchaseFinishedListener IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() { public void onIabPurchaseFinished(IabResult result, Purchase purchase) { // if we were disposed of in the meantime, quit. if (mHelper == null) return; if (result.isFailure()) { alert("Error purchasing: " + result); upgradeDialog.dismiss(); } else if (purchase.getSku().equals(SKU_PREMIUM)) { alert("Thank you for upgrade"); mIsPremium = true; setUserStatus(true); upgradeDialog.dismiss(); } } }; So basically I want to create a method which verify if the user is premium or not. Hope you can help me :D Within your onCreate method you should check the purchase status in your mHelper setup with an mHelper.queryInventoryAsync call. mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { public void onIabSetupFinished(IabResult result) { Log.d(TAG, "Setup finished."); if (!result.isSuccess()) { // Oh noes, there was a problem. complain("Problem setting up in-app billing: " + result); isBillingSupported = false; return; } // Hooray, IAB is fully set up. Now, let's get an inventory of stuff we own. Log.d(TAG, "Setup successful. Querying inventory."); mHelper.queryInventoryAsync(false, mGotInventoryListener); isBillingSupported = true; } }); mGotInventory I defined like this // Listener that's called when we finish querying the items we own IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() { public void onQueryInventoryFinished(IabResult result, Inventory inventory) { Log.d(TAG, "Query inventory finished."); if (result.isFailure()) { complain("Failed to query inventory: " + result); return; } Log.d(TAG, "Query inventory was successful."); // Do we have the premium upgrade? isPremium = inventory.hasPurchase(SKU_PREMIUM); Log.d(TAG, "User is " + (isPremium ? "PREMIUM" : "NOT PREMIUM")); updateUi(); Log.d(TAG, "Initial inventory query finished; enabling main UI."); } }; isPremium is a boolean flag defaulting to false. The updateUi method enables/disables buttons depending on the isPremium state. You will probably want to set isPremium and call updateUi on purchase completion as well to ensure the premium features are enabled immediately. Thanks for your answer, but i have a littl question yet. I want to unlock the three "premium buttons" when the pucharse has made, how can i do it? In my buttons mehod i have something like this if (!mIsPremium) { show a message dialog } else { the user can go to the premium button activity } Sorry for the questions but is the first time im implementing In App Billing on my apps: THansk Logic liked that should work. The onCreate will query the purchases and set the isPremium flag, you can then use it wherever you need to enable premium features. My updateUi method enables/disables buttons, sounds like you wouldn't need that, just check the flag directly on your button presses. You are already setting the flag on purchase successful in your existing code so next time the user pressed the button it should work. Also worth mentioning you must upload a version with in app purchase to the play store at least in alpha and setup your SKU within the play store dev console to get billing enabled. Glad to help. If my answer solved your problem then please mark it as accepted to help both our reputations. Thanks for this answer!! Also, if I'm making these purchases these with a test account, how do I reset/refund these purchases so I can test again?
common-pile/stackexchange_filtered
Problem with Copy Pasting Array Formula in VBA I am trying to put a vba formula which helps me find the median for a range of cells if these values pertain to a paricular category. Here is the sheet sample with data: This is the code i want to put in Cell B2 and then be able to drag it down till B7: =MEDIAN(IF(F2:F100=A2,G2:G100),"NA")) I have tried innumerable ways but can't find its solution. Thanks in advance for the help. Mayank Does this answer your question? Help needed with Median If in Excel If you're using VBA, can you [edit] your question with the code you've tried? your formula has too many ) should be =MEDIAN(IF(F2:F100=A2,G2:G100,"NA")) but the ,"NA" can also be removed. :=MEDIAN(IF(F2:F100=A2,G2:G100)) Where is the VBA in your post? Please show one or some of your innumerable ways you tried and specific issues (errors/undesired results) that occur. For Vba try FormulaArray property. Sheet1.Range("B2").FormulaArray = "=MEDIAN(IF(I:I=A2,J:J))" Sheet1.Range("B2").Copy Sheet1.Range("B3:B4").PasteSpecial Paste:=xlPasteFormulas
common-pile/stackexchange_filtered
react-router-dom match object isExact false I am working on a react project. I try to access the url parameters in the Header component. However, it always returns empty. import React from 'react'; import { Route, Switch } from 'react-router-dom'; import { ConnectedRouter } from 'connected-react-router' import SamplePage from './pages/SamplePage'; import PropertyPage from './pages/PropertyPage'; import LoadingPage from './pages/LoadingPage'; import Header from './header/Header'; import ButtonGroup from './ButtonGroup'; import { Container } from 'semantic-ui-react'; import history from '../history'; const App = () => { return ( <ConnectedRouter history={history}> <div> <Switch> <Route path='/loading' exact component={LoadingPage} /> <Route component={Header} title='Sample page' /> </Switch> <Container style={{ marginTop: '7em' }}> <Switch> <Route path='/page/:pageType/properties/:propertyId' exact component={PropertyPage} /> <Route path='/page/:pageType' exact component={SamplePage} /> </Switch> </Container> <Switch> <Route exact path='/loading' render={() => <div />} /> <Route component={ButtonGroup} /> </Switch> </div> </ConnectedRouter> ); } export default App; I try to access url params in the Header component. The params is empty, and isExact is false. Can anyone help me with this? Thanks. Are you on a url matching path /scorecard/:scorecardType/properties/:propertyId? @OluwafemiSule. Yes, I am. You can see that my pathname under location object. I still cannot figure out how to solve this issue. What I do to walk around this issue is to create a Higher Order Component. Header will be included in the HOC, then it has no problem to get the URL parameters. From screenshot of console.log, react-router is matching on <Route component={Header} title='Sample Scorecard' /> This is correct behavior as Switch looks for the first match. I suggest to not declare rendering for Header as a Route. i.e. <Switch> <Route path='/loading' exact component={LoadingPage} /> <Header title='Sample Scorecard' /> </Switch> This way Switch will only render it when loading path isn't matched. Thanks for your suggestions. I have updated it, but it does not affect the match.params. I still get empty. The pathname in the console.log is /scorecard/SME. That should match the route for the sample page. What is the pathname under the location object Yes. The location is correct. But the params under the match object is empty, and match['path'] is '/'. I'm not sure why match path is '/' if you're on the right location. I have tried to replicate your route setup but nothing jumps at me why you're getting a different result. https://stackblitz.com/edit/react-redux-registration-login-example-2mcghy If my console.log is under SamplePage.js, everything is also good. This only happens when I use it under the Header component.
common-pile/stackexchange_filtered
Add delay constructing a Future Playing with Dart, is it possible to create a delay constructing a Future?: Future<String>.value("Hello").then((newsDigest) { print(newsDigest); }) // .delayed(Duration(seconds: 5)) Yes, this is possible: factory Future.delayed(Duration duration, [FutureOr<T> computation()]) { _Future<T> result = new _Future<T>(); new Timer(duration, () { try { result._complete(computation?.call()); } catch (e, s) { _completeWithErrorCallback(result, e, s); } }); return result; } As you have already discovered Future.delayed constructor creates a future that runs after a delay: From the docs: Future<T>.delayed( Duration duration, [ FutureOr<T> computation() ]) The computation will be executed after the given duration has passed, and the future is completed with the result of the computation. If computation returns a future, the future returned by this constructor will complete with the value or error of that future. For the sake of simplicity, taking a future that complete immediately with a value, this snippet creates a delayed future that complete after 3 seconds: import 'dart:async'; main() { var future = Future<String>.value("Hello"); var delayedFuture = Future.delayed(Duration(seconds: 3), () => future); delayedFuture.then((value) { print("Done: $value"); }); }
common-pile/stackexchange_filtered
How can I perform a case-insensitive filter on a JTable? I am making a table with a text field below it where you can type in a word to filter the table. It works, but what I want to do is be able to filter it with the word typed in, but ignoring the case of the word. Is there a way to accomplish this without creating a custom RowFilter? You can run this SCCEE to see what I'm talking about. I want to be able to type in usa and it'll filter USA. import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.RowFilter; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; public class TestTableSortFilter extends JApplet { private String[] columnNames = {"Country", "Capital", "Population in Millions", "Democracy"}; private Object[][] data = { {"USA", "Washington DC", 280, true}, {"Canada", "Ottawa", 32, true}, {"United Kingdom", "London", 60, true}, {"Germany", "Berlin", 83, true}, {"France", "Paris", 60, true}, {"Norway", "Oslo", 4.5, true}, {"India", "New Delhi", 1046, true} }; private JTable jTable = new JTable(data, columnNames); private TableRowSorter<TableModel> rowSorter = new TableRowSorter<>(jTable.getModel()); private JTextField jtfFilter = new JTextField(); private JButton jbtFilter = new JButton("Filter"); public TestTableSortFilter() { jTable.setRowSorter(rowSorter); JPanel panel = new JPanel(new BorderLayout()); panel.add(new JLabel("Specify a word to match:"), BorderLayout.WEST); panel.add(jtfFilter, BorderLayout.CENTER); add(panel, BorderLayout.SOUTH); add(new JScrollPane(jTable), BorderLayout.CENTER); jtfFilter.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { String text = jtfFilter.getText(); if (text.trim().length() == 0) { rowSorter.setRowFilter(null); } else { rowSorter.setRowFilter(RowFilter.regexFilter(text)); } } }); } } Is there maybe something I can pass to the regexFilter(text), that will give me the desired result? rowSorter.setRowFilter(RowFilter.regexFilter(text)); Add the standard regex case-insensitivity flag: rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text)); I've tested this with your SSCCE (thanks for providing that) and it works. rowSorter.setStringConverter(new TableStringConverter() { @Override public String toString(TableModel model, int row, int column) { return model.getValueAt(row, column).toString().toLowerCase(); } }); rowSorter.setRowFilter(RowFilter.regexFilter(jtfFilter.getText().toLowerCase())); a brief explanation will make your answer better..!! This actually was the only working answer, since I had complex objects with strings inside them! Thanks.
common-pile/stackexchange_filtered
Security difference between webmail access and desktop email client? Is there a difference in privacy and security between webmail access and desktop email clients? Is one inherently more secure than the other? Is it more secure to use an email service that does not offer webmail, but only access via IMAP, POP, SMTP in a desktop email client? Let us consider that both are using equal encryption techniques, ie TLS for the connection between server and client. Interesting question. I have always believed that to be true in the single situation of the e-mail being provided by the ISP itself. The path to aquiring the e-mail on my side is from the ISPs own server. Then they added the ability to aquire that over the web anyways. It still will have gone through many servers to get from the sender to my ISPs mail server. Next would be which one makes it easier to break into? which one would allow for 10,000 passwords to be tossed at it, and how quickly. (reguardless of software used to do that) Access to, hackability, and any password storage methods Next aspect of web based e-mail "clients", can a single log-in/password aquire multiple account information access. In the case of some web based client software, a single log-in provides access to multiple items. Once one gets cracked, the rest of it has been opened up. Security of a local mail client is much more dependent on the physical security of the device than a webmail client is. Local clients tend to have mail passwords saved, whereas it's possible, but less common for webmail clients. Not only does this saved password allow access to mail if you can access the users account, but you hope this password is stored securely. You would also have mail files stored on the machine. There may be sensitive data embedded in the mail files. These would need to be secured for the user only. I forgot that I had loaded Thunderbird on my laptop, and when I reinstalled it 2 years later, it found my old mail. Webmail apps have issue with saved files as well, though proper HTTP caching directives, and the ability to wipe out cache, or with private browsing, mitigates most of this. Good point, where is the data. When it comes to locally being screwed by a password seeking virus, they can be either, the keylogger style or the grab the info right off the computer itself. I wonder which is a more popular virus method, I assume getting it right off the computer is fastest. When it comes to Local Walk-up security , that doesnt exist. When it does, I will be locked out of changing my own computer ;-( so badly, that I wouldnt like it anyway. When it comes to where is my e-mail data, I always percieved that my Web e-mail is out there "on the web" instead of removed from A server and only now local on my computer. Which brings up the complications of backups and redundancy , and archiving at any one of the locations. The security of the email would largely depends on the security of the physical server storage, and not so much on the client access mode (web or imap, etc). The connection mode does little for the overall security as most breaches take place on the server side (probably close to 99%), and not while email is in transit. For any meaningful security you additionally need to use encryption for email storage. The best would be to have each message encrypted on the client side with its own set of keys, with private key never leaving sender's computer in plain form. There are several solutions that provide such strong security. I would look into pgp email solutions or http://cryptoheaven.com However, a solution with connection layer security such as Pop3S / Imap SSL / SMTP TLS for the client connections does provide appearance of security for an average consumer, but offers not much real protection indeed. Accessing email via unencrypted protocols such as HTTP, Pop3, Smtp or Imap are equaly "unsafe" (e.g. any intermediate router between your PC and the final destination may read your data in clear...) Accessing email with HttpS is a good solution. (like with Gmail for example). With an email client such as Thunderbird the access to a mail service via protocols like Pop3S or Imap SSL and SMTP TLS are also secured (encrypted between your PC to the destination). For sure, a safest way is to encrypt the mail itself with GnuPG for example. Even using an unencrypted protocol such as Pop3 nobodies except you and the person you emailed with PGP or GnuPG may read the content of the mail. To make a long story short: easiest way: use email services with Pop3S or Imap SSL and SMTP TLS second choice if your email provider do not use encrypted protocol:encrypt your mail with GnuPG "Parano" way: do both! ;)
common-pile/stackexchange_filtered
According to the Catholic Church, what marks a document as Scripture? Not much to ask beyond the title, but the thing I'm trying to get at here is how the Church determines what is and isn't scripture. Does the church have markers they try to follow? The Canon of Holy Scripture was infallibly fixed by the authority of the Council of Trent, 4th session. As Schroeder, O.P., states in his edition of Trent's decrees (4th sess. fn. 4): For earlier lists, cf. Synod of Laodicea (end of IV cent.), c.60, the genuineness of which canon however is contested (Hefele-Leclercq, Hist. des conciles, I, 1026); Synod of Rome (382) under Pope Damasus (Denzinger, Enchiridion, no. 84); Synod of Hippo (393), c.36, which the III Synod of Carthage (397) made its own in c.47 (idem, no. 92); Innocent I in 405 to Exuperius, bishop of Toulouse (idem, no. 96); Eugene IV in the Council of Florence (Mansi, XXXI, 1736; Hardouin, IX, 1023f.). The Tridentine list or decree was the first infallible and effectually promulgated declaration on the Canon of the Holy Scriptures. St. Robert Bellarmine—Book II, ch. XII of On Councils: Their Nature and Authority (from his De Controversiis)—refutes the Protestants' straw-man argument of Catholics: Catholics do not subject the Sacred Scripture to Councils, but places it before them; nor is there any controversy on this point. But if some Catholics sometimes say scripture depends upon the Church, or a Council, they do not understand this in regard to its authority, or according to what it is, but in regard to the explanation and in regard to us. I could have sworn I'd answered a similar question sometime in the last 10 years, but alas I cannot find it. Anyway, the good Reverend Know-It-All writes: Pope Damasus I, St. Jerome’s patron, assembled the first list of books of the Bible at the Council of Rome (382AD). The process continued in North Africa. A series of Synods (meetings of bishops) were held in North Africa beginning in Hippo in 393, and ending with the Council of Carthage(419). The meetings took up the question of what were the inspired books and what were not. There was a basic agreement on the texts, but even then, 400 years after Christ, there was still a need to make a definitive list. The pope and the North African bishops drew up their list from those books then in use by the Church, particularly those read at Mass. Finally, the list was submitted to Pope Boniface (Damasus’ successor) and the other bishops for confirmation https://stlambert.org/news/rkias-guide-to-reading-the-bible-part-11 In a nutshell is how the Catholic Church figured out what scripture is and what it isn't. It's a little known doctrine in the Catholic Church called, "whatever Christians in general have been doing is probably the right thing to do because God hasn't struck us all dead for doing it so far so lets keep doing it and it's probably the right thing to do." otherwise known as infallibilitas in credendo. The Bible (i.e. the canon of scripture) is the product of the Church. There doesn't need to be a formula (i.e. if it needs to mention God 30 times). If there were a formula, there's honestly no reason the Didache isn't added to the Bible. The Bible is basically a meme that God and the Church get. Great way to explain an unknown! I would have sworn I answered the same question 10 years ago, but alas I cannot find it that makes it sound like you want to close my question
common-pile/stackexchange_filtered