text
stringlengths
15
59.8k
meta
dict
Q: Add URL to entire photo I am using a plugin called Distinctive Portfolio on my Wordpress site. On this page, when you hover over a photo, I simply want to get rid of the tooltip (which is garbled), icon (which is supposed to be a link image but doesn't appear) and make the entire photo clickable. Image of what currently happens when I hover over the photo is below. Am hoping for a CSS solution but if not I can go into the plugin and play around. Please help, thanks! A: Add display:none; to the class .dtp-icon-wrapper .dtp-icon-wrapper { width: 40px; height: 40px; background: hsl(0, 100%, 100%); border-radius: 50%; margin: 0 auto; display: inline-block; position: relative; top: -60px; margin-top: -10px; display: none; } Works fine , the icon does't show anymore. To make the whole image clickable(and if your in control of the HTML) , wrap the following element: <div class="view"> </div> inside a <a> tag.
{ "language": "en", "url": "https://stackoverflow.com/questions/31895309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python dictionaries, key existence with fallback Is there any difference, gotcha or disadvantage between these approaches? foo = dict(key=u"") bar = foo.get('key', 'foobar') vs foo = dict(key=u"") bar = bool(foo['key']) or 'foobar' A: The first piece of code tries to get a value from foo associated with key, and if foo does not have the key key, defaults to foobar. So there are two cases here: * *foo has the key key, so bar is set to foo[key] *foo does not have the key key, so bar is set to "foobar" The second looks at the value associated with the key key in foo, and if that value is falsy (that is, if bool(foo[key])==False), it defaults to foobar. If foo does not have the key key it raises a KeyError. So there are three cases here: * *foo has the key key, and bool(foo[key])==True, so bar is set to True *foo has the key key, and bool(foo[key])==False, so bar is set to "foobar" *foo does not have the key key, so the code raises a KeyError A: The 2nd example will raise KeyError if foo['key'] doesn't exist. If you want to assign a default value to bar if foo['key'] doesn't exist or contains falsey value, this would be the Pythonic way to do it: bar = foo.get('key') or 'foobar' A: Yes: foo.get('key', 'foobar') always returns something (if there is a key names 'key' it will return its value, and if there is no such key it will return 'foobar'). but bool(foo['key']) or 'foobar' can raise a KeyError if there is no such key named 'key'. Furthermore - the use of or here is not indicative, so the get method is preferable. A: You should most definitely not use the second form, because it will throw a KeyError if the key does not exist your dictionary. You're only getting acceptable behavior out of the second form because the key was set. A: This is the problem with using bool() one = {"my_key": None} print "Get:", one.get("my_key") print "Bool:", bool(one.get("my_key")) print "Get with falback:", one.get("my_key", "other") Get: None Bool: False Get with falback: None Note that there is a value in there, None, but bool evaluates to false. You should use get("key", "default"), it's designed to do the job. A: If you think foo = dict(key=u"") will produce a dictionary wich default value is an empty string, you are mistaken. You'll need a defaultdict for that: In [6]: bool(foo['key']) or 'foobar' Out[6]: 'foobar' In [7]: foo = dict(key='') In [9]: bool(foo['nokey']) or 'foobar' KeyError: 'nokey' Either use defaultdict, or dict.get, or even dict.setdefault. The good all way works too: In [10]: try: ....: v = foo['nokey'] ....: except KeyError: ....: v = 'foobar' ....: In [11]: v Out[11]: 'foobar'
{ "language": "en", "url": "https://stackoverflow.com/questions/11971752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: dotnet5 MVC Giving POST Data to API does not work I have done an udemy Tutorial for MVC in dotnet5 and try to implement my own project on this base. I have built a form with a body like this: <form id="genreForm" autocomplete="off" novalidate="novalidate"> <div class=""> Genre &nbsp; </div> <div class="container closed">lorem Ipsum</div> <div> <input type="text" id="newGenreName" /> <input type="text" id="newGenreDescription" /> <button type="button" id="btnSubmit" class="btn btn-success" onclick="onGenreAddForm();">Genre hinzufügen</button> </div> </form> And an ajax request like this: function onGenreAddForm() { var requestData = { GenreName: $("#newGenreName").val(), GenreDescription: $("#newGenreDescription").val() }; $.ajax({ url: routeURL + '/api/Event/AddUpdateGenre', type: 'POST', data: JSON.stringify(requestData), contentType: 'application/json', success: function (response) { }, error: function (xhr) { $.notify("Error", "error"); } }); } which routes to an API Controler looking like this: [HttpPost] [Route("AddUpdateGenre")] public IActionResult AddUpdateGenre(ManagementVM data) { doSthWithData(data); } while the ManagementVM has members like public string GenreName { get; set; } public string GenreDescription { get; set; } Now, when i fire the button, the js fills the requestData with the right values an the right keys, but when i inspect ManagementVM data in the APIController, it is filled with nulls. Can anyone tell me, where is my fault? I followed the same steps described in the tutorial. Thanks a lot! A: solved by adding [FromBody] to the Param in API: public IActionResult AddUpdateGenre([FromBody] ManagementVM data)
{ "language": "en", "url": "https://stackoverflow.com/questions/69973553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove decimal Java variable I have a Spring Boot method in which I have a variable to calculate the vacation days (VACATION_DAYS_GEN_DAILY), the problem is that when I show them in the front it jumps with all the decimals. I need to know how I can remove those tell them. private static final double VACATION_DAYS_GEN_DAILY = 22.0 * 4 / (365 * 4 + 1); public EmployeeDashboardDto getEmployeeDashboardYearDto(Integer year, Integer employeeId) throws QOException { LocalDate fromDate = LocalDate.of(year, 1, 1); LocalDate toDate = LocalDate.of(year, 12, 31); double leftVacationDays; double vacationsPerWorkedDays = 0; int pastVacations = 0; EmployeeView emp = employeeService.getById(employeeId).getBean(); if (fromDate.isBefore(toDate)) { vacationsPerWorkedDays = (ChronoUnit.DAYS.between(fromDate, toDate) - AbsenceDays + 1) * VACATION_DAYS_GEN_DAILY; } leftVacationDays = emp.getCummulatedVacationDays() + vacationsPerWorkedDays; employeeDashboardDto.setLeftVacationDays(leftVacationDays); return employeeDashboardDto; } A: This link maybe helpful or you can use this: double roundOff = Math.round(VACATION_DAYS_GEN_DAILY * 100.0) / 100.0; the output: 21.98
{ "language": "en", "url": "https://stackoverflow.com/questions/66125759", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How many unique IDs can MongoDB generate? I am currently worried and confused about how the MongoDB's unique ids work and what are the limitations of this. Is the MongoDB's way of generating IDs is safe for generating millions or even billions of unique ids? And is there a possible scenario that the uid could be duplicated (if the limit is reached)? A: The short answer to your first question is YES. MongoDB uses ObjectID to generate the unique identifier that is assigned to the _id field. ObjectID is a 96-bit number Use ObjectID as a unique identifier at mongodb site Doing math with this, we could have 2^96 or 7.9228163e+28 unique id. Secondly, the answer to your second question is YES too! The scenario that comes here is when you had used all 2^96 unique ids that mongo gave you. If you going to build a super big application that literary exceeds the limit. You could set the _id on your own. Mongo would notice you whether if _id set is duplicated.
{ "language": "en", "url": "https://stackoverflow.com/questions/73436000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Button does not respond in the media query I have got a button that redirects you to a hype-link i have tried so hard to debug but i don't seem to find the bugs.It works fine on the full size screen but it is not clickable on the media query i applied. 1. First i tried to comment out the hamburg menu because i copied it from some video then but it didn't seem to be the problem. 2. Then i tried to change from max-width to min-width it also didn't work. 3. I also tried using the z-index on the button hoping it gets on the front but also didn't work. Checkout the entire website at https://spectrumsdl.com . Nothing seems clickable when in the media query view port. @media(max-width:650px) { * { padding: 0; margin: 0; box-sizing: border-box; text-decoration: none; font-family: monospace; font-size: 12px; font-family: mon reg; transition: ease-in-out .8s; } .container { width: 100%; height: 100vh; /* background:wheat; */ } .nav { width: 100%; height: 100vh; /* background-color: white; */ top: -900px; position: fixed; display: flex; flex-direction: column; justify-content: center; align-items: center; transition: top 0.8s cubic-bezier(1, 0, 0, 1); } .right { height: auto; width: 100%; align-items: center; display: flex; flex-direction: column; } .nav ul { display: flex; flex-direction: column; list-style-type: none; justify-content: center; align-items: center; } .nav ul li :hover { box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2); border-radius: 3px; transition: .3s; color: var(--textColorSecondary); } li a { display: block; padding: 14px 14px; text-decoration: none; color: var(--textColorMain); } #nav-btn { display: block; color: var(--bottonColor); background-color: white; box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2); height: 2.5em; align-items: center; margin-bottom: 2em; } #nav-btn:hover { color: var(--mainColor); background-color: var(--bottonColor); box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2); transition: .5s; } .change { top: 0; } .hamburger-menu { width: 100%; height: 30px; display: flex; position: fixed; scroll-behavior: none; margin-top: 2em; top: 1em; right: 1em; cursor: pointer; /* background-color: white; */ align-items: flex-end; flex-direction: column; justify-content: space-around; } .nav-item { list-style: none; margin: 25px; text-decoration: none; } .line { width: 35px; /* width: 100%; */ height: 4px; background-color: var(--bottonColor); transition: all 0.8s; } .change .line-1 { transform: rotateZ(-405deg) translate(-8px, 6px); } .change .line-2 { opacity: 0; } .change .line-3 { transform: rotateZ(405deg) translate(-8px, -6px); } /* main-cnt */ /* body{ background-image: linear-gradient(to right ,rgb(96,45,145),rgb(96,45,145, 0.1) ), url("../media/background.jpg"); background-size: cover; background-position:center; background-repeat: no-repeat; background-attachment: fixed; } */ main { display: block; padding: 9em 4em; height: } .main-cnt { display: flex; flex-direction: column; width: 100%; } #bookNowBtn { float: right; padding-top: 10em; display: flex; flex-direction: column; align-items: flex-end; } #bookNowBtn button { font-size: 12px; font-weight: 900; font-family: mon semibold; /* float: right;; */ box-shadow: 1px 1px 1px rgb(255, 255, 255); } #bookNowBtn button:hover { box-shadow: 2px 2px 2px 2px rgba(255, 255, 255, 0.63); transition: .1s; } #mainText { display: flex; flex-direction: column; /* padding-top: 7em; */ color: white; } #mainText h2 { display: flex; font-size: 18px; /* line-height: 1em; */ font-family: mon semibold; } #mainText h2 span { color: var(--bottonColor); font-size: 18px; font-family: mon semibold; } #mainText p { font-size: 15px; margin-top: 1em; } <header> <div class="container"> <div class="nav navbar"> <div class="hamburger-menu"> <div class="line line-1"></div> <div class="line line-2"></div> <div class="line line-3"></div> </div> <div class="sdlLogo" "> <a href="/"> <img src="sdl_logo.svg" alt="sdl_logo" height="75px " width="150px "></a> </div> <div class="right "> <ul> <li class="nav-item active "><a href="/ ">Home</a></li> <li class="nav-item "><a href="about.php ">About</a></li> <li class="nav-item "><a href="service.php ">Services</a></li> <li class="nav-item "><a href="article.php ">Articles</a></li> </ul> <div> <a href="contact.php "> <button class="btn " id="nav-btn ">Contact Us</button></a> </div> </div> </div> </div> </header> <!-- main --> <main> <div id="mainText " class="main-cnt "> <h2> Spectrum <span>Diagnostic</span> Laboratories </h2> <p> Quality results for Quality patient care. </p> </div> <a href="service.php#Mailing " id="bookNowBtn " class="main-cnt "> <button class="btn " type="submit ">Book Now!</button> </a> </main> A: By looking at the site that you have provided, There is container class in media query that has the height: 100vh; property, which is causing this issue. .container { width: 100%; height: 100vh; /* background:wheat; */ } Either remove that class from media query or change to .container { width: 100%; } This will solve your problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/65609716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unrecognized element exceptions after conversion to web application After converting my Web Site Project to a Web Application Project, some of my custom controls are missing, and I keep getting an get unrecognized element exceptions. I can't figure out what's going on. I've tried copying over the web.config and registering the controls in the page directive, but it's still not working. Do I need to adjust the web.config manually, or is it possible that I'm still missing a reference somewhere? I would appreciate some advice on how to fix this. A: It most likely has something to do with the conversion, and I suspect the application namespace. I don't know how thorough the conversion process is, but you might need to update the user control directives and code-behind files. <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MyUserControl.ascx.cs" Inherits="MyNamespace.MyApplication.Controls.MyUserControl" %> Code-behind: namespace MyNamespace.MyApplication.Controls { public partial class MyUserControl : UserControl { ... } } Also, make sure that the user controls are mapped properly in the web.config: <pages> <controls> <add tagPrefix="Custom" src="~/controls/myusercontrol.ascx" tagName="MyUserControl" /> ... </controls> </pages>
{ "language": "en", "url": "https://stackoverflow.com/questions/10456321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: FFMPEG - RTSP: where does sprop-parameter-sets come from? I'm encoding .mp4 video files (h265) with ffmpeg to create RTSP stream, put it to rtsp-simple-server and then after aler9's restreamer the stream is available to watch. I can watch the result in VLC (adding network source rtsp://my.server/stream), but can't watch the stream in Android application - no sprop-parameter-sets headers exist So, the question is: where can I get these headers and how can I add them to the stream, so that everything worked? P.S. if I add the stream to Wowza, these headers (sprop-vps, sprop-sps, sprop-pps) are added by Wowza to the stream, but I need to use the server directly. A: OK, found an answer: '-bsf:v', 'dump_extra'
{ "language": "en", "url": "https://stackoverflow.com/questions/73631222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Unauthorized when calling Google GCM I trying to use Google GCM for sending push notifications. But get a WebException that says that the remote server returns 401 unautorized. I can't foung why it doen't work. Anyone that knows why it doesn't work? Here is my code: ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate); HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send"); Request.Method = "POST"; Request.KeepAlive = false; string postData = "{ 'registration_ids': [ '"+registrationId+"' ], 'data': {'message': '"+message+"'}}"; byte[] byteArray = Encoding.UTF8.GetBytes(postData); Request.ContentType = "application/json"; //Request.ContentLength = byteArray.Length; //Request.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + AuthString); Request.Headers.Add(HttpRequestHeader.Authorization, "Authorization: key=AIzaSyCEygavdzrNM3pWNPtvaJXpvW66CKnjH_Y"); //-- Delegate Modeling to Validate Server Certificate --// //-- Create Stream to Write Byte Array --// Stream dataStream = Request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); //-- Post a Message --// WebResponse Response = Request.GetResponse(); HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode; if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden)) { var text = "Unauthorized - need new token"; } else if (!ResponseCode.Equals(HttpStatusCode.OK)) { var text = "Response from web service isn't OK"; } StreamReader Reader = new StreamReader(Response.GetResponseStream()); string responseLine = Reader.ReadLine(); Reader.Close(); A: Daniel - Dude there is an issue with the GCM documentation ! Use Browser key as the authorization key at the place of Server API key . It will work. A: OK, i am just shooting in the dark here. Take a look at this line: Request.Headers.Add(HttpRequestHeader.Authorization, "Authorization: key=AIzaSyCEygavdzrNM3pWNPtvaJXpvW66CKnjH_Y"); Shouldn't it be: Request.Headers.Add(HttpRequestHeader.Authorization, "key=AIzaSyCEygavdzrNM3pWNPtvaJXpvW66CKnjH_Y"); Since you're telling it this is a Authorization header, there's no need to add 'Authorization: ' again, does it? Also, make sure the string constant 'HttpRequestHeader.Authorization' is 'Authorization'.
{ "language": "en", "url": "https://stackoverflow.com/questions/11431261", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Chrome Extension run JavaScript on newtab I have a Chrome Extention I am working on that replaces the Google logo. I have successfully changed it on the main pages, but have noticed that the regular logo is still displayed in the newtab window. I need to find a way to execute some JavaScript to replace the source of that Google logo to the new one. Here is some of the code I am using. Here is the Manifest.json { "update_url": "https://clients2.google.com/service/update2/crx", "manifest_version": 2, "name": "glogochange", "description": "blabla", "version": "1.0", "content_scripts": [ { "run_at": "document_start", "matches": [ "https://*.google.com/*" ], "css": [ "style.css" ], "js": [ "script.js" ] } ], "web_accessible_resources": [ "newlogo.png" ] } And Here is the JavaScript function DoIT() { var domain, path, button, logo, ilogo, text, logourl; domain = window.location.host; path = window.location.pathname; logo = document.getElementById("hplogo"); ilogo = '//*[@id="logo"]/img'; logourl = chrome.runtime.getURL("newlogo.png"); button = '//*[@id="tsf"]/div[2]/div[3]/center/input[1]'; text = "cool Search"; if(domain == "www.google.com" && path == "/") { XPath(button).value = text; logo.srcset = logourl; logo.width = 292.5; logo.height = 133.5; logo.style.display = "block"; } else if(domain == "www.google.com" && path == "/search") { XPath(ilogo).width = 120; XPath(ilogo).height = 54; XPath(ilogo).srcset = logourl; XPath(ilogo).style.display = "block"; } else if(domain == "www.google.com" && path == "/webhp") { XPath(button).value = text; logo.width = 292.5; logo.height = 133.5; logo.srcset = logourl; logo.style.display = "block"; } } I tried changing the manifest including: "permissions": [ "https://*/*", "http://*/*", "tabs" ] And could not get it to 'inject' on the newtab screen. Can someone please help we out with this?
{ "language": "en", "url": "https://stackoverflow.com/questions/48123475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Delete all Macros/vba when save as xls workbook I am using a procedure that creates a file and copies my workbook (xlsm) and saves as a xls workbook to the created file, and this is working well. I need to remove all Macros and vba when the save as is exacuted, i.e I need to remove the Macros/vba from the workbook being saved NOT the original workbook. I know I could save it as a xlsx workbook to remove all Macros and vba but I need the workbook to be a Macro/vba free xls workbook. I have Google'ed but did not find anything I could use, will continue to look and post back if I get this figured out. A: I found this here: http://enholm.net/index.php/blog/vba-code-to-transfer-excel-2007-xlsx-books-to-2003-xls-format/ It searches through a dirictory looking for xlsx files and changes them to xls files I think though it can be changed to look for xlsm files and change them to xls files as well. When I run it I get: Run-Time error '9' Subscript out of range Debug Sheets("List").Cells(r, 1) = Coll_Docs(i) is highlighted in yellow I do not know enough about vba to figure out what is not working. Thanks Sub SearchAndChange() Dim Coll_Docs As New Collection Dim Search_path, Search_Filter, Search_Fullname As String Dim DocName As String Application.DisplayAlerts = False Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim i As Long Search_path = ThisWorkbook.Path & "\360 Compiled Repository\May_2013" Search_Filter = "*.xlsx" Set Coll_Docs = Nothing DocName = dir(Search_path & "\" & Search_Filter) Do Until DocName = "" Coll_Docs.Add Item:=DocName DocName = dir Loop r = 1 For i = Coll_Docs.Count To 1 Step -1 Search_Fullname = Search_path & "\" & Coll_Docs(i) Sheets("List").Cells(r, 1) = Coll_Docs(i) Call changeFormats(Search_path, Coll_Docs(i)) r = r + 1 Next Application.DisplayAlerts = True Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic End Sub '************************************************************** '* Changes format from excel 2007 to 2003 '*************************************************************** Sub changeFormats(ByVal dir As String, ByVal fileName As String) Workbooks.Open fileName:=dir & fileName ActiveWorkbook.SaveAs fileName:=dir & Replace(fileName, "xlsx", "xls"), FileFormat:=xlExcel8 ActiveWindow.Close End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/16398441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: it keeps saying my variable inside the function is not defined can someone help me with this def draw_card(): randomrd_drawn_int = random.randint(1,20) if card_drawn_int == [1,2,3,4,5,6,7,8,9,10,11,12]: card_drawn = ['Mechanized Infantry'] elif card_drawn_int == [13,14,15,16,17]: card_drawn = ['STRV 122'] elif card_drawn_int == [18,19,20]: card_drawn = ['JAS 37'] return card_drawn print(card_drawn) here is the syntax error by the way NameError: Traceback (most recent call last) Input In [15], in <cell line: 1>() ----> 1 print(card_drawn) NameError: name 'card_drawn' is not defined A: card_drawn is defined inside the function draw_card inside if cases. def draw_card(): randomrd_drawn_int = random.randint(1,20) card_drawn = None if card_drawn_int == [1,2,3,4,5,6,7,8,9,10,11,12]: card_drawn = ['Mechanized Infantry'] elif card_drawn_int == [13,14,15,16,17]: card_drawn = ['STRV 122'] elif card_drawn_int == [18,19,20]: card_drawn = ['JAS 37'] print(card_drawn) return card_drawn I have rewritten the function so it works. You need to learn about the scope in Python : https://www.w3schools.com/PYTHON/python_scope.asp
{ "language": "en", "url": "https://stackoverflow.com/questions/73534082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use Asp:Gridview As Data Entry Is it possible to use an asp:gridview for data entry when the grid has no data source....then when a user clicks the submit button the data gets bound to a data table? I tried to open this project - but it fails every time. Maybe because lowest version of VS I have is 2017? https://www.codeproject.com/Articles/8301/How-to-convert-DataGrid-into-Data-Entry-Form
{ "language": "en", "url": "https://stackoverflow.com/questions/48553268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How RowMapper can be an Anonymous Class I was reading through Spring in Action and found something like this could anyone explain how we have used RowMapper as an Anonymous class if it is an Interface as per RowMapper documentation. public Employee getEmployeeById(long id) { return jdbcTemplate.queryForObject( "select id, firstname, lastname, salary " + "from employee where id=?", new RowMapper<Employee>() { public Employee mapRow(ResultSet rs, int rowNum) throws SQLException { Employee employee = new Employee(); employee.setId(rs.getLong("id")); employee.setFirstName(rs.getString("firstname")); employee.setLastName(rs.getString("lastname")); employee.setSalary(rs.getBigDecimal("salary")); return employee; } }, id); } A: Anonymous class new Something() {...} is not an instance of Something. Instead, it's a subclass/implementation of Something. And so, it's perfectly valid and useful to derive anonymous classes from interfaces. A: Anonymous class are not instance of a class but just another way to define a class, something similar to a nested class, but less reusable since it's method related. Since you can define class that implements interfaces public A implements B { } and you can reference the instance of that class, declaring as an interface B b = new A(); you can do it also with anonymous class. The only thing to do and to remember (for this exist the compiler), is that you have to implements all method defined in the interface itself. That solution, is a more concise way to do this: public EmployeeController { public Employee getEmployeeById(long id) { return jdbcTemplate.queryForObject( "select id, firstname, lastname, salary " + "from employee where id=?", new CustomRowMapper(), id); } class CustomRowMapper implements RowMapper<Employee>() { public Employee mapRow(ResultSet rs, int rowNum) throws SQLException { Employee employee = new Employee(); employee.setId(rs.getLong("id")); employee.setFirstName(rs.getString("firstname")); employee.setLastName(rs.getString("lastname")); employee.setSalary(rs.getBigDecimal("salary")); return employee; } } } A: The syntax new SomeInterface() { // Definition for abstract methods } defines an anonymous class. As long as all methods specified in the interface are defined within the braces, this is a valid class which implements the given interface. Note that this expression defines an anonymous class implicitly and an instance of that class.
{ "language": "en", "url": "https://stackoverflow.com/questions/18534021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: DataGridView: Override Scrollbar Style Im using WinForms and the DataGridView. Is there a way to Style for the Scrollbars to a custom color/appearance. I have been looking for a Flat appearance.
{ "language": "en", "url": "https://stackoverflow.com/questions/13345268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I clear an "if" condition I'm trying to figure out how to clear an "if" condition and how to fix the result = print(x) part of my code. I'm trying to create a little search code based on the variable data, but I can't figure a few things out: import time def start(): data = ["Lucas_Miguel", "João_Batista", "Rafael_Gomes", "Bruna_Santos", "Lucas_Denilson"] print("1" + " - Check Name") print("2" + " - Register a New Name") option = input("Choose an option: ") if option == "1": def other(): name = input("Type the first name: ") for x in data: if name in x: result = print(x) while True: print("Yes " "or " "No") confirm = input("Is the name you want in the options?: ") if confirm == "Yes": break if confirm == "No": print("Yes", " or", " No") try_again = input("Do you want to write again?: ") if try_again == "Yes": return other() other() else: print("Option not available") time.sleep(1) return start() start() The first problem is in the result = print(x) part. It works, but when the answer is more than one name, only the first one appear and I don't know how to fix it. The second problem is in the "confirm = input" part. Basically, if the person answered with "No", when they go back, the answer will still be saved and the input will run twice, the first time with the saved answer and the second with the new answer. So I want to be able to clear that before the person answer it again. I want to apologize already if the code is ugly or weird, but I started a few days ago, so I'm still learning the basics. Also thanks in advance for the help. A: There is quite a bit here to unpack and like the comment on the question suggests you should aim to look at how to ask a more concise question. I have some suggestions to improve your code: * *Split the other into its own function *Try to use more accurate variable names *As much as you can - avoid having multiple for loops happening at the same time *Have a look at list comprehension it would help a lot in this case *Think about whether a variable really belongs in a function or not like data What you're asking for is not immediately clear but this code should do what you want - and implements the improvements as suggested above import time data = ["Lucas_Miguel", "João_Batista", "Rafael_Gomes", "Bruna_Santos", "Lucas_Denilson"] def other(): name_input = input("Type the first name: ") matches = [name for name in data if name_input in name] if len(matches) == 0: print ("No matches") for name in matches: print(name) while True: print("Yes " "or " "No") confirm = input("Is the name you want in the options?: ") if confirm == "Yes": break if confirm == "No": print("Yes", " or", " No") try_again = input("Do you want to write again?: ") if try_again == "Yes": return other() else: return def start(): print("1" + " - Check Name") print("2" + " - Register a New Name") option = input("Choose an option: ") if option == "1": other() else: print("Option not available") time.sleep(1) return start() start() A: The first problem will be solved when you remove 8 spaces before while True:. The second problem will be solved when you add return (without arguments) one line below return other() at the indentation level of if try_again == "Yes": Everybody can see that you are just learning Python. You don't have to apologize if you think, your code is "ugly or weird". We all started with such small exercises.
{ "language": "en", "url": "https://stackoverflow.com/questions/72849365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: R: How to download PDF using rvest while in authentificated session I am trying to scrape PDFs from a newspaper archive that uses password protection, using rvest. The problem is that while I can log in in a session, I couldn't find a way to use the download.file() command within the session. The website is somewhat strange, so the only option I've found so far to actually log in was by actually using the PDF link. Here is my current code (unfortunately, as I can't give out the login details, it is only limitedly reproducible): #login to DLG archive login <- "https://dlgarchiv.lv.de/pdf/616694ca9b67fDLG_14-19_10_2021.pdf" pgsession <- session(login) pgform <- html_form(pgsession)[[1]] filled_form <- html_form_set(pgform, customerno="*******", plz="*****") session_submit(filled_form) #download file download.file(url="https://dlgarchiv.lv.de/pdf/616694ca9b67fDLG_14-19_10_2021.pdf",destfile="test.pdf",mode="wb") As a result, I am only downloading an HTML document of the log-in page, i.e. my log-in is being "forgotten" in between. Looking at the output following the session_submit() command, I am actually getting to the PDF, but I can't download it... <session> https://dlgarchiv.lv.de/pdf/616694ca9b67fDLG_14-19_10_2021.pdf Status: 200 Type: application/pdf Size: 1394950
{ "language": "en", "url": "https://stackoverflow.com/questions/70245048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Internet Explorer 6 Z-Index please take a look at the following website: http://www.solidcamxpress.co.uk/ If you look at it in IE6 (try IE Tester if your running Vista or 7) you will notice that the dark grey masthead appears behind part of the panel, and the top of the main image is chopped off. I'm guessing this is a problem with the z-index which IE6 and 7 are notorious for having problems with. Can anyone help me fix this? need it for the client asap. Thanks. A: Yes this is the infamous "ie6 z-index bug". It has been discussed a couple of time on StackOverflow and on the web. Personnaly, the best resource that I found for this bug is Solutions to the IE z-index Bug: CSS. It clearly describe the bug and the solution. By the way, questions like "Look at my site and please tell me how to fix it" are better answered on doctype.com.
{ "language": "en", "url": "https://stackoverflow.com/questions/3584126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Word Spacing Query I have a word spacing issue which I cannot seem to resolve. The web page is www.c5d.co.uk/captaintwo.php The word spacing under the top images look ridiculous. Yet as far as I can see, the CSS is the same. What am I missing ? If I put a /p tag after Wrigley it works fine but fails validation as there is no opening p tag Relevant HTML and CSS is as follows: .captain{word-spacing:185px;display:inline;} .pres {display:inline; } .ladycaptain{word-spacing:120px;display:inline; } <img class="lewis" src="http://www.c5d.co.uk/captain.png" alt="The Captain"> <img class="socialtwo" src="http://www.c5d.co.uk/president.png" alt="President"> <p class="pres"> <br>Captain: John</p> <p class="captain">Lewis President:</p> Bill Wrigley <img class="lewis" src="http://www.c5d.co.uk/ladycaptain.png" alt="Lady Captain"> <img class="socialtwo" src="http://www.c5d.co.uk/juniorcaptain.png" alt="Junior Captain"> <p class="pres"> <br>Lady Captain: Beryl</p> <p class="ladycaptain">Harrison Junior</p> Captain: Kieran Metcalf A: <br> is outdated. Use the self-closing <br /> instead. The names should be wrapped in something (p, span, h3, something). There are 2 styles (one inline (inside the document) and one attached to #header) that are adding around 500px of space there. That's why there is a large gap. Consider making it easier on yourself.. use 1 class to define each TYPE of object. #people { styles for container div } .box { styles for the individual boxes } .photo { styles for <img> } .title { styles for names of people } Then just apply the classes to the appropriate item like so <div id="people"> <div class="box"> <img src="path/image.jpg" class="photo" /> <h3 class="title">Position, name</h3> </div> <div class="box"> <img src="path/image.jpg" class="photo" /> <h3 class="title">Position, name</h3> </div> etc... </div> A: Make the following changes: .pres { /* display: inline (remove) */ display: inline-block; width: 270px; text-align: center; } .captain { /* display: inline (remove) */ display: inline-block; width: 270px; text-align: center; }
{ "language": "en", "url": "https://stackoverflow.com/questions/15128219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Magento dropdown group selection customer registration I am trying to make a group selection dropdown on the Magento customer registration page work. I have done all of the following: Inserted the following code into template/persistent/customer/form/register.phtml: <label for="group_id" style='margin-top:15px;'><?php echo $this->__('Which group do you belong to? (select "Pet Owner" if you are uncertain)') ?><span class="required">*</span></label> <div style='clear:both'><p style='color:red;'>Note: DVM/DACVO and Institution accounts require administrative approval.</p></div> <div class="input-box" style='margin-bottom:10px;'> <select style='border:1px solid gray;' name="group_id" id="group_id" title="<?php echo $this->__('Group') ?>" class="validate-group required-entry input-text" /> <?php $groups = Mage::helper('customer')->getGroups()->toOptionArray(); ?> <?php foreach($groups as $group){ ?> <?php if ($group['label']=="Pet Owner" || $group['label']=="DVM / DACVO" || $group['label']=="Institution"){?> <option value="<?php print $group['value'] ?>"><?php print $group['label'] ?></option> <?php } ?> <?php } ?> </select> </div> Then the following in /app/code/local/Mage/Customer/controllers/AccountController.php in the createPostAction(): $customer->setGroupId($this->getRequest()->getPost(‘group_id’)); Finally the following in /app/code/local/Mage/Customer/etc/config.xml where group id was added: <fieldsets> <customer_account> <prefix> <create>1</create> <update>1</update> <name>1</name> </prefix> <firstname> <create>1</create> <update>1</update> <name>1</name> </firstname> <middlename> <create>1</create> <update>1</update> <name>1</name> </middlename> <lastname> <create>1</create> <update>1</update> <name>1</name> </lastname> <suffix> <create>1</create> <update>1</update> <name>1</name> </suffix> <email> <create>1</create> <update>1</update> </email> <password> <create>1</create> </password> <confirmation> <create>1</create> </confirmation> <dob> <create>1</create> <update>1</update> </dob> <group_id><create>1</create><update>1</update></group_id> <taxvat> <create>1</create> <update>1</update> </taxvat> <gender> <create>1</create> <update>1</update> </gender> </customer_account> I have tested it several times and every customer is still being added as the default customer group. Can you see what I am doing wrong? A: <script type="text/javascript"> $(document).on('change','#country',function() { var param = 'country='+$('#country').val(); $.ajax({ showLoader: true, url: YOUR_URL_HERE, data: param, type: "GET", dataType: 'json' }).done(function (data) { //data.value has the array of regions }); }); Add this script in your js file. public function getCountries() { $country = $this->directoryBlock->getCountryHtmlSelect(); return $country; } use \Magento\Customer\Model\ResourceModel\Group\Collection and the above code in your block. <div class="field group_id required"> <label for="group_id" class="label"><span><?php echo __('Group') ?></span></label> <div class="control"> <select name="group_id"> <?php foreach ($groups as $key => $data) { ?> <option value="<?php echo $data['value']; ?>"><?php echo $data['label']; ?></option> <?php }?> </select> </div> </div> And in the phtml file add the above field. I know it's an old post, but giving the solution just in case anyone needs it. A: Create your own module instate of using /app/code/local/Mage/Customer/controllers/AccountController.php. Please add the following code in your congig.xml if your module name Custom and namespace Mymodule. <global> <fieldsets> <customer_account> <group_id><create>1</create><update>1</update></group_id> </customer_account> </fieldsets> </global> <frontend> <routers> <customer> <args> <modules> <Mymodule_Custom before="Mage_Customer_AccountController">Mymodule_Custom</Mymodule_Custom> </modules> </args> </customer> </routers> This will override your AccountController. Now find the following code for the controller. <?php require_once(Mage::getModuleDir('controllers','Mage_Customer').DS.'AccountController.php'); class Mymodule_Custom_AccountController extends Mage_Customer_AccountController { public function createPostAction() { $session = $this->_getSession(); if ($session->isLoggedIn()) { $this->_redirect('*/*/'); return; } $session->setEscapeMessages(true); // prevent XSS injection in user input if (!$this->getRequest()->isPost()) { $errUrl = $this->_getUrl('*/*/create', array('_secure' => true)); $this->_redirectError($errUrl); return; } $customer = $this->_getCustomer(); try { $errors = $this->_getCustomerErrors($customer); if (empty($errors)) { if($this->getRequest()->getPost('group_id')){ $customer->setGroupId($this->getRequest()->getPost('group_id')); } else { $customer->getGroupId(); } $customer->cleanPasswordsValidationData(); $customer->save(); $this->_dispatchRegisterSuccess($customer); $this->_successProcessRegistration($customer); return; } else { $this->_addSessionError($errors); } } catch (Mage_Core_Exception $e) { $session->setCustomerFormData($this->getRequest()->getPost()); if ($e->getCode() === Mage_Customer_Model_Customer::EXCEPTION_EMAIL_EXISTS) { $url = $this->_getUrl('customer/account/forgotpassword'); $message = $this->__('There is already an account with this email address. If you are sure that it is your email address, <a href="%s">click here</a> to get your password and access your account.', $url); $session->setEscapeMessages(false); } else { $message = $e->getMessage(); } $session->addError($message); } catch (Exception $e) { $session->setCustomerFormData($this->getRequest()->getPost()) ->addException($e, $this->__('Cannot save the customer.')); } $errUrl = $this->_getUrl('*/*/create', array('_secure' => true)); $this->_redirectError($errUrl); } } ?> Hope this will work for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/16074835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Thread after Service is destroyed I have an android Service called MyService. I have an Activity with two buttons (start service/stop service). When user clicks the button "start service", MyService is started using startService(new Intent(this, MyService.class)); When user clicks the button "stop service", MyService is stopped using stopService(new Intent(this, MyService.class)); In MyService I create a Thread T that performs some long running task. My question is: If the Service is destroyed, is T also destroyed even if it is still running? A: No, ending a thread you explicitly created is not the responsibility of the Android framework. You need to extend onDestroy(). Here is the javadoc for this method: Called by the system to notify a Service that it is no longer used and is being removed. The service should clean up an resources it holds (threads, registered receivers, etc) at this point. Upon return, there will be no more calls in to this Service object and it is effectively dead. Do not call this method directly. I would also suggest that you make your thread use Interrupts so that you can end it gracefully.
{ "language": "en", "url": "https://stackoverflow.com/questions/6079405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: RegEx - MatchCollection get subMatches I have a text file like this: Start <Not Present> Start <Word> End Start <Word> End Start <Antoher> End End I have to write a regEx that provide as result only "Start...End" blocks that contains <Word>. I've tried with something like this: (Start[\s\S]+?(<Word>.*)[\s\S]+?End) and I get two submatches as result. First submatch: Start <Not Present> Start <Word> End Second submatch: Start <Word> End As you can see the second one is correct but the first one is wrong. I want only submatches where <Word> is inside a "Start...End" block. How can I do that? Thank you. A: (?s)Start(?:(?!Start|End).)*<Word>(?:(?!End).)*End (?!Start|End). matches any one character (including \n, thanks to the (?s) modifier) unless it's the first character of Start or End. That makes sure that you're only matching the innermost set of Start and End delimiters. I used . in Singleline mode (via the inline (?s) modifier) to match any character including linefeed because you mentioned MatchCollection, indicating that you're using the .NET regex flavor. That [\s\S] hack is usually only needed in JavaScript. CORRECTION: I had assumed you were talking about the class System.Text.RegularExpressions.MatchCollection from the .NET framework, but I've just learned that VBScript also contains a class called MatchCollection. It's probably the VBScript flavor you're using (via ActiveX or COM), so the regex should be: Start(?:(?!Start|End)[\S\s])*<Word>(?:(?!End)[\S\s])*End Sorry about the confusion. More info available here. A: Two problems: * *You are using a "greedy" match - just add a ? to make it non-greedy. Without this, it will match a Start and End that spans two pairs - the first Start and the second End - and put it at both the start and the end of <Word> *The expression [\s\S] matches everything - it's the same as a dot .. You want just white space [\s] Try this (you can remove the redundant outer brackets too): Start(.*?<Word>.*?)End A: [\s\S] doesn't make much sense. \s matches whitespaces and \S does the exact opposite - it matches non-whitespaces. So [\s\S] is pretty much equivalent to .. I am also unsure what you want to achieve with the .* after <Word>. That would just match the whitespaces after <Word>. (Start[\s]+(<Word>)[\s]+End) As far as I can tell, it works on your test case in http://regexpal.com/.
{ "language": "en", "url": "https://stackoverflow.com/questions/12371296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can a System.Web.Http endpoint be an IObservable? Can a System.Web.Http endpoint be an IObservable? Can it be done while still using Attributes such as Route and AcceptVerbs? Basically, I want to make the following code example into an IObservable stream so I'm subscribing and handling it via reactive extensions: [Route("{id}")] [AcceptVerbs("GET")] public async Task<IHttpActionResult> example(int id) { return Ok(await Service.GetExampleAsync(id)); } Edit: I'm looking for a more elegant solution like https://blogs.msdn.microsoft.com/jeffva/2010/09/15/rx-on-the-server-part-5-of-n-observable-asp-net (Observable from IHttpHandler) but hopefully more mature after seven years? A: There is no direct way. But you could publish your own Observable. The main problem is, you need to return a value in the example function. One solution could be to create an Observable in which you pass a TaskCompletionSource. This would allow you to set the result from the Event handler. public class Request { public int Parameter { get; } public Request(int parameter) { Parameter = parameter; } public TaskCompletionSource<IHttpActionResult> Result { get; } = new TaskCompletionSource<IHttpActionResult>(); } public class Handler { public Subject<Request> ExampleObservable { get; } = new Subject<Request>(); [Route("{id}")] [AcceptVerbs("GET")] public async Task<IHttpActionResult> example(int id) { var req = new Request(id); ExampleObservable.OnNext(req); return await req.Result.Task; } } In the example above, we push a Request in the ExampleObservable. You can subscribe to this and use Request.Result.SetResult(...) to return the request. ExampleObservable.Subscribe(req => req.Result.SetResult(Ok(Service.GetExample(id)));
{ "language": "en", "url": "https://stackoverflow.com/questions/47131066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I display some columns from a table? I have a table where I store messages. I would like to display the columns from the table. So I need a while to make it. But I have an error like: Notice: Undefined index: subject in .. I hope someone can help me, thanks a lot <?php //Proceso de conexión con la base de datos $conex = mysql_connect("localhost", "root", "root") or die("No se pudo realizar la conexion"); mysql_select_db("carpe",$conex) or die("ERROR con la base de datos"); //Iniciar Sesión session_start(); //Validar si se está ingresando con sesión correctamente if (!$_SESSION){ echo '<script language = javascript> alert("usuario no autenticado") self.location = "login.php" </script>'; } $id_from = $_SESSION['id']; echo $id_from; $consulta=mysql_query("select * from messages where id_from='".$id_from."'"); if($consulta === FALSE) { die(mysql_error()); // TODO: better error handling } while($filas=mysql_fetch_array($consulta)){ echo $filas['id']; $id_to=$filas['id_to']; $status=$filas['status']; $subject=$filas['subject']; $text=$filas['text']; $time=$filas['time']; $deleted=$filas['deleted']; ?> <label> <?php echo $id,$id_to,$subject,$text;?></label><br> <?php }?> A: Undefined index: subject in Are you 100% sure table messages has a field name subject ??? I believe case sensitive is important here. Because that is what would cause the error. A: You can get table structure by executing this query: DESCRIBE messages; Alternatively, you can use mysql_list_fields to get information about table columns.
{ "language": "en", "url": "https://stackoverflow.com/questions/14115961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQLDeveloper sometimes suddenly doesn't open Worksheet on connect I'm using SQLDeveloper since about > 12 years (currently 20.2) and have to deal with about 70 different databases. I have activated under ( Properties / Database / Worksheet) "Open a Worksheet on connect". So, usually whenever I open a new session via Connections, a new Worksheet is automatically opened. Unfortunately sometimes and suddenly it doesn't work anymore and no new Worksheet gets opened on new connect. I have then always to "Open SQL Worksheet" manually, which works. This happens already since years and many versions and I don't have any clue, why. Even uncheck and check this property doesn't help. After restarting, it works again like a charm. Does anybody have an idea, why and if I can reactivate it without restarting? I don't like restart, to avoid loosing all detailed working results.
{ "language": "en", "url": "https://stackoverflow.com/questions/70424616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to find character from linked list pointer character So I need to delete a character from a linked list. However, the normal way (data->c==val) does not seem to work here. This is my struct: struct ll { char *c = new char; ll *prev; ll *next; }; This is my character pointer that I need to find: char *x=new char[1]; x[0]='R'; x[1]='\0'; This is the function I want to use to delete the linked list with this character: void del(ll *data, char *val) { ll *temp, *temp2; bool sm = false; char * x = val; while (data != nullptr) { if (data->prev == nullptr) { if (data->c == x) { temp = data; data = data->next; data->prev = nullptr; delete temp; } } else { if (data->c == x) { temp = data; data = data->prev; data->next = temp->next; temp2 = data->next; temp2->prev = data; delete temp; } } data = data->next; } } What am I doing wrong here? It seems like the if statement doesn't work correctly whenever I compare the two characters. I took the linked list from a file so does that have anything to do with it? A: You're making 2 mistakes here: 1) You're writing past the end of the array here, since it can only hold 1 character, not 2 like you're attempting to access: char *x=new char[1]; x[0]='R'; x[1]='\0'; You're only using one char anyway, so why make it an array? Replace it by: char x = 'R'; 2) You're not comparing the chars, but the memory addresses they're located at. Of course this won't work. You have to dereference the pointers (i.e. access the stored values) for it to work. Rewrite it like so: if (*data->c == *x) A: Since you create the object to look for this way char *x=new char[1]; it will never match anything in the list, because you have allocated a new piece of memory. You need to compare what the pointers point to. A: First of all, you are making an illegal write when you are initializing char x, by trying to access it's index 1. If you create an array of length N, you can access only the indices [0, N). In this case, as you created an array of length 1, you can not access its index 1, as it is out of bounds. You should instead create an array of length 2, if you intend to put the '\0' character. Secondly, when comparing, you should match the contents to which the char* points to, not the pointer itself, which is only an address. As you are trying to compare a character to another, using their pointers, you should change the innermost if checks (i.e. if (data->c == x) with the following: if (*data->c == *x) Thirdly, your code has another bug, related to how deletion of linked list elements is implemented. Basically, you should consider the case where temp2 variable may be nullptr. Finally, I recommend you look into std::string, which may be a better way to represent strings. Alternatively, if your linked list only has single characters, you may simply use character variables, as opposed to allocating a character array for each node in your list. Here is a working version of your code with the updates I mentioned above. A: you try to compare string like we compare character reason why it don't work. you can use strcmp instead or use character and not string. A: Why don't use std::string? The struct: struct ll { std::string c; ll *prev; ll *next; }; The string initialization: ll obj; obj.c = "R"; Your del function: void del(ll *data, char *val) { ll *temp, *temp2; bool sm = false; std::string x = val; while (data != nullptr) { if (data->prev == nullptr) { if (data->c == x) { temp = data; data = data->next; data->prev = nullptr; delete temp; } } else { if (data->c == x) { temp = data; data = data->prev; data->next = temp->next; temp2 = data->next; temp2->prev = data; delete temp; } } data = data->next; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/49448831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jquery two elements, toggles on focus/click ... works but lags This works as I want it to http://jsfiddle.net/nosfan1019/gvQYh/ but there is a noticeable delay if the focus/click changes to a sibling element. Any ideas? A: try this: The focus event is sent to an element when it gains focus. This event is implicitly applicable to a limited set of elements, such as form elements (<input>, <select>, etc.) and links (<a href>). $('#ooo').bind('focus click', function () { $('#kkk').text('hello'); }); $('#ooo').blur( function () { // you can use `blur` handler $('#kkk').empty(); }); http://jsfiddle.net/gvQYh/1/ A: After a little wrangling I have a solution :) $('#ooo').focus(function () { $('#kkk').text('hello'); visible = true; }); $('* :not(#ooo)').focus( function() { if (visible) { $('#kkk').empty(); visible = false; } });​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ http://jsfiddle.net/nosfan1019/3nK84/
{ "language": "en", "url": "https://stackoverflow.com/questions/11404850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Lambda http trigger I created a lambda function in AWS. I want to trigger it by a API Gateway/http call. after creating the http trigger i can see the following: but when I try to use a GET/POST calls to this address I receive "internal server error". I checked the logs and I see the following: The IAM role configured on the integration or API Gateway doesn't have permissions to call the integration. Check the permissions and try again. What should I do? which permission I need? A: Quoting from the docs here When an API is integrated with an AWS service (for example, AWS Lambda) in the back end, API Gateway must also have permissions to access integrated AWS resources (for example, invoking a Lambda function) on behalf of the API caller. To grant these permissions, create an IAM role of the AWS service for API Gateway type. When you create this role in the IAM Management console, this resulting role contains the following IAM trust policy that declares API Gateway as a trusted entity permitted to assume the role: { "Version": "2012-10-17", "Statement": [ { "Sid": "", "Effect": "Allow", "Principal": { "Service": "apigateway.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }
{ "language": "en", "url": "https://stackoverflow.com/questions/65479142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Animate Progress Bar with start time and end time in JS/Jquery I want to animate a progress bar with js/jquery. I have the start time like this: "2020-02-21 05:38:33" and the end time: "2020-02-21 05:41:43". I think this could maybe be calculated with the current time and the start and end time. A: I created a sample progress bar with Bootstrap, jQuery & momentjs. Hope this will help you. $(document).ready(function(){ var start = moment('2020-02-21 05:38:33'); var end = moment('2020-02-21 20:00:00'); var formattedPercentage = 0; var interval = setInterval(function(){ var now = moment(); var percentage = now.diff(start) / end.diff(start) * 100; if (percentage > 100) { formattedPercentage = 100; clearInterval(interval); } else { formattedPercentage = percentage.toFixed(2); } // Use formattedPercentage as you need $('#example-progress-bar .progress-bar').width(formattedPercentage+'%').html(formattedPercentage+'%') }, 500); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/> <div id="example-progress-bar" class="progress"> <div class="progress-bar progress-bar-striped" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/60332338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Geocoder goes good in an Activity and in another returns null always I am working in a app with maps, in the first activity I have a NavigationDrawer with differents fragments, in one of them I get the last Location every 10 seconds and with it set a TextView with the address of that location. Everything was going perfect since I create a new Activity for details of a Place with a MapView and when you put a Marker it get its address, but it always return null I don´t know why.. There is my code. 1rst Activity with Fragment public void setLocationListeners() { if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_PERMISSION_LOCATION); } else { mLocationCallback = new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult) { Location lastLocation = locationResult.getLastLocation(); Address address = getAddress(lastLocation.getLongitude(), lastLocation.getLatitude(), getContext()); myLocation = new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude()); if (address == null) { ((TextView) mView.findViewById(R.id.txtVosEstas)).setText(String.valueOf( lastLocation.getLongitude() + " " + lastLocation.getLatitude())); } else ((TextView) mView.findViewById(R.id.txtVosEstas)).setText(address.getAddressLine(0).split(",")[0]); ((TextView) mView.findViewById(R.id.txtBearing)).setText(String.valueOf(lastLocation.getBearing())); ((TextView) mView.findViewById(R.id.txtVelocidad)).setText(String.valueOf(lastLocation.getSpeed())); } }; } } "getAddress" is the static method in my MapHelper public static Address getAddress(double lng, double lat, Context c) { Geocoder geocoder = new Geocoder(c, Locale.getDefault()); try { List<Address> addresses = geocoder.getFromLocation(lat, lng, 1); return addresses.get(0); } catch (IOException e) { e.printStackTrace(); } catch (IndexOutOfBoundsException e) { } return null; } I call the same method in the other Activity when the map is ready. @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() { @Override public void onMapLongClick(LatLng latLng) { mMap.clear(); mMap.addMarker(new MarkerOptions().position(latLng)); String lat = String.format("%.7f", latLng.latitude); String lng = String.format("%.7f", latLng.longitude); ((TextView) findViewById(R.id.txtLat)).setText(lat); ((TextView) findViewById(R.id.txtLng)).setText(lng); Address address = getAddress(Double.valueOf(lat), Double.valueOf(lng), getApplicationContext()); ((MultiAutoCompleteTextView) findViewById(R.id.txtDireccion)).setText(address != null? address.getAddressLine(0) : "Sin dirección"); } }); if (mLugar != null){ mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mLugar.getLatLng(), 15)); MarkerOptions marker = new MarkerOptions() .position(mLugar.getLatLng()) .title(mLugar.getNombre()); mMap.addMarker(marker); } } And in it I never get results.
{ "language": "en", "url": "https://stackoverflow.com/questions/45368377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Error while implementing facebook-sdk-swift, app crashes in AppDelegate When I add SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions) to application(_, didFinishLaunchingWithOptions:) method in AppDelegate, the app crashes with error: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSConcreteMutableData isEqualToString:]: unrecognized selector sent to instance 0x600000054340' Without it the app runs fine. I also tried Objective-C version of the SDK as well, however I get the same error with the respective method call: FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) A: I had the same issue with version 4.18.0 Facebook SDK. I reverted to an older version 4.17.0 and I no longer get the crash.
{ "language": "en", "url": "https://stackoverflow.com/questions/41414591", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is spring data neo4j making large number of http calls to get related nodes Why is SDN making a large number of http calls to fetch the related graph having defined @Fetch attribute on the fields. Seems like no eager loading. A: For historic reasons SDN up to 3.2.2 heavily uses core Neo4j API calls. While this is fast for embedded it slows down when connected via REST. The following blog post explains this in regards to history and future of SDN: Spring Data Neo4j 3.3.0 – Improving Remoting Performance. Apart from the SDN 3.3.0 performance gains there is also a rewritten SDN in the works that specifically focusses on Neo4j over REST via Cypher: SDN4 / neo4j-ogm.
{ "language": "en", "url": "https://stackoverflow.com/questions/28811414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Tika to search files with Solr and Drupal I am using Apache Tika with Solr to search nodes with attachments (zips, pdfs, etc), in the DB we have indexed nodes with files. looks as if it all is configured correct with Solr (Tika too) but the results are empty. I am only getting results for one PDF file that I created to test, It contain one word ‘MyTestNew’.autocomplete shows it but not after submit. search works by title but not by file contents. http://screencast.com/t/lhSvs0iJS We think maybe it’s a problem in the code. Maybe module_invoke_all() for the apache search integrated module. But not sure for now.’
{ "language": "en", "url": "https://stackoverflow.com/questions/23920039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can host buffer be reused after returning from cuMemcpyHtoDAsync? The documentation does not say that explicitly so I am assuming the buffer cannot be reused. But want to make sure if that is the correct assumption. A: It is permissible to overwrite the contents of a host buffer which you have used as an argument to an asynchronous host to device transfer, as long as you take steps to ensure that the transfer has completed. The return status alone does not tell you that the transfer is complete. You need to use an explicit synchronization command on the host after the asynchronous copy is launched to confirm this.
{ "language": "en", "url": "https://stackoverflow.com/questions/42403719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I see what files Git is going to push to the server in Xcode? I have Git setup on an Xcode project and I make many small local commits before I push them to the server. However, I am not able to tell easily what all of the file changes are if I would do a git push. I know that you can look in the organizer and see all of your individual commits, but I can't seem to find an aggregate view of these changes. Essentially, if I commit changes locally to a file multiple times, I want to see the aggregate of those changes before I push the file to the server. Does something like this exist in Xcode, or in some 3rd party tools for Xcode? A: Command Line git diff --name-only origin/master Will list the files that you have changed but not pushed. git diff origin/master directory_foo/file_bar.m Will list the line by line diff of all the un-pushed changes to directory_foo/file_bar.m. GUI Tool If your looking for GUI Tools for a Git workflow, I use Xcode to commit locally and SourceTree to push and pull. Before Xcode and SourceTree I was a diehard command line SCM person. But I really like committing locally with Xcode, it streamlined a multi-step process of reviewing the change diffs and committing very nicely. The more I've used SourceTree the more I like it and the less I use the command line. I've always liked Atlassian's products and the $10 license for indies and small startups rocks. Now I just Love them to death for buying SourceTree and making free on the Mac App Store. I think SourceTree does exactly what you want to do. On the tool bar the red 3 shows I have 3 commits to push. You just select master and origin/master to get an aggregate of what will be pushed. The bottom left pain shows the files changed and the right shows the aggregated diff for that file. FYI: Two awesome presentations on Git (Absolutely Must Watch) Git For Ages 4 And Up http://www.youtube.com/watch?v=1ffBJ4sVUb4 Advanced Git http://vimeo.com/49444883 A: You can tell the changes of your local repository vs your remote repository from the Terminal in your local repository directory by using the command git diff [local] [remote] for example: git diff master origin/master A: Use git show to retrieve the commits you made. Get the SHA identification of your commits and: git diff 0da94be..59ff30c Another option is: git diff origin/master The command above show the diff of the files to be pushed Source: https://stackoverflow.com/a/3637039/2387977 A: I tried with Eclipse and found it very straight forward. Right click project, 'Compare With', 'Branch, Tag or Reference' Under 'Remote Tracking', select 'origin/master' I got the full list of files modified.
{ "language": "en", "url": "https://stackoverflow.com/questions/16565540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Failed exec.Command with fileName contain two spaces I want to open the file contain two spaces with explorer from Go's exec.Command(). This command works as expected from Windows PowerShell. Explorer "file://C:\Users\1. Sample\2. Sample2" And Using Go's exec.Command() works with fileName contain space like this. exec.Command(`explorer`, "file://C:\Users\1. Sample").CombinedOutput() But failed with fileName contain two spaces like this exec.Command(`explorer`, "file://C:\Users\1. Sample\2. Sample2").CombinedOutput() Please tell me how to solve this. This code works as expected. Thanks. exec.Command(`explorer`, `file://C:\Users\1. Sample\2. Sample2`).CombinedOutput() But actual input is string(not raw string literal) as below. So I think that I need to convert string to raw string. url := "file://C:\Users\1. Sample\2. Sample2" <I need to convert to raw string literal?> result, err := exec.Command(`explorer`, url).CombinedOutput() if err != nil { log.Fatal(err) } A: Having 2 spaces in file names has nothing to do with failing to run the command. You are using interpreted string literals: "file://C:\Users\1. Sample\2. Sample2" In interpreted string literals the backslash character \ is special and if you want your string to have a backslash, you have to escape it, and the escape sequence is 2 backslahses: \\: "file://C:\\Users\\1. Sample\\2. Sample2" Or even better: use raw string literals (and then you don't need to escape it): `file://C:\Users\1. Sample\2. Sample2` That weird 2 character in your file name may also cause an issue. If you include that in Go source code, it will be interpreted and encoded as UTF-8 string. You pass this as a parameter, but your OS (windows) may use a different character encoding when checking file names, so it may not find it. Remove that weird 2 character from the file name if correcting the string literal is not sufficient to make it work. When you run the command from PowerShell, it works because PowerShell does not expect an interpreted string and it uses the encoding that is also used to store file names. Also Cmd.CombinedOutput() (just like Cmd.Run() and Cmd.Start()) returns an error, be sure to check that as it may provide additional info.
{ "language": "en", "url": "https://stackoverflow.com/questions/36766174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Create image grid - bootstrap4 I'm trying to create an image grid with that little space between columns equal to the image below: The problem is that I can not make the right margin(red line), image below shows the problem: JSfiddle: https://jsfiddle.net/castordida/0zy7qd5m/ <div class="container gridhome mt-5 mb-5 p-0"> <div class="row" style="height:469px;"> <div class="col-sm-8 h-100" style="background-color:#000;"> <span class="categoria"><a href="#1">test</a></span> <h3>TESTE</h3> <a href="#" class="inteira"></a> </div> <div class="col-sm-4 h-100 p-0"> <div class="col-sm-12 h-50 p-0"> <div class="h-100 ml-1" style="background-color:#919191;"> <span class="categoria"><a href="#">test</a></span> <h3>TESTE</h3> </div> <a href="#" class="inteira"></a> </div> <div class="col-sm-12 h-50 p-0"> <div class="h-100 ml-1 mt-1" style="background-color:#919191;"> <span class="categoria"><a href="#">test</a></span> <h3>TESTE</h3> </div> <a href="#" class="inteira"></a> </div> </div> </div> <div class="row mt-1" style="height:234.5px;"> <div class="col-sm-4 h-100 p-0"> <div class="h-100" style="background-color:#919191;"> <span class="categoria"><a href="#1">test</a></span> <h3>TESTE</h3> <a href="#" class="inteira"></a> </div> </div> <div class="col-sm-4 h-100 p-0"> <div class="h-100 ml-1" style="background-color:#919191;"> <span class="categoria"><a href="#">test</a></span> <h3>TESTE</h3> <a href="#" class="inteira"></a> </div> </div> <div class="col-sm-4 h-100 p-0"> <div class="h-100 ml-1" style="background-color:#919191;"> <span class="categoria"><a href="#">test</a></span> <h3>TESTE</h3> <a href="#" class="inteira"></a> </div> </div> </div> </div> A: Ok it's due to the fact there is a gab between your picture at right... But the fixed height doesn't mention it... There are many ways to correct this... First : https://jsfiddle.net/y0x7kpza/ Add an overflow:hidden to the first .row Second: https://jsfiddle.net/d0a52xwk/ Reaffect the height of the two div on the right in taking care of the margin-top of these elements. .h-50-bis{ height:calc(50% - 0.125rem); }
{ "language": "en", "url": "https://stackoverflow.com/questions/56827978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Spring Social Facebook error I'm using Spring Social Facebook plugin; I have a very simple scenario: I want to display, on my web page, my user account Feeds; so far I have built a very simple JUnit test in order to list my FB wall posts but I'm facing some issues with Spring Social integration I'm using spring 4.0.5 and spring social 1.1.0 From what I saw in the documentation, I don't need to use the spring social connect framework (maybe I'll use the ConnectionRepository in future in order to not always do a FB and/or twitter connection on every request, but now I don't need to handle several users) So, after I created a test APP on FB and obtained the appClientID and appClientSecret, I wrote this simple XML configuration: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:facebook="http://www.springframework.org/schema/social/facebook" xmlns:twitter="http://www.springframework.org/schema/social/twitter" xmlns:social="http://www.springframework.org/schema/social" xmlns:linkedin="http://www.springframework.org/schema/social/linkedin" xmlns:c="http://www.springframework.org/schema/c" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/social/facebook http://www.springframework.org/schema/social/spring-social-facebook.xsd http://www.springframework.org/schema/social/linkedin http://www.springframework.org/schema/social/spring-social-linkedin.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/social/twitter http://www.springframework.org/schema/social/spring-social-twitter.xsd http://www.springframework.org/schema/social http://www.springframework.org/schema/social/spring-social.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder location="classpath:configuration.properties" ignore-resource-not-found="true" ignore-unresolvable="true" /> <context:component-scan base-package="it.spring" /> <bean id="connectionFactoryLocator" class="org.springframework.social.connect.support.ConnectionFactoryRegistry"> <property name="connectionFactories"> <list> <bean class="org.springframework.social.facebook.connect.FacebookConnectionFactory"> <constructor-arg value="${facebook.appKey}" /> <constructor-arg value="${facebook.appSecret}" /> </bean> <bean class="org.springframework.social.twitter.connect.TwitterConnectionFactory"> <constructor-arg value="${twitter.appKey}" /> <constructor-arg value="${twitter.appSecret}" /> </bean> </list> </property> </bean> </beans> And I wrote this simple java class (I'm behind a proxy but i can reach FB....my network administrator granted me to reach FB): public class SocialNetworkSvcImpl implements SocialNetworkingSvc { private static final Log logger = LogFactory.getLog(SocialNetworkSvcImpl.class.getName()); @Autowired private Environment env; @Value("${facebook.appId}") private String facebookAppId; @Value("${facebook.appSecret}") private String facebookAppSecret; @Value("${facebook.clientToken}") private String facebookClientToken; @Value("${facebook.appNamespace}") private String facebookAppNamespace; private ClientHttpRequestFactory requestFactory; @Autowired private ConnectionFactoryRegistry cfr; @Override public PagedList<Post> getPosts() throws Exception { try { FacebookConnectionFactory fcc = (FacebookConnectionFactory)cfr.getConnectionFactory("facebook"); Facebook facebook = fcc.createConnection(fcc.getOAuthOperations().authenticateClient()).getApi(); if( proxyEnabled ) { if( requestFactory != null ) { ((FacebookTemplate)facebook).setRequestFactory(requestFactory); } else { throw new IllegalArgumentException("Impossibile settare la requestFactory; proxy abilitato ma requestFactory null"); } } PagedList<Post> result = facebook.feedOperations().getHomeFeed(); result.addAll(facebook.feedOperations().getFeed()); return result; } catch (Exception e) { String messagge = "Errore nel recupero feed: "+e.getMessage(); logger.fatal(messagge, e); throw e; } } @PostConstruct public void initialize() { if( proxyEnabled ) { if( !StringUtils.hasText(proxyHost) ) { throw new IllegalArgumentException("Impossibile proseguire; valore proxyHost non ammesso: "+proxyHost); } if( proxyPort <= 0 ) { throw new IllegalArgumentException("Impossibile proseguire; valore proxyPort non ammesso: "+proxyPort); } if( !StringUtils.hasText(basicHeaderValue) ) { throw new IllegalArgumentException("Impossibile proseguire; valore basicHeaderValue non ammesso: "+basicHeaderValue); } String userName = null; String password = null; if( !StringUtils.hasText(proxyAuthUsername) ) { if( logger.isInfoEnabled() ) { logger.info("Nessun valore per proxyAuthUsername; controllo se siamo nel profilo sviluppo e se è presente come paramteri della JVM"); } boolean svil = false; String[] profili = env.getActiveProfiles(); for (int i = 0; i < profili.length; i++) { if( profili[i].equalsIgnoreCase("svil") ) { svil = true; break; } } if( svil ) { if(System.getProperty("usernameProxy") != null) { userName = System.getProperty("usernameProxy"); } } } else { if( logger.isInfoEnabled() ) { logger.info("Valorizzo la username del proxy dal file di properties"); } userName = proxyAuthUsername; } if( !StringUtils.hasText(proxyAuthPassword) ) { if( logger.isInfoEnabled() ) { logger.info("Nessun valore per proxyAuthPassword; controllo se siamo nel profilo sviluppo e se è presente come paramteri della JVM"); } boolean svil = false; String[] profili = env.getActiveProfiles(); for (int i = 0; i < profili.length; i++) { if( profili[i].equalsIgnoreCase("svil") ) { svil = true; break; } } if( svil ) { if(System.getProperty("passwordProxy") != null) { password = System.getProperty("passwordProxy"); } } } else { if( logger.isInfoEnabled() ) { logger.info("Valorizzo la password del proxy dal file di properties"); } password = proxyAuthPassword; } if( (StringUtils.hasText(userName) && !StringUtils.hasText(password)) || (!StringUtils.hasText(userName) && StringUtils.hasText(password)) ) { throw new IllegalArgumentException("Impossibile proseguire; settata solo "+(StringUtils.hasText(userName)?" la username ":" la password ")+" per accesso al proxy"); } try { requestFactory = new HttpComponentsClientHttpRequestFactory(); HttpHost proxy = new HttpHost(proxyHost, proxyPort); CredentialsProvider credsProvider = null; if( (StringUtils.hasText(userName) && StringUtils.hasText(password)) ) { credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(userName, password)); } HttpClientBuilder builder = HttpClients.custom(); if( credsProvider != null ) { builder.setDefaultCredentialsProvider(credsProvider); } builder.setProxy(proxy); CloseableHttpClient httpClient = builder.build(); ((HttpComponentsClientHttpRequestFactory)requestFactory).setHttpClient(httpClient); } catch (Exception e) { String message = "Errore nell'inizializzazione del servizio di connessione a social network: "+e.getMessage(); logger.fatal(message, e); throw new IllegalStateException(message); } } else { if( logger.isInfoEnabled() ) { logger.info("Proxy non abilitato; ci si collega direttamente ai social network"); } } } } But i'm having an error. This is my log: 2014-07-30 09:47:04,717 DEBUG [org.springframework.web.client.RestTemplate] Created POST request for "https://graph.facebook.com/oauth/access_token" 2014-07-30 09:47:04,718 DEBUG [org.springframework.web.client.RestTemplate] Setting request Accept header to [application/x-www-form-urlencoded, multipart/form-data] 2014-07-30 09:47:04,718 DEBUG [org.springframework.web.client.RestTemplate] Writing [{client_id=[${facebook.appKey}], client_secret=[e927afa9c6b3fb7e0e9344e38a5df46b], grant_type=[client_credentials]}] using [org.springframework.social.facebook.connect.FacebookOAuth2Template$1@f653852] 2014-07-30 09:47:04,761 DEBUG [org.apache.http.client.protocol.RequestAddCookies] CookieSpec selected: best-match 2014-07-30 09:47:04,797 DEBUG [org.apache.http.client.protocol.RequestAuthCache] Auth cache not set in the context 2014-07-30 09:47:04,800 DEBUG [org.apache.http.impl.conn.PoolingHttpClientConnectionManager] Connection request: [route: {s}->https://graph.facebook.com:443][total kept alive: 0; route allocated: 0 of 5; total allocated: 0 of 10] 2014-07-30 09:47:04,862 DEBUG [org.apache.http.impl.conn.PoolingHttpClientConnectionManager] Connection leased: [id: 0][route: {s}->https://graph.facebook.com:443][total kept alive: 0; route allocated: 1 of 5; total allocated: 1 of 10] 2014-07-30 09:47:04,867 DEBUG [org.apache.http.impl.execchain.MainClientExec] Opening connection {s}->https://graph.facebook.com:443 2014-07-30 09:47:04,890 DEBUG [org.apache.http.impl.conn.HttpClientConnectionOperator] Connecting to graph.facebook.com/173.252.100.27:443 2014-07-30 09:47:04,892 DEBUG [org.apache.http.impl.conn.HttpClientConnectionOperator] Connect to graph.facebook.com/173.252.100.27:443 timed out. Connection will be retried using another IP address 2014-07-30 09:47:04,893 DEBUG [org.apache.http.impl.conn.HttpClientConnectionOperator] Connecting to graph.facebook.com/2a03:2880:2110:cf07:face:b00c:0:1:443 2014-07-30 09:47:04,896 DEBUG [org.apache.http.impl.conn.DefaultManagedHttpClientConnection] http-outgoing-0: Shutdown connection 2014-07-30 09:47:04,896 DEBUG [org.apache.http.impl.execchain.MainClientExec] Connection discarded 2014-07-30 09:47:04,897 DEBUG [org.apache.http.impl.conn.DefaultManagedHttpClientConnection] http-outgoing-0: Close connection 2014-07-30 09:47:04,897 DEBUG [org.apache.http.impl.conn.PoolingHttpClientConnectionManager] Connection released: [id: 0][route: {s}->https://graph.facebook.com:443][total kept alive: 0; route allocated: 0 of 5; total allocated: 0 of 10] 2014-07-30 09:47:04,901 INFO [org.apache.http.impl.execchain.RetryExec] I/O exception (java.net.SocketException) caught when processing request to {s}->https://graph.facebook.com:443: Network is unreachable 2014-07-30 09:47:04,902 DEBUG [org.apache.http.impl.execchain.RetryExec] Network is unreachable java.net.SocketException: Network is unreachable at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:579) at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:239) at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:123) at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:318) at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:363) at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:219) at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195) at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:86) at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108) at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82) at org.springframework.http.client.HttpComponentsClientHttpRequest.executeInternal(HttpComponentsClientHttpRequest.java:87) at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48) at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:52) at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:545) at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:506) at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:334) at org.springframework.social.facebook.connect.FacebookOAuth2Template.postForAccessGrant(FacebookOAuth2Template.java:58) at org.springframework.social.oauth2.OAuth2Template.authenticateClient(OAuth2Template.java:194) at org.springframework.social.oauth2.OAuth2Template.authenticateClient(OAuth2Template.java:181) at it.spring.service.impl.SocialNetworkSvcImpl.getPosts(SocialNetworkSvcImpl.java:129) at it.eng.comi.test.ComiSocialTests.testFeeds(ComiSocialTests.java:54) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:233) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:176) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) 2014-07-30 09:47:04,914 INFO [org.apache.http.impl.execchain.RetryExec] Retrying request to {s}->https://graph.facebook.com:443 ... 2014-07-30 09:47:11,128 ERROR [it.spring.service.impl.SocialNetworkSvcImpl] Errore nel recupero feed: I/O error on POST request for "https://graph.facebook.com/oauth/access_token":Network is unreachable; nested exception is java.net.SocketException: Network is unreachable org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://graph.facebook.com/oauth/access_token":Network is unreachable; nested exception is java.net.SocketException: Network is unreachable at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:561) at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:506) at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:334) at org.springframework.social.facebook.connect.FacebookOAuth2Template.postForAccessGrant(FacebookOAuth2Template.java:58) at org.springframework.social.oauth2.OAuth2Template.authenticateClient(OAuth2Template.java:194) at org.springframework.social.oauth2.OAuth2Template.authenticateClient(OAuth2Template.java:181) at it.spring.service.impl.SocialNetworkSvcImpl.getPosts(SocialNetworkSvcImpl.java:129) at it.eng.comi.test.ComiSocialTests.testFeeds(ComiSocialTests.java:54) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:233) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:176) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) Caused by: java.net.SocketException: Network is unreachable at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:579) at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:239) at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:123) at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:318) at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:363) at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:219) at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195) at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:86) at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108) at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82) at org.springframework.http.client.HttpComponentsClientHttpRequest.executeInternal(HttpComponentsClientHttpRequest.java:87) at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48) at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:52) at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:545) ... 35 more 2014-07-30 09:47:11,130 ERROR [it.eng.comi.test.ComiSocialTests] I/O error on POST request for "https://graph.facebook.com/oauth/access_token":Network is unreachable; nested exception is java.net.SocketException: Network is unreachable org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://graph.facebook.com/oauth/access_token":Network is unreachable; nested exception is java.net.SocketException: Network is unreachable at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:561) at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:506) at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:334) at org.springframework.social.facebook.connect.FacebookOAuth2Template.postForAccessGrant(FacebookOAuth2Template.java:58) at org.springframework.social.oauth2.OAuth2Template.authenticateClient(OAuth2Template.java:194) at org.springframework.social.oauth2.OAuth2Template.authenticateClient(OAuth2Template.java:181) at it.spring.service.impl.SocialNetworkSvcImpl.getPosts(SocialNetworkSvcImpl.java:129) at it.eng.comi.test.ComiSocialTests.testFeeds(ComiSocialTests.java:54) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:233) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:176) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) Caused by: java.net.SocketException: Network is unreachable at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:579) at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:239) at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:123) at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:318) at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:363) at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:219) at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195) at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:86) at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108) at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82) at org.springframework.http.client.HttpComponentsClientHttpRequest.executeInternal(HttpComponentsClientHttpRequest.java:87) at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48) at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:52) at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:545) ... 35 more Instead if I generate an APP Token on FB and directly use it in FacebookTemplate, all works pretty good. How can I solve this issue? Am I wrong with anything? Any tip is really really appreciated Thank you Angelo A: There are a couple of things wrong that I see right away. The primary problem you're having is a network problem--not a code problem or a Spring Social problem. Even if your network admin says you can see Facebook, the exception you show tells me otherwise. That's something you'll need to work out on your end. Once you get past that, I doubt this will work anyway. You obtain your access token via authenticateClient(), which only grants you a client token. But then you try to use it for user-specific requests, such as obtaining the home feed. You must have a user token to do that operation and you can only get a user token via user authorization, aka the "OAuth Dance". Spring Social's ConnectController can help you with that.
{ "language": "en", "url": "https://stackoverflow.com/questions/25032514", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I sum a calculation between two columns in Mysql? What I would like to do is the following: SELECT SUM(ABS(`number_x` - `number_y`)) AS `total_difference` FROM `table` Where the table is as follow: id | number_x | number_y 1 | 4 | 2 2 | 3 | 2 3 | 2 | 4 So the answer should be: (4 - 2 = 2) + (3 - 2 = 1) + (2 - 4 = 2) = 5 Can I do this in MySQL and how? Thanks! A: The query you posted should work with no problem: SELECT SUM(ABS(`number_x` - `number_y`)) AS `total_difference` FROM `table` Or if you want to write it with a subquery like so: SELECT SUM(diff) AS `total_difference` FROM ( SELECT Id, ABS(number_x - number_y) diff FROM TableName ) t A: SELECT SUM(ABS(`number_x` - `number_y`)) AS `total_difference` FROM `table` OR You can write other way, but i'll prefer above only SELECT ABS(SUM(number_x) - SUM(number_y)) AS total_difference FROM table
{ "language": "en", "url": "https://stackoverflow.com/questions/12954024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: javascript loop create a row every 4 elements I can't do my function, could someone help me, thank you. I have a json file with a lot of entries, I create html in js. I would like to create a row every 4 elements. I'm really sorry I can't format my code well function createUserList(usersList) { usersList.forEach(user => { const listItem = document.createElement("div"); listItem.setAttribute("class", "row"); listItem.innerHTML = ` <div class="col-12 col-md-4 col-lg-3 isotope-item"> <a class="img-thumbnail-variant-3" href="single-portfolio.html"> <div class="adaptHaut"> <span class="adaptTitle"> <span class="vertBts type">${user.type}</span><span style="color: #92C13B;">${user.nom}</span> </span> <figure class="adaptImg"> <img src="images/${user.image}" alt="" width="418" height="315"/> </figure> </div> <div class="caption adaptHover"> <p class="heading-5 hover-top-element adaptDescription">Compétences scientifiques,intérêt pour les technologies de laboratoire.</p> <div class="divider"></div> <p class="small hover-bottom-element adaptSecondDescription">Le BTS ABM est proposé à Toulouse, Montpellier et Lille.!</p> <span class="icon arrow-right linear-icon-plus"></span> </div> </a> </div>` searchResult.appendChild(listItem); }) } { "results": [{ "nom": "Analyse Biologie Médical", "image": "MBS-phot-2.jpg", "type": "BTS" }, { "nom": "Diététique", "image": "diet.webp", "type": "BTS" }, { "nom": "Nutrition Santé", "image": "m2ns.jpg", "type": "BTS" }, { "nom": "Nutrition Santé", "image": "dieteticien.jpg", "type": "BACHELOR" }, { "nom": "Analyse Biologie Médical", "image": "MBS-phot-2.jpg", "type": "BTS" }, { "nom": "Diététique", "image": "diet.webp", "type": "BTS" }, { "nom": "Nutrition Santé", "image": "m2ns.jpg", "type": "BTS" }, { "nom": "Nutrition Santé", "image": "dieteticien.jpg", "type": "BACHELOR" } ] } A: The following is an attempt on joining 4 divs into a row and inserting an <hr> between the rows. Every time the expression i&&!(i%4) of loop index i is true an <hr> element is inserted before the current element. function createUserList(usersList) { document.getElementById("searchresult").innerHTML=usersList.map((user,i) =>`${i&&!(i%4)?"<hr>":""} <div class="col-12 col-md-4 col-lg-3 isotope-item"> <a class="img-thumbnail-variant-3" href="single-portfolio.html"> <div class="adaptHaut"> <span class="adaptTitle"> <span class="vertBts type">${user.type}</span> <span style="color: #92C13B;">${user.nom}</span> </span> <figure class="adaptImg"> <img src="images/${user.image}" alt="" width="41.8" height="31.5"/> </figure> </div> <div class="caption adaptHover"> <p class="heading-5 hover-top-element adaptDescription">Compétences scientifiques,intérêt pour les technologies de laboratoire.</p> <div class="divider"></div> <p class="small hover-bottom-element adaptSecondDescription">Le BTS ABM est proposé à Toulouse, Montpellier et Lille.!</p> <span class="icon arrow-right linear-icon-plus"></span> </div> </a> </div>`).join("") } const usrs= { "results": [{ "nom": "Analyse Biologie Médical", "image": "MBS-phot-2.jpg", "type": "BTS" }, { "nom": "Diététique", "image": "diet.webp", "type": "BTS" }, { "nom": "Nutrition Santé", "image": "m2ns.jpg", "type": "BTS" }, { "nom": "Nutrition Santé", "image": "dieteticien.jpg", "type": "BACHELOR" }, { "nom": "Analyse Biologie Médical", "image": "MBS-phot-2.jpg", "type": "BTS" }, { "nom": "Diététique", "image": "diet.webp", "type": "BTS" }, { "nom": "Nutrition Santé", "image": "m2ns.jpg", "type": "BTS" }, { "nom": "Nutrition Santé", "image": "dieteticien.jpg", "type": "BACHELOR" } ] } createUserList(usrs.results) .isotope-item {display:inline-block} <h2>Results</h2> <div id="searchresult"></div> A: Instead of creating a new element on each iteration use map to create a template string for each object, and then join that array of strings (map returns a new array) into one HTML string. Then assign that HTML to a containing element. (Sidenote: if your data is tabular you should probably use a table.) Here's a pared back example to show you how map/join work together. const arr = [ { name: 'Rita', nom: 18, img: 'img1' }, { name: 'Sue', nom: 19, img: 'img2' }, { name: 'Bob', nom: 40, img: 'img3' } ]; // Accepts the array of objects function createHTML(arr) { // `map` returns a new array of HTML strings which // is `joined` up before that final string is returned // from the function return arr.map(obj => { const { name, nom, img } = obj; return `<div>${name} - ${nom} - ${img}</div>`; }).join(''); } // Get the container and assign the result of calling the // function with the array of objects const container = document.querySelector('.container'); container.innerHTML = createHTML(arr); <div class="container"></div> Additional documentation * *Destructuring assignment
{ "language": "en", "url": "https://stackoverflow.com/questions/73334702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: View can't reuse for multiple textfiled's left View I'm facing the problem when I create a 1 padding view for 3 different UITextField Left view. Add into 3 different UITextField as left view. for 1 TextFeild its output fine but for all TextFeild getting blank scree. code is here. let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 40)) txtlink.leftView = paddingView txtlink.leftViewMode = UITextFieldViewMode.Always txtlink1.leftView = paddingView txtlink1.leftViewMode = UITextFieldViewMode.Always txtlink2.leftView = paddingView txtlink2.leftViewMode = UITextFieldViewMode.Always I don't know what is problem. something view related problem i guess.
{ "language": "en", "url": "https://stackoverflow.com/questions/39038709", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Setting Selenium WebDriver with Perl I am creating a sample script using perl for Selenium WebDriver. I have downloaded selenium-server-standalone-2.32.0.jar file and I am executing following code: use Selenium::Remote::Driver; use Test::More qw( no_plan ) ; my $driver = new Selenium::Remote::Driver(); $driver->get("http://www.google.com"); $driver->find_element('q','name')->send_keys("Hello WebDriver!"); ok($driver->get_title =~ /Google/,"title matches google"); $driver->quit(); but for this code to work I have to start java server using following command: java -jar selenium-server-standalone-2.32.0.jar Do I have to explicitly start the server to run the script? Or, there is something else I can do like setting environment variable etc. so that I don't have to start the server like in java we don't explicitly start the server. A: The documentation clearly states: To use this module, you need to have already downloaded and started the Selenium Server (Selenium Server is a Java application). A: In order to use any of the "unofficial bindings" (like the Perl bindings) you need to first launch the standalone-server jar file. As well, you need to do this in all the bindings if the browser is opening in a machine other than where the script is running (e.g. using RemoteWebdriver). Hope that helps. A: You can also use this, so you don't have to start the Selenium Server yourself: `use Selenium::PhantomJS;` `my $driver = Selenium::PhantomJS->new;`
{ "language": "en", "url": "https://stackoverflow.com/questions/16565393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Regular Expression check length I have been trying to make a regular expression for my mobile phones but I can't seem to get it to work: Here are the conditions for my regular expression: * *must start with 09 *total length is 9 Here is my regular expression: [0]{1}[9]{1}[0-9]{7} Valid mobile number 091123456 Invalid mobile number 0991234567 || 09912345 A: Easiest way: ^09[0-9]{7}$ Explanation: ^09 => begins by 09 [0-9] => any character between 0 and 9 {7} exactly seven times $ => Ends with the latest group ([0-9]{7}) A: If you use matcher.contains() instead of matcher.find() it will match against the whole string instead of trying to find a matching substring. Or you can add ^ and $ anchors as suggested in other answer. If you don't really need to use a regexp, perhaps it would be more readable to just use string.startsWith("09") && string.length() == 9
{ "language": "en", "url": "https://stackoverflow.com/questions/37792664", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Cannot assign custom radial for scipy rbf imported in julia through pycall? I have imported scipy.interpolate.Rbf from python to Julia 1.6 using PyCall. It works, but when I am trying to assign the radial function value to multiquadric it doesn't allow me to do so, due to syntax issue. For example: using PyCall interpolate = pyimport("scipy.interpolate") x = [1,2,3,4,5] y = [1,2,3,4,5] z = [1,2,3,4,5] rbf = interpolate.Rbf(x,y,z, function='multiquadric', smoothness=1.0) for the above example I am getting this error: LoadError: syntax: unexpected "=" Stacktrace: [1] top-level scope This is due to the use of function variable. May I know what can be the way around this error, so that i can assign the multiquadric radial for the rbf. Look forward to the suggestions. Thanks!! A: Your problem is that function is a reserved keyword in Julia. Additionally, note that 'string' for strings is OK in Python but in Julia you have "string". The easiest workaround in your case is py"" string macro: julia> py"$interpolate.Rbf($x,$y,$z, function='multiquadric', smoothness=1.0)" PyObject <scipy.interpolate.rbf.Rbf object at 0x000000006424F0A0> Now suppose you actually need at some point to pass function= parameter? It is not easy because function is a reserved keyword in Julia. What you could do is to pack it into a named tuple using Symbol notation: myparam = NamedTuple{(:function,)}(("multiquadric",)) Now if you do: some_f(x,y; myparam...) than myparam would get unpacked to a keyword parameter.
{ "language": "en", "url": "https://stackoverflow.com/questions/67731789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Jackson for beginners in Eclipse let me just say that I'm still learning Java and the subtleties of Eclipse, and I come to you because I am unsure how to properly phrase my question to Google or to StackOverflow's search engine. Apologies if its infinitely trivial. I am trying to understand the process of converting JSON-format strings into objects in Java. I found following example online: import java.io.IOException; import org.apache.log4j.Logger; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper;public class JsonToJavaConverter { private static Logger logger = Logger.getLogger(JsonToJavaConverter.class); public static void main(String args[]) throws JsonParseException, JsonMappingException, IOException { JsonToJavaConverter converter = new JsonToJavaConverter(); String json = "{\n" + " \"name\": \"Garima\",\n" + " \"surname\": \"Joshi\",\n" + " \"phone\": 9832734651}"; // converting JSON String to Java object converter.fromJson(json); } public Object fromJson(String json) throws JsonParseException, JsonMappingException, IOException { User garima = new ObjectMapper().readValue(json, User.class); logger.info("Java Object created from JSON String "); logger.info("JSON String : " + json); logger.info("Java Object : " + garima); return garima; } public static class User { private String name; private String surname; private long phone; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public long getPhone() { return phone; } public void setPhone(long phone) { this.phone = phone; } @Override public String toString() { return "User [name=" + name + ", surname=" + surname + ", phone=" + phone + "]"; } }} Now, here's the silly part (please don't string me up for asking): import org.apache.log4j.Logger; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; Are all underlined in red with Eclipses only hint, being that "The import org.apache.log4j cannot be resolved". As a newcomer to both Eclipse and Java, this leaves me absolutely dumbstruck. Could anyone please tell me what needs doing to resolve this basic issue? Deeply appreciated. A: You need to add the libraries (jar files) to the project's build path in Eclipse. You can find these libraries in Maven Central here: Log4j Jackson A: You need to add the relevant Jar files to your projects classpath http://javahowto.blogspot.co.uk/2006/06/set-classpath-in-eclipse-and-netbeans.html A: You need to add the log4j jar to your classpath. Assuming that you're not using maven or gradle, you can download it from Apache's site. Then put it in some suitable shared location and add it to your project's classpath. I think it's about the 3rd or 4th item in the Project Properties dialog, iirc.
{ "language": "en", "url": "https://stackoverflow.com/questions/21633677", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: asp.net ajax 4.0 with MVC -externalize templates i have created project referring to http://weblogs.asp.net/johnkatsiotis/archive/2008/07/23/asp-net-ajax-4-0-template-example.aspx this example . now i want to separate the" some data....." template to another page. with the "" remains in the same aspx page. PROBLEM : in .js file var t = new Sys.Preview.UI.Template.getTemplate($get("myTemplate")); t.createInstance($get("data"), {....,...,some data} this statement get the templates from the same page ie from where this page is called... now that i have separated the two div (templates) it gives me an error .... "Microsoft JScript runtime error: 'null' is null or not an object" what i can do to separate two div tags in different pages A: well...i got this answer after loooong research so thank you all who replied to my questions ok to externalize the ajax template 1st create a partial view (.ascx) and cut paste the template[ie- .....] now on your main page there is only an empty div now add this script to it calling it onclick[button,link] <script type="text/javascript"> function calltemp2() { debugger; $.get("/Templates/SelectTemp2", function(result) { alert(result); $("#Renderthisdiv").html(result); }); } </script> create another empty div having id Renderthisdiv imp!! give j query reference and lastly cut-paste this to external template (.ascx) <script type="text/javascript"> Sys.Application.add_init(appInit); function appInit() { start(); } </script> run it hopefully there is no problem
{ "language": "en", "url": "https://stackoverflow.com/questions/1801900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the difference between the = operator and the reserved word by when assigning a remeber in jetpack compose? I would like to know the difference between: var textFieldState = remember { mutableStateOf("") } and var textFieldState by remember { mutableStateOf("") } Is there any advantage over the other? A: Is there any advantage over the other? The first really should be a val and not a var. Otherwise, they are equivalent. Or, to quote the documentation: There are three ways to declare a MutableState object in a composable: * *val mutableState = remember { mutableStateOf(default) } *var value by remember { mutableStateOf(default) } *val (value, setValue) = remember { mutableStateOf(default) } These declarations are equivalent, and are provided as syntax sugar for different uses of state. You should pick the one that produces the easiest-to-read code in the composable you're writing. In those three: * *In the first, mutableState holds a MutableState, and you use .value and .value= to manipulate the contents *In the second, value holds a MutableState, but the by syntax tells the compiler to treat it as a property delegate, so we can pretend that value just holds the underlying data *In the third, a destructuring declaration gives you getter and setter references to manipulate the content in the underlying MutableState A: The by in this context is a kotlin property delegate. Any class that implements the operator fun operator fun getValue(thisRef: Any?, prop: KProperty<*>): T can use this syntax. Using = will eagerly assign the variable (importantly without delegation), the by will delegate to the operator function. The remember in this case is just a shortcut function to creating the Remember delgate that wraps the value you are creating inside the { ... } block. A typical example is the kotlin Lazy<T> class : val myValue : Int by lazy { 1 }. If used with the by operator you will return the Int value, if used with = it will return Lazy<Int> as you have not used delegation. It is also worth noting that delgates can be setters as well by using this operator fun : operator fun setValue(thisRef: Any?, prop: KProperty<*>, value: T).
{ "language": "en", "url": "https://stackoverflow.com/questions/69699761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Given a list of random hexadecimal colors, sort them based on "likeness" For example, this list of hexadecimal values: { "colors" : [{"hex" : "#fe4670"}, {"hex" : "#5641bc"}, {"hex" : "#d53fc3"}, {"hex" : "#6b5e09"}, {"hex" : "#4dd685"}, {"hex" : "#88d63f"}, {"hex" : "#eb93f3"}, {"hex" : "#f44847"}, {"hex" : "#32d159"}, {"hex" : "#6e9bde"}, {"hex" : "#c3ec64"}, {"hex" : "#81cce5"}, {"hex" : "#7233b6"}, {"hex" : "#bb90c3"}, {"hex" : "#728fde"}, {"hex" : "#7ef46a"}, {"hex" : "#f7cfff"}, {"hex" : "#c8b708"}, {"hex" : "#b45a35"}, {"hex" : "#589279"}, {"hex" : "#51f1e1"}, {"hex" : "#b1d770"}, {"hex" : "#db463d"}, {"hex" : "#5b02a2"}, {"hex" : "#909440"}, {"hex" : "#6f53fe"}, {"hex" : "#4c29bd"}, {"hex" : "#3b24f8"}, {"hex" : "#465271"}, {"hex" : "#6243"}, {"hex" : "#dbcc4"}, {"hex" : "#187c6"}, {"hex" : "#1085e2"}, {"hex" : "#b521e9"}, {"hex" : "#4bd36d"}, {"hex" : "#11bc34"}, {"hex" : "#455c47"}, {"hex" : "#a71bbf"}, {"hex" : "#988fc2"}, {"hex" : "#226cfe"}] } Ideally it should group "greens", "blues", "purples", etc. I've yet to come up with a good way to group them. Converting the colors to HSV and then sorting by Hue, then Sat then Val works almost fine, but there are a few exceptions that stand out: Another method I've read about is converting them to a LAB color space and then calculating the DeltaE. I've had mixed success with this: (this is sorting the whole list against one color). I'd like to sort the distance of every color against every color. A: The following example selects the first color for use as a comparison color. It first adds that color to a new array, then iterates through the rest of the colors comparing the colors looking for the most similar color. For each color it iterates, it subtracts the red from the second color in the comparison from that of the first, then the green, then the blue. It then finds the absolute values (no negative numbers). After that it adds those values together and divides by three. This number is the average difference between the two colors. Once it finds the closest color, it selects that color as the new comparison color, removes it from the original array of colors, and pushes it into the sorted array. It does this until there are no colors left. It definitely needs some work as can be seen when supplied with a larger data set, but it is all I had time for last night. I will continue to work on this until I have something better. const sort = data => { data = Object.assign([], data); const sorted = [data.shift()]; while(data.length) { const [a] = sorted, c = { d: Infinity }; for(let [i, b] of Object.entries(data)) { const average = Math.floor(( Math.abs(a.r - b.r) + Math.abs(a.g - b.g) + Math.abs(a.b - b.b) ) / 3); if(average < c.d) { Object.assign(c, { d: average, i: i }); } } sorted.unshift(data.splice(c.i, 1)[0]); } return sorted.reverse(); }; const test = (title, data) => { document.body.insertAdjacentHTML('beforeend', `<h2>${title}</h2>`); for(let c of data) { document.body.insertAdjacentHTML('beforeend', `<swatch style="background: rgb(${c.r},${c.g},${c.b})"></swatch>`); } return test; } const data = [ {"hex": "#fe4670"},{"hex": "#5641bc"},{"hex": "#d53fc3"},{"hex": "#6b5e09"}, {"hex": "#4dd685"},{"hex": "#88d63f"},{"hex": "#eb93f3"},{"hex": "#f44847"}, {"hex": "#32d159"},{"hex": "#6e9bde"},{"hex": "#c3ec64"},{"hex": "#81cce5"}, {"hex": "#7233b6"},{"hex": "#bb90c3"},{"hex": "#728fde"},{"hex": "#7ef46a"}, {"hex": "#f7cfff"},{"hex": "#c8b708"},{"hex": "#b45a35"},{"hex": "#589279"}, {"hex": "#51f1e1"},{"hex": "#b1d770"},{"hex": "#db463d"},{"hex": "#5b02a2"}, {"hex": "#909440"},{"hex": "#6f53fe"},{"hex": "#4c29bd"},{"hex": "#3b24f8"}, {"hex": "#465271"},{"hex": "#6243"}, {"hex": "#dbcc4"}, {"hex": "#187c6"}, {"hex": "#1085e2"},{"hex": "#b521e9"},{"hex": "#4bd36d"},{"hex": "#11bc34"}, {"hex": "#455c47"},{"hex": "#a71bbf"},{"hex": "#988fc2"},{"hex": "#226cfe"} ].reduce((m, e) => (m.push(Object.assign(e, { r: parseInt(e.hex.substring(1, 3), 16) || 0, g: parseInt(e.hex.substring(3, 5), 16) || 0, b: parseInt(e.hex.substring(5, 7), 16) || 0 })), m), []); const bigdata = (() => { const data = []; const rand = () => Math.floor(Math.random() * 256); for(let i = 0; i < 1000; ++i) { data.push({r: rand(), g: rand(), b: rand()}); } return data; })(); test('Unsorted', data)('Sorted', sort(data))('A Larger Dataset', sort(bigdata)); swatch { display: inline-block; border: 1px solid; margin-left: 1px; margin-top: 1px; width: 20px; height: 20px; } h2 { margin: 0; font-family: Verdana, Tahoma, "Sans Serif"} The following snippet does mostly the same thing, except that it searches the sorted array to find the closest match in that array, then inserts the color from the unsorted array next to its closest match. It doesn't seem to do as good of a job gradienting the swatches, but it does seem to group the colors together better. const sort = data => { data = Object.assign([], data); const sorted = [data.shift()]; while(data.length) { const a = data.shift(), c = { d: Infinity }; for(let [i, b] of Object.entries(sorted)) { const average = Math.floor(( Math.abs(a.r - b.r) + Math.abs(a.g - b.g) + Math.abs(a.b - b.b) ) / 3); if(average < c.d) { Object.assign(c, { d: average, i: i }); } } sorted.splice(c.i, 0, a); } return sorted.reverse(); }; const test = (title, data) => { document.body.insertAdjacentHTML('beforeend', `<h2>${title}</h2>`); for(let c of data) { document.body.insertAdjacentHTML('beforeend', `<swatch style="background: rgb(${c.r},${c.g},${c.b})"></swatch>`); } return test; } const data = [ {"hex": "#fe4670"},{"hex": "#5641bc"},{"hex": "#d53fc3"},{"hex": "#6b5e09"}, {"hex": "#4dd685"},{"hex": "#88d63f"},{"hex": "#eb93f3"},{"hex": "#f44847"}, {"hex": "#32d159"},{"hex": "#6e9bde"},{"hex": "#c3ec64"},{"hex": "#81cce5"}, {"hex": "#7233b6"},{"hex": "#bb90c3"},{"hex": "#728fde"},{"hex": "#7ef46a"}, {"hex": "#f7cfff"},{"hex": "#c8b708"},{"hex": "#b45a35"},{"hex": "#589279"}, {"hex": "#51f1e1"},{"hex": "#b1d770"},{"hex": "#db463d"},{"hex": "#5b02a2"}, {"hex": "#909440"},{"hex": "#6f53fe"},{"hex": "#4c29bd"},{"hex": "#3b24f8"}, {"hex": "#465271"},{"hex": "#6243"}, {"hex": "#dbcc4"}, {"hex": "#187c6"}, {"hex": "#1085e2"},{"hex": "#b521e9"},{"hex": "#4bd36d"},{"hex": "#11bc34"}, {"hex": "#455c47"},{"hex": "#a71bbf"},{"hex": "#988fc2"},{"hex": "#226cfe"} ].reduce((m, e) => (m.push(Object.assign(e, { r: parseInt(e.hex.substring(1, 3), 16) || 0, g: parseInt(e.hex.substring(3, 5), 16) || 0, b: parseInt(e.hex.substring(5, 7), 16) || 0 })), m), []); const bigdata = (() => { const data = []; const rand = () => Math.floor(Math.random() * 256); for(let i = 0; i < 1000; ++i) { data.push({r: rand(), g: rand(), b: rand()}); } return data; })(); test('Unsorted', data)('Sorted', sort(data))('A Larger Dataset', sort(bigdata)); swatch { display: inline-block; border: 1px solid; margin-left: 1px; margin-top: 1px; width: 20px; height: 20px; } h2 { margin: 0; font-family: Verdana, Tahoma, "Sans Serif"}
{ "language": "en", "url": "https://stackoverflow.com/questions/22973926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript: DOM event not happening in setTimeout So this my JS code for (var i=0; i<500; i++) { var compare = cryptoSName[i].innerHTML if (compare == crypto) { document.getElementById("cryptotable" + i).style.color = "#00000" document.getElementById('price' + i).innerHTML= "$" + (tradeMsg.message.msg.price.toFixed(4));; document.getElementById('perc' + i).innerHTML= tradeMsg.message.msg.perc + "%"; setTimeout(function() { document.getElementById("cryptotable" + i).style.color = "#ff0000" }, 500); } } when I run this, it throws an error saying that cannot read property style of null Now, If I remove this, It works perfectly fine. What am I doing wrong here? Also, My goal here is to change the color of an element just for few seconds. How can I achieve that? (I was trying to do with setTimeout function) A: Because you're using var, i is hoisted: to the interpreter, your code actually looks something like this: var i; for (i=0; i<500; i++) { var compare = cryptoSName[i].innerHTML // ... So at the end of your loop, i has a value of 500, and you don't have an element with an ID of ...500. Use let instead, since let has block scoping and isn't hoisted, unlike var: for (let i = 0; i<500; i++) {
{ "language": "en", "url": "https://stackoverflow.com/questions/49641665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP Script Automatic Download new file added in FTP Server I'm currently using a Raspberry Pi for an automatic video player I want to ask, whether is it possible or not a PHP program that can automatically (say for each day) download new files added in FTP Server. i.e. I have an FTP Server that contains Video Files, each day it will check if there is a new video file added and the program would download the new file automatically into some directory (my raspberry pi storage) Currently this is the basic download script that i have for an ftp <?php // define some variables $local_file = '/mydirectory/video.mp4'; $server_file = '/FTPdirectory/video.mp4'; $ftp_server="xx"; $ftp_user_name="xx"; $ftp_user_pass="xx"; $conn_id = ftp_connect($ftp_server); // login with username and password $login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); ftp_pasv($conn_id, TRUE); // try to download $server_file and save to $local_file if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) { echo "Successfully written to $local_file\n"; } else { echo "There was a problem\n"; } // close the connection ftp_close($conn_id); ?> Thanks! A: Definitely! Set up a cron job to call the PHP script: http://www.cyberciti.biz/faq/how-do-i-add-jobs-to-cron-under-linux-or-unix-oses/ Alternatively you can use Kermit to automate FTP as well: http://www.columbia.edu/kermit/ftpscripts.html A: What I'd do is loop through a local dir with PHP, make a list (json for easy storage) of all files and then compare that to FTP. If there's items that aren't in the local list, get them through FTP using Kermit as suggested by Jeremy Morgan.
{ "language": "en", "url": "https://stackoverflow.com/questions/22788987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding subscripts to tick labels (ggplot2) I need to include a subscript 2 in my tick labels, but I cannot seem to make it work. Here is the most recent code that I have tried out: All the relevant code As you can see, the subscript turns out fine when pasting the vector. The ggplot2 code returns the following plot: My plot The subscript 2 just appears as a blank square. Any input will be appreciated! A: You need to use expression, here an example: tibble(x = 1,y = 1) %>% ggplot(aes(x = 1,y = 1))+ geom_point()+ scale_x_continuous( breaks = 1, labels = expression(paste("Ambient ",CO[2])) )
{ "language": "en", "url": "https://stackoverflow.com/questions/69231833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Heroku ArgumentError ( is not a recognized provider) I am trying to upload profile pictures to Google Cloud using Paperclip and Fog gems. so far this what I have In my Gemfile gem "paperclip", git: "git://github.com/thoughtbot/paperclip.git" gem 'fog' In my user model has_attached_file :avatar, styles: {:big => "200x200>", thumb: "50x50>"}, storage: :fog, fog_credentials: "#{Rails.root}/config/gce.yml", fog_directory: "google-bucket-name" validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/ When I run this locally, I am able to upload it fine over to google. However, when I try to do this on Heroku, I am getting this error 015-10-13T19:47:15.703642+00:00 app[web.1]: SQL (2.1ms) UPDATE "users" SET "avatar_file_name" = $1, "avatar_content_type" = $2, "avatar_file_size" = $3, "avatar_updated_at" = $4, "updated_at" = $5 WHERE "users"."id" = $6 [["avatar_file_name", "3.jpeg"], ["avatar_content_type", "image/jpeg"], ["avatar_file_size", 8587], ["avatar_updated_at", "2015-10-13 19:47:15.140362"], ["updated_at", "2015-10-13 19:47:15.695467"], ["id", 3]] 2015-10-13T19:47:15.707684+00:00 app[web.1]: (0.9ms) ROLLBACK 2015-10-13T19:47:15.711451+00:00 app[web.1]: F, [2015-10-13T19:47:15.711260 #3] FATAL -- : 2015-10-13T19:47:15.711457+00:00 app[web.1]: ArgumentError ( is not a recognized provider): 2015-10-13T19:47:15.711459+00:00 app[web.1]: vendor/bundle/ruby/2.1.0/gems/fog-core-1.32.1/lib/fog/core/services_mixin.rb:12:in `new' 2015-10-13T19:47:15.711461+00:00 app[web.1]: vendor/bundle/ruby/2.1.0/gems/fog-core-1.32.1/lib/fog/storage.rb:22:in `new' 2015-10-13T19:47:15.711463+00:00 app[web.1]: vendor/bundle/ruby/2.1.0/bundler/gems/paperclip-8339e0fce5d8/lib/paperclip/storage/fog.rb:217:in `connection' 2015-10-13T19:47:15.711465+00:00 app[web.1]: vendor/bundle/ruby/2.1.0/bundler/gems/paperclip-8339e0fce5d8/lib/paperclip/storage/fog.rb:227:in `directory' 2015-10-13T19:47:15.711468+00:00 app[web.1]: vendor/bundle/ruby/2.1.0/bundler/gems/paperclip-8339e0fce5d8/lib/paperclip/storage/fog.rb:101:in `block in flush_writes' 2015-10-13T19:47:15.711470+00:00 app[web.1]: vendor/bundle/ruby/2.1.0/bundler/gems/paperclip- Not sure what's going on. A: After a lot of debugging, turns out my fog_credentials hash is not going through as expected on heroku. Instead of passing "#{Rails.root}/config/gce.yml", I am doing this. has_attached_file :avatar, styles: {:big => "200x200>", thumb: "50x50>"}, storage: :fog, fog_credentials: { aws_access_key_id: '<your_access_id>' aws_secret_access_key: '<your secret>' provider: 'Google' }, fog_directory: "google-bucket-name" validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/
{ "language": "en", "url": "https://stackoverflow.com/questions/33111528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: c++ regexp for not preceded by backslash and preceded by backslash I can only find negative lookbehind for this , something like (?<!\\). But this won't compile in c++ and flex. It seems like both regex.h nor flex support this? I am trying to implement a shell which has to get treat special char like >, < of | as normal argument string if preceded by backslash. In other word, only treat special char as special if not preceded by 0 or even number of '\' So echo \\>a or echo abc>a should direct output to a but echo \>a should print >a What regular expression should I use? I'm using flex and yacc to parse the input. A: In a Flex rule file, you'd use \\ to match a single backslash '\' character. This is because the \ is used as an escape character in Flex. BACKSLASH \\ LITERAL_BACKSLASH \\\\ LITERAL_LESSTHAN \\\\< LITERAL_GREATERTHAN \\\\> LITERAL_VERTICALBAR \\\\| If I follow you correctly, in your case you want "\>" to be treated as literal '>' but "\\>" to be treated as literal '\' followed by special redirect. You don't need negative look behind or anything particularly special to accomplish this as you can build one rule that would accept both your regular argument characters and also the literal versions of your special characters. For purposes of discussion, let's assume that your argument/parameter can contain any character but ' ', '\t', and the special forms of '>', '<', '|'. The rule for the argument would then be something like: ARGUMENT ([^ \t\\><|]|\\\\|\\>|\\<|\\\|)+ Where: [^ \t\\><|] matches any single character but ' ', '\t', and your special characters \\\\ matches any instance of "\" (i.e. a literal backslash) \\> matches any instance of ">" (i.e. a literal greater than) \\< matches any instance of "\<" (i.e. a literal less than) \\\| matches any instance of "\|" (i.e. a literal vertical bar/pipe) Actually... You can probably just shorten that rule to: ARGUMENT ([^ \t\\><|]|\\[^ \t\r\n])+ Where: [^ \t\\><|] matches any single character but ' ', '\t', and your special characters \\[^ \t\r\n] matches any character preceded by a '\' in your input except for whitespace (which will handle all of your special characters and allow for literal forms of all other characters) If you want to allow for literal whitespace in your arguments/parameters then you could shorten the rule even further but be careful with using \\. for the second half of the rule alternation as it may or may not match " \n" (i.e. eat your trailing command terminator character!). Hope that helps! A: You cannot easily extract single escaped characters from a command-line, since you will not know the context of the character. In the simplest case, consider the following: LessThan:\< BackslashFrom:\\< In the first one, < is an escaped character; in the second one, it is not. If your language includes quotes (as most shells do), things become even more complicated. It's a lot better to parse the string left to right, one entity at a time. (I'd use flex myself, because I've stopped wasting my time writing and testing lexers, but you might have some pedagogical reason to do so.) If you really need to find a special character which shouldn't be special, just search for it (in C++98, where you don't have raw literals, you'll have to escape all of the backslashes): regex: (\\\\)*\\[<>|] (An even number -- possibly 0 -- of \, then a \ and a <, > or |) as a C string => "(\\\\\\\\)*\\\\[<>|]"
{ "language": "en", "url": "https://stackoverflow.com/questions/15254052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I want to add and use function in laravel I want to add a new function called Age to calculate age of a person using his birthday. So I worked with Resource Controller (RESTFUL). I don't know how to add this function and how to use it in views. My function is : public function getBirthday($date){ return (int) ((time() - strtotime($date)) / 3600 / 24 / 365); } A: First of all, add that method that would return person's age to your Person model class: public function getAgeAttribute() { return (int) ((time() - strtotime($this->born_at) / 3600 / 24 / 365); } In your controller you'll need to pass a model object to the view: public someControllerAction() { // get person from the database or create a new model $person = ...; return view('some.view')->with(['person' => $person]); } And then, in the Blade template you can display age by doing: {{ $person->age }} I'm just not sure why you mention resource controllers. Usually they do not have a related view that they use to render HTML, but instead they return plain data, that is later serialized (e.g. to JSON) and used as controller response.
{ "language": "en", "url": "https://stackoverflow.com/questions/31495939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to avoid The SFSafariViewController's parent view controller was dismissed. issue? I have UINavigationController as a RootViewController. My app goes to FB App and returns to through this ViewController. But It does not drop the completion handler of Facebook SDK. But I am taking FBSDKError as in the title. How can I construct navigation cycle in order to avoid this error? Could you please help me? BR, A: I had the same issue occurring when added this to the info plist - Application does not run in background - YES or source code <key>UIApplicationExitsOnSuspend</key> <true/> Hope this would help someone, obviously you have to measure if you need this setting in the plist or not Set this to NO / <false/> and this problem goes
{ "language": "en", "url": "https://stackoverflow.com/questions/40959052", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PostgreSQL 9.5 IF-THEN-ELSE inside FUNCTION not available? My problem While trying to CREATE a FUNCTION in my PostgreSQL database, version 9.5, I get the following error: ERROR: syntax error at or near "IF" LINE 3: IF strpos(trem_outcome, 'VALIDATED') = 0 THEN Here's the FUNCTION I'm talking about: CREATE OR REPLACE FUNCTION countValid(outcome text) RETURNS integer AS $$ BEGIN IF strpos(outcome, 'VALIDATED') = 0 THEN RETURN 1; END IF; RETURN 0; END $$ LANGUAGE SQL Looks like the IF-THEN-ELSE control statements aren't available to me here, although I'm inside a FUNCTION right? What am I missing? Some context I ultimately wanna sum(countValid()) of a huge set of data, like follows: SELECT table1.tbl1_pk, count(table2.tbl2_outcome) as registered, sum(countValid(table2.tbl2_outcome)) as validated FROM table1 JOIN table2 ON table2.tbl2_tbl1_fk = table1.tbl1_pk GROUP BY table1.tbl1_pk; Where my tables are like: +---------------------------------------+ | table1 | +---------------+-----------------------+ | tbl1_pk (int) | tbl1_other_crap (w/e) | +---------------+-----------------------+ | 1 | ... | | 2 | ... | | 3 | ... | +---------------+-----------------------+ +------------------------------------------------+ | table2 | +---------+-----------------------+--------------+ | tbl2_pk | tbl2_tbl1_fk | tbl2_outcome | | (int) | (int -> tbl1.tbl1_pk) | (text) | +---------+-----------------------+--------------+ | 1 | 1 | VALIDATED | | 2 | 1 | FLUNKED | | 3 | 3 | VALIDATED | | 4 | 3 | VALIDATED | | 5 | 1 | FLUNKED | | 6 | 2 | VALIDATED | | 7 | 3 | VALIDATED | +---------+-----------------------+--------------+ I'd expect the following result set: +---------------+------------------+-----------------+ | tbl1_pk (int) | registered (int) | validated (int) | +---------------+------------------+-----------------+ | 1 | 3 | 1 | | 2 | 1 | 1 | | 3 | 3 | 3 | +---------------+------------------+-----------------+ Minimal reproducible example I can reproduce my issue on an even simpler function: CREATE OR REPLACE FUNCTION countValid(outcome text) RETURNS integer AS $$ BEGIN IF 1 = 1 THEN RETURN 1; END IF; RETURN 0; END $$ LANGUAGE SQL ... which triggers: ERROR: syntax error at or near "IF" LINE 3: IF 1 = 1 THEN I'm open to entirely different approaches, although I'd much rather have my work executed in a single query. A: You do not need that function. Just use count(table2.tbl2_outcome = 'VALIDATED' or null)
{ "language": "en", "url": "https://stackoverflow.com/questions/35671728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cocoa - getting privileges within the application I know how to get the right privileges in order to run an external executable by using the Security framework. This time I want to avoid having a helper tool. So how can I acquire privileges to run my tasks within the application, and not with a helper tool? A: I solved this by coding a helper tool which launches my main application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7086087", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Delegated event handler for a set of dynamic elements My JS is as follows: $(document).ready(function(){ $('#data1').change(function(){ title = $('#title1').val(); url = $('#url1').val(); $.post('library/edit.php',{title:title, url:url},function(res){ alert ("updated !"); }); }); }); and my HMTL-markup: <div id="data1"> <input name="title1" type="text" id="title1" /> <input name="url1" type="text" id="url1" /> </div> I wrote that code to call to a PHP file on change of textbox. that code works as expected. But now I've added more textboxes as follows: <div id="div1"><input name="title1" type="text" id="title1" /> <input name="url1" type="text" id="url1" /></div> <div id="div2"><input name="title2" type="text" id="title2" /> <input name="url2" type="text" id="url2" /></div> <div id="div3"><input name="title3" type="text" id="title3" /> <input name="url3" type="text" id="url3" /></div> Now I want the same functionality so that any of these textboxes works like title1 in my earlier code. So if input#title-3 is changed I want the change to be uploaded via POST to my PHP-script. Important: The number of boxes are dynamic. A: $(document).ready(function(){ $('#data1').on('change','[id^=title],[id^=url]',function(){ var index = $(this).attr('id').replace('title',"").replace('url',""); var title = $("#title" + index).val(); var url = $("#url" + index).val(); var hid = $("#hid" + index).val(); // you can put in here in sequence all the fields you have $.post('library/edit.php',{title:title, url:url, hid : hid},function(res){ alert ("updated !"); }); }); }); so by this answer if any text box whoes id starts with title changes. the function passed in will be invoked. indezx variable will store the index of the group of the elements that are changing. and then is being callculated by removing title from title1 or title2 A: I think the answer you have it right here: I wrote that code to call to php file on change of textbox. That script (jQuery I guess) it must be associatte with the $('#xxx1').onchange() right? (or similar) If you modify the function, add a class to the input field (also in the php) and each time you call the function, start listening again.. I think you can call any function you may want. Example (guessing your code) HTML <div id="data1" class="dynamicDiv"> <input name="title1" type="text" id="title1" /> <input name="url1" type="text" id="url1" /> </div> jQuery // enable the function on document ready $(document).ready(function(){ startListening('.dynamicDiv'); }); // each time an ajax call is completed, // run the function again to map new objects $(document).ajaxComplete(function(){ startListening('.dynamicDiv'); }); // and finally the function function startListening(obj){ $(obj).onchange(function(){ // ajax call // function call // or whatever... }); } PHP // some code.... // some code.... // remember here to add "dynamicDiv" as a class in the object return object; A: Since your elements are dynamically generated you need to use event delegation, then you can use [id^="value"] to select the appropriate elements based on the first part of their id attribute $(document).ready(function(){ $(document).on('change','[id^="data"]',function(){ var title = $(this).find('[id^="title"]').val(); var url = $(this).find('[id^="url"]').val(); var hidden = $(this).find('[id^="hid"]').val(); $.post('library/edit.php',{title:title, url:url, hid:hidden},function(res){ alert ("updated !"); }); }); }); Note: I suggest you bind to the closest parent of your data divs that is present at page load instead of binding to the document
{ "language": "en", "url": "https://stackoverflow.com/questions/18097955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Matplotlib: Lines on Top of Bars, Legend on the Left, No Splines I'm having trouble tweaking the graph below. Here's what the dataframe looks like: Year Some All Ratio 0 2016 9 157 0.057325 1 2017 13 189 0.068783 2 2018 21 216 0.097222 3 2019 18 190 0.094737 4 2020 28 284 0.098592 Here's what I want to do: * *The orange line should be in front of the bars. I tried using the zorder parameter and it didn't help. I also tried switch the order of the axes object, but I couldn't get the line to be assigned to the primary axis. *I want the legend on the left side. You'll notice in the code below that I'm using a somewhat large figsize argument. If I use a smaller one, the legend will magically move to the left, but I don't want to use a smaller one. *I want to label the bar graphs on top of each bar with its corresponding value. I tried iterating over each value and individually annotating the bars with ax.annotate, but I couldn't center the values automatically. In this minimal example, all the values are three digits long, but in the original data I have numbers that four digits long and I couldn't find a good way to make it centered for all of them. *Finally, I want to get rid of the top and right spines. My code below didn't remove them for some reason. The code to help people get started follows below. data = {'Year': {0: '2016', 1: '2017', 2: '2018', 3: '2019', 4: '2020'}, 'Some': {0: 9, 1: 13, 2: 21, 3: 18, 4: 28}, 'All': {0: 157, 1: 189, 2: 216, 3: 190, 4: 284}, 'Ratio': {0: 0.05732484076433121, 1: 0.06878306878306878, 2: 0.09722222222222222, 3: 0.09473684210526316, 4: 0.09859154929577464}} df = __import__("pandas").DataFrame(data) ax = df.plot(x="Year", y="Ratio", kind="line", linestyle='-', marker='o', color="orange", figsize=((24,12)) ) df.plot(x="Year", y="All", kind="bar", ax=ax, secondary_y=True ) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) A: Your asking quite a number of things. * *To get the line on top of the bar, it seems we have to first draw the bars and afterwards the line. Drawing the line last shrinks the xlims, so we have to apply them explicitely. *Moving the legend is more complicated. Normally you just do ax1.legend(loc='upper left'), but in our case with two plots this seems to always draw a second legend with the last drawn plot as only entry. *There is a function set_bbox_to_anchor with little documentation. It defines some box (x, y, width, height), but there is also a seemingly inaccessible loc parameter that controls how the box and the position relate. "The default for loc is loc="best" which gives unpredictable results when the bbox_to_anchor argument is used." Some experimentation might be needed. The best solution, is to guard the *Setting the text is simple. Just iterate over the y positions. Place at x position 0,1,2,.. and center horizontally (vertically at bottom). *To remove the spines, it seems there are two axes over each other (what probably also causes the zorder not to work as desired). You'll want to hide the spines of both of them. *To remove the ticks, use ax1.axes.yaxis.set_ticks([]). *To switch the ax2 ticks to the left use ax2.yaxis.tick_left(). import pandas as pd from matplotlib import pyplot as plt data = {'Year': {0: '2016', 1: '2017', 2: '2018', 3: '2019', 4: '2020'}, 'Some': {0: 9, 1: 13, 2: 21, 3: 18, 4: 28}, 'All': {0: 157, 1: 189, 2: 216, 3: 190, 4: 284}, 'Ratio': {0: 0.05732484076433121, 1: 0.06878306878306878, 2: 0.09722222222222222, 3: 0.09473684210526316, 4: 0.09859154929577464}} df = pd.DataFrame(data) ax1 = df.plot(x="Year", y="All", kind="bar", ) for i, a in df.All.items(): ax1.text(i, a, str(a), ha='center', va='bottom', fontsize=18) xlims = ax1.get_xlim() ax2 = df.plot(x="Year", y="Ratio", kind="line", linestyle='-', marker='o', color="orange", ax=ax1, secondary_y=True, figsize=((24, 12)) ) ax2.set_xlim(xlims) # needed because the line plot shortens the xlims # ax1.get_legend().set_bbox_to_anchor((0.03, 0.9, 0.1, 0.1)) # unpredictable behavior when loc='best' # ax1.legend(loc='upper left') # in our case, this would create a second legend ax1.get_legend().remove() # remove badly placed legend handles1, labels1 = ax1.get_legend_handles_labels() handles2, labels2 = ax2.get_legend_handles_labels() ax1.legend(handles=handles1 + handles2, # create a new legend labels=labels1 + labels2, loc='upper left') # ax1.yaxis.tick_right() # place the yticks for ax1 at the right ax2.yaxis.tick_left() # place the yticks for ax2 at the left ax2.set_ylabel('Ratio') ax2.yaxis.set_label_position('left') ax1.axes.yaxis.set_ticks([]) # remove ticks for ax in (ax1, ax2): for where in ('top', 'right'): ax.spines[where].set_visible(False) plt.show()
{ "language": "en", "url": "https://stackoverflow.com/questions/59837199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it required to map account table while doing login process I have two table user_details user_id | int(11) | role_id | tinyint(4) | account_id | int(11) | username | varchar(200) | password | varchar(250) | is_locked | varchar(1) | is_account_active | varchar(1) | account_details account_id | int(11) account_name | varchar(100) address | varchar(200) is_account_active | tinyint(1) I want to block all user once they account has been blocked. So they can't able to login into my application. I have add is_account_active column to user table so that i can avoid the joining of account_details table while user login into application. Is this good practice to do.
{ "language": "en", "url": "https://stackoverflow.com/questions/30658390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS and R markdown (bookdown). How can I use a CSS to build css boxes without changing the overall template? Ok, I assume this can be a very naive question, but I did not find any helpful solution. I have an "R markdown" for teaching statistics in which I use a CSS file to customize some appearance for all my questions. I have imported this CSS file from here and it is pretty cool because I can easily create a question box, such as this one: However, now, in my R Markdown file, every time I type "1. " "2. " etc, it becomes a question box. How can I modify the CSS to prevent transforming all my lists into a "question box" ? Thank you. Please check the CSS file below: body { counter-reset: li; /* initialize counter named li */ } h1 { font-family:Arial, Helvetica, sans-serif; font-weight:bold; } h2 { font-family:Arial, Helvetica, sans-serif; font-weight:bold; margin-top: 24px; } ol { margin-left:0; /* Remove the default left margin */ padding-left:0; /* Remove the default left padding */ } ol > li { position:relative; /* Create a positioning context */ margin:0 0 10px 2em; /* Give each list item a left margin to make room for the numbers */ padding:10px 80px; /* Add some spacing around the content */ list-style:none; /* Disable the normal item numbering */ border-top:2px solid #317EAC; background:rgba(49, 126, 172, 0.1); } ol > li:before { content:"Exercise " counter(li); /* Use the counter as content */ counter-increment:li; /* Increment the counter by 1 */ /* Position and style the number */ position:absolute; top:-2px; left:-2em; -moz-box-sizing:border-box; -webkit-box-sizing:border-box; box-sizing:border-box; width:7em; /* Some space between the number and the content in browsers that support generated content but not positioning it (Camino 2 is one example) */ margin-right:8px; padding:4px; border-top:2px solid #317EAC; color:#fff; background:#317EAC; font-weight:bold; font-family:"Helvetica Neue", Arial, sans-serif; text-align:center; } li ol, li ul {margin-top:6px;} ol ol li:last-child {margin-bottom:0;} .oyo ul { list-style-type:decimal; } hr { border: 1px solid #357FAA; } div#boxedtext { background-color: rgba(86, 155, 189, 0.2); padding: 20px; margin-bottom: 20px; font-size: 10pt; } div#template { margin-top: 30px; margin-bottom: 30px; color: #808080; border:1px solid #808080; padding: 10px 10px; background-color: rgba(128, 128, 128, 0.2); border-radius: 5px; } div#license { margin-top: 30px; margin-bottom: 30px; color: #4C721D; border:1px solid #4C721D; padding: 10px 10px; background-color: rgba(76, 114, 29, 0.2); border-radius: 5px; } A: If someone faces the same question, this is the solution. In the CSS file, start the commands with a specific string (below) and then, on Markdown, use the div notation. Such as: <div class="question"> 1. My first question 1. My second question </div> /* -----------Question counter ---------*/ body { counter-reset: li; } h1 { font-family:Arial, Helvetica, sans-serif; font-weight:bold; } h2 { font-family:Arial, Helvetica, sans-serif; font-weight:bold; margin-top: 24px; } .question ol { margin-left:0; /* Remove the default left margin */ padding-left:0; /* Remove the default left padding */ } .question ol>li { position:relative; /* Create a positioning context */ margin:0 0 10px 2em; /* Give each list item a left margin to make room for the numbers */ padding:10px 80px; /* Add some spacing around the content */ list-style:none; /* Disable the normal item numbering */ border-top:2px solid #317EAC; background:rgba(49, 126, 172, 0.1); } .question ol>li:before, .question ol>p>li:before { content:"Questão " counter(li); /* Use the counter as content */ counter-increment:li; /* Increment the counter by 1 */ /* Position and style the number */ position:absolute; top:-2px; left:-2em; -moz-box-sizing:border-box; -webkit-box-sizing:border-box; box-sizing:border-box; width:7em; /* Some space between the number and the content in browsers that support generated content but not positioning it (Camino 2 is one example) */ margin-right:8px; padding:4px; border-top:2px solid #317EAC; color:#fff; background:#317EAC; font-weight:bold; font-family:"Helvetica Neue", Arial, sans-serif; text-align:center; } .question ol ol { counter-reset: subitem; } .question li ol, .question li ul {margin-top:6px;} .question ol ol li:last-child {margin-bottom:0;}
{ "language": "en", "url": "https://stackoverflow.com/questions/66036254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: VSCode copy and paste 1 line without newline character being prepended In VScode when you copy a line of text and then put your cursor in the middle of quotes and hit Ctrl+V it pastes the new line above where you intended it to go. In IntelliJ and PyCharm when you copy a line of code with Ctrl+C without selecting any text then they intelligently remove the \n character at the end of the string while it is in memory. So when you paste it in middle of quotes you get the desired behavior. Since VS team is not likely going to fix this anytime soon I was wondering if anyone has a macro for it. https://github.com/Microsoft/vscode/issues/61840 A: A combination of keys would help you: * *Home *Shift + End *Ctrl + Alt + C But since you want to do it with just Ctrl + Alt + C, you can install extension called macros to make a macro, recorded multiple key combinations. Create your own custom macros by adding them to your settings.json: "macros": { "copyWithoutNewLine": [ "cursorHome", "cursorEndSelect", "editor.action.clipboardCopyAction", "cancelSelection", "cursorUndo", "cursorUndo", "cursorUndo" ] } Created macro can have a custom name, in this example it's copyWithoutNewLine. And this macro executes all above stated commands to copy line. After creating macro, you need to add it to keybindings.json to run it: { "key": "ctrl+alt+c", "command": "macros.copyWithoutNewLine", "when": "editorTextFocus && !editorHasSelection" } When key combination of Ctrl + Alt + C is pressed, it will copy it without a new line, and you can paste it where ever you want. A: Having struggled with this for long myself too, I finally stumbled across the solution. Add these lines to keybindings.json: { "key": "cmd+alt+ctrl+v", // insert your desired shortcut here "command": "editor.action.insertSnippet", "args": { "snippet": "$CLIPBOARD"}, "when": "inputFocus" }, Now, pressing cmd+option+ctrl+v (or whatever shortcut you define) should paste without newline, regardless of how it was copied. For an explanation and more cool things you can do with snippets, see https://code.visualstudio.com/docs/editor/userdefinedsnippets#:~:text=In%20Visual%20Studio%20Code%2C%20snippets,%3A%20Enable%20it%20with%20%22editor.
{ "language": "en", "url": "https://stackoverflow.com/questions/53791340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Excel formatting DD-MMM-YYYY, must be in this format I have some data below. Please see below. I need excel to put these dates in this format exactly DD-MMM-YYYY. MMM must be in all caps as well. Like JUN not Jun. Also, for DD, it cannot be 3, it must be 03. Excel date formats that are in excel do not give me this option. It seems to me like it might be a custom formatting option. How can I format in this format precisely? I will look around at the custom formats and try to figure this out. Thank you. Have EFFECTIVE_START_DATE 3-Jun-2019 3-Jun-2019 Want EFFECTIVE_START_DATE 03-JUN-2019 03-JUN-2019 A: There is no custom format for months in all-caps. If you can reference the existing cell, then use TEXT to get the date formatted as you want and then UPPER to convert to upper case. =UPPER(TEXT(A2,"dd-mmm-yyyy")) A: This worked UPPER(TEXT(C2, "DD-MMM-YYYY"))
{ "language": "en", "url": "https://stackoverflow.com/questions/60082179", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ionic cordova build android I am trying to build my ionic 2 project using the command ionic cordova build android but I cant successfully build it. Hope you can help me with this problem, Thanks in advance. Here is the error: > cordova build android × Running command - failed! [ERROR] Cordova encountered an error. You may get more insight by running the Cordova command above directly. [ERROR] An error occurred while running cordova build android (exit code 1): ANDROID_HOME=C:\Users\kiel\AppData\Local\Android\sdk JAVA_HOME=C:\Program Files\Java\jdk1.8.0_144 Subproject Path: CordovaLib Unzipping C:\Users\kiel\.gradle\wrapper\dists\gradle-3.3-all\55gk2rcmfc6p2dg9u9ohc3hw9\gradle-3.3-all.zip to C:\Users\kiel\.gradle\wrapper\dists\gradle-3.3-all\55gk2rcmfc6p2dg9u9ohc3hw9 Exception in thread "main" java.util.zip.ZipException: error in opening zip file at java.util.zip.ZipFile.open(Native Method) at java.util.zip.ZipFile.<init>(ZipFile.java:225) at java.util.zip.ZipFile.<init>(ZipFile.java:155) at java.util.zip.ZipFile.<init>(ZipFile.java:169) at org.gradle.wrapper.Install.unzip(Install.java:215) at org.gradle.wrapper.Install.access$600(Install.java:27) at org.gradle.wrapper.Install$1.call(Install.java:75) at org.gradle.wrapper.Install$1.call(Install.java:48) at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:69) at org.gradle.wrapper.Install.createDist(Install.java:48) at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:107) at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61) Error: cmd: Command failed with exit code 1 Error output: Exception in thread "main" java.util.zip.ZipException: error in opening zip file at java.util.zip.ZipFile.open(Native Method) at java.util.zip.ZipFile.<init>(ZipFile.java:225) at java.util.zip.ZipFile.<init>(ZipFile.java:155) at java.util.zip.ZipFile.<init>(ZipFile.java:169) at org.gradle.wrapper.Install.unzip(Install.java:215) at org.gradle.wrapper.Install.access$600(Install.java:27) at org.gradle.wrapper.Install$1.call(Install.java:75) at org.gradle.wrapper.Install$1.call(Install.java:48) at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:69) at org.gradle.wrapper.Install.createDist(Install.java:48) at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:107) at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61) Picked up _JAVA_OPTIONS: -Xmx1g A: Have you tried to use Ant instead of graddle? Try this command: ionic cordova build android -- --ant
{ "language": "en", "url": "https://stackoverflow.com/questions/46132872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Could'nt get data from database with limit in mongoose I want to get data from database with limit like this but dont work: topic.find({}).limit(10).exec(function(err,topic){topic2.find({}).limit(5).exec(function(err,topic2){console.log(topic+topic2)}})) But if i try with this(only change the limit of outside and inside) ,it works.So i want to learn why: topic.find({}).limit(5).exec(function(err,topic){topic2.find({}).limit(10).exec(function(err,topic2){console.log(topic+topic2)}}))
{ "language": "en", "url": "https://stackoverflow.com/questions/49565039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Link Twitter Account with Passportjs after local user auth is completed with passportjs I just want to link twitter account after there is still user. Firstly i have a router.js like that // GET Registration Page router.get('/signup', function(req, res){ res.render('register',{noty: req.flash('message')}); }); // Handle Registration POST router.post('/signup', passport.authenticate('signup', { successRedirect: '/connect_twitter', failureRedirect: '/signup', failureFlash : true })); /* GET Twitter Auth*/ router.get('/login/twitter', passport.authenticate('twitter')); router.get('/login/twitter/return', passport.authenticate('twitter', { failureRedirect: '/' }), function(req, res) { res.redirect('/home'); }); if its success, i redirected "/connect_twitter" with req.user != null , that is current user. In the "/connect_twitter" a redirect twitter with a button. When twitter return user's tokens, i use this strategy passport.use(new TwitterStrategy({ consumerKey: config.twitter.consumer_key, consumerSecret: config.twitter.consumer_secret, callbackURL: config.tw_callback }, function(token, tokenSecret, profile, cb) { // In this example, the user's Twitter profile is supplied as the user // record. In a production-quality application, the Twitter profile should console.log(profile); findOrCreateUser = function(){ // find a user in Mongo with provided username User.findOne({'tw_user_id': profile.id}, function(err, user) { // In case of any error, return using the done method if (err){ return cb(err); } // already exists if (user) { user.tw_token = token; user.tw_token_secret = tokenSecret; user.save(function(err){ if (err) { throw err; } console.log("User Updating successfull !"); }) return cb(null, user); } else { // create the user var newUser = new User(); // set the user's local credentials newUser.password = createHash(token); newUser.username = profile.username; newUser.email = null; newUser.tw_token = token; newUser.tw_user_id = profile.id; newUser.tw_token_secret = tokenSecret; // save the user newUser.save(function(err) { if (err){ console.log('Error in Saving user: '+err); throw err; } console.log('User Registration succesful'); return cb(null, newUser); }); } }); }; process.nextTick(findOrCreateUser); })); The problem is how to access current_user or anything about the current user in this function function(token, tokenSecret, profile, cb)? As i think, If i access that, i linked current user with these tokens. Or Is there better (any) way to link twitter with the current user ? Thanks in advance.. A: In the passportjs docs Association in Verify Callback One downside to the approach described above is that it requires two instances of the same strategy and supporting routes. To avoid this, set the strategy's passReqToCallback option to true. With this option enabled, req will be passed as the first argument to the verify callback. passport.use(new TwitterStrategy({ consumerKey: TWITTER_CONSUMER_KEY, consumerSecret: TWITTER_CONSUMER_SECRET, callbackURL: "http://www.example.com/auth/twitter/callback", passReqToCallback: true }, function(req, token, tokenSecret, profile, done) { if (!req.user) { // Not logged-in. Authenticate based on Twitter account. } else { // Logged in. Associate Twitter account with user. Preserve the login // state by supplying the existing user after association. // return done(null, req.user); } } )); With req passed as an argument, the verify callback can use the state of the request to tailor the authentication process, handling both authentication and authorization using a single strategy instance and set of routes. For example, if a user is already logged in, the newly "connected" account can be associated. Any additional application-specific properties set on req, including req.session, can be used as well. By the way, you can handle with the current user and its data to link any social strategy including Twitter. A: You can do that in 2 ways: * *Instead of trying to get req.user inside Twitter Strategy, you can get user email fetched from twitter response and match it with user with same email inside database. Normally, you cannot get email directly from Twitter API, you need to fill request form here to get elevated access. After request accepted, you will be able to get email from Twitter API. *After twitter login, you can save user twitter profile information inside a temp table and redirect a page like /user/do_login?twitter_profile_id=<user_twitter_profile_id_fetched_from_twitter_response>. When you redirect to /user/do_login you will be able to access req.user and also you will have user profile id. In this action, you can grab user profile info from temp table and merge it with req.user. By the way, I assume that, you are using stored session.
{ "language": "en", "url": "https://stackoverflow.com/questions/34495417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Swift 3 draw a polyline with Google Maps during run I have found the below for drawing a path during a run/walk with Apple Maps extension NewRunViewController: MKMapViewDelegate { func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! { if !overlay.isKindOfClass(MKPolyline) { return nil } let polyline = overlay as! MKPolyline let renderer = MKPolylineRenderer(polyline: polyline) renderer.strokeColor = UIColor.blueColor() renderer.lineWidth = 3 return renderer } } However I am trying to do it with Google Maps and can't find the solution. Lots and lots of answers are for Apple Maps, but not much on Google Maps. A: Try this let path = GMSMutablePath() //Change coordinates path.add(CLLocationCoordinate2D(latitude: -33.85, longitude: 151.20)) path.add(CLLocationCoordinate2D(latitude: -33.70, longitude: 151.40)) path.add(CLLocationCoordinate2D(latitude: -33.73, longitude: 151.41)) let polyline = GMSPolyline(path: path) polyline.strokeColor = UIColor.blue polyline.strokeWidth = 3.0 polyline.map = mapView A: This is my solution with Swift 5. private var trackLocations: [CLLocation] = [] func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { for location in locations { self.trackLocations.append(location) let index = self.trackLocations.count if index > 2 { let path = GMSMutablePath() path.add(self.trackLocations[index - 1].coordinate) path.add(self.trackLocations[index - 2].coordinate) let polyline = GMSPolyline(path: path) polyline.strokeColor = Global.iOSMapRendererColor polyline.strokeWidth = 5.0 polyline.map = self.mapView } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/41354890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Model location of LUIS container service I am following this instruction video from Microsoft Azure team. docker run has to come with where the model & data is located. Following the guide in the video, I download the 'exported data' from LUIS, say under azure-luis/input then, I run the following command docker run -i -t my-docker-image-repo-id EULA=accept BILLING=https://southcentralus.api.cognitive.microsoft.com/luis/v2.0 APIKEY=my-unique-api-key --mount type=bind,input=/Users/#####/Developers/azure-luis/input --mount type=bind,source=/Users/#####/Developers/azure-luis/output but I kept getting the following message A folder must be mounted at the location '/input' where models and other input data can be read. where did I do wrong?
{ "language": "en", "url": "https://stackoverflow.com/questions/54754921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jmeter - pass command-line parameter that contains hyphen I run my jmeter tests via bat file %JMETER_HOME%\jmeter -n -t %RUNNER%\My.jmx -Jusers=1 -Jloop=1 etc. But today I had to add some more parameters, and one of them was -Jclient_id=450a-b58d-204ebfe22d1e I've started getting error "Java SE has stopped working" (which in debug appeared to be "Unhandled exception at 0x012A96E0 in java.exe: 0xC0000005: Access violation reading location 0x58B86598." I do understand that it's because of hyphen in the new parameter, but how can i deal with it? Any advice would be appreciated. A: I cannot reproduce it on my system (bash 3.2.57, Java 1.8.0.65) You can try working it around as follows: * *Surround cliend id with quotation marks like -Jclient_id="450a-b58d-204ebfe22d1e" *Define the values in user.properties file (lives under "bin" folder of your JMeter installation) like: users=1 loops=1 client_id=450a-b58d-204ebfe22d1e See Apache JMeter Properties Customization Guide for more information on different JMeter properties types and ways of working with them
{ "language": "en", "url": "https://stackoverflow.com/questions/36356792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Replace word with special characters from string in Java I am writing a method which should replace all words which matches with ones from the list with '****' characters. So far I have code which works but all special characters are ignored. I have tried with "\\W" in my expression but looks like I didn't use it well so I could use some help. Here's code I have so far: for(int i = 0; i < badWords.size(); i++) { if (StringUtils.containsIgnoreCase(stringToCheck, badWords.get(i))) { stringToCheck = stringToCheck.replaceAll("(?i)\\b" + badWords.get(i) + "\\b", "****"); } } E.g. I have list of words ['bad', '@$$']. If I have a string: "This is bad string with @$$" I am expecting this method to return "This is **** string with ****" Note that method should be aware of case sensitive words, e.g. TesT and test should handle same. A: I'm not sure why you use the StringUtils you can just directly replace words that match the bad words. This code works for me: public static void main(String[] args) { ArrayList<String> badWords = new ArrayList<String>(); badWords.add("test"); badWords.add("BadTest"); badWords.add("\\$\\$"); String test = "This is a TeSt and a $$ with Badtest."; for(int i = 0; i < badWords.size(); i++) { test = test.replaceAll("(?i)" + badWords.get(i), "****"); } test = test.replaceAll("\\w*\\*{4}", "****"); System.out.println(test); } Output: This is a **** and a **** with ****. A: The problem is that these special characters e.g. $ are regex control characters and not literal characters. You'll need to escape any occurrence of the following characters in the bad word using two backslashes: {}()\[].+*?^$| A: My guess is that your list of bad words contains special characters that have particular meanings when interpreted in a regular expression (which is what the replaceAll method does). $, for example, typically matches the end of the string/line. So I'd recommend a combination of things: * *Don't use containsIgnoreCase to identify whether a replacement needs to be done. Just let the replaceAll run each time - if there is no match against the bad word list, nothing will be done to the string. *The characters like $ that have special meanings in regular expressions should be escaped when they are added into the bad word list. For example, badwords.add("@\\$\\$"); A: Try something like this: String stringToCheck = "This is b!d string with @$$"; List<String> badWords = asList("b!d","@$$"); for(int i = 0; i < badWords.size(); i++) { if (StringUtils.containsIgnoreCase(stringToCheck,badWords.get(i))) { stringToCheck = stringToCheck.replaceAll("["+badWords.get(i)+"]+","****"); } } System.out.println(stringToCheck); A: Another solution: bad words matched with word boundaries (and case insensitive). Pattern badWords = Pattern.compile("\\b(a|b|ĉĉĉ|dddd)\\b", Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE); String text = "adfsa a dfs bb addfdsaf ĉĉĉ adsfs dddd asdfaf a"; Matcher m = badWords.matcher(text); StringBuffer sb = new StringBuffer(text.length()); while (m.find()) { m.appendReplacement(sb, stars(m.group(1))); } m.appendTail(sb); String cleanText = sb.toString(); System.out.println(text); System.out.println(cleanText); } private static String stars(String s) { return s.replaceAll("(?su).", "*"); /* int cpLength = s.codePointCount(0, s.length()); final String stars = "******************************"; return cpLength >= stars.length() ? stars : stars.substring(0, cpLength); */ } And then (in comment) the stars with the correct count: one star for a Unicode code point giving two surrogate pairs (two UTF-16 chars).
{ "language": "en", "url": "https://stackoverflow.com/questions/27782438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Eliminate each duplicate value from columns I have a table including some rows. If the row in its column is duplicate value, I don't want it. Let me exemplify. ColA ColB ColC ColD 1 X Q 9 2 Y W 9 3 Z E 9 3 X R 9 3 Y T null 2 Z null null I expect (ordering is negligible) ColA ColB ColC ColD 1 X Q 9 2 Y W null 3 Z E null null null R null null null T null null null null null I would write for each column almost same select clauses but I don't think it is efficient. A: This seems to do it (but I wonder about the purpose of it ): WITH CTE AS ( SELECT 1 as ColA, 'X' as ColB,'Q' as ColC,'9' as ColD UNION SELECT 2,'Y','W',9 UNION SELECT 3,'Z','E',9 UNION SELECT 3,'X','R',9 UNION SELECT 3,'Y','T',null UNION SELECT 2,'Z',null,null) select AA.ColA, BB.ColB, CC.ColC, DD.ColD from (select ColA, ROW_NUMBER() over (order by ColA) RowA from ( select DISTINCT ColA from CTE) A) AA FULL JOIN (select ColB, ROW_NUMBER() over (order by ColB) RowB from ( SELECT DISTINCT ColB from CTE) B ) BB ON BB.RowB = AA.RowA FULL JOIN (select ColC, ROW_NUMBER() over (order by ColC) RowC from ( SELECT DISTINCT ColC from CTE) C ) CC ON CC.RowC = AA.RowA FULL JOIN (select ColD, ROW_NUMBER() over (order by ColD) RowD from ( SELECT DISTINCT ColD from CTE) D ) DD ON DD.RowD = AA.RowA DBFIDDLE A: You want to suppress values when selecting data from the table? This is typically not done in SQL, but in the app displaying the data. But if you want to, you can do this in SQL (using windw functions). For this to work you'd have to specify the order in which to select the rows. You say, you don't care about the order, so in below query I simply generate some row number we can base this on: with numbered as ( select t.*, row_number() over order by (newid()) as rn from mytable ) select case when count(*) over (partition by cola order by rn) = 1 then cola end as a, case when count(*) over (partition by colb order by rn) = 1 then colb end as b, case when count(*) over (partition by colc order by rn) = 1 then colc end as c, case when count(*) over (partition by cold order by rn) = 1 then cold end as d from numbered order by rn; A: If you have a column that specifies the ordering, then you can use row_number(): select (case when row_number() over (partition by colA order by ordcol) = 1 then colA end), (case when row_number() over (partition by colB order by ordcol) = 1 then colB end), (case when row_number() over (partition by colC order by ordcol) = 1 then colC end), (case when row_number() over (partition by colD order by ordcol) = 1 then colD end) from tablename t; If you don't have such a column, then it becomes tricker. You can generate one: with t as ( select t.*, row_number() over (order by (select null)) as ordcol from tablename t ) select (case when row_number() over (partition by colA order by ordcol) = 1 then colA end), (case when row_number() over (partition by colB order by ordcol) = 1 then colB end), (case when row_number() over (partition by colC order by ordcol) = 1 then colC end), (case when row_number() over (partition by colD order by ordcol) = 1 then colD end) from t;
{ "language": "en", "url": "https://stackoverflow.com/questions/68812384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: unbuffered read from stdin in python I'm writing a python script that can read input through a pipe from another command like so batch_job | myparser My script myparser processes the output of batch_job and write to its own stdout. My problem is that I want to see the output immediately (the output of batch_job is processed line-by-line) but there appears to be this notorious stdin buffering (allegedly 4KB, I haven't verified) which delays everything. The problem has been discussed already here here and here. I tried the following: * *open stdin using os.fdopen(sys.stdin.fileno(), 'r', 0) *using -u in my hashbang: #!/usr/bin/python -u *setting export PYTHONUNBUFFERED=1 right before calling the script *flushing my output after each line that was read (just in case the problem was coming from output buffering rather than input buffering) My python version is 2.4.3 - I have no possibility of upgrading or installing any additional programs or packages. How can I get rid of these delays? A: I've encountered the same issue with legacy code. It appears to be a problem with the implementation of Python 2's file object's __next__ method; it uses a Python level buffer (which -u/PYTHONUNBUFFERED=1 doesn't affect, because those only unbuffer the stdio FILE*s themselves, but file.__next__'s buffering isn't related; similarly, stdbuf/unbuffer can't change any of the buffering at all, because Python replaces the default buffer made by the C runtime; the last thing file.__init__ does for a newly opened file is call PyFile_SetBufSize which uses setvbuf/setbuf [the APIs] to replace the default stdio buffer). The problem is seen when you have a loop of the form: for line in sys.stdin: where the first call to __next__ (called implicitly by the for loop to get each line) ends up blocking to fill the block before producing a single line. There are three possible fixes: * *(Only on Python 2.6+) Rewrap sys.stdio with the io module (backported from Python 3 as a built-in) to bypass file entirely in favor of the (frankly superior) Python 3 design (which uses a single system call at a time to populate the buffer without blocking for the full requested read to occur; if it asks for 4096 bytes and gets 3, it'll see if a line is available and produce it if so) so: import io import sys # Add buffering=0 argument if you won't always consume stdin completely, so you # can't lose data in the wrapper's buffer. It'll be slower with buffering=0 though. with io.open(sys.stdin.fileno(), 'rb', closefd=False) as stdin: for line in stdin: # Do stuff with the line This will typically be faster than option 2, but it's more verbose, and requires Python 2.6+. It also allows for the rewrap to be Unicode friendly, by changing the mode to 'r' and optionally passing the known encoding of the input (if it's not the locale default) to seamlessly get unicode lines instead of (ASCII only) str. *(Any version of Python) Work around problems with file.__next__ by using file.readline instead; despite nearly identical intended behavior, readline doesn't do its own (over)buffering, it delegates to C stdio's fgets (default build settings) or a manual loop calling getc/getc_unlocked into a buffer that stops exactly when it hits end of line. By combining it with two-arg iter you can get nearly identical code without excess verbosity (it'll probably be slower than the prior solution, depending on whether fgets is used under the hood, and how the C runtime implements it): # '' is the sentinel that ends the loop; readline returns '' at EOF for line in iter(sys.stdin.readline, ''): # Do stuff with line *Move to Python 3, which doesn't have this problem. :-) A: In Linux, bash, what you are looking for seems to be the stdbuf command. If you want no buffering (i.e. an unbuffered stream), try this, # batch_job | stdbuf -o0 myparser If you want line buffering, try this, # batch_job | stdbuf -oL myparser A: You can unbuffer the output: unbuffer batch_job | myparser
{ "language": "en", "url": "https://stackoverflow.com/questions/33305131", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: How to focus on one Entry when Using TextChange for multiple entries I have 2 entries. When I tap anything on entry 1 I would like to get "Yess" on entry 2 and when I type anything on entry 2 I would like to get "Noo" The problem: When I tap on entry 1, entry 2 change and get the value "Noo" but entry 1 change too and get the value "yess". Question : How can make entry 2 change when tapping on entry 1 without changing entry 1. And the same for entry 2 Here is Xaml code : <Entry ClassId="1" x:Name="myWord1"TextChanged="OnEntryTextChange"/> <Entry ClassId="2" x:Name="myWord2" TextChanged="OnEntryTextChange"/> Code : private async void OnEntryTextChange(object sender, TextChangedEventArgs e) { var EntryTapped = (Xamarin.Forms.Entry)sender; Device.BeginInvokeOnMainThread(() => { if (EntryTapped.ClassId == "1") { myWord2.Text="Noo"; } else if (EntryTapped.ClassId == "2") { myWord1.Text="yess"; } }); } Thanks for your help A: You could use the Focused event instead of TextChanged event. <StackLayout> <Entry ClassId="1" x:Name="myWord1" Focused="EntryFocused"/> <Entry ClassId="2" x:Name="myWord2" Focused="EntryFocused"/> </StackLayout> private void EntryFocused(object sender, FocusEventArgs e) { var EntryTapped = (Xamarin.Forms.Entry)sender; if (EntryTapped.ClassId == "1") { myWord2.Text = "Noo"; } else if (EntryTapped.ClassId == "2") { myWord1.Text = "yess"; } } A: There are several ways of doing this: * *Using bindings In this case you would have 2 private variables and 2 public variables, and the entries binded to each one. Check this link how to implement INotifyPropertyChanged private string entry1String; private string entry2String; public string Entry1String { get => entry1String; set { entry2String = "Noo"; entry1String = value; OnPropertyChanged(Entry1String); OnPropertyChanged(Entry2String); } } public string Entry2String { get => entry2String; set { entry1String = "Yees"; entry2String = value; OnPropertyChanged(Entry1String); OnPropertyChanged(Entry2String); } } Another way could be using a variable as a Semaphore. While the variable is True, the method cannot be fired at the same time by another. private bool semaphoreFlag=false; private async void OnEntryTextChange(object sender, TextChangedEventArgs e) { if(semaphoreFlag) return; semaphoreFlag=true; var EntryTapped = (Xamarin.Forms.Entry)sender; Device.BeginInvokeOnMainThread(() => { if (EntryTapped.ClassId == "1") { myWord2.Text="Noo"; } else if (EntryTapped.ClassId == "2") { myWord1.Text="yess"; } }); semaphoreFlag=false; }
{ "language": "en", "url": "https://stackoverflow.com/questions/69370031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to search for a function in namespaces not 'required' or 'used' in Clojure? How can I search for a function in namespaces not 'required' or 'used' in a Clojure source file? Basically what I'd like to do is have source files: main.clj, a.clj, b.clj, c.clj all compiled together but not directly import / require / use a, b, or c in main. Instead I have main take a command line parameter that would then search for the right function (perhaps even just a fully qualified symbol). I looked at ns-publics but it requires a namespace symbol. I tried bultitude to get all the namespaces from with the src/ dir and I get back the lib.a, lib.b, lib.c, lib.main etc, but since main doesn't use or require or otherwise refer to the other namespaces I get an error using ns-publics. No namespace lib.a found as per the try in the-ns source code. How can I look at the public interface of code included in the project but not directly referred to by a specific file, or even a dependency of a reference? A: Here's a simple workaround which might help until a better solution comes up. It returns a list of all public symbols defined in a file. Let's read the file and look for all def sexps. Ignore private ones, i.e. ones like defn-. (let [file (with-in-str (str "(" (slurp filename) ")") (read)) defs (filter #(.matches (str (first %)) "^def.*[^-]$") file) symbols (map second defs)] symbols) Caveats: * *Well, it's simply naïve. *It doesn't get rid of all private definitions. Ones defined with ^{:private true} or ^:private are not filtered out. *Definitions can be generated using macros. The last point is especially troubling. The only reasonable way to detect definitions generated with macros is to evaluate the file with the reader, at least partially. A: Parsing isn't going to work because clojure is very dynamic. So, something like this might work... (load-file "file_with_stuff.clj") (ns-publics (find-ns 'file-with-stuff)) (remove-ns 'file-with-stuff) If you want to do everything dynamically, then you can generate the symbols using symbol -- should still work. Removing the ns is optional. It won't do any harm, but it does put you back where you started.
{ "language": "en", "url": "https://stackoverflow.com/questions/14266910", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get ProcessGroup from processor Is there an API to get a ProcessGroup by id from a custom processor or an ExecuteScript processor? I know that it is possible by using the REST-API, but for security reasons, I don't have the chance to use the credentials to invoke the API from a service. Regards A: If you use a InvokeScriptedProcessor using groovy you can use context.procNode.processGroup from the ProcessContext If you want to extract all the parents in a breadcrum way, you can use this: import groovy.json.*; import org.apache.nifi.groups.*; class GroovyProcessor implements Processor { def REL_SUCCESS = new Relationship.Builder() .name("success") .description('FlowFiles that were successfully processed are routed here').build() def ComponentLog log @Override void initialize(ProcessorInitializationContext context) { log = context.logger } @Override Set<Relationship> getRelationships() { return [REL_SUCCESS] as Set } void executeScript(ProcessSession session, ProcessContext context) { def flowFile = session.get() if (!flowFile) { return } def breadcrumb = getBreadCrumb(context.procNode.processGroup) + '->' + context.getName() flowFile = session.putAttribute(flowFile, 'breadcrumb', breadcrumb) // transfer session.transfer(flowFile, this.REL_SUCCESS) } // Recursive funtion that gets the breadcrumb String getBreadCrumb(processGroup) { def breadCrumb = '' if(processGroup.parent != null) breadCrumb = getBreadCrumb(processGroup.parent) + '->' return breadCrumb + processGroup.name } @Override void onTrigger(ProcessContext context, ProcessSessionFactory sessionFactory) throws ProcessException { def session = sessionFactory.createSession() try { executeScript( session, context) session.commit() } catch (final Throwable t) { log.error('{} failed to process due to {}; rolling back session', [this, t] as Object[]) session.rollback(true) throw t } } @Override PropertyDescriptor getPropertyDescriptor(String name) { null } @Override List<PropertyDescriptor> getPropertyDescriptors() { return [] as List } @Override void onPropertyModified(PropertyDescriptor descriptor, String oldValue, String newValue) { } @Override Collection<ValidationResult> validate(ValidationContext context) { null } @Override String getIdentifier() { null } } processor = new GroovyProcessor()
{ "language": "en", "url": "https://stackoverflow.com/questions/55288989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to slice a value which is inside and obj and pass to next metod which uses it as an object I have a specific situation where I have a method that getting an object as follow async ({ locale }, ctx) => { const lang = await LanguageService(ctx).getLanguage({ locale, }); return lang.direction ? 'rtl' : 'ltr'; }, The { locale } is equal to a request as locale: en_US. The next method I need to use getLanguage accepts { locale } but I have to pass only the en. So I thought to do slice but if I send it as for example const sliced = locale.slice(0,2) const lang = await LanguageService(ctx).getLanguage({ sliced, // or locale: sliced }); From the next method the locale is showed as undefined and I have no clue how to pass only en in this situation I have The method getLanguage async getLanguage({ id, locale }) { console.log('locale: ', locale); if (!id && !locale) { const errorMessage = 'Specify ID or locale'; throw new ApolloError(errorMessage); } const filter = id ? { id } : { locale }; try { return await this.withDAO(({ languages }) => languages.selectFirst(filter) ); } catch (error) { throw new ApolloError(error.message); } } This method needs { locale } and I need to pass en and not en_US I have no clue how to reach that as when I reach this above method the console.log(locale) is showing undefined when I use slice. There is a way I can use that obj in the way I need
{ "language": "en", "url": "https://stackoverflow.com/questions/69483368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Group by array contents I have a List<Tuple<string,long,byte[]>> and I want to group by the contents of the byte array. Is there a simple way to do this with GroupBy and a lambda? Ideally, I want to do this without creating an intermediate data structure (like a string to hold the elements of the array). A: You can achieve that using custom IEqualityComparer<byte[]> (or even better, generic one: IEqualityComparer<T[]>) implementation: class ArrayComparer<T> : IEqualityComparer<T[]> { public bool Equals(T[] x, T[] y) { return x.SequenceEqual(y); } public int GetHashCode(T[] obj) { return obj.Aggregate(string.Empty, (s, i) => s + i.GetHashCode(), s => s.GetHashCode()); } } I'm pretty sure GetHashCode could be implemented much better, but it's just an example! Usage: var grouped = source.GroupBy(i => i.Item3, new ArrayComparer<byte>())
{ "language": "en", "url": "https://stackoverflow.com/questions/15841178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to show a message when collection view is empty I`m trying to show a message only when my collection view is empty. Well, I try set return 1 when my if is true but when I have this, it only show one item in my collection view (even if I had more). And when I return this (code bellow) it shows all the items I have in my collection view but when I try to delete it, the last one is not "deletable", I mean, the last one stays there. How can I show this message only if I have no items in my collection view? func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if self.movies.count > 0 { self.favCollectionView.backgroundView = nil return self.movies.count } else { let rect = CGRect(x: 0, y: 0, width: self.favCollectionView.bounds.size.width, height: self.favCollectionView.bounds.size.height) let noDataLabel: UILabel = UILabel(frame: rect) noDataLabel.text = "No favorite movies yet." noDataLabel.textAlignment = .center noDataLabel.textColor = UIColor.gray noDataLabel.sizeToFit() self.favCollectionView.backgroundView = noDataLabel return 0 } } Update I did it like this: func numberOfSections(in collectionView: UICollectionView) -> Int { return 2 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if section == 0 { return self.movies.count} else if section == 1 { if self.movies.count < 1 { return 1 } else { return 0 } } return 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = favCollectionView.dequeueReusableCell(withReuseIdentifier: "FavCollectionCell", for: indexPath) as! FavoritesCollectionViewCell if indexPath.section == 0 { let movie = movies[indexPath.row] let imgStg: String = movie.posterURL! let imgURL: URL? = URL(string: imgStg) let imgSrc = ImageResource(downloadURL: imgURL!, cacheKey: imgStg) cell.favTitleLabel.text = movie.title cell.favPosterImageView.layer.cornerRadius = cell.favPosterImageView.frame.size.width/2 cell.favPosterImageView.clipsToBounds = true //image cache with KingFisher cell.favPosterImageView.kf.setImage(with: imgSrc) return cell } else { let rect = CGRect(x: 0, y: 0, width: self.favCollectionView.frame.width, height: self.favCollectionView.frame.height) let noDataLabel: UILabel = UILabel(frame: rect) noDataLabel.text = "No favorite movies yet." noDataLabel.textAlignment = .center noDataLabel.textColor = UIColor.gray noDataLabel.sizeToFit() let cell = UICollectionViewCell() cell.contentView.addSubview(noDataLabel) return cell } } For @Lamar's solution, but the app crashed with error: A: I make use of the backgroundView in an extension as such: extension UICollectionView { func setEmptyMessage(_ message: String) { let messageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height)) messageLabel.text = message messageLabel.textColor = .black messageLabel.numberOfLines = 0; messageLabel.textAlignment = .center; messageLabel.font = UIFont(name: "TrebuchetMS", size: 15) messageLabel.sizeToFit() self.backgroundView = messageLabel; } func restore() { self.backgroundView = nil } } and I use it as such: func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if (self.movies.count == 0) { self.collectionView.setEmptyMessage("Nothing to show :(") } else { self.collectionView.restore() } return self.movies.count } A: Maybe little bit late but here is little more constraint based solution. Still may help some one. First create some empty state message (You can also create own, more complex view with image or something). lazy var emptyStateMessage: UILabel = { let messageLabel = UILabel() messageLabel.translatesAutoresizingMaskIntoConstraints = false messageLabel.textColor = .darkGray messageLabel.numberOfLines = 0; messageLabel.textAlignment = .center; messageLabel.font = UIFont.systemFont(ofSize: 15) messageLabel.sizeToFit() return messageLabel }() Then add two methods and call them whenever you like. func showEmptyState() { collectionView.addSubview(emptyStateMessage) emptyStateMessage.centerXAnchor.constraint(equalTo: collectionView.centerXAnchor).activate() emptyStateMessage.centerYAnchor.constraint(equalTo: collectionView.centerYAnchor).activate() } func hideEmptyState() { emptyStateMessage.removeFromSuperview() } A: Use backgroundView of your Collection View to display the no results message. A: I would say have two sections in your collectionView, where one is for the actual data to be displayed, then the other one when you don't have any data. Assuming we are populating data in section 0. in numberOfRowsInSection you'd have something like: if section == 0 { return movies.count} else if section == 1 { if movies.count < 1 { return 1 } else { return 0 } } return 0 in your cellForItemAt you'd do something like that: if indexPath.section == 0 { // let cell = ... // show your data into your cell return cell }else { // here you handle the case where there is no data, but the big thing is we are not dequeuing let rect = CGRect(x: 0, y: 0, width: self.favCollectionView.frame.width, height: self.favCollectionView.frame.height) let noDataLabel: UILabel = UILabel(frame: rect) noDataLabel.text = "No favorite movies yet." noDataLabel.textAlignment = .center noDataLabel.textColor = UIColor.gray noDataLabel.sizeToFit() let cell = UICollectionViewCell() cell.contentView.addSubview(noDataLabel) return cell } A: Why don't you use: open var backgroundView: UIView? // will be automatically resized to track the size of the collection view and placed behind all cells and supplementary views.` You can show it whenever collection is empty. Example: var collectionView: UICollectionView! var collectionData: [Any] { didSet { collectionView.backgroundView?.alpha = collectionData.count > 0 ? 1.0 : 0.0 } }
{ "language": "en", "url": "https://stackoverflow.com/questions/43772984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: php menu generator with multidimensial array I need help with my array. For several hours trying to find a solution but I can not cope. I tried to do it in such a way, however, the code turned out to be completely useless. private function findKey($array, $keySearch,$app,$klucz='') { foreach ($array as $key => $item) { if ($key == $keySearch) { $c2 = []; $cache = [ 'nazwa'=>$app->nazwa, 'link'=>$app->link, 'child'=>[] ]; // echo $klucz; echo '<br />'; if($klucz && $klucz != '/'){ // echo $klucz; // $k = explode('/',$klucz); // $url = "/2/22/"; // debug($klucz); $parts = explode('/',$klucz); debug($klucz); debug($parts); $x = 0; $last = $parts[count($parts)-1]; $arr = array(); while ($bottom = array_pop($parts)) { if($bottom != $last){ $arr = array($bottom => $arr); $x++; }else{ array_push($arr, $cache); } } // $arr['child'] = $cache; debug($arr); // exit; // print_r($output); // exit; // self::buildKey($k); // print_r($c2); echo "<br />"; } } else { $klucz = $klucz.'/'.$key; if (is_array($item) && self::findKey($item, $keySearch,$app,$klucz)) { // return true; } } } // return false; } I need to create array from loop. From mysql I get data as object, and this data view like this: |id|nazwa|link|parent| |1|abc|abcc|0| |2|aaa|bbb|1| |3|aas|bbc|2| |4|asdasd|adsasd|2| |5|asdasd|serae|4| |6|rywer|twet|0| And now I need array whose use data from mysql and display it at array like this: array( [1]=>array( id=>1, nazwa=>abc link=>abcc child=>array( [2]=>array( id=>2, nazwa=>aaa link=>bbb child=>array( [3]=>array( id=>3, nazwa=>aas link=>bbc child=>array( ) ), [4]=>array( id=>4, nazwa=>asdasd link=>adsasd child=>array( [5]=>array( id=>5, nazwa=>asdasd link=>serae child=>array( ) ), ) ), ) ) ) ), [6]=>array( id=>6, nazwa=>rywer link=>twet child=>array( ) ), ) I think just a simple, good loop or function but I can not deal with it. A: Try my code link to online demo: <?php $data = array( array( 'id' => 1, 'name' => 'abc', 'link' => 'abcc', 'parent' => 0 ), array( 'id' => 2, 'name' => 'aaa', 'link' => 'bbb', 'parent' => 1 ), array( 'id' => 3, 'name' => 'aas', 'link' => 'bbc', 'parent' => 2 ), array( 'id' => 4, 'name' => 'asdasd', 'link' => 'adsasd', 'parent' => 2 ), array( 'id' => 5, 'name' => 'asdasd', 'link' => 'serae', 'parent' => 4 ), array( 'id' => 6, 'name' => 'rywer', 'link' => 'twet', 'parent' => 0 ) ); function buildMenu($data) { usort($data, function($a, $b) { if ($a['parent'] == $b['parent']) { if ($a['id'] == $b['id']) { return 0; } return ($a['id'] < $b['id']) ? -1 : 1; } return ($a['parent'] < $b['parent']) ? -1 : 1; }); $shortcuts = array(); $menu = array(); foreach($data as &$row) { if ($row['parent'] <= 0) { $menu[] = &$row; $shortcuts[$row['id']] = &$row; continue; } else { $parent = $row['parent']; if (!isset($shortcuts[$parent])) { throw new \Exception("Menu cannot be build"); } $parentItem = &$shortcuts[$parent]; } if (!isset($parentItem['child'])) { $parentItem['child'] = array(); } $parentItem['child'][] = &$row; $shortcuts[$row['id']] = &$row; } return $menu; } print_r(buildMenu($data)); It uses references to keep it clean. On the beggining of buildMenu function I have also sorted your sorce array to have data sorted by parent ID, increasingly. Please also consider using english variable names. If you would like to generate <ul> menu from this array, use this code: $menu = '<ul>'; function buildUl($data) { $menuHtml = ''; foreach ($data as $menuItem) { $menuHtml .= '<li>'; $menuHtml .= '<a href="'.$menuItem['link'].'">'.$menuItem['name'].'</a>'; if (!empty($menuItem['child'])) { $menuHtml .= '<ul>'; $menuHtml .= buildUl($menuItem['child']); $menuHtml .= '</ul>'; } $menuHtml .= '</li>'; } return $menuHtml; } $menu .= buildUl(buildMenu($data)); $menu .= '</ul>'; echo $menu; Updated example: http://sandbox.onlinephpfunctions.com/code/27cfa95c066be9b1526b71566e2ec2f2093bdc34 A: Things are way easier when you use objects: $data = [ ['id' => 1, 'nazwa' => 'abc', 'link' => 'abcc', 'parent' => 0], ['id' => 2, 'nazwa' => 'aaa', 'link' => 'bbb', 'parent' => 1], ['id' => 3, 'nazwa' => 'aas', 'link' => 'bbc', 'parent' => 2], ['id' => 4, 'nazwa' => 'asdasd', 'link' => 'adsasd', 'parent' => 2], ['id' => 5, 'nazwa' => 'asdasd', 'link' => 'serae', 'parent' => 4], ['id' => 6, 'nazwa' => 'rywer', 'link' => 'twet', 'parent' => 0], ]; $objectTree = []; $objects = []; foreach ($data as $row) { $obj = (object)$row; $obj->childs = []; $objects[$obj->id] = $obj; } foreach ($objects as $obj) { if ($obj->parent == 0) { $objectTree[] = $obj; } else { $objects[$obj->parent]->childs[] = $obj; } } var_export($objectTree); Demo: http://rextester.com/RZRQLX19028
{ "language": "en", "url": "https://stackoverflow.com/questions/42891769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Clean tuple to string I have a variable p which print(p) = ('180849', '104735') and I want it to be p = 180849 104735 So, basically get rid off ( and ' and , Any help with that please? A: You can directly unpack the elements to print function. By default print function insert space between the values(this can be controlled via sep argument) >>> p = ('180849', '104735') >>> print(*p) 180849 104735 >>> print(*p, sep='-') 180849-104735 A: How about this, it is the easier way! tup = ('this', 'is', 'a', 'tuple') res = " ".join(tup) I hope you like it.
{ "language": "en", "url": "https://stackoverflow.com/questions/69961323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Access listbox from another class? I made a class so when the user selects item from listbox it uninstalls that item, except the problem is I can't access the list box. I tried public aswell, but in the code of form1.cs the only thing clostest to that list box is keep in mind name of listbox is ProgramslistBox Ok guys I re edited this post; private void button1_Click(object sender, EventArgs e) { if(ProgramsListbox.SelectedIndex == -1) { MessageBox.Show("Please select an item to uninstall!"); } else { ProgramsListbox_SelectedIndexChanged("",EventArgs.Empty); } } this code is the FORM1.CS class, and I have another class called UninstallItem.cs is where I want my code to be, this below is my other class namespace PC_TECH_Registery_Cleaner { class UninstallItem { public void uninstallSelectedItem() { Form1 c = new Form1(); } } } And this below is still in my FORM1.CS class, I was experimenting with it : public void ProgramsListbox_SelectedIndexChanged(object sender, EventArgs e) { //this will access the Uninstall item class so we can uninstall selected item. UninstallItem c = new UninstallItem(); c.uninstallSelectedItem(); } A: The 2 easy ways to think about this are either * *Call the method in your class from the event handler in your form *Have a method on your class which matches the signature of an event handler, and subscribe to the event. The first requires no major change private MyClass myClass = new MyClass(); public void ProgramsListbox_SelectedIndexChanged(object sender, EventArgs e) { myClass.DoSomething(); } The second requires your class to have a specific method that matches the signature of that event handler currently in your form public class MyClass { public void DoSomething(object sender, EventArgs e) { var listBox = (ListBox)sender; // read selected index perhaps, or selected item maybe } } And then in your form private MyClass myClass = new MyClass(); protected override void OnLoad(EventArgs e) { this.ProgramsListBox.SelectedIndexChanged += myClass.DoSomething; } A: Within your Form1.cs create instance of UnIstallItem class and use it. Then on Button Click call "RemoveSelected" method of UnInstaItem class by passing programsListBox to it and it should remove the selected item. public class Form1:Form { ListBox ProgramsListbox; UninstallItem unistall; public Form1(){ InitializeComponent(); uninstall = new UninstallItem(); button1.Click+= button1_Click; } void button1_Click(object sender, EventArgs e){ unistall.RemoveSelected(ProgramsListbox); } } Then in your external class; public class UninstallItem{ public UninstallItem{} public void RemoveSelected(ListBox list) { if(list.SelectedIndex==-1) { MessageBox.Show("Please Select Item from List"); return; } list.Items.RemoveAt(list.SelectedIndex); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/37110526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Obtaining destination ip address in Powershell (Invoke-WebRequest) I'm writing script for automation of TCP connections and I have a question. Is there an option to get destination IP address, when you call (for example): Invoke-WebRequest google.com Problem is, when I call this command, destination IP address is always different, so I can't use command like ''test-connection''. I would like to hear further explanation. I know that Google has multiple public addresses, but why are they different when I call Invoke-WebRequest, or Test-Connection? Example: 1. Destination IP from wireshark capture 2. IP address from Test-Connection command: google.com 172.217.18.78 Greetings A: Google has a huge userbase. They want to be reachable via multiple addresses, as that provides robust connections and some load balancing too. The technique is called DNS Round Robin. In case one of the multiple IP addresses doesn't work, most modern browsers will automatically try and use other addresses. If you would like to test a connection to particular IP, you could do a name lookup and pick one of the results. Like so, # Get a list of all Google IPs $googles = [Net.Dns]::GetHostAddresses("www.google.com") # Use IP address for the 1st entry test-connection $googles[0].IPAddressToString
{ "language": "en", "url": "https://stackoverflow.com/questions/44754928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Joi Schema should contain one or another chema I'm looking into using Joi for api validation. So it must be like one or another chema Joi.object({ email: Joi.string().required(), notes: Joi.object({ title: Joi.string().required(), details: Joi.string().required() }) }) try for another Joi.object({ first_name: Joi.string().prefs({ convert: false }), last_name: Joi.string().prefs({ convert: false }), cell_phone_1: Joi.number().min(1e9).max(9999999999).prefs({ convert: false }), }).or('first_name', 'last_name')) Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/73649772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I add the class name of an object as the index of the serializated json in JMSSerialize I have a simple class like: class Car { public doors; public color; public seats; } If I serialize a new object with: $this->get('jms_serializer')->serialize($newCar, 'json'); I will get something like: {doors:1, color: 'red', seats: 4} I wonder if it's possible to have this instead (Edit: and to be able to deserialize the same string): car:{doors:1, color: 'red', seats: 4} Thanks A: You can try this: // Encode $className = get_class($newCar); $jmsSerialize = $this->get('jms_serializer')->serialize($newCar, 'json'); $resultJSONEncode = json_encode([$className=>$jmsSerialize]); var_dump($resultJSONEncode); // Decode $resultJSONDecode = json_decode($resultJSONEncode, true); $jmsDesrialize = $this->get('jms_serializer')->deserialize($resultJSONDecode[$className], $className, 'json'); var_dump($jmsDesrialize);
{ "language": "en", "url": "https://stackoverflow.com/questions/37862708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to deploy a python webapp with dependencies using virtualenv? I'm looking for a way to automate deployment of web applications written in Python to a server. I would like to use virtualenv to have a clean environment for this application. However, I am wondering how to manage dependencies when deploying to the server ? In development, I have a virtualenv in which I install external libraries using pip, so I am looking for a way to automatically install those dependencies in production ? Thank you for your time A: With pip you can create a requirements file: $ pip freeze > requirements.txt Then in the server to install all of these you do: $ pip install -r requirements.txt And with this (if the server has everything necessary to build the binary packages that you might have included) all is ready.
{ "language": "en", "url": "https://stackoverflow.com/questions/3211080", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: javafx shape3d texturing: Don't strectch the image I'm working now with javafx to build a maze and I want the walls to be textured with some seamless texture (that can be repeated). The maze is randomly generated so I don't know the size of any walls. I started by using a PhongMaterial with the desired texture, but it expand the image to fill the whole wall (a Box), so my texture is totally stretched. Is there any way to force the Material to replicate the texture as needed ? The code is like: Image img = new Image(new FileInputStream("img.jpg"), 400, 400, true, false); Material mat = new PhongMaterial(Color.WHITE, img, null, null, null); Box w = new Box(100,10,10); w.setMaterial(mat); Something like an ImagePattern seems a good idea, but there is no Material that accept it. Thanks in advance for any help A: As @fabian mentioned, Box is not suitable for customizing the texture. By default the image you set as diffuse map will be applied for each of its six faces, and, as you already discovered, this means that it will stretch the image to accommodate the different sides. Using the FXyz library, we can easily try the Carbon-Kevlar pattern. But obviously we have to select a size for it. Like 100 x 30. @Override public void start(Stage primaryStage) { Box box = new Box(100, 30, 50); PhongMaterial material = new PhongMaterial(); Patterns pattern = new Patterns(100, 30); material.setDiffuseMap(pattern.createPattern(Patterns.CarbonPatterns.CARBON_KEVLAR, false)); box.setMaterial(material); Scene scene = new Scene(new Group(box), 500, 400, true, SceneAntialiasing.BALANCED); primaryStage.setScene(scene); primaryStage.show(); } While the texture fits perfectly fine the front face with dimensions 100x30, this image is distorted to fit in the same way the other faces 50x50 and 100x50. Solution 1 We can try to generate our own Box, so we can decide how to apply the diffuse map. Creating a TriangleMesh for a cuboid is easy in terms of vertices and faces or normals. The tricky part is setting the texture coordinates. In the following snippet I set them based on one of the different possible 2D net images of the 3D cuboid: public MeshView createCuboid(float w, float h, float d) { float hw = w / 2f; float hh = h / 2f; float hd = d / 2f; float points[] = { hw, hh, hd, hw, hh, -hd, hw, -hh, hd, hw, -hh, -hd, -hw, hh, hd, -hw, hh, -hd, -hw, -hh, hd, -hw, -hh, -hd}; float L = 2 * w + 2 * d; float H = h + 2 * d; float tex[] = { d / L, 0f, (d + w) / L, 0f, 0f, d / H, d / L, d / H, (d + w) / L, d / H, (2 * d + w) / L, d / H, 1f, d / H, 0f, (d + h) / H, d / L, (d + h) / H, (d + w) / L, (d + h) / H, (2 *d + w) / L, (d + h) / H, 1f, (d + h) / H, d / L, 1f, (d + w) / L, 1f}; float normals[] = { 1f, 0f, 0f, -1f, 0f, 0f, 0f, 1f, 0f, 0f, -1f, 0f, 0f, 0f, 1f, 0f, 0f, -1f, }; int faces[] = { 0, 0, 10, 2, 0, 5, 1, 0, 9, 2, 0, 5, 3, 0, 4, 1, 0, 9, 4, 1, 7, 5, 1, 8, 6, 1, 2, 6, 1, 2, 5, 1, 8, 7, 1, 3, 0, 2, 13, 1, 2, 9, 4, 2, 12, 4, 2, 12, 1, 2, 9, 5, 2, 8, 2, 3, 1, 6, 3, 0, 3, 3, 4, 3, 3, 4, 6, 3, 0, 7, 3, 3, 0, 4, 10, 4, 4, 11, 2, 4, 5, 2, 4, 5, 4, 4, 11, 6, 4, 6, 1, 5, 9, 3, 5, 4, 5, 5, 8, 5, 5, 8, 3, 5, 4, 7, 5, 3}; TriangleMesh mesh = new TriangleMesh(); mesh.setVertexFormat(VertexFormat.POINT_NORMAL_TEXCOORD); mesh.getPoints().addAll(points); mesh.getTexCoords().addAll(tex); mesh.getNormals().addAll(normals); mesh.getFaces().addAll(faces); return new MeshView(mesh); } Now we can generate the image, but using the net dimensions: @Override public void start(Stage primaryStage) { MeshView box = createCuboid(100, 30, 50); PhongMaterial material = new PhongMaterial(); Patterns pattern = new Patterns(300, 160); material.setDiffuseMap(pattern.createPattern(Patterns.CarbonPatterns.CARBON_KEVLAR, false)); box.setMaterial(material); box.getTransforms().addAll(rotateX, rotateY); Scene scene = new Scene(new Group(box), 500, 400, true, SceneAntialiasing.BALANCED); primaryStage.setScene(scene); primaryStage.show(); } Note that the image is not distorted anymore. You can play with its size to get a more fine or dense pattern (with a bigger image pattern). Note that you can find this Cuboid primitive in the FXyz library, among many other 3D primitives. Also you can find different texture modes (density maps, images, patterns...)
{ "language": "en", "url": "https://stackoverflow.com/questions/49130485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Bit shifting 16 bit from left to right C# I have an array of 8 bit with the following representation. Data[i] = 192=11000000, data[i+1]= 85=01010101, i need to transform the represenatation into 16bit array where newArr[i] =343=101010111. The same numbers only shifted to right. My first idea was to use the field i have bpp (number of bits =10). So var t=16-10. Data[i] >>t. And Data[i+1]>>t however this doesn't give the correct answer. Please help A: I have these two functions for you, to shift in a byte-array: static public void ShiftLeft(this byte[] data, int count, bool rol) { if ((count <0) || (count > 8)) throw new ArgumentException("Count must between 0 and 8."); byte mask = (byte)(0xFF << (8 - count)); int bits = rol ? data[0] & mask : 0; for (int i = data.Length - 1; i >= 0; i--) { int b = data[i] & mask; data[i] = (byte)((data[i] << count) | (bits >> (8 - count))); bits = b; } } static public void ShiftRight(this byte[] data, int count, bool rol) { if ((count <0) || (count > 8)) throw new ArgumentException("Count must between 0 and 8."); byte mask = (byte)(0xFF >> (7 - count)); int bits = rol ? data[data.Length - 1] & mask : 0; for (int i = 0; i < data.Length; i++) { int b = data[i] & mask; data[i] = (byte)((data[i] >> count) | (bits << (8 - count))); bits = b; } } For your code example, call them like this: byte[] data = ...; ShiftLeft(data, 2, false); Assuming you want to copy 2 bytes into 1 ushort, you can use this code (make sure it is even in length!): byte[] data = ...; short[] sdata = new short[data.Length / 2]; Buffer.BlockCopy(data, 0, sdata, 0, dataLen); If you want to copy 1 byte into 1 ushort, then this would be the answer: byte[] data = ...; short[] sdata = Array.ConvertAll(data, b => (short)b); A: I take your question to mean you want to do this conversion: combine aaaaaaaa and bbbbbbbb into bbbbbbbbaaaaaaaa and then apply a right-shift by 6, yielding 000000bbbbbbbbaa. Then this will be your code: using System; public class Test { public static void Main() { byte[] src = new byte[2] { 192, 85 }; ushort[] tgt = new ushort[1]; for ( int i = 0 ; i < src.Length ; i+=2 ) { tgt[i] = (ushort)( ( src[i+1]<<8 | src[i] )>>6 ); } System.Console.WriteLine( tgt[0].ToString() ); } } If what you want to do is combine to aaaabbbbbbbbaa, then this will require |-ing a src[i]<<10 in a second step, as there is no circular shift operator in C#. A: my final code :D public override short[] GetShortDataAlignedRight() { short[] ReturnArray = new short[_channels[0].Data.Length / 2]; if (_channels[0].Bpp == 8) { Buffer.BlockCopy(_channels[0].Data, 0, ReturnArray, 0, _channels[0].Data.Length); } else { short tempData; int offsetHigh = 8 - (16 - _channels[0].Bpp); int offsetLow = (16 - _channels[0].Bpp); for (int i = 0, j = 0; i < _channels[0].Data.Length; i += 2, j++) { tempData = (short)(_channels[0].Data[i] >> offsetLow); tempData |= (short)(_channels[0].Data[i + 1] << offsetHigh); ReturnArray[j] = tempData; } } return ReturnArray; }
{ "language": "en", "url": "https://stackoverflow.com/questions/16379483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How does the connection manager discard unconsumed connection? I am trying to debug a connection leak issue in my app where the connection manager is using more connections than I would have wanted. One lead I have is the following: According to Apache HttpClient quick start, if response content is not fully consumed for any reason, the pooling connection manager can not safely reuse the underlying connection and will discard it. Can anyone point me to the code block that does the checking of unconsumed content in a connection and the discarding of the connection? // Please note that if response content is not fully consumed the underlying // connection cannot be safely re-used and will be shut down and discarded // by the connection manager. try (CloseableHttpResponse response1 = httpclient.execute(httpGet)) { System.out.println(response1.getCode() + " " + response1.getReasonPhrase()); HttpEntity entity1 = response1.getEntity(); // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity1); } A: HttpClient version 4.x and 5.x wrap HTTP response entity with a proxy that releases the underlying connection back to the pool upon reaching the end of the message stream. In all other cases HttpClient assumes the message has not been fully consumed and the underlying connection cannot be re-used. https://github.com/apache/httpcomponents-client/blob/master/httpclient5/src/main/java/org/apache/hc/client5/http/impl/classic/ResponseEntityProxy.java
{ "language": "en", "url": "https://stackoverflow.com/questions/71215585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reading data from a BLE smartband failed with app inventor I have a smartband (DS-D6) that communicates values through AT commands with the use of two UUIDs (0000190b-0000-1000-8000-00805f9b34fb and 0000190a-0000-1000-8000-00805f9b34fb). I confirmed these two UUIDs are working using a Serial BLE Terminal App. However, only one of the UUID (0000190b-0000-1000-8000-00805f9b34fb) is working, with app inventor (using latest BLE extension). I don’t know what is going wrong. The device is connected but there is no response to AT commands when I use 0000190a-0000-1000-8000-00805f9b34fb service UUID, while everything works well using the other UUID. I double checked the UUID numbers carefully and also confirmed them using nRFconnect app. I tried to interchange characteristic UUID values, still it didn't work. I don't understand what is causing this behavior that only of the service UUIDs is working with app inventor while both of them are working with BLE serial APP. I attached here the relevant blocks from App inventor. Please note that I am using only of the service UUIDs at a time. More information about the smartband can be found in the following link https://github.com/fanoush/ds-d6/wiki/Bracelet-commands
{ "language": "en", "url": "https://stackoverflow.com/questions/61851049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Detect faces in python with MTCNN, Opencv and multithreading I'm here because I'm really stuck on my project. At the beginning of my project, it was just a simple face detection that worked pretty well using Python, Opencv, and the MTCNN model. The problem was that the program was pretty slow and I tried to make it faster. My research then, unfortunately, led me to multithreading and I didn't really know what I was getting into. In my program, I'm using 1 function: process_frame() 2 variables: frame and frame_buffer The purpose of this program is therefore to have both image processing and simultaneous playback of video streams in order to gain performance. The problem is that imshow() of my function "process_frame" works very well, I have pictures with a face detected. However, as soon as I enter my main loop, I have a simple video stream without detection. I was just wondering if my problem would not come from a problem with the synchronization of my threads. I know that adding multithreading can slow down my program more than anything else but you have to practice to understand ahah I would be pleased to have a little help because I admit to being stuck for a long time Below is the code: import cv2 import numpy as np from mtcnn import MTCNN import threading import time import tensorflow as tf from threading import Lock #import pdb #pdb.set_trace() lock = Lock() cap = cv2.VideoCapture(0) frame_buffer = [] frame = None def process_frame(): global frame_buffer, stop_event, lock, frame while not stop_event.is_set(): try: lock.acquire() if frame is None: print("frame vide") continue print ("frame copié avec succes") frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frame = cv2.resize(frame, (320,240)) frame = frame_buffer except Exception as e: print("Une exception a été levée lors du traitement de l'image :", e) continue finally : lock.release() try: model = MTCNN(min_face_size=10) predictions = model.detect_faces(frame) print(f"{len(predictions)} visages détectés") except Exception as e: print("Une exception a été levée lors de la détection des visages :", e) try: predictions = [prediction for prediction in predictions if prediction['confidence'] > 0.5] print(f"{len(predictions)} visages filtrés") except Exception as e: print("Une exception a été levée lors de la filtration des prédictions :", e) for face in predictions: try: x, y, w, h = face['box'] with lock : cv2.rectangle(frame, (x,y), (x+w, y+h), (255, 0, 0), 2) cv2.imwrite("parth/image_traitee_process_frame.jpg", frame_buffer, [cv2.IMWRITE_JPEG_QUALITY, 100]) except Exception as e: print("Une exception a été levée lors de l'ajout de l'annotation du rectangle :", e) print ("frame mis a jour avec succes") #frame_buffer = frame print ("Copie de la liste de frame : ", frame, "dans frame_buffer : ", frame_buffer) time.sleep(0.01) stop_event = threading.Event() thread = threading.Thread(target=process_frame) thread.daemon = True thread.start() start_time = time.perf_counter() frame_count = 0 def stop_thread(): stop_event.set() thread.join() while True: ret, frame = cap.read() if ret: frame_buffer = frame.copy() else : frame = frame_buffer frame = frame_buffer print ("valeur de frame_buffer après cap.read : ", frame_buffer) print (cap.get(cv2.CAP_PROP_FRAME_WIDTH)) print (cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) cv2.imwrite("parth/image_traitee_boucle_while.jpg", frame_buffer, [cv2.IMWRITE_JPEG_QUALITY, 50]) if not ret: break lock.acquire() #frame_buffer = frame lock.release() frame_count += 1 elapsed_time = time.perf_counter() - start_time if elapsed_time > 1.0: print("Frames par seconde : ", frame_count / elapsed_time) start_time = time.perf_counter() frame_count = 0 lock.acquire() #print(frame_buffer.shape) cv2.imshow("Output", frame_buffer) lock.release() key = cv2.waitKey(1) & 0xFF if key == ord("q"): break cap.release() cv2.destroyAllWindows() stop_thread() I tried a lot of things like catching some exceptions with try-except but I have nothing. with some print statements, ret is set to true, frame in my loop got the position in cap.read() but I don't know where is the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/75374417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using Insert Iterators when reading from file can you use Insert Iterators while reading from a file to put the data into STL container? for example: FILE *stream; fread(back_inserter(std::list), sizeof(int), 1, stream); A: C++ streams are not compatible with C stdio streams. In other words, you can't use C++ iterators with FILE* or fread. However, if you use the C++ std::fstream facilities along with istream_iterator, you can use an insertion iterator to insert into a C++ container. Assuming you have an input file "input.txt" which contains ASCII text numbers separated by whitespace, you can do: #include <iostream> #include <fstream> #include <vector> #include <iterator> int main() { std::ifstream ifs("input.txt"); std::vector<int> vec; // read in the numbers from disk std::copy(std::istream_iterator<int>(ifs), std::istream_iterator<int>(), std::back_inserter(vec)); // now output the integers std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, "\n")); } A: no you can't. And it's fundamentally not-portable to store int like that. Your code will break if you write your file with a big-endian machine and try to read it with a little-endian machine. But nobody prevents you to. Just define your own forward iterator that reads binary from a istream. You will likely want to stop using FILE and fread/fopen/fclose function as they are from C era. then you will be able to write : std::copy_n(your_custom_forward_iterator, count, back_inserter<std::list<....> >);
{ "language": "en", "url": "https://stackoverflow.com/questions/3795326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get the most value from another column I want to get data historical and the production. My stored procedure is as follows: ALTER PROCEDURE [dbo].[pCaRptACInactivas]( @CodAsesor VARCHAR(15), @CodOficina VARCHAR(4)) AS SET NOCOUNT ON DECLARE @CodArbolConta VARCHAR(25) IF @CodOficina = '%' SET @CodArbolConta = '%' ELSE SELECT @CodArbolConta = CodArbolConta + '%' FROM tClOficinas WHERE CodOficina LIKE @CodOficina SELECT tabACInactivas.CodOficina, tabACInactivas.NomOficina, tabACInactivas.NomAsesor, MAX(tabACInactivas.CodPrestamo) CodPrestamo, tabACInactivas.CodAsociacion, tabACInactivas.NombreAsociacion, MAX(tabACInactivas.Ciclo) AS Ciclo, COUNT(DISTINCT tabACInactivas.CodUsuario) AS CantSocias, MAX(tabACInactivas.FechaEstado) AS FechaCancelacion--, FROM ( SELECT tClOficinas.CodOficina, tClOficinas.NomOficina, tCaClAsesores.CodAsesor, tCaClAsesores.NomAsesor, tCaPrestamos.CodPrestamo, tCaAsociacion.CodAsociacion, tCaAsociacion.NombreAsociacion, tCaPrestamos.Ciclo, tCaPrCliente.CodUsuario, tCaPrestamos.FechaEstado, tClParametros.FechaProceso FROM tCaPrestamos WITH(NOLOCK) INNER JOIN tCaProducto WITH(NOLOCK) ON tCaProducto.CodProducto = tCaPrestamos.CodProducto INNER JOIN tClOficinas WITH(NOLOCK) ON tClOficinas.CodOficina = tCaPrestamos.CodOficina INNER JOIN tCaAsociacion WITH(NOLOCK) ON tCaAsociacion.CodAsociacion = tCaPrestamos.CodAsociacion INNER JOIN tCaPrCliente WITH(NOLOCK) ON tCaPrCliente.CodPrestamo = tCaPrestamos.CodPrestamo INNER JOIN tClParametros WITH(NOLOCK) ON tClParametros.CodOficina = tClOficinas.CodOficina INNER JOIN tCaClAsesores ON tCaClAsesores.CodAsesor = tCaAsociacion.CodAsesor WHERE tCaPrestamos.Estado = 'CANCELADO' AND DATEDIFF(DAY, tCaPrestamos.FechaEstado, tClParametros.FechaProceso) > 30 AND NOT EXISTS(SELECT 1 FROM tCaPrestamos Pr INNER JOIN tCaPrCliente PrCl ON PrCl.CodPrestamo = Pr.CodPrestamo WHERE Pr.Estado NOT IN ('TRAMITE', 'APROBADO') AND Pr.FechaDesembolso >= tCaPrestamos.FechaEstado AND Pr.CodAsociacion = tCaPrestamos.CodAsociacion ) AND tCaProducto.Tecnologia = 3 AND tCaPrestamos.CodAsesor LIKE @CodAsesor AND tCaPrestamos.CodOficina IN (SELECT CodOficina FROM tClOficinas WHERE CodArbolConta LIKE @CodArbolConta) UNION ALL SELECT tClOficinas.CodOficina, tClOficinas.NomOficina, tCaClAsesores.CodAsesor, tCaClAsesores.NomAsesor, tCaHPrestamos.CodPrestamo, tCaAsociacion.CodAsociacion, tCaAsociacion.NombreAsociacion, tCaHPrestamos.Ciclo, tCaHPrCliente.CodUsuario, tCaHPrestamos.FechaEstado, tClParametros.FechaProceso FROM tCaHPrestamos WITH(NOLOCK) INNER JOIN tCaProducto WITH(NOLOCK) ON tCaProducto.CodProducto = tCaHPrestamos.CodProducto INNER JOIN tClOficinas WITH(NOLOCK) ON tClOficinas.CodOficina = tCaHPrestamos.CodOficina INNER JOIN tCaAsociacion WITH(NOLOCK) ON tCaAsociacion.CodAsociacion = tCaHPrestamos.CodAsociacion INNER JOIN tCaHPrCliente WITH(NOLOCK) ON tCaHPrCliente.CodPrestamo = tCaHPrestamos.CodPrestamo INNER JOIN tClParametros WITH(NOLOCK) ON tClParametros.CodOficina = tClOficinas.CodOficina INNER JOIN tCaClAsesores ON tCaClAsesores.CodAsesor = tCaAsociacion.CodAsesor WHERE tCaHPrestamos.Estado = 'CANCELADO' AND DATEDIFF(DAY, tCaHPrestamos.FechaEstado, tClParametros.FechaProceso) > 30 AND NOT EXISTS(SELECT 1 FROM tCaHPrestamos Pr INNER JOIN tCaHPrCliente PrCl ON PrCl.CodPrestamo = Pr.CodPrestamo WHERE Pr.Estado NOT IN ('TRAMITE', 'APROBADO') AND Pr.FechaDesembolso >= tCaHPrestamos.FechaEstado AND Pr.CodAsociacion = tCaHPrestamos.CodAsociacion ) AND tCaProducto.Tecnologia = 3 AND tCaHPrestamos.CodAsesor LIKE @CodAsesor AND tCaHPrestamos.CodOficina IN (SELECT CodOficina FROM tClOficinas WHERE CodArbolConta LIKE @CodArbolConta) )tabACInactivas GROUP BY tabACInactivas.CodAsociacion, tabACInactivas.NombreAsociacion, tabACInactivas.NomOficina, tabACInactivas.CodOficina, tabACInactivas.NomAsesor I want the CantSocias column takes the most value of the Ciclo column, but not working A: That stored procedure that you have posted up is way too large and blocky to even try to interpret and understand. So I will go off of your last sentence: I want the CantSocias column takes the most value of the Ciclo column, but not working Basically if you want to set a specific column to that, you can do something like this: update YourTable set CantSocias = ( select max(Ciclo) from YourOtherTable ) -- here is where you can put a conditional WHERE clause A: You may need to create a sub query to get the most value of Ciclo and join back to your query. An example of what I mean is here: create table #Product ( ID int, ProductName varchar(20) ) insert into #Product(ID, ProductName) select 1,'ProductOne' union select 2,'ProductTwo' create table #ProductSale ( ProductID int, Number int, SalesRegion varchar(20) ) insert into #ProductSale(ProductID,Number,SalesRegion) select 1,1500,'North' union select 1, 1200, 'South' union select 2,2500,'North' union select 2, 3200, 'South' --select product sales region with the most sales select * from #Product p select ProductId, Max(Number) as Bestsale from #ProductSale ps group by ProductID --combining select p.ID, p.ProductName, tp.Bestsale, ps.SalesRegion from #Product p inner join (select ProductId, Max(Number) as Bestsale from #ProductSale ps group by ProductID) as tp on p.ID = tp.ProductID inner join #ProductSale ps on p.ID = ps.ProductID and tp.Bestsale = ps.Number
{ "language": "es", "url": "https://stackoverflow.com/questions/7680629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to pair a Windows 10 phone with PC for debugging? I get a code on my phone - but where do I enter it? I tried connecting by usb, entering the wifi url into my PC's browser ("insecure connection"),... A: Edited (May2016): With later Win10 mobile its now possible to debug a phone running Windows 10 Mobile via WIFI. Follow the guidance here: https://msdn.microsoft.com/en-us/windows/uwp/debug-test-perf/device-portal-mobile
{ "language": "en", "url": "https://stackoverflow.com/questions/36730193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Combo box automatically assigns a value, when not wanted. C# Windows Forms I'm having this issue with ComboBox controls. I select a value for the combo box (Already pre-setted) and it AUTOMATICALLY assigns the same value to another ComboBox next to it. Despite their data source is the same List, I want to select two different values (from that same list) for those two combo boxes. cmbEmpresas.DataSource = Empresa.listaDeEmpresas; cmbEmpresas.DisplayMember = "NombreEmpresa"; //This works OK cmbLlegada.DataSource = Locacion.listaDeLocaciones; cmbLlegada.DisplayMember = "Ciudad"; //These two represent a starting and arriving location for a trip //they both have objects of the type "Locación" cmbSalida.DataSource = Locacion.listaDeLocaciones; cmbSalida.DisplayMember = "Ciudad"; As it is shown in the previous image, both cmbLlegada and cmbSalida have the same value, I did not want this to happen, I just selected cmbSalida's value and it automatically changed cmbLlegada's value.
{ "language": "en", "url": "https://stackoverflow.com/questions/53405094", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Xamarin form: How display activityindicator instantly while in async task? public async Task ShowIndicator(Func<Task> action) { actionEnabled = false; IndicatorVisibility = true; await Task.Delay(5000); await action.Invoke(); IndicatorVisibility = false; actionEnabled = true; } I am using the above code to run some Task while showing the indicator by setting the viewmodel properties of the IndicatorVisibility. If I placed the Task.Delay, it will ok but will slow down the code. If I am not placed it, the indicator won't show straightaway coz it will set to second to last indicator visibility to false. Is it possible to wait the indicator displayed itself before execute the action from the above code? A: I had the same issue. This has the exact problem, the activity indicator never appers or appears too late: async void GoDetail(object obj) { Busy = true; DetailsViewModel.Initialize(_items, this.SelectedItem); await App.Current.MainPage.Navigation.PushAsync(new xxxPage()); Busy = false; } This fixes it, activity indicator appears instantly...: async void GoDetail(object obj) { Busy = true; Device.BeginInvokeOnMainThread(async () => { DetailsViewModel.Initialize(_items, this.SelectedItem); await App.Current.MainPage.Navigation.PushAsync(new xxxPage()); Busy = false; }); } A: Try this code public Task ShowIndicator(Func<Task> action) { actionEnabled = false; IndicatorVisibility = true; Device.BeginInvokeOnMainThread(async () => { await action.Invoke(); IndicatorVisibility = false; actionEnabled = true; }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/48758553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Get Join table data as a result of ActiveRecord:Relation I am using rails 5 and oracle as a database. My query look like this.. DefaultConfig.where("role_id = ?","1001").joins(:config_param) Now i want to get the result object as a config_param object not a default_config.. is it possible to do? Thanks for any help class DefaultConfig < ApplicationRecord self.table_name = "default_config" belongs_to :role belongs_to :config_param end class ConfigParam < ApplicationRecord self.table_name = "config_param" has_many :default_configs, foreign_key: "param_id" end A: ConfigParam.joins(:default_configs).where(default_config: { role_id: 1001 })
{ "language": "en", "url": "https://stackoverflow.com/questions/44964713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: XAML adding text based on a trigger <dxg:GridControl Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" ItemsSource="{Binding Notes}" AutoGenerateColumns="None" ColumnGeneratorTemplateSelector="{StaticResource ColumnTemplateSelector}" dependencyProperties:BestFitColumn.IsEnabled="True" SelectedItem="{Binding SelectedRow}"> <dxg:GridControl.Columns> <dxg:GridColumn FieldName="Priority" Header="{x:Static meta:MetaCommon.Importance}"> <dxg:GridColumn.CellTemplate> <DataTemplate> <Image> <Image.Style> <Style BasedOn="{StaticResource SmallIcon}" TargetType="Image"> <Style.Triggers> <DataTrigger Binding="{Binding RowData.Row.Priority}" Value="H"> <Setter Property="Source" Value="{x:Static helper:IconHelper.HighImportance}" /> <Setter Property="ToolTip" Value="{x:Static meta:MetaCommon.High}" /> </DataTrigger> </Style.Triggers> </Style> </Image.Style> </Image> </DataTemplate> I'm wondering if it's possible to add text in the case where RowData.Row.Priority=H. I can't seem to find any way myself and was wondering if I just missed something or if have to create a work around and do something outside of this statement. A: You can move your DataTrigger under DataTemplate.Triggers. Have it set the Visibility for a new TextBlock with the text you want. <DataTemplate> <Grid> <Image/> <TextBlock Visibility="Collapsed"/> </Grid> <DataTemplate.Triggers> </DataTemplate.Triggers> </DataTemplate>
{ "language": "en", "url": "https://stackoverflow.com/questions/42835107", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Facebook Login Invalid Key Hash After First Login I have added the key hash logged by this call (plus an equals sign) to the settings for my app on the Facebook developer site. Log.d("MyApp", FacebookSdk.getApplicationSignature(this)); I can repeat the following steps indefinitely. Facebook login works the first time, but fails on all subsequent attempts. Facebook App (v91.0.0.17.68) Facebook Android SDK (v4.15.0) * *Revoke Facebook Login at https://www.facebook.com/settings?tab=applications *Login with Facebook * *Success *Login with Facebook * *Invalid key hash. The key hash KEY_HASH does not match any stored key hashes. Configure your app key hashes at http://developers.facebook.com/apps/FACEBOOK_APP_ID The KEY_HASH in the error messages exactly matches one of the key hashes I have saved to the app on the Facebook developer site (at the link listed in the error message). This only happens when the Facebook app is installed on the device. Facebook login succeeds multiple times in a row using the fallback web login. I've found this and this question that have a combined single answer of "revoke Facebook Login manually in the app before trying to log in again" which seems like a hacky workaround to me. Why do you have to revoke Facebook Login before logging in again? With the web fallback login it just says "you've already authorized this app". I would expect the same behavior here. Edit: This only happens with a debug build. I can login repeatedly with the Facebook app installed if I use a release build (minify disabled just to reduce the changes). A: Same thing happened to me and I had generated hash from debugkey for debugging in dev enviroment but when building it for Google Play the problem was appearing. You need to generate hash with the certificate and alias that you will sign the app for publishing in Google Play. Edit: You need to add key hash for both debug key and release key.
{ "language": "en", "url": "https://stackoverflow.com/questions/39236593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cannot insert the value NULL into column 'X', table 'DB139.dbo.Y'; column does not allow nulls. INSERT fails I'm working on a SQL Server. I have created the following table: CREATE TABLE Payment( Cust_ID CHAR(4), Credit_Card_Number CHAR(16), Payment_Number INTEGER, Date DATE, Fee MONEY, PRIMARY KEY (Cust_ID, Credit_card_number, Payment_number)) ALTER TABLE Payment ADD CONSTRAINT FK_CustPays FOREIGN KEY (Cust_ID) REFERENCES Customer(Cust_ID) ON DELETE CASCADE ; ALTER TABLE Payment ADD CONSTRAINT FK_CardPayment FOREIGN KEY (Credit_Card_Number) REFERENCES Credit_card(Credit_card_number) ON DELETE CASCADE ; As you can probably tell, this is a weak entity. I suspect this is the reason why I can't insert values into it with the INSERT INTO statement, like this: Insert into Payment(Payment_number,Date,Fee) Values ('918702','2016-08-12',93); I get the error Cannot insert the value NULL into column 'Cust_ID', table 'DB139.dbo.Payment'; column does not allow nulls. INSERT fails. I have successfully inserted data into all of my other tables this way. The only 2 tables that have also been affected by this are the other 2 weak entities (the tables Savings_account and Checking_account). As you can tell, I haven't included any NULL values, so I'm not sure what this error is about. Here are the 2 other weak entities, for reference (after the "Account" table): CREATE TABLE Account( Account_number CHAR(10), Balance MONEY, Name_of_bank VARCHAR(50), Date_of_creation DATE, PRIMARY KEY (Account_number)) ALTER TABLE Account ADD Account_number CHAR(16) CONSTRAINT FK_AccountNumberDouble FOREIGN KEY (Credit_card_number) REFERENCES Credit_card(Credit_card_number) ON DELETE CASCADE ; ALTER TABLE Account ADD Cust_ID CHAR(4) CONSTRAINT FK_CustIDTriple FOREIGN KEY (Cust_ID) REFERENCES Customer(Cust_ID) ; CREATE TABLE Savings_account( Account_number CHAR(10), Interest_rate INTEGER, PRIMARY KEY (Account_number)) ALTER TABLE Savings_account ADD CONSTRAINT FK_SavingsAccount FOREIGN KEY (Account_number) REFERENCES Account(Account_number) ; CREATE TABLE Checking_account( Account_number CHAR(10), Overdraft_limit MONEY, PRIMARY KEY (Account_number)) ALTER TABLE Checking_account ADD CONSTRAINT FK_CheckingAccount FOREIGN KEY (Account_number) REFERENCES Account(Account_number) ; Any help is appreciated. A: you should be insert value for Cust_ID because it not identity and it primary key.. or you alter Cust_ID to identity
{ "language": "en", "url": "https://stackoverflow.com/questions/74634066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: ThreadStart, field initializer cannot reference the non-static field I am trying to use Threads in my app but i get a error. I searched a solution at MSDN and other forums but i didn't get it. public class ClickingThread { private const int MOUSEEVENTF_LEFTDOWN = 0x0002; private const int MOUSEEVENTF_LEFTUP = 0x0004; [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo); public ClickingThread() { } public void MouseClicking() { int X = Cursor.Position.X; int Y = Cursor.Position.Y; Thread.Sleep(100); mouse_event(MOUSEEVENTF_LEFTUP, X, Y, 0, 0); mouse_event(MOUSEEVENTF_LEFTDOWN, X, Y, 0, 0); } public void Click() { while (true) { MouseClicking(); } } } And when i try to use method from this class like this ClickingThread clicker = new ClickingThread(); Thread click = new Thread(new ThreadStart(clicker.Click)); I get an error (second line -> clicker.Click)"A field initializer cannot reference the non-static field, method etc." Thanks for advices.
{ "language": "en", "url": "https://stackoverflow.com/questions/32863440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }